text:
Q: "Duplicate entry ... for key PRIMARY" when inserting both "Krakow" and "Kraków" I have an Entity LocationsCoordinates for saving coordinates of locations in a database with unique location and country (making a composite primary key) which is defined as below:
@Entity
@Table(name = "LOCATIONS_COORDINATES")
@IdClass(LocationsCoordinatesPK.class)
public class LocationsCoordinates  implements Serializable {

    private static final long serialVersionUID = -4580217081464519853L;

    @Id
    @Column(name = "LOCATION")
    String location;

    @Id
    @Column(name = "COUNTRY")
    String country;

    @Column(name = "LATITUDE")
    Double latitude;

    @Column(name = "LONGITUDE")
    Double longitude;

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getCountry() {
        return country;
    }

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

    public Double getLatitude() {
        return latitude;
    }

    public void setLatitude(Double latitude) {
        this.latitude = latitude;
    }

    public Double getLongitude() {
        return longitude;
    }

    public void setLongitude(Double longitude) {
        this.longitude = longitude;
    }

}

--
public class LocationsCoordinatesPK implements Serializable
{
    private static final long serialVersionUID = -4675306358956719620L;

    String location;

    String country;

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getCountry() {
        return country;
    }

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

while batch insert in jpa of locations in utf-8 character set with coordinates, for example
public class SampleDAO {

    protected EntityManager entityManager;

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this. entityManager = entityManager;
    }

public void saveCoordinates(){
ArrayList<LocationsCoordinates> coordinates = new ArrayList<LocationsCoordinates>();

LocationsCoordinates coordinate = new LocationsCoordinates();
coordinate.setLocation("Krakow");
coordinate.setCountry("Poland");
coordinate.setLatitude(25.25817);
coordinate.setLongitude(55.30472);
coordinates.add(coordinate);

coordinate = new LocationsCoordinates();
coordinate.setLocation("Kraków");
coordinate.setCountry("Poland");
coordinate.setLatitude(25.25817);
coordinate.setLongitude(55.30472);
coordinates.add(coordinate);
save(coordinates);
}

@Transactional
public <LocationsCoordinates> List<LocationsCoordinates > save(List<LocationsCoordinates > list) {
    List<LocationsCoordinates > returnList = new ArrayList<LocationsCoordinates >();
        for(LocationsCoordinates  ob : list){
            returnList.add(entityManager.merge(ob));
        }
        return returnList;
    }
}
}

On calling save function, I am getting the following exception
2013-10-09 19:42:41,892 [ERROR ][pool-1-thread-1] JDBCExceptionReporter - Duplicate entry 'Poland-Kraków' for key 'PRIMARY'
2013-10-09 19:42:41,984 [ERROR ][pool-1-thread-1] TaskUtils$LoggingErrorHandler - Unexpected error occurred in scheduled task.
org.springframework.dao.DataIntegrityViolationException: could not insert: [com.reppify.core.dto.LocationsCoordinates]; SQL [insert into LOCATIONS_COORDINATES (LATITUDE, LONGITUDE, COUNTRY, LOCATION) values (?, ?, ?, ?)]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not insert: [com.reppify.core.dto.LocationsCoordinates]
    at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:643)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:104)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:516)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:392)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at $Proxy28.save(Unknown Source)
    at com.reppify.accenture.scoring.ScoreConnections.scoreConnections(ScoreConnections.java:308)
    at com.reppify.parser.job.accenture.JobLoader.synchronizeJob(JobLoader.java:155)
    at com.reppify.parser.job.accenture.JobLoader.startJobLoader(JobLoader.java:51)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:64)
    at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:53)
    at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(Unknown Source)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.exception.ConstraintViolationException: could not insert: [com.reppify.core.dto.LocationsCoordinates]
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2454)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2874)
    at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:79)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
    at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:76)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:512)
    ... 25 more
Caused by: java.sql.BatchUpdateException: Duplicate entry 'Poland-Kraków' for key 'PRIMARY'
    at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2024)
    at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1449)
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
    at org.hibernate.jdbc.BatchingBatcher.addToBatch(BatchingBatcher.java:56)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2434)
    ... 37 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'Poland-Kraków' for key 'PRIMARY'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
    at com.mysql.jdbc.Util.getInstance(Util.java:382)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1039)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3603)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3535)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1989)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2150)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2626)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415)
    at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1976)
    ... 41 more

As "Krakow" and "Kraków" are different string values, so these are not be considered duplicate but as we can see in exception these are considered as same value. please help.

A: Try to use utf8_general_ciutf8_bin as collation for the column in MySQL.
This doesn't seem to be a Java problem, but a MySQL problem.
Find more about collations here
This is the correct CREATE TABLE
CREATE TABLE `locations_coordinates` (
  `COUNTRY` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '',
  `LOCATION` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '',
  `LATITUDE` double DEFAULT NULL,
  `LONGITUDE` double DEFAULT NULL,
  PRIMARY KEY (`COUNTRY`,`LOCATION`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


text:
Q: How add init to es6 modules in webpack I'm using webpack and es6.
I have page-transition in webpage Barba.js
I must reinit my codes with Barba Event Barba newPageReady Event, I have many separate modules like menuEvent.js, parallaxEvent.js, inviewEvent.js, touchEvents.js, plugins and librarys.js these modules are imported to mainFile.js
Reinit Code
I dont have any idea how to add init to each module and add initialize scripts in Barba Event...

A: Solution:

menuEventjs:

export class menuEvent {
    static init() {
        //codes
    }
}

Barba:

import { menuEvent } from './menuEvent'

Barba.Dispatcher.on('newPageReady', function(currentStatus, oldStatus, container)    {
    menuEvent.init()
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wireless connection with Linux command line I have a Java program to run on an Ubuntu box. This program should ask the user to enter the login and password of the wifi network with which it wants to connect and then the Java program must use the login and pass to connect automatically.
I found iwconfigm but it doesn't work
I launched the command:
iwconfig wlan0 essid login key pass
Error for wireless request "Set Encode" (8B2A)
       invalide argument "pass"

So, how do I connect to the wireless network via the command line?

A: The problem with giving this answer is that there is not a single answer, but very many, depending on the authorization scheme used.
Since most home networks use WPA/WPA2 with PSK, I will tell you how to do it in this case. A proper treatment of all possible subcases is too long for this forum.
   wpa_passphrase your_network_name your_password > wpa.conf
   ifconfig wlan0 down
   ifconfig wlan0 up
   iwconfig wlan0 essid your_network_name
   wpa_supplicant -B -Wnl80211 -i wlan0 -c wpa.conf
   dhclient wlan0

These commands have to be executed as root.


text:
Q: can bootstrap modal open different pages i have like 20 links on a page and all of them open the same modal but with different sets of content..
the links are like :
978

6

however problem is that the modal is filled with the content from the first click and then remains .. is it possible that the modal is updated with the content related to each click ...
as i dont want to have 20+ modals on the page ... must be simpler solution ???

A: i don't know where you are redirecting your page i'm considering links are null i.e href="#"
you need to write a script for that and specify different id's to your links,
in your case it would be
978

 6

and paste this javascript

here is the jsfiddle link
http://jsfiddle.net/bizamajig/THBm7/12/


text:
Q: Should I use the PostgreSQL bit string? I've been learning about the bit string data type lately, and I am quite curious about:

*

*At the bottom of this doc page there is the sentence:

... plus 5 or 8 bytes overhead depending on the length of the string

*How are bit strings handled in other languages such as PHP, Java, C#, C++, etc., through drivers like Npgsql, ODBC, etc.
For question #1, using smallint or bigint will be much more storage efficient, and would perhaps offer a performance gain since integers are supported everywhere. Most programming languages handle bit operations on integers with ease. If that is the case, what is the point of introducing the bit-string data type? Is it Only for cases that need a large amount of bit masks? Bit field indexing maybe? I'm more curious about how bit field indexing is done in PostgreSQL.
For #2, I'm confused, more than curious. For example, what if I store week day bit masks in a bit(7) field, one bit for a day, with lowest bit representing Monday. Then I query for the value in PHP and C++. What will I get? The documentation says I'll have a bit string, however a bit string is not something I can use directly - as with integers. Then in this case, should I give up on bit field?
Can anyone elaborate why and when I should use bit or bit varying?

A: All PostgreSQL types are useful for some things and less useful for others.  In general, you get more out of worrying about functionality first and performance later.  PostgreSQL has a large number of functions for manipulating various kinds of data types and these are no exception.
I would expect on the application layer, unless your db driver handles it through some sort of type conversion, you'd get a string representation and have to handle this.  So it may or may not be useful in that capacity.
Where it is likely useful is when you want to select records based on bitwise operations, such as a bitwise or or a bitwise and, or otherwise manipulate the data in SQL queries.  Unless you are doing this, many of the more esoteric features of PostgreSQL are less helpful.
Note also for longer strings of binary information there is a large object interface which allows you to do streaming etc. and a bytea interface which allows a more compact string representation.
tl; dr:  If you need it you will know it.  Otherwise file it away in the "reserved for future use" section of your mind.

A: If you only have a few variables I would consider keeping separate boolean columns.

*

*Indexing is easy. In particular, indexes on expressions are easy.

*Conditions for queries and partial indexing are easy to write and read and meaningful.

*A boolean column occupies 1 byte. For only a few variables this occupies the least space.

*Unlike the other options boolean columns allow NULL values for individual bits if you should need that. You can always define columns NOT NULL if you don't.

Optimizing storage
If you have more than a hand full variables but less than 33, an integer column may serve you best. (Or a bigint for up to 64 variables.)

*

*Occupies 4 bytes on disk.

*Very fast indexing for exact matches (= operator).

*Handling individual values may be slower / less convenient than with bit string or boolean.

With even more variables, or if you want to manipulate the values a lot, or if you don't have huge tables and disk space / RAM is no issue, or if you are not sure what to pick, I would consider bit(n) or bit varying(n).

*

*Occupies at least 5 bytes (or 8 for very long strings) plus 1 byte for each group of 8 bits (rounded up).

*You can use bit string functions and operators directly.

Examples
For just 3 bits of information, individual boolean columns get by with 3 bytes, an integer needs 4 bytes and a bit string 6 bytes (5 + 1).
For 32 bits of information, an integer still needs 4 bytes, a bit string occupies 9 bytes for the same (5 + 4) and boolean columns occupy 32 bytes.
Further reading

*

*Is there any difference between integer and bit(n) data types for a bitmask?

*Calculating and saving space in PostgreSQL

*Can I convert a bunch of boolean columns to a single bitmap in PostgreSQL?


text:
Q: How to handle NSNull values In Objective C, a common practice is to often forgo checking for nil, instead relying on the fact that messaging nil silently fails.
For example, to validate a string:
if ([myString length] > 1) { // Short and sweet

If myString is nil, this check will fail - as intended. It's a huge improvement over what one may assume would be the correct implementation, explicitly checking for nil:
if (myString && [myString length] > 1) { // Redundant nil check

However, particularly in the case of a web API, myString could conceivable equal [NSNull null] - similar to nil, but with different behavior. Of primary concern, is that messaging NSNull causes an exception. For example, our short simple solution from earlier will cause an exception:
// Causes an exception, because [NSNull null] is an object
NSString *myString = (id)[NSNull null];
if ([myString length] > 1) {

To further complicate things, a simple nil check will actually pass because [NSNull null] is a valid object:
NSString *myString = (id)[NSNull null];
if (myString) { // Evals to YES

So, the only way to be completely safe is to both check for NSNull and do your regular implicit nil check, by calling a method:
if (myString != (id)[NSNull null] && [myString length] > 1) { // Short and sweet

My Question: is this really necessary? Is there a more concise option with less duplicate code, that I've overlooked? Are my conclusions, in fact, correct?

A: NSNull objects typically crop up with people reading JSON files containing null values.
In that case, there is a chance that the server that supplied the null value thinks you should do something different than with no value. For example, if you get a dictionary and there might be a string stored under some key, you might get a string with non-zero length, you might get an empty string because the server sent you an empty string, you might get nothing because the server sent you nothing, or you might get [NSNull null] because the server sent you a null value. Up to you to decide if the empty string, nothing, and [NSNull null] need to be treated differently or not.
By the way: I have always used some extensions to the NSDictionary class, for example - (NSString*)stringForKey, which will return either an NSString or nil, 100% guaranteed. If you do that, all your error checking is in one method. And you can do things like converting NSNumber to NSString, or NSNull to nil, or NSDictionary etc. to nil, and never worry about it again. Of course you need to check if it is appropriate.

A:
is this really necessary?

If some API can return NSNull instead of a string, then yes, you should check for it. It's usually not necessary since NSNull is not a string and won't be returned by most methods that would return a string. But a collection such as a dictionary, for example, can have any object as a value. If you're not sure that the value will be a string, you should take appropriate precautions.

Is there a better way to handle the possibility of NSNull that I've overlooked?

Another way that you could do roughly the same thing but protect yourself from other types (NSNumber, for example) is to check the type of the thing that you get back rather than comparing specifically against [NSNull null]:
if ([myString isKindOfClass:[NSString class]] && [myString length] > 1) { //...

A: In addition to the other answers, you could consider replacing NSNull instances with empty strings before parsing your API response into model objects. Similarly, you could traverse a mutable copy of the response dictionary and remove keys whose values contain NSNull.
Basically, do it up front when you get the response so that your code isn't littered with NSNull checks.

A: Another way to approach this is to use a Category:
@interface NSNull (Utilities)

- (NSString *)stringValue;

@end

@implementation NSNull (Utilities)

- (NSString *)stringValue
{
    return nil;
}

@end

And then simply:
[myDictionary[@"key"] stringValue] // returns nil for NSNull values


text:
Q: Where does the output from the ssh ForceCommand script go? I have a perl script that does a bunch of stuff like limit that commands that can be run through ssh (using SSH_ORIGINAL_COMMAND). The script works fine except for the fact that I am unable to see the output from the script (a bunch of things that I am printing) anywhere.
I have checked /var/log/auth.log but I don't see anything there.
Here is what the line in my sshd_config looks like:
ForceCommand /some/path/my_script.pl
I am running Ubuntu 12.x

A:
Where does the output from the ssh ForceCommand script go?

The ForceCommand is the command that is run by the connecting user. Therefore if it produces some output, it goes to the user who is connecting.


text:
Q: javascript regex - match between slashes I have a URL: https://api.example.com/main/user1/collection1/contents/folder1/test.js
To capture only collection1, I tried the following but it returns user1 along with it, how can I exclude user1?
(?:\/user1\/)[^\/]*
To capture only folder1/test.js, the following also returns contents and I want to exclude it
contents\/(.*)$

A: If you want to use a regex. you could try (?:\/user1\/)([^\/]+) to capture only collection1.
This captures the part after /user1/ in a capturing group ([^\/]+).

const pattern = /\/user1\/([^\/]+)/;
const str = "https://api.example.com/main/user1/collection1/contents/folder1/test.js";
matches = str.match(pattern);
console.log(matches[1]);

To capture only folder1/test.js you could use folder1\/.*$

const pattern = /folder1\/.*$/;
const str = "https://api.example.com/main/user1/collection1/contents/folder1/test.js";
matches = str.match(pattern);
console.log(matches[0]);

Without regex you might use URL:

const str = "https://api.example.com/main/user1/collection1/contents/folder1/test.js";
const url = new URL(str);
const parts = url.pathname.split('/');
console.log(parts[3]);
console.log(parts[5] + '/' + parts[6]);


text:
Q: Javascript Console returns incorrect sorted array I entered the following code into the chrome console.
var array = [25,7,8,41];
array.sort();

It returns [25,41,7,8]. What's going on?

A:
The sort() method sorts the items of an array.
The sort order can be either alphabetic or numeric, and either
  ascending (up) or descending (down).
By default, the sort() method sorts the values as strings in
  alphabetical and ascending order.
This works well for strings ("Apple" comes before "Banana"). However,
  if numbers are sorted as strings, "25" is bigger than "100", because
  "2" is bigger than "1".
Because of this, the sort() method will produce an incorrect result
  when sorting numbers.

If you would like this to be corrected you can write a comparison function as the first parameter passed to the sort method. There is one listed in the reference!
EDIT: Posted here for future cases...
var points = [40, 100, 1, 5, 25, 10];
function myFunction() {
    points.sort(function(a, b){return a-b});
    console.log(points);
}

Reference

A: By default the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -
 function sortNumber(a,b) {
        return a - b;
    }

    var Array = [25 , 7 , 8 , 41];
    Array.sort(sortNumber);

source How to sort an array of integers correctly

A: Everything in javascript is object by default and when you try to sort it is trying to sort it alphabetically.
You have to write your own compare function to sort them numerically
check the following code snippet

var array = [25,7,8,41];
array.sort(sortCompare);
function sortCompare(a,b){
  return a-b;
}
console.log(array);

A: Sort method sorts items of an array. Sort method by itself interprets items as strings.
Since "2" in "25" is a lower number than "7" in "7", it returns that 25 is indexed before 7 for example. In order to sort numbers in ascending order user:
var array = [25,7,8,41];
array.sort(function(a, b){return a-b});

Check this example as well.

A: To expand on the other answers here with a solution to the problem you are facing-- from MDN's array.sort page:

To compare numbers instead of strings, the compare function can simply subtract b from a. The following function will sort the array ascending (if it doesn't contain Infinity and NaN):

function compareNumbers(a, b) {
    return a - b;
}


text:
Q: How do I read css file relatively from my master page? In my ASP.NET project.  I put my css file in
\App_Themes\Default\theme.css

This is right under my project folder with all the aspx, master, web.config, etc.
How do I read that into a string using relative pathing from my .Master page?  In C#.

A: In the *.aspx page:
<head runat="server">
    <link runat="server" href="~/App_Themes\Default\theme.css"
          rel="stylesheet" type="text/css" />
</head>

Or from the code behind:
string path = ResolveUrl("~/App_Themes\Default\theme.css");
// or
string path = ResolveClientUrl("~/App_Themes\Default\theme.css");

(Description of the behavior and the difference between the twocan be found at: http://www.andornot.com/blog/post/ResolveUrl-vs-ResolveClientUrl.aspx)

A: This should return the full path to your css folder
Server.MapPath("App_Themes\Default\theme.css")

more info can be found here http://msdn.microsoft.com/en-us/library/ms178116.aspx


text:
Q: why my Handler doesn't work with UI thread I'm trying to understand how Handler works in a pair with Looper, but i have some problem. I need to do some long operation in a back thread and then to send some result in a textView.
I get the following error after pressing a button:

Only the original thread that created a view hierarchy can touch its views.

public class MainActivity extends AppCompatActivity {
Button mButton;
TextView mTextView;
ConsumeThread mConsumeThread;

class ConsumeThread extends Thread{
    public Handler mHandler;

    @Override
    public void run() {
        Looper.prepare();
        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg){
                int arg = msg.what;
                someLongOperation(arg);
            }
        };
        Looper.loop();
    }

    private void someLongOperation(int arg){
        // do some long operation
        arg += 1000;
        mTextView.setText("Operation's code is " +arg); // fatal exception
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mTextView = (TextView)findViewById(R.id.txt_view);
    mButton = (Button) findViewById(R.id.button);

    mConsumeThread = new ConsumeThread();
    mConsumeThread.start();

    mButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            if(mConsumeThread.mHandler != null){
                Message msg = mConsumeThread.mHandler.obtainMessage(10);
                mConsumeThread.mHandler.sendMessage(msg);
            }
        }
    });
}

A: To get Main Thread Handler You have get Handler as follows .
Because:-

Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it

So you need to get Handler which is associated with MainThread. For that you can use one of the following:-

*

*With Context
Handler mainHandler = new Handler(getMainLooper()){
@Override
public void handleMessage(Message msg) {
}
};

*Or Directly with Looper even when do not have Context
Handler mainHandler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
}
};

I assume that you are doing some long running task . So its better if you go with AsyncTask.

A: private void someLongOperation(int arg){
    // do some long operation
    arg =+ 1000;
    mTextView.setText("Operation's code is " +arg); // fatal exception
}

//see  here, you are in worker thread, so you can't excess UI toolkit or else exception, so if you want to do something ui related task in worker thread, use runOnUi, see here
runOnUiThread(new Runnable() {
                @Override
                public void run() {

                   textview.setText("");

                }
            })

A: You can't update the UI from another thread. You have to move the code that updates the UI to the UIThread.
Try Using:
runOnUiThread(new Runnable() {
    @Override
    public void run() {
       //TextView Update Code
   }
});

Tip: Try to reduce the number of lines of code you put inside this, as then there would be no purpose of using another thread.

A: Only the original thread that created a view hierarchy can touch its views
You have to do ui related work on the main thread...
So you can do it like this...
    private void someLongOperation(int arg){
            // do some long operation
            arg =+ 1000;
            MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
            mTextView.setText("Operation's code is " +arg); // fatal exception
             }
          });

        }


text:
Q: Angularjs - ng-route not working on IE9 - the views are not displayed I'm a beginner with Angularjs. I'm going to develop an application with this framework and Coldfusion for retrieving data from the database.
I have a problem with the compatibility on IE9 (mandatory and used by default in my office). All works in Chrome and Firefox, and I do not know why the application does not work on IE9.
The view is not shown when you click on the button in the top menu (in order to display all contacts or the view with the form foradding a contact). I think that it's a problem with the "ng-route" dependency, but I'm not sure.
I'm using the version AngularJS v1.2.23 and the dependency "ng-route" (angular-route.min.js).
here my code:

*

*index.html

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="Expires" content="0">
        <title>Application</title>
        <link rel="stylesheet" href="lib/css/bootstrap-3.1.1/css/bootstrap.min.css">
        <link rel="stylesheet" href="lib/css/bootstrap-3.1.1/css/bootstrap-theme.min.css">
        <link rel="stylesheet" href="css/styles.css" rel="stylesheet">
        <link rel="stylesheet" href="css/select.css" rel="stylesheet">

Application

All contacts

Add contacts

@Copy right 2014

*app.js (controller)
var app=angular.module('ContactsApp', ['ngRoute', 'ui.bootstrap']);
app.config(function($routeProvider){
    $routeProvider.when('/all-contacts',
    {
      templateUrl: 'template/allContacts.html',
      controller: 'ctrlContacts'
    })
    .when('/view-contacts/:contactId',
    {
      templateUrl: 'template/viewContact.html',
      controller: 'ctrlViewContacts'
    })
    .when('/search-contacts',
    {
      templateUrl: 'template/fastSearch.html',
      controller: 'ctrlContactSearch'
    })
    .when('/add-contacts',
    {
      templateUrl: 'template/manageContact.html',
      controller: 'ctrlAddContacts'
    })
    .otherwise({redirectTo:'/all-contacts'});
});

app.controller('ctrlContacts', function ($scope, ContactService){
    $scope.contacts=null;
    $scope.search = function(searchText) {
        if (searchText.length>2) {
            ContactService.fastSearch(searchText).success(function(contacts){
                $scope.contacts = contacts;
            });
        }else{
            $scope.contacts=null;
        }
    }

    // recherche
    $scope.searchText = null;
    $scope.razRecherche = function() {
        $scope.searchText = null;
    }

    // tri
    $scope.champTri = null;
    $scope.triDescendant = false;
    $scope.triEmails = function(champ) {
        if ($scope.champTri == champ) {
            $scope.triDescendant = !$scope.triDescendant;
        } else {
            $scope.champTri = champ;
            $scope.triDescendant = false;
        }
    }

    $scope.cssChevronsTri = function(champ) {
        return {
            glyphicon: $scope.champTri == champ,
            'glyphicon-chevron-up' : $scope.champTri == champ && !$scope.triDescendant,
            'glyphicon-chevron-down' : $scope.champTri == champ && $scope.triDescendant
        };
    }

    $scope.confirmDel = function (id) {
        if(confirm('Do you want to delete this contact?')){
            ContactService.delContact(id).success(function(){
                ContactService.getContact().success(function(contacts){
                    $scope.contacts = contacts;
                });
            });
        }
        $scope.orderby = orderby;
    };

    $scope.setOrder = function (orderby) {
        if(orderby === $scope.orderby){
            $scope.reverse = !$scope.reverse;
        }
        $scope.orderby = orderby;
    };

});

app.controller('NavbarController', function($scope, $location){
    $scope.getClass=function(path){

        if($location.path().substr(0,path.length) == path){
            return true;
        }else{
            return false;
        }

    }
});

...

*appService.js
    app.factory('ContactService', function($http){
        var factory={};

        factory.getContact=function(id){
            return $http.get('http://dev.remede.eurostat.cec/amadese/AngularVersion/contacts.cfc?method=getContacts&subsString=' + id);
        };

        factory.loadPersonById=function(id){
            return $http.get('http://dev.remede.eurostat.cec/amadese/AngularVersion/contacts.cfc?method=loadPersonById&idPerson=' + id);
        };

        factory.loadCategory=function(id){
            return $http.get('http://dev.remede.eurostat.cec/amadese/AngularVersion/categories.cfc?method=loadCategory&typeContact=' + id);
        };

        factory.getCountry=function(id){
            return $http.get('http://dev.remede.eurostat.cec/amadese/AngularVersion/countries.cfc?method=getCountries&countryid=' + id);
        };

        factory.fastSearch=function(string){
            if (string){
                chaine='http://dev.remede.eurostat.cec/amadese/AngularVersion/contacts.cfc?method=fastSearch&subsString=' + string;
            }else{
                chaine='';
            }
            //alert(chaine);
            return $http.get(chaine);
        };

        factory.addNewPerson=function(objContact){
            //alert(objContact);
            return $http.get('http://dev.remede.eurostat.cec/amadese/AngularVersion/contacts.cfc?method=addNewPerson&jsStruct=' + JSON.stringify(objContact))
        };

        return factory;
    })

*allContacts.html (view)

View all contacts

                Person

                Company

                Date

                Description

            Action

        {{contact.PERSON}}
        {{contact.COMPANY}}
        {{contact.REQUESTTRUEDATE}}
        {{contact.REQUESTDESCRIPTION}}

        <button class="inline btn btn-default" data-ng-click="confirmDelPerson(contact.ID)">

        </button>

Loading data...

Could you please help me to solve this problem?
Many thanks in advance for your help.

A: I have found the solution by adding the following "meta" tag in the "head" part of the page:
<meta http-equiv="X-UA-Compatible" content="IE=edge">

With this tag, all works now perfectly in IE9.

A: I ran into the same problem where I just got a blank page in IE 9.  In chrome, FF and IE 10 and 11 routing worked fine and the first page of my app, the login page, would appear.  I tried the meta tag but it did not fix the issue. I also tried moving ng-app to the body tag.  Still didn't fix it.  One other strange thing was when I opened IE developer tools suddenly it would work and my login page would appear. I did some additional searching and found that using console.log anywhere in the JavaScript can cause issues in IE.  Once I removed all console.log calls in JS files, added the meta tag and moved ng-app to the body tag, routing worked on IE 9 in both standard and compatibility mode.

A: This may be a shot in the dark but I have seen it happen before ..
Try moving
ng-app="ContactsApp" class="ng-app:ContactsApp" id="ng-app"
To the body tag and not the html tag
I don't know why this happens but I have had a similar issue, moving the tag to the body fixed it for me


text:
Q: How to get Interior Mutability on a Copy type? I have a few Copy types, and I really appreciate the handiness of them being Copy.
I would like one of those types to contain a mutable field, using Interior Mutability as in cell::Cell. There are probably other solutions for the problem I am trying to solve, but Interior Mutability is cheap. I like cheap.
However, it turns out that cell::Cell is not Copy, and from the comments is unlikely to become Copy as the maintainers fear this would be error-prone.
A comment by the OP is my current beacon of hope:

It's not the absolute end of the world if it doesn't for my own data structures (since I can just make my own version of Cell)

Though I do not see how they purport to achieve this feat.
The core issue I have is that UnsafeCell:

*

*is mandatory to implement Interior Mutability,

*is not Copy.

Which seems to close the door to any hope of implementing a CopyCell, unless I am missing a trick (a way to unsafe impl the Copy trait?).

MCVE:
#[derive(Clone, Copy)]
struct HelloWorld(Cell<u32>);

  |
3 | #[derive(Clone, Copy)]
  |                 ^^^^
4 | struct HelloWorld(Cell<u32>);
  |                   ---------- this field does not implement `Copy`

What should I replace Cell with for HelloWorld to be Copy?

Note: at the moment, the only way I can see of achieving the desired outcome is to use a &Cell<T>; with all the lifetimes implications.

A: I think there's a good reason that UnsafeCell doesn't implement Copy: it would be unsafe in the general case. Reading from an UnsafeCell is an unsafe operation, as shown by the get method's signature: it returns a raw pointer, and dereferencing a raw pointer is an unsafe operation. A copy would implicitly read the value, which could race with another thread writing to the same UnsafeCell. Cell doesn't have that race because it is !Sync (i.e. two threads can't access the same Cell).
Personally, I would just use Clone::clone instead of messing with references. Cell's clone is #[inline], so it's highly likely that the call will be optimized away in release builds.


text:
Q: Counting the sum coins, using Matlab Image Processing Toolbox I am trying to develop a program which would find a circular objects (coins) and measure their size, based on which I will assign values. I need to take into account the position form which a particular photo is taken, e.g. angle. Since some coins will appear larger than others from different angles, the value assignment will be defective, hence I am trying to solve it with projective transformation (projecting a tilted image) and so far, I am failing to project oblique photos in a way that produces more or less equal measurements of the diameters. My code is below:
    I = imread('coins2.jpg');
    imshow(I);
    M = ginput(4);
    X = ginput(4);
    P = maketform('projective', M, X);
    I = imtransform(I, P, 'nearest');
    G = rgb2gray(I);
    K = medfilt2(G);
    [centers,radii] = imfindcircles(K,[90 140],'ObjectPolarity','dark','Sensitivity',0.95);
    h = viscircles(centers, radii);
    arr = [];
       for r = 1:length(radii)
          if (radii(r)) >= 105
             arr(r) = 1;
          elseif (radii(r)) < max(radii) && radii(r) > 100
             arr(r) = 0.2;
          elseif(radii(r)) < 100 && (radii(r)) > 95
             arr(r) = 0.05;
          elseif (radii(r)) < 95 && (radii(r)) > 90
             arr(r) = 0.1;
          end
       end
   result = sum(arr);

A: If you have the option to detect corners in the pictures (for example, coins on a rectangular support), you could use this Matlab file:
https://kr.mathworks.com/matlabcentral/fileexchange/35531-perspective-control-correction to detect 4 corners manually or automatically to correct the perspective, and you would then be able to use imfindcircles as usual.


text:
Q: Mongoose to update MongoDB collection of array of number ids I have the following user Schema
const UserSchema = new mongoose.Schema({
  name: String,
  username: String,
  email: String,
  picture: String,
  id: { type: String, unique: true },
  accessCount: Number,
  appliedIds: [Number],
  general: {
   citizenship_code: String,
   gender: String,
   currentLocation: String,
   phone: String,
 }
});

And I wanna update the appliedIds field. The appliedIds field is an array of numbers that will have an indeterminate number of indexes.
My function is as follow:
router.route('/myCustomRoute/:id/apply')
  .post(async (req, res) => {
     const { nModified } = await Job.findOne({ id: req.params.id }).updateOne({
       $addToSet: { applicants: req.body.applicantId },
     });

     const test = await User.findOneAndUpdate({ id: req.body.applicantId}, { appliedIds: req.params.id })

Obviously, the applicantId is getting replaced entirely here, how can I just add a new item in this array instead of replacing it entirely?

A: You'll want to push to the appliedIds fields in your findOneAndUpdate call.
const test = await User.findOneAndUpdate(
  { id: req.body.applicantId},
  { $push: { appliedIds: req.params.id } }
)

MongoDB $push


text:
Q: Login and different keyboard layout I set up a server remotely accessible via ssh, without any DE. My password contains some characters that are not present in a standard US keyboard, however they can be typed using deadkeys. When I access the server via ssh, there is no problem since, on the client side, I've already logged in and so I can choose whatever keyboard layout I like.
Now I want to access the server directly, not remotely, (since I'm having problem with ssh), but with the US key, I cannot select different keyboard layout before the log in.
How can I solve this problem?


text:
Q: Top 5 Folders Consuming The Most Space? My hard drive is full.
What is the easiest way to find out the TOP 5 FOLDERS that consume the most disk space?
A python solution would be greatly appreciated. I use Ubuntu Linux.

A: Not a python solution, but one using the shell is to use du. To list the number of kilobytes in each folder under /var/ then sort by size with the largest one last, run the following in a shell prompt:
du -k --max-depth 1 /var/|sort -n

If you want this under python, use the always super-handy subprocess module:
import subprocess
p = subprocess.Popen(["/usr/bin/du", "-k", "--max-depth", "1"], stdout=subprocess.PIPE)
(output, stderr) = p.communicate()

Split output by newline, then by tab, then sort, and you'll have the results in python.

A: Not a Python solution and not a code example:
http://www.jgoodies.com/freeware/jdiskreport/index.html

A: A simple and pure python solution:
import os

def get_folder_size(folder_path):
    folder_size = 0
    for (path, dirs, files) in os.walk(folder_path):
        for file in files:
            filename = os.path.join(path, file)
            folder_size += os.path.getsize(filename)
    return folder_size

def get_file_size(file):
    return os.path.getsize(file)

print get_folder_size("/home/magnun")
print get_file_size("/home/magnun/background.png")

This functions returns the size (a long type) in bytes, you may need to convert it into MBytes, GBytes and etc.

A: You could just check the properties of each folder and look for the total size of the files in it. In Ubuntu, just right click on the folder, click properties and check the contents size. Not a python solution, but much easier (not everything needs a script to find the answer).  The biggest folders will likely be the ones at the top of the tree.


text:
Q: Java servlet not called I'm new in Java servlets so  I'll be appreciate for understanding. I am struggling with servlet. After sending registration form from html, servlet is not called. I literally tried many things to set it up, but every time I've got error:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Jan 13 11:23:30 GMT 2020
There was an unexpected error (type=Not Found, status=404).
No message available
It seems like html for is no redirecting to my servlet. I've even put simple sout do init() and anything happend.
Here's my java class:
I've even tried different annotations, like instead urlPatterns just name ="/registration" or just same "/registration"
@WebServlet(urlPatterns = "/registration")
public class Register extends HttpServlet {

public void init() throws ServletException {
    System.out.println("init");
}

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    System.out.println("post");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    String name = request.getParameter("userName");
    String password = request.getParameter("password");
    String email = request.getParameter("email");

    System.out.println(name + password + email);

}

Here is my html file:
in action="" I've tried put "registration" and result is same as with "/registration"
<!DOCTYPE html>
<html>
<head>
    <title>Enter Your Name</title>
</head>
<body>

    <form action="/registration" method="post">
    <input type="text" name="userName">
    <input type="email" name="email">
    <input type="password" name="password">
    <input type="submit">
</form>
</body>
</html>

Here's my .xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         id="WebApp_ID" version="3.1"
>
    <!-- Config here. -->
</web-app>

Insted of annotations I've tried to configure servlet by web.xml but it still didn't work.
EDIT:
Firstly I'm oppening http://localhost:8080/addUser.html, then passing datas. Secondly I'm redirected to http://localhost:8080/registration but the error is same.


text:
Q: Confusion with applying KCL to three phase delta connection Below is a 3-phase delta connected for balanced loads Z:

Since phase-to-phase voltages (voltage across loads) have 120 degrees phase differences and since the loads have the same impedance we can conclude that the currents Iux, Izw, Ivy across the loads also must have 120 degrees phase difference with the same RMS values. So one can draw the phasor for these currents as:

I'm experiencing some confusion for writing the node currents as KCL. For example, take node M above in my first drawing.
Vectorially for the currents at node M which one is correct and why?
Ir = Iux + Izw ?
Ir = Iux - Izw ?
According to what I read Ir must be sqrt(3) times the load current, but I don't know how they derive this by using KCL considering the phasor diagrams.

A: From your connection diagram
$$ I_R = I_{ux}+I_{zw} = I_{ux}-I_{wz} $$
From your phasor diagram
$$ I_{ux} = |I_{load}|\angle  90^\circ$$
$$ I_{wz} = |I_{load}|\angle -30^\circ$$
Thus
$$ I_R = |I_{load}|\angle  90^\circ - |I_{load}|\angle -30^\circ =
\sqrt{3}|I_{load}|\angle 120^\circ$$


text:
Q: How to enable help mode by default in ed After starting ed, help mode can be enabled using the H command. Is there a way to enable help mode by default, so that I do not have to type H every time I use ed?

A: With standard ed, you will have to enter H manually at the start of an interactive editing session, or include H at the start of any ed editing script.
The OpenBSD ed manual suggests this for ed scripts:

H
Toggles the printing of error explanations.  By default,
explanations are not printed.  It is recommended that ed scripts
begin with this command to aid in debugging.

The GNU ed implementation has a command line option, -v (or --verbose), which enables H in the editing session.  You may alias ed to ed -v if you want this to be the default behavior.

-v, --verbose
be verbose; equivalent to the H command


text:
Q: Unrecognized option "resources" under "twig.form" I didn't touch my project since a week and today I have this error when I want to go on my website
Unrecognized option "resources" under "twig.form"
I don't know why.. This was working very fine before...
Here is my config.yml :
twig:
debug:            "%kernel.debug%"
strict_variables: "%kernel.debug%"
globals:
    breadcrumb_trail: "@apy_breadcrumb_trail"
form:
    resources:
      - 'AppBundle:Form:fields.html.twig'

If you have any idea.. :)

A: If you are on SF3 or higher, check that the yaml definition hasn't changed to specify a form template: the current one (3.0.*) should be like this:
twig:
    form_themes:
        - 'bootstrap_3_layout.html.twig'

source


text:
Q: How to find dead pixels in android programmatically Please guide me, I have a task to write a code that checks the android phone/tablet screen for dead pixels. Is there any API  are provided for this.
Thank you in advance.

A: There are no API's that allow you to find dead pixels - after all Android believes that is has asked the display to show a certain color at that point, and it cannot tell that the hardware is actually showing something different. (The screenshot routines, only usable in certain limited circumstances, will likewise not show dead pixels - they show the color that should be there).


text:
Q: Errors: java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression The code is not allowing me to log in from the database:
       package Business;

import java.io.Serializable;
import java.sql.*;

public class Student implements Serializable {

    private int iD;
    private String password;
    private String firstName;
    private String lastName;
    private String street;
    private String city;
    private String state;
    private double zip;
    private String eMail;
    private double gpa;
    private String message;

    /**
     * No arg constructor that sets the default value of all
     * customer properties to an empty string value.
     */
    public Student() {
        this.iD = 0;
        this.password = "";
        this.firstName = "";
        this.lastName = "";
        this.street = "";
        this.city = "";
        this.state = "";
        this.zip = 0;
        this.eMail = "";
        this.gpa = 0;
    }

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

    public void setPassword(String password) {
        this.password = password;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public void SetLastName(String lastName) {
        this.lastName = lastName;
    }

    public void setStreet(String street) {
        this.street = street;
    }

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

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

        public void setZip(double zip) {
        this.zip = zip;
    }

          public void setEMail (String email) {
        this.eMail = email;
    }
          public void setGpa(double gpa) {
        this.gpa = gpa;
    }

    public int getID() {
        return iD;
    }

    public String getPassword() {
        return password;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getStreet() {
        return street;
    }

    public String getCity() {
        return city;
    }
    public String getState() {
        return state;
    }

    public double getZip() {
        return zip;
    }
      public String getEMail() {
        return eMail;
    }

    public double getGpa() {
        return gpa;
    }
    public String getMessage() {
        return this.message;
    }

    public boolean login(String password) throws SQLException {
        boolean yes_no = false;

        /* Verify password against database password for the userId */
        if (password.equals(this.password)) {
            this.message = "Thank you, you are logged in.";
            yes_no = true;
        } else {
            this.message = "Sorry Your Login Information seems to be incorrect.";
            yes_no = false;
        }

        /* Returns true or false based on the condition statement above */
        return yes_no;
    }

    /**
     * Establishes connection with the database containing the customer information
     * @return Connection
     */
    public Connection studentConnect() {
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        } catch (ClassNotFoundException e) {
            System.out.println("Errors: " + e);
        }

        Connection connect = null;
        try {
            connect = DriverManager.getConnection("jdbc:odbc:RegisDB");
        } catch (SQLException e) {
            System.out.println("You have Errors: " + e);
        }

        return connect;
    }

    /**
     * Takes the student Id and retrieves the information from the customers
     * data table and stores it in the properties of the customer object.
     * @param iD
     * @throws SQLException
     */
    public void findDB(int iD)  {

        Connection con = studentConnect();
        Statement statement = null;
        ResultSet result = null;

        String sql = "Select * From Students Where iD = " + iD + ";";

        try {
            statement = con.createStatement();
            result = statement.executeQuery(sql);
            while (result.next()) {
                this.iD = result.getInt("iD");
                this.password = result.getString("password");
                this.firstName = result.getString("firstName");
                this.lastName = result.getString("lastName");
                this.street = result.getString("street");
                this.city = result.getString("city");
                this.state = result.getString("state");
                this.zip = result.getDouble("zip");
                this.eMail = result.getString("eMail");
                this.gpa = result.getDouble("gpa");
            }
            con.close();

        } catch (SQLException e) {
            System.out.println("Errors: " + e);
        }
    }

    /**
     * Takes in the parameters of the customer database and inserts the parameters taken into
     * the database for the addition of customers to the database.
      * @param password
     * @param firstName
     * @param lastName
     * @param street
     * @param city
     * @param state
      * @param zip
     * @param email
     * @param gpa
     * @throws SQLException
     */
    public void insertDB(String password, String firstName, String lastName, String street, String city, String state, double zip, String email, double gpa) throws SQLException {
        Connection con = studentConnect();
        Statement statement;
        ResultSet result;
        int resultVal;
        String sql = "INSERT INTO Students (password, firstName, lastName, street, city, state, zip, eMail, gpa) VALUES ('" + password + "','" + firstName + "','" + lastName + "','" + street + "','" + city +"','" + state +"','" + zip + "','" + eMail +"','" + gpa + "');";

        try {
            statement = con.createStatement();
            resultVal = statement.executeUpdate(sql);

            System.out.println(resultVal);
        } catch (SQLException e) {
            System.out.println("Error: " + e);
            System.out.println(e.getStackTrace());
        } finally {
            con.close();
        }
    }

    /**
     * Takes in student id and locates the customer in the database, performs
     * an sql update and deletes the customer from the database.
     * @param iD
     * @throws SQLException
     */
    public void deleteDB(int iD) throws SQLException {
        Connection con = studentConnect();
        Statement statement;
        int resultVal;

        String sql = "DELETE FROM Students WHERE iD = " + iD + "';";

        try {
            statement = con.createStatement();
            resultVal = statement.executeUpdate(sql);
            System.out.println(resultVal);
        } catch (SQLException e) {
            System.out.println("Errors: " + e);
        } finally {
            con.close();
        }
    }
}

I am getting the Error page once I try to log on followed by the
Errors: java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression.
error.
Here is my Servlet:
@WebServlet(urlPatterns = {"/StudentLoginServlet"})
public class StudentLoginServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP GET and POST
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */

            String iD = request.getParameter("iD");
            String pw = request.getParameter("pw");
            System.out.println(iD);
            System.out.println(pw);

            Student s1=new Student();
            s1.findDB(iD);

            String fn=s1.getFirstName();
            System.out.println(fn);

            String ln=s1.getLastName();
            System.out.println(ln);

            String pwdb=s1.getPassword();
            System.out.println(pwdb);
            RequestDispatcher rd;

            HttpSession ses1=request.getSession();
            ses1.setAttribute("s1", s1);

            if (pw.equals(pwdb)){
                rd= request.getRequestDispatcher("/ViewStudentSchedule.jsp");
                rd.forward(request,response);

            }
            else{
                rd= request.getRequestDispatcher("/LoginError.jsp");
                rd.forward(request,response);

            }

        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP GET method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP POST method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

SIDENOTE:
The table is called "Students" in the database
and I'm accessing the following(correct casing/in order in the database):
ID
Password
FirstName
LastName
Street
City
State
Zip
EMail
GPA

A: That error suggests that the iD column in your database is something numeric; but you're trying to compare it to a String value.  You need to change your database so that the iD column is some kind of varchar or text field.

A: Remove single quotes from your query like
String sql = "Select * From Students Where iD = " + iD + ";";


text:
Q: Possible to log Django development server using cmd ">>"? Is it possible to output Django's runserver output into a text file? such as:
python manage.py runserver>>Log.txt?

A: Django uses python logging module and you can configure it in your settings.py to output into file.
Example for you

A: You can achieve it by adding following lines into settings.py.
This will both write a log file in DEBUG level and also display on console in INFO level.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': /path/to/django/debug.log,
            'maxBytes': 50000,
            'backupCount': 2,
        },
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
        },
    },
    'root': {
        'handlers': ['file', 'console'],
        'level': 'DEBUG'
    },
    'loggers': {
        'django': {
            'handlers': ['file', 'console'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

Please also have a look Django documentaton for additional information.


text:
Q: iPhone:Set imageView in transparent portion of the Image I am making an application in which user will be allowed to select a photo frame firstly and after that he/she can have to select 2 photos from gallery for that photo frame (photo frame is an image which coontains two transparent holes in which we have to set the selected photos)and he/she can crop these image according to them.And after he/she is done with cropping a new view will get open with that selected photo frame and those two cropped images will be set in those two transparent whole. I have finished till the cropping is done.
Question
How to set those two images in the transparent portion so that it will show properly in all the devices and the transparent portion keeps changing according to the photo frames the user will select.

A: Add new image on view.
Add gesture to move and resize (zoom) new image, set perfect position for new image (i.e at centre of frame), Then send image view to back side of you main image view.
After that render both view, and make new image with UIGraphicsContext.
I have render code for you.
    UIGraphicsBeginImageContextWithOptions(self.viewCombineImages.bounds.size, false, 0.0)
    self.viewCombineImages.layer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

A: As per your requirement here you can set 3 ImageView.

*

*Image view with Person1 Image.

*Image View with Person2 Image.

*Image View with Frame Image.

so the stack of subview is like UIViewController->UIView->Person Image View1, Person ImageView 2 -> Frame Image View.
Like this screenshot.

And did not need transparent image position just do both image size half of the frame and set it below frame image view and you can achieve this like my screenshot.

A: If above frame is .png file, it is possible to make transparent those parts. I thought you need three UIImageViews.
upper - decoration frame
under - person1's image view / person2's image view.
If user select two images, apply each picture on image view.
And adjust those size and coordinate. You can use
[person1ImageView setFrame:CGRectMake(x,y,width,height)];

Also, you can rotate those by using
person1ImageView.transform =  CGAffineTransformMakeRotation(radians);


text:
Q: Why does this recursive javascript function expression return undefined? I wrote a solution to this standard everyday homework problem to solve Pascal's Triangle recursively.  Console.log shows the answer my function derived.  Printing to innerHTML of a div writes the answer to the screen.  Stepping through the javascript debugger in chrome shows the solution array exists right before return returnArray.  But still at the end of the day, the function returns "undefined".  I don't get it.
var generate = function (numRows) {
    var startRow = 1;
    var startCol = 1;
    var endRow = parseInt(numRows);
    var rowArray = [];
    var returnArray = [];
    var triVal;

    var triangle = function (row, col) {
        //base case
        if (col == 1 || col == row) {   //If the element is the either first or last element then initialize it with 1
            if (col == 1) {
                rowArray = [];
            }
            triVal = 1;
            rowArray.push(triVal);

            if (col == row) {
                returnArray.push(rowArray);
            }
        }
        else {
            //calc
            triVal = returnArray[row - 2][col - 2] + returnArray[row - 2][col - 1]
            triVal = typeof (triVal) === "undefined" ? 1 : triVal;
            rowArray.push(triVal);
        }
        if (col == row && row == endRow) { //stop the function and return
            console.log(JSON.stringify(returnArray));
            myDiv2.innerHTML = JSON.stringify(returnArray);
            return returnArray;
        }
        else {
            if (col == row) {
                col = 1;
                row = row + 1;
            } else {
                col = col + 1;
            }
            triangle(row, col);
        }
    }
    triangle(startRow, startCol);
};
var test = generate(4);
console.log('test is: ' + test); //Why does it returned undefined

My first solution was in the form function generate(numRows){}; but the homework calls for the solution to be in the expression form var generate = function(numRows) {};   The first way returns my expected result.  The second does not.  What fundamental of javascript don't I understand?

A: var generate = function (numRows) {

    //numRows == 0 ? numRows = 1 : numRows = numRows;
    if (numRows == 0) { return [];}

    var startRow = 1;
    var startCol = 1;
    var endRow = parseInt(numRows);
    var rowArray = [];
    var returnArray = [];
    var triVal;

    var triangle = function (row, col) {
        //base case
        if (col == 1 || col == row) {   //If the element is the either first or last element then initialize it with 1
            if (col == 1) {
                rowArray = [];
            }
            triVal = 1;
            rowArray.push(triVal);

            if (col == row) {
                returnArray.push(rowArray);
            }
        }
        else {
            //calc
            triVal = returnArray[row - 2][col - 2] + returnArray[row - 2][col - 1]
            triVal = typeof (triVal) === "undefined" ? 1 : triVal;
            rowArray.push(triVal);
        }
        if (col == row && row == endRow) { //stop the function and return
            console.log(JSON.stringify(returnArray));
            myDiv2.innerHTML = JSON.stringify(returnArray);
            return returnArray;
        }
        else {
            if (col == row) {
                col = 1;
                row = row + 1;
            } else {
                col = col + 1;
            }
            triangle(row, col);
        }
    }
    triangle(startRow, startCol);
    return returnArray;  //duh...the obvious answer!!!
};
var test = generate(1);
console.log('test is: ' + (JSON.stringify(test)));


text:
Q: Creating custom images for PyTorch Dataset I'm trying to create a dataset for training a robot in a 2D world.
The World is going to have labels like "free", "unknown", "obstacle" to identify different components of the map.
This will most likely be with matrices using integers for the labels e.g. free=1, unknown=2 etc.
I want to use this dataset to train a CNN to learn the value of each state in the map.
The current plan is to break this world down into multiple binary matrices to separate the different labels.
So, eventually the neural net will have input like feeding in RGB images (but the different matrix layers here will represent the different labels).
I was looking at the DataLoader class in Pytorch and it allows us to create custom datasets.
However, in my dataset I don't have .jpg files, but separate matrix layers to represent the different labels in the map at each state.
Does anyone know how I can create a dataset like the one I want in PyTorch?


text:
Q: TypeError: object array may be self-referencing python So, I ran into this error:
temp7:
1.68219771725e-06
temp6:
[[array([-60800056.33037408], dtype=object)]]
Exception in thread Thread-4:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/opt/ros/indigo/lib/python2.7/dist-packages/rospy/timer.py", line 223, in run
    self._callback(TimerEvent(last_expected, last_real, current_expected, current_real, last_duration))
  File "/home/husky/catkin_ws/src/huskybot_ekf_v2/src/meas_update.py", line 194, in meas_update_step
    thisJ = temp7 * math.exp(temp6)

It seems like on the very last line thisJ =temp7* math.exp(temp6), that I can't take the exponent of temp6. Does anyone know the cause?
for i in range(0,len(line_features)-1):
    for k in range(0, len(m)):
        mkx = m[k][0]
        mky = m[k][1]
        posex = predicted_pose.x
        posey = predicted_pose.y
        poseth = predicted_pose.theta

        distx = math.pow((mkx - posex), 2);
        disty = math.pow((mky - posey), 2);

        q = distx + disty
        angle = math.atan2(mky-posey, mkx-posex) - poseth

        expected_meas = numpy.array([[math.sqrt(q)],
                                    [angle],
                                    [0]
                                    ])

        H = numpy.array([[-(mkx-posex)/math.sqrt(q), -(mky-posey)/math.sqrt(q) , 0],
                        [(mky-posey)/q, -(mkx-posex)/q, -1],
                        [0 , 0, 0]])
        Qt = 0.5
        innovation_cov = H*predicted_cov*numpy.transpose(H)+Qt
        innovation = ave_meas_dist - expected_meas

        dd = [[2]]
        #dd = array[0]

        #print 0.5*numpy.array(dd)
        temp5 = -1/2 * numpy.dot(numpy.transpose(innovation), numpy.linalg.inv(innovation_cov))
        temp6 = numpy.dot(temp5, innovation)
        print math.sqrt(numpy.linalg.det(2*math.pi*innovation_cov)) * numpy.array(dd)
        temp7 = math.sqrt(numpy.linalg.det(2*math.pi*innovation_cov))
        thisJ =temp7* math.exp(temp6)

A: I tried to reproduce the error. The error I got is:
TypeError: must be real number, not list

If the error is same then it was solved by doing this:
thisJ = temp7 * math.exp(temp6[0][0])

Because temp6 type is list containing list containing array object. Please do correct me if I am wrong.


text:
Q: How to handle setInverval and clearInterval on react native I want to change the value of state [time] every second when a button is pressed. I have the code below, but unfortunately the code doesn't work.
Do you have any suggestion on how can I handle this issue ?
Many thanks !
import React,{useState} from 'react';
import {View,Text,StyleSheet,TouchableOpacity} from 'react-native';
import { AntDesign } from '@expo/vector-icons';

const TimeButton = () =>{

  const [time,setTime] = useState(10)

  let intervalId:any = null;

  return(
    <View style={styles.container}>
      <TouchableOpacity>
         <AntDesign name="caretleft" size={24} color="black" />
      </TouchableOpacity>
      <Text>{time}</Text>
      <TouchableOpacity onPressIn={() => {
        intervalId = setInterval(setTime(time+1), 1000)

        }} onPressOut={() => clearInterval(intervalId)}>
          <AntDesign name="caretright" size={59} color="black" />
      </TouchableOpacity>
    </View>
  )
}

const styles = StyleSheet.create({
  container:{
    flex:1,
    flexDirection:'row',
    alignItems:'center',
    justifyContent:"center"
  }
})

export default TimeButton;

A: Please Check this demo may hope it will help you https://snack.expo.io/eUOetcDe6
    import React,{useState} from 'react';
    import {View,Text,StyleSheet,TouchableOpacity} from 'react-native';
    import { AntDesign } from '@expo/vector-icons';
    let intervalId;
    let Time=10;
    const TimeButton = () =>{
      const [time,setTime] = useState(Time)
      const StartInterval=()=>{
            intervalId=setInterval(() => {
              Time++;
              setTime(Time);
            }, 1000);
      }
      const StopInterval=()=>{
        clearInterval(intervalId);
      }
      return(
        <View style={styles.container}>
            <TouchableOpacity style={{backgroundColor:'black',padding:10}} onPress={StartInterval}>
              <Text style={{color:'white',fontWeight:'bold'}}>Start</Text>
          </TouchableOpacity>
            <Text>{time}</Text>
          <TouchableOpacity style={{backgroundColor:'#6200ee',padding:10}} onPress={StopInterval}>
            <Text style={{color:'white',fontWeight:'bold'}}>Stop</Text>
          </TouchableOpacity>

        </View>
      )
    }

    const styles = StyleSheet.create({
      container:{
        flex:.2,
        flexDirection:'coulam',
        alignItems:'center',
        justifyContent:"space-around"
      }
    })

    export default TimeButton;

A: note that setInterval take a callback(fancy name for passing a function to another function), so using setInterval should be like
   onPressIn={() => {

              intervalId = setInterval(() => setTime(time+1), 1000));

   }};

and while you are doing some async operation I wont use setTime based on the old state that when being used it may had been changed, so to be more determined use the function version of the setTime to update the state of time
  setTime(oldTime => oldTime + 1);


text:
Q: Adding items to ListView causes first item appear again and again When the app starts, I load some objects from the Device's SD Card and add them to a ListView.
Objects = new ArrayList<DataObject>();
Items = new ArrayList<MenuItem>();
Adapter = new MenuItemAdapter(this, Items);

listView.setAdapter(Adapter);

LoadObjects();

When I load objects I deserialize the object, check it's unique ID and if it's already in the list of Objects it should not be added. My method LoadObjects loads tries to load all files in a directory with a given extension. Then if successful, tries to load it into the Items list by using this method:
private boolean LoadObject(DataObject obj)
{
     for (DataObject do : Objects)
     {
          if (do.GetID().equals(obj.GetId())
              return false;
     }

     boolean added = Objects.add(do);

     if (added)
     {
          Items.add(new MenuItem(do.GetID(), do.GetName());
          Adapter.notifyDataSetChanged();
     }

     return added;
}

When this method is run "onCreate" it works fine, it loads in all the objects that can be loaded and is stored on the SD Card. When I try to add one after this method, the first item appears in the list where the new item should be added. I input a new name with a Dialog to create a new DataObject, which will later call LoadObject(new DataObject(name));
I've tried:

*

*Resetting the Items adapter

*Adding a "Add" method on the custom Adapter so that instead of adding to Items, I add through the Adapter by Adapter.Add(new DataObject(name)) which adds to it's own list; I also have a SetList adapter, to recreate the list without success.

*Skip the notifyDataSetChanged

*Cleared the Object list, Items list, Create a new Adapter each time - reloading all Objects, all MenuItem's, recreating the adapter and setting a new List - all with the same result.

*Skip LoadObjects() and just let all newly added items appear, first one is correct - but whatever I add later shows up as the same as #1 from the ListView.
And I have to use FragmentActivity and not ListActivity because I have some Dialogs I need to show.
Simply put, I use the ListView to show specific Files from the SD Card to be able to load them onto another Activity later - but this hinders me from adding any new items without having to restart the Activity just to show new items, which means I need to be able to start out with an empty list and then

A: Probably becouse you use Adapter that have multiple references. Try to rename and don't name variables with uppercase.(see also import list to see what Adapter did you have there)

A: Your attempt #4 has to work. Give next loadObject() a shot:
private boolean LoadObject(DataObject obj)
{
     for (DataObject do : Objects)
     {
          if (do.GetID().equals(obj.GetID())
              return false;
     }

     Objects.add(obj);
     Items.add(new MenuItem(obj.GetID(), obj.GetName());
     Adapter = new MenuItemAdapter(this, Items);
     listView.setAdapter(Adapter);

     return true;
}

A: Seems that the problem occured due to a ListView being inside a RelativeLayout, altough I can't figure out why.
This is how my Layout was first:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <ListView
        android:id="@+id/main_menulist"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </ListView>
</RelativeLayout>

When I instead created a new Layout with a ListView only, the problem no longer occured:
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_menulist"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</ListView>

I've only read about how you should not put a ListView in a ScrollView, but I've used this type of solution (perhaps not by dynamically adding items) before and it's worked.


text:
Q: Migrating data from old container to new partitioned container using change feed 1.Is using azure cosmosdb changefeed right approach, to migrate data from old containers to new partitioned containers?
2.Will azure cosmosdb changefeed have documents which are not at all modified even once till now?
3.If above are true, what are the steps involved in migrating data using azure cosmosdb change feed.

A: You can certainly use Change Feed to achieve all this. Cosmos DB has several options to consume the Change Feed, one of them is using Azure Functions.
If you go with the Functions option, you can quickly do a simple migration mixing the Cosmos DB Trigger (with StartFromBeginning to true) and the Cosmos DB Output binding like so:
[FunctionName("Migration")]
public static async Task Run(
    [CosmosDBTrigger(
        databaseName: "your-source-database",
        collectionName: "your-source-collection",
        ConnectionStringSetting = "Connection-String-Setting-Name-For-Source-Account",
        StartFromBeginning = true,
        CreateLeaseCollectionIfNotExists = true,
    )] IReadOnlyList<Document> source,
    [CosmosDB(
        databaseName: "your-destination-database",
        collectionName: "your-destination-collection",
        ConnectionStringSetting = "Connection-String-Setting-Name-For-Destination-Account" // In case your destination is on a different account, otherwise, it could be the same value as the Trigger
    )] IAsyncCollector<Document> destination,
    ILogger log)
{
    foreach(var doc in source){
          await destination.AddAsync(doc);
    }
}

There are some optimizations that can be applied for Multi master or geo-distributed applications (like using PreferredLocations if your Function is running on a different region).
Keep in mind that the Function acts as a live migration. It will start migrating documents that exist before it was deployed, and then it will continue to migrate new documents while it keeps running if your source collection keeps getting insert/updates.
If what you are needing is a cold migration, you could also use the Data Migration Tool


text:
Q: Passing an object to a COM method I have an api for a third-party app I'm working with. In the api, they say the input parameter of type "VARIANTARG" needs to be passed in.
So I found this online, for using VARIANTARG in C#:
http://www.pinvoke.net/default.aspx/Structures/VARIANTARG.html
Here is my question. There are two properties in this VARIANTARG object which I'm not sure how to set:
public unsafe ushort* bstrVal;
public unsafe ushort** pbstrVal; // Note the double pointer on this one

Here is what I tried:
VARIANTARG v = new VARIANTARG();

//---------------------------------
//??? What goes here??? ???
string myString = "aaa";
v.bstrVal = &myString;
//  public unsafe ushort* bstrVal;
//??? and here:
v.pbstrVal = "???";
//  public unsafe ushort** pbstrVal;
//---------------------------------

MyCOMObj_App.SendTag(v);

Can you tell me how I'm supposed to set these two properties to some string value, and how to pass that to the COM Method?
Just for your reference....here is the VARIANTARG struct definition:
StructLayout(LayoutKind.Explicit, Size=16)]
struct VARIANTARG {
    [FieldOffset(0)]
    public ushort vt;

    [FieldOffset(2)]
    public ushort wReserved1;

    [FieldOffset(4)]
    public ushort wReserved2;

    [FieldOffset(6)]
    public ushort wReserved3;

    [FieldOffset(8)]
    public long llVal;

    [FieldOffset(8)]
    public int lVal;

    [FieldOffset(8)]
    public byte bVal;

    [FieldOffset(8)]
    public short iVal;

    [FieldOffset(8)]
    public float fltVal;

    [FieldOffset(8)]
    public double dblVal;

    [FieldOffset(8)]
    public short boolVal;

    [FieldOffset(8)]
    public int scode;

    //[FieldOffset(8)]
    //public CY cyVal;

    [FieldOffset(8)]
    public double date;

    [FieldOffset(8)]
    public unsafe ushort* bstrVal;

    //[FieldOffset(8)]
    //public unsafe IUnknown* punkVal;

    //[FieldOffset(8)]
    //public unsafe IDispatch* pdispVal;

    //[FieldOffset(8)]
    //public unsafe SAFEARRAY* parray;

    [FieldOffset(8)]
    public unsafe byte* pbVal;

    [FieldOffset(8)]
    public unsafe short* piVal;

    [FieldOffset(8)]
    public unsafe int* plVal;

    [FieldOffset(8)]
    public unsafe long* pllVal;

    [FieldOffset(8)]
    public unsafe float* pfltVal;

    [FieldOffset(8)]
    public unsafe double* pdblVal;

    [FieldOffset(8)]
    public unsafe short* pboolVal;

    [FieldOffset(8)]
    public unsafe int* pscode;

    //[FieldOffset(8)]
    //public unsafe CY* pcyVal;

    [FieldOffset(8)]
    public unsafe double* pdate;

    [FieldOffset(8)]
    public unsafe ushort** pbstrVal;

    //[FieldOffset(8)]
    //public unsafe IUnknown** ppunkVal;

    //[FieldOffset(8)]
    //public unsafe IDispatch** ppdispVal;

    //[FieldOffset(8)]
    //public unsafe SAFEARRAY** pparray;

    [FieldOffset(8)]
    public unsafe VARIANTARG* pvarVal;

    [FieldOffset(8)]
    public unsafe void* byref;

    [FieldOffset(8)]
    public sbyte cVal;

    [FieldOffset(8)]
    public ushort uiVal;

    [FieldOffset(8)]
    public uint ulVal;

    [FieldOffset(8)]
    public ulong ullVal;

    [FieldOffset(8)]
    public int intVal;

    [FieldOffset(8)]
    public uint uintVal;

    //[FieldOffset(8)]
    //public unsafe DECIMAL* pdecVal;

    [FieldOffset(8)]
    public unsafe sbyte* pcVal;

    [FieldOffset(8)]
    public unsafe ushort* puiVal;

    [FieldOffset(8)]
    public unsafe uint* pulVal;

    [FieldOffset(8)]
    public unsafe ulong* pullVal;

    [FieldOffset(8)]
    public unsafe int* pintVal;

    [FieldOffset(8)]
    public unsafe uint* puintVal;

    [FieldOffset(8)]
    public unsafe void* pvRecord;

    //[FieldOffset(12)]
    //public unsafe IRecordInfo* pRecInfo;

    //[FieldOffset(0)]
    //public DECIMAL decVal;
}

A: The structure represents a Variant, which is here implemented as a C++ union. There are a lot of fields that overlap, such as the bool, float, long, etc. You don't need to set all fields, you only need to set one field and the type.
See, for instance: http://msdn.microsoft.com/en-us/library/ms891678.aspx
Which one depends on which function you call; it should tell you what types of input it expects.


text:
Q: Nullish coalescing operator not working or not enabled? I was looking into how to set a variable in javascript and I found out about the Nullish coalescing operator (??) in one of the posts I saw on here.
But now, when I try to use it, I get this error:
Unexpected token, expected ,

for this line:
var oldBookScript = (localStorage.getItem(book.id) ?? newBookScript);

I want the variable oldBookScript to have the value of localStorage.getItem(book.id) but if that is null or empty, I want it to have the value of newBookScript
Do I need to enable it somehow?
Thanks!

A: It is a syntactical construct, which means that in order to run code with it, you need to be in an environment that's up-to-date enough to support it.
For example, the most recent versions of Node, Chrome, and Firefox (among others) will all run fine with your code, but older environments (like IE11) will throw a SyntaxError.
In standard scripts, given that it's syntax, there's no way to "enable" it on a particular environment - either it's supported or it isn't. The usual approach in this situation is to use Babel to transpile the source code (which has all the modern syntax) down to ES6 or ES5 so that obsolete browsers can understand it.
But if you're using React, your code's JSX is already being transpiled. The most up-to-date versions of create-react-app does support the nullish coalescing operator. Upgrade to a more recent version of create-react-app, if possible. If you have a more manual setup, you'll need to make sure your code is being transpiled with Babel and use Babel 7.8.0 or later.
See these docs from Babel on integrating it into React via the @babel/preset-react preset.


text:
Q: Stresses put through joints on a steel climbing wall Being a fan of stackoverflow, I thought I could try this question here, hope its not too off topic.
I'm wanting to build a free standing climbing wall in my garden and dont know where to start working out its strength and so construction.
It will be made from interlocking (using bolts) 50cmx50cmx50cm mild steel cubes stacked 3m tall with a base of 1mx1m. The 4 base cubes will then be bolted to a concrete foundation.
If I then bolt other cubes to the side of the main stack to create an overhang how can I work out the stress put onto the joints between the overhang and the main stack and between the stack and the foundations?
The bolts between the cubes will be 3cm long and 2cm diameter.
I havent decided what fixings to use between the stack and concrete as I believe this is where the problem will lie.
Thanks for any help its much appreciated!

A: Dave, to answer your question, we need to know the wall thickness and weight of each cube.  BUT I can tell you that if you give any reasonable answer (like wall thickness = 1/8 of an inch = about 3.2mm), and choose steel bolts with right-sized steel washers, that it will be pretty hard to fail.  Also, assuming your bolts are 60ksi tensile strength steel (which is not a very high quality bolt), they will hold about 29K pounds each (tensile strength).  That is over 13 metric tons PER BOLT : Certainly not the weak link in your design.
the major sress-strain "weak point" for the interface between the overhanging cubes and the rest of the structure will be shear stress on the bolts converting into tearing forces in the cube wall (think of sticking a nail into aluminum foil, and then pulling it towards you, tearing the foil).  If you used 2cm diameter bolts and 3.2mm thick steel wall in the cubes, each cube would be about 38.4 kg. (84.5 lbs.).  If we assume 60ksi steel for the cubes as well as the bolts, each bolt would support about (0.099 inch^2)(60ksi) = 5950 lbs. = 26500N of shear before irreversibly deforming the hole.  One bolt in each corner gives 4 x 5950 lbs. = about 24000 pounds.  Enough to support well over 100 large men hanging off the wall.
For the other cube-to-cube interfaces, assuming the bolt holes are near the cube edges, the weak point will be tension in the bolt converting into a force which tends to pull the nut or bolt out of the cube, thereby ripping the cube wall (think of a nail inserted into foil, and then pulled through so that the head of the nail rips through the foil).  Good choices for washers will greatly strengthen these weak points.  Assuming you get the right washers (say, 25-30mm thick steel, ID = 2.1cm and OD = 4cm) and attach the cubes very near the corners, then the cube wall would be expected to support (2/3)(3.1416)(0.04m)(0.0032m)((39.36in/1m)^2)(60ksi) = 24920 lbs = 111kN PER BOLT.  (The 2/3 is a fudge factor, since the steel opposite the bolt from the cube corner will not aid as much in resisting pull-through.)  Four bolts --> about 100K lbs or 444kN.  That is roughly the same force as needed to support 500 large men.
The metal to concrete connection does not need to be the weak point of your structure, but it does require a little thought for structural integrity over time (rust prevention).  Chooing the right size, shape and material for the bolts and embedding them deeply enough into rebar-reinforced concrete during the pour will ensure that the mode of failure is NOT having the bolt rip out of the concrete.  Certainly four 2-cm diameter bolts total, one at each of the four corners of the 1m x 1m structure, would do the trick.
The resistance of the structure to leaving the ground would be the weight of the structure, including the concrete.  The resistance to tipping would be about (2)(111kN)(0.9m) = about 200kNm, or ((width of concrete foundation)/2)(weight of concrete + structure), whichever is less.  It is almost guaranteed that the least of these will be governed by the weight of your concrete.  You can greatly increase resistance to tipping (from, say, a hurricane or tornado) by digging post holes at the four corners of your foundation, widen them at the very bottom, and fill the holes with rebar-reinforced concrete as part of the monolithic pour of your foundation.


text:
Q: C: _access_s() can't find the folder This is a structure of a location where is the application executed:

The purpose of an application is to check if there is the folder named Folder. This is a function that is responsible for this:
bool Initialize(const char * c_pszFolder)
{
    if (_access_s(c_pszFolder, 00) != 0)
    {
        printf("Error! Folder doesn't exist.");
        return false;
    }

    printf("Success! Folder does exist.");
    return true;
}

Here is how the function is called:
int main()
{
    Initialize("Folder");
}

According to a documentation the second argument of _access_s() is the number of a case you want to test. In my case I would use: 00 Existence only.. Although, when I run the application the app return false, which is really confusing due to results of debugging:

After trying to get more information by using _get_errno() I've got errno value 2, which stands for: ENOENT  No such file or directory. But the folder exists.

A: Just change your current directory like this
Project | Properties | Select Configuration | Configuration Properties | Debugging | Working directory


text:
Q: How to move files between Document Types in Documents and Media Portlet Liferay I want to know can we move the files in the Documents and Media between Documents Type.
Eg.
I have uploaded a file demo.pdf in Basic Documents. Now I want to move the demo.pdf to Contract Document Type.
How to achieve the above.
Please guide me to achieve this.
Thanks in advance.

A: You can't move files to a different Document Type, but you can edit each file individually to move them to a particular Document Type.
Think of Document-type as field for a file like title, description etc, albeit a special one. Document types are not folders.
Or else you can write code to change the Document-type for more that one file, but that would be quite an effort.


text:
Q: How to write a case statement in the Where clause of Oracle SQL? Please tell me this problem.
TABLE:PPP
+-------+---------+---------+----------+
|No     |  Flag_A | Flag_B  |   Qty    |
+-------+---------+---------+----------+
|100    |    P    |    0    |    10    |
|300    |    B    |    1    |    20    |
|500    |    C    |    0    |    30    |
|100    |    P    |    0    |    40    |
|100    |    P    |    0    |    50    |
|300    |    B    |    1    |    60    |
|500    |    C    |    1    |    70    |
|100    |    P    |    0    |    80    |
|500    |    B    |    2    |    90    |
+-------+---------+---------+----------+

SELECT NO, SUM(QTY) AS QTY
  FROM PPP
 WHERE
   CASE FLAG_B IN (
     WHEN FLAG_A = 'P' THEN '0'
     WHEN FLAG_A = 'C' THEN '1'
     WHEN FLAG_A = 'B' THEN '0' , '1' <- how to write?
    END
   )
GROUP BY NO

I want get this result.
+----+-----+
| No | Qty |
+----+-----+
| 100|  180|
| 300|   80|
| 500|  100|
+----+-----+

What should i write sql?

A: This would be simpler phrased with boolean logic:
where (flag_a = 'P' and flag_b = 0)
   or (flag_a = 'C' and flag_b = 1)
   or (flag_a = 'B' and flag_b in (0, 1))

We can factorize a little:
where (flag_a in ('B', 'P') and flag_b = 0)
   or (flag_a in ('B', 'C') and flag_b = 1)

Or we can use tuple equality:
where (flag_a, flag_b) in (('P', 0), ('C', 1), ('B', 0), ('B', 1))

flag_b looks like a number, so I compared it against literal numbers; if that's really a string, then you can add back the single quotes around the literals.

A: Using DECODE() function containing CASE..WHEN expression in it for the case flag_a='B'  might be an alternative way to get the desired results such as
SELECT no, SUM(qty) AS qty
  FROM ppp
 WHERE DECODE(flag_a,'P',0,'C',1,'B', CASE WHEN flag_b IN (0,1) THEN flag_b END)=flag_b
 GROUP BY no

Demo
P.S: I think there's an issue, which needs to fixed, with the data for No=500


text:
Q: Codeigniter Link to Accordion Item with Pagination Using Codeigniter 3 and Bootstrap 4.
Background, I have a section of my website displaying 'Random Records', clicking on these should take you to the corresponding record. However it only works for my first page of records.
I have setup pagination in CI and it all works as expected, I can navigate through my pages and view 50 results on each page.
The 50 results on each page are displayed in a (click to expand) accordion list. The href of the accordion has the following format;
On page 1;

*

*Item 1 results/#item1

*Item 2 results/#item2

*Item 3 results/#item3

*etc.

On page 2;

*

*Item 51 results/50#item51

*Item 52 results/50#item52

*Item 53 results/50#item53

*etc.

Any where on my site I'm able to link to a (page 1) accordion item using the following URL;
example.com/#item2
However this only works for the records on page 1.
When I attempt to link to any record above 50 (page 2, 3, etc.) using this URL, I'm taken to page 1 - nothing happens.
example.com/#item52
Presumably this is because I'm missing the pagination segment of the URL /50.
For example this works;

*

*example.com/50#item52

*example.com/150#item154
The trouble is I don't know what page a record will be on (50/100/150/etc), so creating a direct link is very difficult.
I know that if I wasn't using an accordion this would be much easier but... I am, and can't change at this stage.
Is there any way around this?
Any advice is appreciated.


text:
Q: MVC .net for restful api I'm more acquainted with Java technologies and i'm running a project where i need to use the .Net framework for the backend. The goal of the project is to to expose a public api handling any request type PUT, POST, GET, DELETE. The payload will only be in JSON. The backend will be interacting with a database and third party libraries also written in .Net.
What are the technologies in .Net that are best suited for this. Is it Asp.Net with C#. Are there other framework people would recommend (Spring.Net for instance. Also There seems to be different version of .Net 3 & 4. Are all the versions equally valid for this type of project.
Finally what are the tools people use to develop, test unit and do integration test in the .Net environment.
Thank you
ken

A: Have a look at WebAPI for building RESTful services, along with ASP.NET MVC 4 and C#. I would recommend Visual Studio 2012 and .NET Framework 4.5 if you are able to use these.
There are a variety of test frameworks in the .NET space (including MSTest, NUnit, and xUnit) and isolation frameworks such as Moq.

A: ASP.NET Web API allows you to create RESTful services and work with JSON data. Normal ASP.NET MVC also allows you to send JSON between your client and server, but Web API is the future. You could use normal ASP.NET (web forms) or ASP.NET MVC, MVC allows you to have a better organisation of your presentation logic and is just awesome. When you use Web API along with ASP.NET MVC, web API will be in charge of dealing with your data, and your asp.net MVC will be in charge of serving up your views. There are tonnes of material out there on ASP.NET MVC and Web API, so I won't bother posting any here. Finally, if you want your application to be more interactive and are focusing on good UX, then you could integrate as much AJAX as possible into your apps and even better make use of javascript frameworks such as knockout to create a highly responsive UI. Here is a good write up on using Web API with Knockout.js. Also a must read book for aspiring asp.net MVC developers. The book covers unit testing with Visual Studio and Moq and Dependency Injection with Ninject briefly but well, you could unit test your javascript with Qunit, though it has nothing to do with .NET specifically.


text:
Q: Laptop suddenly not seeing wifi and bluetooth While on the laptop, everything was normal, and all of the sudden the wifi options from the bottom right disappeared.
I've reinstalled windows and wifi still doesn't show up, when usually it would just detect the wirless network and connect.
Is it Possible to be a hardware problem ? Are the bluetooth and wifi receivers on the same board, and maybe something  happened with that ?

A: Wireless and Bluetooth are often on the same card or card device. This makes it easier for Airplane Mode to turn both off.

*

*Does your laptop have a Wireless button or Function key? and did that get disabled / turned off. Check that.

*Windows 10 Network Settings:  Is Airplane Mode ON?  Turn Airplane Mode OFF.

*Look in Device Manager and make sure the Bluetooth and Wireless drivers are both shown as installed and active (no red or orange marks).
Orange marks indicate disabling by hardware issue or some other disabling.
These are the things that affect Wireless.