Q: Threejs: Disable frustum culling for some objects In order to solve the problem of z-fighting, I limited the near and far of camera to a small range.But when I want to add a larger object,it was culled by view frustum.
I tried object3d.frustumCulled property,not working as expected,the reason is as follows:
https://github.com/mrdoob/three.js/issues/12170
So,is there a way to ensure that some specific objects are not frustum culled without changing the camera near and far? THX.

A: Culling doesn't mean that an object is drawn or not. It can be either drawn or not drawn depending on where it is. It is an optimization that tries to say something like this:

Hey, i have a really cheap check (plane/sphere intersection) that i can do and tell you if you need to attempt to draw this at all.

So you do a cheap check, and if the object is guaranteed to be entirely out of the frustum, you never issue the draw call. If it intersects, you have to issue a draw call, but you may still see nothing if none of the triangles are actually in the frustum.
If you download something like specter.js and inspect your draw calls, you will infact see that with frustumCulled = false you get a draw call for every object in your scene. Your screen may be empty.


Q: How to detect the screen DPI using VB.NET? I need the screen DPI so i can adjust my program accordingly.
So my question is How to detect the screen DPI using VB.NET?

A: try this:
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim g As Graphics = Me.CreateGraphics()
    MessageBox.Show("ScreenWidth:" & Screen.PrimaryScreen.Bounds.Width & " ScreenHeight:" & Screen.PrimaryScreen.Bounds.Height & vbCrLf & " DpiX:" & g.DpiX & " DpiY:" & g.DpiY)
End Sub


Q: How to continue at particular step - spookyjs? I am using spookyjs to test my application.
Question
Is there anyway to enforce the spookyJs to start at particular step?
How to force start at particular step spookyJs?
Example
SpookyJs will run step by step, Suppose some connection error happened at particular step and server got stopped, Now how can I continue the test from particular step instead of running from beginning.
Any suggestion will be grateful


Q: Helper not available in the view I am migrating from 1.3 to 2.0.6 and have the following problem:

Notice (8): Undefined variable: session [APP/View/Users/login.ctp, line 2]
Fatal error: Call to a member function flash() on a non-object in login.ctp on line 2

Why is there a problem accessing the session helper?

A: That's not how to use helpers

Notice (8): Undefined variable: session [APP/View/Users/login.ctp, line 2]
Fatal error: Call to a member function flash() on a non-object in login.ctp

Whilst it's not in the question your login.ctp template looks something like this:
<?php
echo $session>flash(); # line 2

That's not how helpers are expected to be used in CakePHP 2.x:

you can use [the helper] in your views by accessing an object named after the
  helper:
<!-- make a link using the new helper -->
<?php echo $this->Link->makeEdit('Change this Recipe', '/recipes/edit/5'); ?>

The code you're looking for is:
# echo $session->flash(); # wrong
echo $this->Session->flash(); # right

Note also that Session needs to be in the controller $helpers array.
In 1.2 and earlier versions of CakePHP helpers were expected to be variables, this changed but was still supported in 1.3. If your 1.3 CakePHP application has been using helpers in this way, it has been relying on backwards-compatibility with earlier versions. In 2.0 helpers are not variables, and only possible to access as a view class property. Be sure to read the migration guides - for more information on what has changed.


Q: How to show count for messages which are hidden below the scroll using jQuery? I need to show counter for loaded but scroll down messages in conversation screen. Suppose there are 15 messages in total but showing only 6 on browser right now. It means 9 messages are hidden in below so counter should display 9. But when I scroll up or down counter should change the value accordingly visible and hidden messages.
        function isScrolledIntoView(elem) {
         var $elem = $(elem);
        var $window = $(window);

        var docViewTop = $window.scrollTop();
            var docViewBottom = docViewTop + $window.height();

            var elemTop = $elem.offset().top;
            var elemBottom = elemTop + $elem.height();

        return ((elemBottom <= docViewBottom) && (elemTop >=        docViewTop));
        }
            var message = $('#messages');
            $(window).scroll(function() {
        if (isScrolledIntoView('#hiddenElem')) {
      message.text("Visible");
        } else {
      message.text("Invisible");
    }
  });

Check code in this JS Fiddle. Also JavaScript code written for show hidden or visible element.

A: You have to compare the position of each messages with the scrolled value.
So you need to loop throught them.
Here is something working:
var messages=$(".msg");

$(window).scroll(function(){
  var counter=0;
  for(i=0;i<messages.length;i++){
    if( messages.eq(i).offset().top < $(window).scrollTop() ){
      counter++;
    }
  }
  // Display result.
  $("#messages").html(counter);
});

Updated Fiddle


Q: addTextChangedListener Null Pointer Exception Been looking at other questions but none of them solved my problem.
I have an editText and I need to implement an addTextChangedListener to this field so i can update values of other text views in real time.
public class MainActivity extends ActionBarActivity {

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

    EditText billText = (EditText)findViewById(R.id.billValue);
    billText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3) {
            // TODO Auto-generated method stub

        }

    });

Anything wrong in my code that I may be missing?

A: As far as I can guess, following line causing NullPointerException because your editText is null
billText.addTextChangedListener(new TextWatcher() {

May be the EditText you are trying to access here isn't in the activity_main.xml layout. So at first, make sure that the EditText with id billValue exists in the activity_main.xml.

A: You are creating a new instance of an interface not a class. Instead, you may write your activity class as
public class MainActivity extends ActionBarActivity implements TextWatcher

and add some methods to your class:
    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterTextChanged(Editable arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1,
            int arg2, int arg3) {
        // TODO Auto-generated method stub

    }

Try it, you will not have an exception I guess.

A: Do like the following -
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    billText.addTextChangedListener(new TextWatcher()
    {
      public void onTextChanged(CharSequence s,
      int start, int before, int count)
      {
        EditText billText = (EditText) view.findViewById(R.id.billText);
        billText_val = billText.getText().toString().toLowerCase();
        //do anything with this value

      }

    public void beforeTextChanged(CharSequence s, int start, int count, int after)
    {

    }

    public void afterTextChanged(Editable s)
    {

    }
 });
}

A: You are doing that fine There Might be an Issue with the Reference of your EditText
Anyhow here is my sample code attached for this purpose.
et_email = (EditText) findViewById(R.id.et_regstepone_email);

et_email.addTextChangedListener(this);

    @Override
public void afterTextChanged(Editable s) {
    // TODO Auto-generated method stub

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
    // TODO Auto-generated method stub

}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    // TODO Auto-generated method stub

    if(count==0&&et_email.length()==0){
        et_email.setCompoundDrawables(null, null, null, null);

    }else if(count>0){

    }

}

A: I had exactly the same problem.
Check the ID of your EditText in other layout xml files of the same activity. In my case it was the xml in layout-v21. I was overriding the ID of the EditText element in it.


Q: How to compare two column values incrementally and copy entire row if the cells in those columns meet a condition I am trying to compare two columns in one workbook and based on a certain condition copy the row where that condition is met to another workbook.
This is for a "database" I am working on. I have a Master sheet and then several versions of sub-masters that are catered specifically to certain individuals.
I have tried to some success by creating two different With statements and using a delete function on the sub-sheet but it is clunky and I'm not a fan of it. Please see the example code below.
Public Sub Workbook_Open()

Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim copyFrom As Range
Dim lRow As Long
Dim strSearch As String
Dim vrtSelectedItem As Variant

Set wb1 = Application.Workbooks.Open("C:\Users\myfolder\Desktop\Excel Master Test\ROLE BASED TRACKER DRAFT.xlsx")
Set ws1 = wb1.Worksheets("Master")

Set wb2 = ThisWorkbook
Set ws2 = wb2.Worksheets("Sheet1")

'~~> Specifies which resources info. you are retrieving
strSearch = "117"
ws2.Cells.Clear

'~~> Copying the header information and formatting.
ws1.Range("1:1").Copy
ws2.Range("1:1").PasteSpecial

With ws1

    '~~> Remove any filters
    .AutoFilterMode = False

    lRow = .Range("A" & .Rows.Count).End(xlUp).Row

    With .Range("L1:L" & lRow)
        .AutoFilter Field:=1, Criteria1:=strSearch
         Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
    End With

    .AutoFilterMode = False

End With

'~~> Destination File

With ws2
    If Application.WorksheetFunction.CountA(.Rows) <> 0 Then
        lRow = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Row + 1
    Else
        lRow = .Range("A" & Rows.Count).End(xlUp).Row
    End If
    copyFrom.Copy .Rows(lRow)
End With

With ws2
        '~~> Remove any filters
    .AutoFilterMode = False

    lRow = .Range("A" & .Rows.Count).End(xlUp).Row

    With .Range("AD1:AD" & lRow)
        .AutoFilter Field:=1, Criteria1:=strSearch
        .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    End With

    .AutoFilterMode = False

End With

With ws1

    '~~> Remove any filters
    .AutoFilterMode = False

    lRow = .Range("A" & .Rows.Count).End(xlUp).Row

    With .Range("AD1:AD" & lRow)
        .AutoFilter Field:=1, Criteria1:=strSearch
         Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
    End With

    .AutoFilterMode = False

End With

'~~> Destination File

With ws2
    If Application.WorksheetFunction.CountA(.Rows) <> 0 Then
        lRow = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Row + 1
    Else
        lRow = .Range("A" & Rows.Count).End(xlUp).Row
    End If
    copyFrom.Copy .Rows(lRow)
End With

With ws2.Sort
    .SetRange Range("A2:A12000")
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

wb1.Save
wb1.Close
wb2.Save

End Sub

This is the code that I am trying to get work. I keep getting a Type Mismatch error on my cell comparison lines. '' If ws1.Range("AD1:AD" & lRow) <> ws1.Range("L1:L" & lRow) Then ''
Public Sub Workbook_Open()

Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim copyFrom As Range
Dim lRow As Long
Dim strSearch As String
Dim vrtSelectedItem As Variant

Set wb1 = Application.Workbooks.Open("C:\Users\myfolder\Desktop\Excel Master Test\ROLE BASED TRACKER DRAFT.xlsx")
Set ws1 = wb1.Worksheets("Master")

Set wb2 = ThisWorkbook
Set ws2 = wb2.Worksheets("Sheet1")

'~~> Specifies which resources info. you are retrieving
strSearch = "117"
ws2.Cells.Clear

'~~> Copying the header information and formatting.
ws1.Range("1:1").Copy
ws2.Range("1:1").PasteSpecial

With ws1

    '~~> Remove any filters
    .AutoFilterMode = False

    lRow = .Range("A" & .Rows.Count).End(xlUp).Row

    If ws1.Range("AD1:AD" & lRow) <> ws1.Range("L1:L" & lRow) Then

        With .Range("AD1:AD" & lRow)
            .AutoFilter Field:=1, Criteria1:=strSearch
            Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
        End With

        .AutoFilterMode = False

    End If

End With

'~~> Destination File

With ws2
    If Application.WorksheetFunction.CountA(.Rows) <> 0 Then
        lRow = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Row + 1
    Else
        lRow = .Range("A" & Rows.Count).End(xlUp).Row
    End If
    copyFrom.Copy .Rows(lRow)
End With

With ws1

    '~~> Remove any filters
    .AutoFilterMode = False

    lRow = .Range("A" & .Rows.Count).End(xlUp).Row

    If ws1.Range("AD1:AD" & lRow) = ws1.Range("L1:L" & lRow) Then

        With .Range("L1:L" & lRow)
            .AutoFilter Field:=1, Criteria1:=strSearch
            Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
        End With

        .AutoFilterMode = False

    End If

End With

'~~> Destination File

With ws2
    If Application.WorksheetFunction.CountA(.Rows) <> 0 Then
        lRow = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Row + 1
    Else
        lRow = .Range("A" & Rows.Count).End(xlUp).Row
    End If
    copyFrom.Copy .Rows(lRow)
End With

With ws2.Sort
    .SetRange Range("A2:A12000")
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

wb1.Save
wb1.Close
' wb2.Save

End Sub

A: I just wanted to thank everyone who helped. I am going to just stick with my initial solution of filter, copy, paste, filter, delete, filter, copy, paste, sort.
See my first code block for what I am talking about. Cheers.


Q: would a css grid framework be a good fit for creating application like layouts? I have a webapp that I am making and it has some particular layout needs that are closer to an application than a website.
The layout has:

*

*a left sidebar that is fixed to the left side of the browser window and has a static width until it stacks, this sidebar will have tabs in it

*a content area that will expand to a certain max-width and then stop

*a right side bar that is fixed the the right edge of the content

I've been struggling to really determine if using a grid system, like bootstrap, would be an appropriate fit for something like this. Having some rows/columns and a collapsible grid in the content area seems like it would make sense, but in the sidebars it seems like its best to not use a grid system at all. I don't particularly like the idea doing some layout in the html with bootstrap3 and some in css.
Basically my app has the same layout as http://qz.com/ and I want similar responsive design breaks, and with that I would like to know if there is one or more css frameworks that support that type of layout with little overriding.

A: if you have some experience with resposive design and media queries, i would code it myself to avoid the thousands of lines of unnecessary code that comes with frameworks/libraries. bootstrap is great, but it also requires a bit of effort to master, and it would be a bit overkill for this one layout (if i understand you correctly).
if you just need this one layout, i would really recommend you do code it from scratch (personally i'd use something like jQuery and LESS). i hope i understood your question correctly, and sorry if this was not very hands-on.
to sum it up: in my opinion you're probably better off coding it yourself, but bootstrap and other frameworks will provide valuable insight and inspiration for how to do it.


Q: Spring Transaction not working I'm having a problem with transactions, when execution reaches

taskExecutor.execute();

I get an Exception:

Caused by: org.springframework.transaction.IllegalTransactionStateException: No existing transaction found for transaction marked with propagation 'mandatory'

I know this error is self-explanatory, but I can't get it to work properly.
This is how I get the controller and make the call:
ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/applicationContext.xml");
BeanFactory beanFactory = context;
FacadeControler f = beanFactory.getBean("facadeController");
f.method(reservation);

This is my FacadeController:
package xxx;

import ...

@Service
public class FacadeControllerImpl implements FacadeController {

    static Logger logger = Logger.getLogger(FacadeControllerImpl.class);

    @Qualifier("executor")
    @Autowired
    private TaskExecutor taskExecutor;

    @Transactional(propagation=Propagation.REQUIRED)
    public Reservation method(Reservation reservationFromEndpoint){

    ...
    taskExecutor.execute();
    ...

    }

Here is the Executor:
@Component("executor")
public class QueueTaskExecutor implements TaskExecutor {

  final static Logger logger = LoggerFactory.getLogger(QueueTaskExecutor.class);

  @Autowired
  protected QueuedTaskHolderDao queuedTaskDao;

  @Autowired
  protected Serializer serializer;

  @Override
  @Transactional(propagation=Propagation.MANDATORY)
  public void execute(Runnable task) {

      logger.debug("Trying to enqueue: {}", task);

      AbstractBaseTask abt;
      try {
          abt = AbstractBaseTask.class.cast(task);
      } catch (ClassCastException e) {
          logger.error("Only runnables that extends AbstractBaseTask are accepted.");
          throw new IllegalArgumentException("Invalid task: " + task);
      }

      // Serialize the task
      QueuedTaskHolder newTask = new QueuedTaskHolder();
      byte[] serializedTask = this.serializer.serializeObject(abt);
      newTask.setTriggerStamp(abt.getTriggerStamp());

      logger.debug("New serialized task takes {} bytes", serializedTask.length);

      newTask.setSerializedTask(serializedTask);

      // Store it in the db
      this.queuedTaskDao.persist(newTask);

      // POST: Task has been enqueued
  }

}
Here is my applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:task="http://www.springframework.org/schema/task"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/task
 http://www.springframework.org/schema/task/spring-task-3.0.xsd
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<!-- Where to look for Spring components -->
<context:annotation-config />
<context:component-scan base-package="com.xxx"/>

<!-- @Configurable with AspectJ -->
<context:spring-configured/>

<!-- A task scheduler that will call @Scheduled methods -->
<!--     <task:scheduler id="myScheduler" pool-size="10"/> -->
<!--     <task:annotation-driven scheduler="myScheduler"/> -->

<!-- DataSource -->
<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="myDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/bbdd"/>
    <property name="username" value="user"/>
    <property name="password" value="pass"/>
</bean>

<!-- JPA Entity Manager -->
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="myEntityManagerFactory">
    <property name="dataSource" ref="myDataSource" />
    <property name="jpaVendorAdapter">
             <bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter"></bean>
    </property>
    <property name="persistenceUnitName" value="comm_layer" />
    <property name="jpaPropertyMap">
        <map>
            <entry key="eclipselink.weaving" value="false"/>

            <entry key="eclipselink.ddl-generation" value="create-or-extend-tables"/>
            <entry key="eclipselink.logging.level" value="INFO"/>
        </map>
    </property>
</bean>

 <!-- Transaction management -->
<tx:annotation-driven mode="aspectj" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
    <property name="jpaDialect">
        <bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
    </property>
    <property name="entityManagerFactory" ref="myEntityManagerFactory"/>
</bean>

<bean id="facadeController" class="xxx.FacadeControllerImpl">


Q: Is there a way to ask a context in EF how big its tracking set is? I'm running into what appears to be a fairly typical problem in EF.  As I continue accessing my context, the number of items it tracks and enumerates over in detect changes increases.  Eventually, everything slows to a crawl.  Here's what I'm currently doing to address the problem:
public class ContextGenerator
{
    private IContext _context;
    private string _connString;
    private int accessCount;

    public ContextGenerator(string conn)
    {
        _connString = conn;
    }

    public IContext Instance
    {
        get
        {
            if (accessCount > 100)
            {
                Dispose();
            }
            if (_context == null)
            {
                var conn = EntityConfigurationContext.EntityConnection(_connString);
                _context = new MyDbContext(conn);
                accessCount = 0;
            }
            ++accessCount;

            return _context;
        }
    }

    public void Dispose()
    {
        _context.Dispose();
        _context = null;
    }
}

This mostly works to prevent my context from getting too unwieldy, as it disposes and creates a new one every 100 accesses, but it seems very clunky and messy.  Furthermore, 100 was chosen arbitrarily and there's no guarantee that somebody won't insert a million things with only one access.  Is there a way to instead ask the context itself if it's gotten "too big"?
Or if anyone has a better idea for tackling this problem, I'm open to suggestions.

A: Each context should be a single Unit of Work, therefore I would highly recommend you have 1 context per operation (unless you relly have to).
For more info on what EF is currently tracking checkout Context.ChangeTracker


Q: XML xquery retrieve the descendent nodes value from a xml string I'm reading a XML document using XQuery in SQL Server. This is my XML:
  declare @xml as xml='
  <contactdata>
    <contacts>
      <groupkey>24</groupkey>
      <groupname>Test Group One</groupname>
      <contact>
        <contactkey>100</contactkey>
        <contactname>Test Contact One</contactname>
      </contact>
      <contact>
        <contactkey>111</contactkey>
        <contactname>Test Contact Two</contactname>
      </contact>
    </contacts>
    <contacts>
      <groupkey>26</groupkey>
      <groupname>Test Group Two</groupname>
       <contact>
        <contactkey>101</contactkey>
        <contactname>Test Contact Six</contactname>
      </contact>
    </contacts>
  </contactdata>';

In order to retrieve the each contact details under every group, I'm using this XQuery syntax
select
    c.value('(groupkey)[1]','int'),
    c.value('(groupname)[1]','nvarchar(max)'),
    c.value('(contact/contactkey)[1]','int'),
    c.value('(contact/contactname)[1]','nvarchar(max)')
from
@xml.nodes('contactdata/contacts') as Contacts(c)

But this will return only the first contact under each group.

But I need this output

Please help.

A: Just change your query to this:
select
    c.value('(../groupkey)[1]','int'),
    c.value('(../groupname)[1]','nvarchar(max)'),
    c.value('(contactkey)[1]','int'),
    c.value('(contactname)[1]','nvarchar(max)')
from
    @xml.nodes('contactdata/contacts/contact') as Contacts(c)

You need to get a list of all <contact> elements - and then extract that necessary data from those XML fragments. To get the groupkey and groupname, you can use the ../ to navigate "up the tree" one level to the parent node.


Q: GCM Notification not register for token and not receiving notifications This is my appdelegate where is my notification implementations goes on. Sometimes I register with token and token is received. But not receiving notifications. But some time there is no registration with token at all. This is my code below.

import UIKit
import UserNotifications
import RxSwift
//import Firebase
//import Messages

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    let gcmMessageIDKey = "gcm.message.shopflow.key"
    var window: UIWindow?
    let userdefaults = Foundation.UserDefaults.standard

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
//        FirebaseApp.configure()

        // [START set_messaging_delegate]
//        Messaging.messaging().delegate = self
        // [END set_messaging_delegate]
        UNUserNotificationCenter.current().delegate = self
        registerForPushNotifications()
        checkReachability()
        checkRegisterdUser()

        // Check whether the app has opened from a notification or a normal launch
        //crashing code
//        let remoteNotif = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary
//        if remoteNotif != nil {
//            let notifName = remoteNotif?["aps"] as! String
//            print("Notification: \(notifName )")
//        }else{
//            print("Not remote")
//        }

        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        checkReachability()
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        checkReachability()
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        checkReachability()
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    // check connectivity
    func checkReachability(){
        if ReachabilityHelper.shared.checkNetworkReachability(){

        }else{
            showNetworkAlert()
        }
    }

    // show network alert
    func showNetworkAlert(){

        let alertController = UIAlertController(title: "Connection Error", message:"An active internet connection is needed to use this app.Please make sure you are connected and try again.", preferredStyle: .alert)

        let okAction = UIAlertAction(title:  NSLocalizedString("Retry", comment: ""), style: UIAlertActionStyle.default) {
            UIAlertAction in

            if ReachabilityHelper.shared.checkNetworkReachability(){
                //print("Connected")

            }else{
               // print("Not connected")
                self.showNetworkAlert()
            }

        }

        alertController.addAction(okAction)
        window!.rootViewController?.present(alertController, animated: true, completion: nil)
    }

    func checkRegisterdUser(){

       // let storyBoard = UIStoryboard(name: storyboardIdentifier., bundle: <#T##Bundle?#>)

        if UserDefaults.standard.bool(forKey: Key.loginStatus){
            let vc = UIStoryboard(name: storyboardIdentifier.home.rawValue, bundle: nil).instantiateViewController(withIdentifier: viewControllerIdentifiers.tabBar.rawValue) as! UITabBarController
            Constants.AppObjects.appDelegate.window?.rootViewController = vc

           // self.present(vc, animated: true, completion: nil)
        }
    }

    func registerForPushNotifications() {

//        if #available(iOS 10.0, *) {
//          // For iOS 10 display notification (sent via APNS)
//          UNUserNotificationCenter.current().delegate = self
//
//          let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
//          UNUserNotificationCenter.current().requestAuthorization(
//            options: authOptions,
//            completionHandler: {_, _ in })
//        } else {
//          let settings: UIUserNotificationSettings =
//          UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
//            UIApplication.shared.registerUserNotificationSettings(settings)
//        }
//
//        UIApplication.shared.registerForRemoteNotifications()

                    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
                        (granted, error) in
                        print("Permission granted: \(granted)")

                        guard granted else { return }
                        self.getNotificationSettings()
                    }

    }

    func getNotificationSettings() {
        UNUserNotificationCenter.current().getNotificationSettings { (settings) in
            print("Notification settings: \(settings)")
            guard settings.authorizationStatus == .authorized else { return }
            DispatchQueue.main.async(execute: {
                UIApplication.shared.registerForRemoteNotifications()
            })
        }
    }

//    private func application(_ application: UIApplication, didRegister notificationSettings: UNNotificationSettings) {
////        if notificationSettings. != UIUserNotificationType() {
//        application.registerForRemoteNotifications()
////      }
//    }

    // This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
    // If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
    // the FCM registration token.
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
        userdefaults.set("NA", forKey: "DEVICE_TOKEN")
        userdefaults.synchronize()
      print("Registration failed!")
    }

    func application(_ application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // With swizzling disabled you must set the APNs token here.
        // Messaging.messaging().apnsToken = deviceToken

        let tokenParts = deviceToken.map { data -> String in
            return String(format: "%02.2hhx", data)
        }

        let token = tokenParts.joined()
        print("Device Token: \(token)")
        userdefaults.set(token, forKey:"DEVICE_TOKEN")
        userdefaults.synchronize()

        _ = HomeViewModel().deviceToken().subscribe(onNext:{ message in

            if message == response.success.rawValue{
                //print("Signup done")
                print("new Device Token device registation")
            }else if message != ""{
               print("shopErrors:fail Device Token device registation")
                //print(alertMessage)
            }

        }).disposed(by: DisposeBag())

    }

//    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//
//        if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as! [NSObject : AnyObject]? {
//
//        }
//    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
      // If you are receiving a notification message while your app is in the background,
      // this callback will not be fired till the user taps on the notification launching the application.
      // TODO: Handle data of notification

      // With swizzling disabled you must let Messaging know about the message, for Analytics
      // Messaging.messaging().appDidReceiveMessage(userInfo)

      // Print message ID.
      if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
      }

      // Print full message.
      print(userInfo)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
      // If you are receiving a notification message while your app is in the background,
      // this callback will not be fired till the user taps on the notification launching the application.
      // TODO: Handle data of notification

      // With swizzling disabled you must let Messaging know about the message, for Analytics
      // Messaging.messaging().appDidReceiveMessage(userInfo)

      // Print message ID.
      if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
      }

      // Print full message.
      print(userInfo)

      completionHandler(UIBackgroundFetchResult.newData)
    }

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
      // Let FCM know about the message for analytics etc.
//        Messaging.messaging().appDidReceiveMessage(userInfo)
      // handle your message
    }

}

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

  // Receive displayed notifications for iOS 10 devices.
  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification,
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)

    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
      print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([.alert, .sound, .badge])
  }

  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse,
                              withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
      print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    completionHandler()
  }

  func registerForPushNitfication(){
    registerForPushNotifications()
  }
}

//extension AppDelegate: MessagingDelegate{
//    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
//        let dataDic: [String: String] = ["token": fcmToken]
//        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDic)
//
//        userdefaults.set(dataDic["token"], forKey:"DEVICE_TOKEN")
//        userdefaults.synchronize()
//
//        _ = HomeViewModel().deviceToken().subscribe(onNext:{ message in
//
//            if message == response.success.rawValue{
//                //print("Signup done")
//                print("shopErrors:new Device Token device registation")
//            }else if message != ""{
//               print("shopErrors:fail Device Token device registation")
//                //print(alertMessage)
//            }
//
//        }).disposed(by: DisposeBag())
//    }
//
//}

I register for APNs and enable push notifications and also background notification fetch capability. But I couldn't resolve this. Anyone can find an answer?


Q: Unable to configure Swagger in Spring project, getting File not found exception I am trying to configure swagger for my spring application. Below is the configuration. However, getting an error
[springfox/documentation/spring/web/SpringfoxWebMvcConfiguration.class] cannot be opened because it does not exist
Spring version - 4.0.4
Springfox version - 2.9.2
It's NOT a maven project, I have all the required jar files added to the classpath.
Spring-context.xml
<bean id="Swagger" class="skt.test.SwaggerConfig" />

<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>

    <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>

Swagger config class
package skt.test;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
          .select()
          .apis(RequestHandlerSelectors.any())
          .paths(PathSelectors.any())
          .build();

    }

}

Jar files included
https://i.imgur.com/sYaYnrY.png
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: skt.test.SwaggerConfig; nested exception is java.io.FileNotFoundException: class path resource [springfox/documentation/spring/web/SpringfoxWebMvcConfiguration.class] cannot be opened because it does not exist
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:160)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:299)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4682)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5143)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:932)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:633)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:344)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:475)
Caused by: java.io.FileNotFoundException: class path resource [springfox/documentation/spring/web/SpringfoxWebMvcConfiguration.class] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
    at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:50)
    at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:82)
    at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:102)
    at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:77)
    at org.springframework.context.annotation.ConfigurationClassParser.asSourceClass(ConfigurationClassParser.java:551)
    at org.springframework.context.annotation.ConfigurationClassParser$SourceClass.getRelated(ConfigurationClassParser.java:760)
    at org.springframework.context.annotation.ConfigurationClassParser$SourceClass.getAnnotationAttributes(ConfigurationClassParser.java:741)
    at org.springframework.context.annotation.ConfigurationClassParser.collectImports(ConfigurationClassParser.java:366)
    at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:340)
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:249)
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:206)
    at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:426)
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:249)
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:206)
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:174)
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:156)
    ... 39 more

A: You need below library ,
     <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.5.0</version>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.5.0</version>
    </dependency>

If you are not using pom just download it from
https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui/2.5.0
https://mvnrepository.com/artifact/io.springfox/springfox-swagger2/2.5.0
To get more insight you can follow here
https://github.com/mayurbavisiya/Spring4Swagger
In your spring file you need to write
<mvc:resources mapping="/swagger-ui.html" location="classpath:/META-INF/resources/swagger-ui.html"/>

Hope this will help you out.


Q: ResourceReferenceKeyNotFoundException on NotifyIcon I'm using WPF NotifyIcon, and actually I'm trying to learn how to display a simple NotifyIcon in the system tray. Actually In the MainWindow I put this code:
 private TaskbarIcon tb;

 public MainWindow()
 {
      InitializeComponent();
 }

 private void MetroWindow_StateChanged(object sender, EventArgs e)
 {
      if (WindowState == WindowState.Minimized)
      {
          tb = (TaskbarIcon)FindResource("TestNotifyIcon");
      }
 }

essentially when the main window is minimized the tb should show the Icon declared in a Dictionary like this:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:PrimoCalendarExport.Utils.Resources.UIDictionary"
                xmlns:tb="http://www.hardcodet.net/taskbar">

<tb:TaskbarIcon x:Key="TestNotifyIcon"
              IconSource="/Utils/Images/Test.ico"
              ToolTipText="hello world" />

</ResourceDictionary>

this dictionary of resource is located inside a folder, in particular:
Project name
   \Utils
       \Resources
          \Dictionary
             \InlineToolTip.xaml

Now the problem's that when I minimize the main window I get this error:

ResourceReferenceKeyNotFoundException

so seems that the TestNotifyIcon can't be located in the project. I don't know what am I doing wrong, I followed all the steps of the tutorial, someone maybe know my mistake? Thanks.

A: It appears you are looking in the wrong place for the resource. You are looking in the XAML of the metro window however you should be looking in the main window XAML specify to the program where to look using something like this: (I am not currently on visual studio)
 private void MetroWindow_StateChanged(object sender, EventArgs e)
 {
      if (WindowState == WindowState.Minimized)
      {
          tb = (TaskbarIcon)this.FindResource("TestNotifyIcon");
      }
 }

or
 private void MetroWindow_StateChanged(object sender, EventArgs e)
 {
      if (WindowState == WindowState.Minimized)
      {
          tb = (TaskbarIcon)MainWindow.FindResource("TestNotifyIcon");
      }
 }


Q: How to post values of each item in model from view to controller as a List or Array? example of view priority list of orders
i have a orders model, i need the user to arrange orders in order of priority by numbers.
for each order a different number of priority and post to the controller the id of the order and the priority number that he selected for the order.
post it to the controller as a list/array of pairs (id, position).
and also how to receive in the actionResult a list/array of value pairs.
this is my PackerController:
    public ActionResult SetByCity(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        var supplier = db.Suppliers.Where(s => s.Id == id).FirstOrDefault();

        var mySupplierOrders = db.Orders.Where(o => o.SupplierId == supplier.Id && o.SupplierApproval == 1).Include(o => o.Clients).Include(o => o.Suppliers);
        return View(mySupplierOrders.OrderBy(o => o.Clients.BusinessAddress).ToList());
    }

and this is the view for "SetByCity":
    @foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.Id)

                @Html.DisplayFor(modelItem => item.Clients.BusinessName)

                @Html.DisplayFor(modelItem => item.Clients.BusinessAddress)

                @Html.DisplayFor(modelItem => item.CreateDate)

                @Html.DisplayFor(modelItem => item.PayDate)

                @Html.DisplayFor(modelItem => item.Discount)

                @Html.DisplayFor(modelItem => item.TotalPrice)

                <form method="post" action="@Url.Action("SetOrdersPosition", "Packer")" id="editform">
                    <input type="hidden" name="Id" value="@item.Id">
                    <input type="number" name="Position" min="1" max="@Model.Count()">@*i need to put all the positions and id's of all the items in a pairs list and send it to the controller*@
                </form>

    }

<input type="submit" value="send" form="editform" />

and this is the receiving actionResult "SetOrdersPosition" in the PackerController:
    [HttpPost]
    public ActionResult SetOrdersPosition(List<id,position>)
    {
        //does something...
    }

i don't know what to put in the parameters that the SetOrdersPosition gets...

A: Hope you are using the Model name called "Suppliers".
So in get method pass that into view.
You needs to do come little changes accordingly to use Begin Form in your view, so that you can directly post your model data to controller.
Use this item inside body.
Don't forget to declare the model which you are using in the view page like below.
@model MVC.Models.Suppliers
@using (Html.BeginForm("SetOrdersPosition", "Packer", FormMethod.Post))
    {

        @foreach (var item in Model)
           {

            @Html.DisplayFor(modelItem => item.Id)

            @Html.DisplayFor(modelItem => item.Clients.BusinessName)

            @Html.DisplayFor(modelItem => item.Clients.BusinessAddress)

            @Html.DisplayFor(modelItem => item.CreateDate)

            @Html.DisplayFor(modelItem => item.PayDate)

            @Html.DisplayFor(modelItem => item.Discount)

            @Html.DisplayFor(modelItem => item.TotalPrice)

            <input type="submit" value="Submit"/>

     }

}

Controller Code [HttpPost]
 public ActionResult SetOrdersPosition(Suppliers _suppliers)
  {
    //does something...
  }


Q: Expanding to consumer to cater for each producer? I have the following socket connection codes. Where for every connection is one new thread. After receiving the data which is done via the producer then I put into a queue for next database processor which is the consumer. This works fine but the moment the queue gets build up it can hang or even take even hours to clear cause is like so many producers and just one single consumer. I am thinking is it possible for me to have one consumer handles one producer meaning each message goes into its own queue gets process and that it. What changes can I do to handle it or must I build a thread pooling ?
public class cServer {
   private LinkedBlockingQueue<String> databaseQueue = new LinkedBlockingQueue<String>();
   class ConnectionHandler implements Runnable {

    private Socket receivedSocketConn1;
    ConnectionHandler(Socket receivedSocketConn1) {
      this.receivedSocketConn1=receivedSocketConn1;
    }
      // gets data from an inbound connection and queues it for databse update
      public void run() { // etc

         // you already have most of this in your existing code.
         // it uses the shared databaseQueue variable to queue message Strings
         BufferedWriter w = null;
         BufferedReader r = null;
          String message="";
          try {

             PrintStream out = System.out;
             BufferedWriter fout = null;
             w =  new BufferedWriter(new OutputStreamWriter(receivedSocketConn1.getOutputStream()));
             r = new BufferedReader(new InputStreamReader(receivedSocketConn1.getInputStream()));

             int m = 0, count=0;
             int nextChar=0;

             while ((nextChar=r.read()) != -1)
             {

                  message += (char) nextChar;

                  if (nextChar == '*')
                  {

                     databaseQueue.add(message);
                     message="";
                  }
                 }
              }
              catch (IOException ex)
              {
                   System.out.println("MyError:IOException has been caught in in the main first try");
                   ex.printStackTrace(System.out);
              }
              finally
              {
                try
                {

                    if ( w != null )
                    {
                        w.close();
                    }
                    else
                    {
                        System.out.println("MyError:w is null in finally close");
                    }
                }
                catch(IOException ex){
                   System.out.println("MyError:IOException has been caught in w in finally close");
                   ex.printStackTrace(System.out);
                }

              }
      }

   }

   class DatabaseProcessor implements Runnable {

      // updates databaase with data queued by ConnectionHandler
      Connection dbconn = null;
      Statement stmt = null;
      Statement stmt1 = null;
      Statement stmt2 = null;
      Date connCreated = null;
      public void run()
      { // this is just like the QueueProcessor example I gave you
         // open database connection
         //createConnection();
             while (true)
             {

                try
                {
                    int count=0;
                    String message = "";
                    message = databaseQueue.take();
                    if (message.equals(null)) {
                       System.out.println("QueueProcessor is shutting down");
                    break; // exit while loop, ends run() method
                    }
                    System.out.println("Message taken from queue is :"+message);

                }
                catch (Exception e)
                {
                e.printStackTrace();
                }
            }//while true
           //closeConnection();
     }//run
   }

   public static void main(String[] args) {
      new cServer();
   }
   cServer() { // default constructor
      new Thread(new DatabaseProcessor()).start();
      try
      {
               final ServerSocket serverSocketConn = new ServerSocket(5000);
               while (true)
                    {
                        try
                        {
                                Socket socketConn1 = serverSocketConn.accept();
                                new Thread(new ConnectionHandler(socketConn1)).start();
                        }
                        catch(Exception e)
                        {
                            System.out.println("MyError:Socket Accepting has been caught in main loop."+e.toString());
                            e.printStackTrace(System.out);
                        }
                    }
      }
      catch (Exception e)
      {
         System.out.println("MyError:Socket Conn has been caught in main loop."+e.toString());
         e.printStackTrace(System.out);
         //System.exit(0);
      }
      databaseQueue.add(null);
   }
}


Q: In DynamoDb, is there a way to atomically check a secondary index for an item before writing it? I've got an object like this:
{
     "id": (UUID generated at call time)
     "referenceId": (Foreign key for another system)
     "referenceType": (enum)
}

The primary index is just

*

*Primary key: id

And I've got a secondary index like

*

*Primary key: referenceId

*Secondary key: referenceType

So what I want to do, is query the secondary index with the referenceId and referenceType, and then if that's empty, write the record to the table.
The problem is, Conditional Expressions can only check same index you're querying. And I've looked into DynamoDb Transactions, but they say you can't have two transactions target the same item.
Is there a way to make this work?

A: If I understand your question correctly, your item has three attributes: id,
referenceId and referenceType.  You've also defined a global secondary index with a composite primary key of referenceId and referenceType.
Assuming all these attributes are part of the same item, you shouldn't need to read the secondary index before deciding to write to the table.  Rather, you could perform a PUT operation on the condition that referenceId and reference type don't yet exist on that item.
ddbClient.putItem({
    "TableName": "YOUR TABLE NAME",
    "Item": { "PK": "id" },
    "ConditionExpression": "attribute_exists(referenceId) AND attribute_exists(referenceType)"
  })

You may also want to check out this fantastic article on DynamoDB condition expressions.

A: As I understand the question, your table PK is generated "at call time" so it would be different for two different requests with the same reference ID and reference type.
That being the case, your answer is no.
If you've got a requirement for uniqueness of a key set by a foreign system, you should consider using the same key or some mashup of it for your DDB table.
Alternately, modify the foreign system to set the UUID for a given reference ID & type.


Q: Why does mapping over a DataFrame using a case class fail with "Unable to find encoder for type stored in a Dataset"? I have already imported spark.implicits._ But still I get error

Error:(27, 33) Unable to find encoder for type stored in a Dataset.  Primitive types (Int, String, etc) and Product types (case classes) are supported by importing spark.implicits._  Support for serializing other types will be added in future releases.

I have a case class like:
case class User(name: String, dept: String)

and I am converting Dataframe to dataset using:
val ds = df.map { row=> User(row.getString(0), row.getString(1) }

or
val ds = df.as[User]

Also, when I am trying the same code in Spark-shell I get no error, only when I run it through IntelliJ or submit the job I get this error.
Any reasons why?

A: Moving declaration of case class out of scope did the trick!
Code structure will then be like:
package main.scala.UserAnalytics

// case class *outside* the main object
case class User(name: string, dept: String)

object UserAnalytics extends App {
    ...
    ds = df.map { row => User(row.getString(0), row.getString(1)) }
}


Q: How to make first post bigger in wordpress This is probably very easy to do, but unfortunately I'm not too good with coding. I am honestly trying to learn though.
I have a theme in wordpress that makes posts tagged with "spotlight" twice the size of the rest. I would like to change this so that it's automatically the first post that is this size. I hope that makes sense.
A snippet of the code I have:
// Get blog layout setting
    $blog_layout      = get_theme_mod( 'blog_layout_setting', 'three-columns' );
    $portfolio_layout = get_theme_mod( 'portfolio_layout_setting', 'four-columns' );

    if ( is_tax( 'ct_portfolio' ) || is_page_template( 'templates/template-portfolio.php' ) ) :

        if ( 'four-columns' == $portfolio_layout ) {

            if ( has_tag( 'spotlight' ) ) {
                $classes[] = 'col-lg-6 col-md-8 col-sm-12';
            } else {
                $classes[] = 'col-lg-3 col-md-4 col-sm-6';
            }

        } else {

            if ( has_tag( 'spotlight' ) ) {
                $classes[] = 'col-md-8 col-sm-12';
            } else {
                $classes[] = 'col-md-4 col-sm-6';
            }

        }

I'm pretty sure it's just to change the "if ( has_tag( 'spotlight' )" to something i++ or i=1, or something like that. I might also be completely wrong. I feel like the answer is staring me in the face, but I just can't grasp it. I've tried searching around, but haven't found a good answer.
I would be really happy for any help, and I really do learn from this.
Thanks in advance.

A: Please refer this jsFiddle code. I hope this solves your problem.
You just needed to add the CSS to your style.css
.myspotlight{
background-color:red;
}

and
the javascript to the particular php file which runs the loop of all your articles and creates the list of articles.
 $( "article" ).first().addClass("myspotlight");

The jquery code basically appends the necessary class to the first  tag that it finds


Q: Flutter: why can't I create a DateTime object with all 0 values? So I want to make a Stopwatch in Flutter.
static void startTrip() {
  SharedPrefsHelper().setIsCurrentlyOnTrip(true);

  _elapsedTime = DateTime(
    0, //year
    0, //month
    0, //day
    0, //hour
    0, //minute
    0, //second
    0, //millisecond
    0, //microsecond
  );

  _timer = Timer.periodic(Duration(seconds: 1), (Timer timer) {
    _elapsedTime.add(Duration(seconds: 1));
    print('new time: $_elapsedTime');
    _controller.sink.add(_elapsedTime); //same object/reference, but this is for the StreamBuilder to update
  });

  //TODO
}

As you can see I first attempted to use a DateTime object to keep track of the time.
But DateTime(0, 0, 0, 0, 0, 0, 0, 0) initializes to -0001-11-30 00:00:00.000. And the value doesn't update after I try to add 1 second, it always prints out the same.
Go and try it out your self on dartpad by running this code:
DateTime elapsedTime = DateTime(0, 0, 0, 0, 0, 0, 0, 0);
print(elapsedTime);
elapsedTime.add(Duration(seconds: 1));
print(elapsedTime);

Does anyone know why this happens?
For now I will just use an int to keep track of the time instead and do the formatting myself.
P.S so this is how I did it, if anyone wants the code:
int hours = elapsedTime ~/ 3600;
int minutes = (elapsedTime % 3600) ~/ 60; //get rid of all additional hours, then divide by 60
int seconds = elapsedTime % 60; //get rid of all additional minutes

String h = hours > 9 ? hours.toString() : '0$hours';
String m = minutes > 9 ? minutes.toString() : '0$minutes';
String s = seconds > 9 ? seconds.toString() : '0$seconds';

A: You can try this:
DateTime elapsedTime = DateTime.utc(0);
print(elapsedTime);
elapsedTime = elapsedTime.add(Duration(seconds: 1));
print(elapsedTime);

Note: The lowest value for day and month is 1 and not 0.


Q: Loading Clojure code in Eclipse plug-in I have this kind of problem. I have Clojure code contained in Eclipse plug-in (denoted A) in *.clj files. I don't want AOT compilation. However, I need to load the clojure code from another Clojure plug-in B. This is possible when B depends on A. Clojure can easily access the classpath and everything works. But I want the plug-in A to be plugged as extension to B. But there is a problem because I could not find a way how to load a Clojure file contained in A from *.clj file contained in B. I would like to use the Clojure 'load' function which can load *.clj files from classpath but this function just cannot see contents of plug-in A event when I explicitely start the plug-in like this
 (org.eclipse.core.runtime.Platform/getBundle "A")

Reaction to Laurent's answer
Laurent, thank you very much! This is very interesting. However, I think this mayby solves a harder problem then my original one. You discribed how to call clojure code from java plug-in which is totaly awesome. I need to call clojure code from clojure plug-in which I think may be easier. I imagine that I would create extension point and provide clojure functions like this
<extension point="transforms">
  <function namespace="my.nemaspace" fn="my-transform"/>
</extension>

So I do not need any magic with IExecutableExtensionFactory. I can read the extension registry from clojure code. What I cannot do is load the function specified in the extension. Is this doable or did I just misunderstood something? I noticed that you are using clojure.osgi. This looks cool, is there any documentation for that project?

A: The problem you're having with regards to classloaders is to be expected : if the dependencies of your Eclipse plugins/OSGi bundles are A -> B, with the Clojure jar bootstraped from B, then not being able to see resources of A from B is normal.
There can be no cycles among dependencies of Eclipse plugins, so there can be no cycles among classloader hierarchies.
This is the same problem that you would face if you were to write extensions to B from A with regular Eclipse machinery : plugin B would declare an interface, and an extension point. Then plugin A could implement the interface, and declare an extension to the extension point. This last part allows the Eclipse framework to do some tricks with the bundles: it sees that A declares an extension to B, thus instanciates a class from A implementing the interface declared in B (this works since A depends on B), and gives B the implementation instance from A which is also OK since it implements the interface in B !
(Not sure this is clear).
Anyway, back to plugins written in Clojure.
With Clojure, you don't have, out of the box, such separate environments provided by classloaders, because everything gets aggregated in one "Clojure environment" living in the classloader realm of the plugin embedding the clojure jar.
So one possibility would just be, when plugin A starts, to load the relevant namespaces from A. Then they would be loaded at the right time, and available to any other Clojure code.
Another possibility would be to use the Extension Point/Extension machinery. Eclipse provides a way to use "factories" to create instances of extension points. In Counterclockwise, we leverage this feature, and have a generic factory class (written in java, so no AOT) which takes care of loading the right namespace from the right bundle.
Here are more detail concerning how to extend extension points.
An example from Counterclockwise:
There is an existing Extension Point in the Eclipse framework for contributing hyperlink detectors for the Console contents. Counterclockwise extends this extension point to add nrepl hyperlinks.
In the java world, you would have to directly declare, in your extension, some class of yours which implements interface IPatternMatchListenerDelegate.
But with CCW, for probably the same reasons as you, I try to avoid AOT at all costs, so I can't give a java class name in the extension, or I would have either had to write it in java and compile it, or write a gen-class in Clojure and AOT-compile it.
Instead, CCW leverages a hidden gem of plugin.xml's possibilities: in almost every place, when you have to provide a class name, you can instead provide an instance of IExecutableExtensionFactory whose create() method will be called by the Eclipse framework to create an instance of the desired class.
This allowed me to write a generic class for calling into the Clojure world: I just use, in place of the class name I should have written, the class name ccw.util.GenericExecutableExtension
Extract from plugin.xml :
<extension point="org.eclipse.ui.console.consolePatternMatchListeners">
<consolePatternMatchListener
   id="ccw.editors.clojure.nREPLHyperlink"
   regex="nrepl://[^':',' ']+:\d+">
    <class class="ccw.util.GenericExecutableExtension">
       <parameter
             name="factory"
             value="ccw.editors.clojure.nrepl-hyperlink/factory">
       </parameter>
    </class>
</consolePatternMatchListener>

Note the class attribute, and how I can give parameters to the factory via the parameter element (the factory has to implement interface IExecutableExtension for being able to be initialized with the parameters).
Finally, you can see that in namespace ccw.editors.clojure.nrepl-hyperlink, the function factory is rather simple and just calls the make function:
(defn make []
  (let [state (atom nil)]
    (reify org.eclipse.ui.console.IPatternMatchListenerDelegate
      (connect [this console]  (dosync (reset! state console)))
      (disconnect [this]       (reset! state nil))
      (matchFound [this event] (match-found event @state)))))

(defn factory "plugin.xml hook" [ _ ] (make))

Please note that I'm showing this as an example, and the relevant code in Counterclockwise is not ready to be released as an independant library "ready for consumption".
But you should nonetheless be able to roll your own solution (it's quite easy once you get all the pieces in place in your head).
Hope that helps,
--
Laurent

A: Another solution occured to me: it is possible, in Eclipse, despite what I said in my previous answer, to create cyclic dependencies between the classloaders!
Eclipse guys needed to introduce this so that certain types of libraries (log4j, etc.) could work in an OSGi environment (which is what Eclipse is based upon).
This requires to leverage the Eclipse-BuddyPolicy mechanism (Third Party libraries and classloading).
It's quite easy: if you want plugin B to see all classes and resources of plugin A, just add this to plugin B's META-INF/MANIFEST.MF file:
Eclipse-BuddyPolicy: dependent

The line above indicates that plugin B's classloader will be able to access what its dependents classloaders have access to.
I created a sample set of plugins named A and B where B has 2 commands (visible in the top menu) : the first applies a text transformation on the "hello" hard coded string by calling clojure code in B. The second dynamically loads an new text transformation from plugin A, so that when you invoke the first command again, you see the result of applying transformations from B and transformations from A.
In your case, it may not even be required to use Eclipse Extension Point / Extension mechanism at all, after all. It will all depend on how you intent plugin B to "discover" plugin A relevant information.
The github repository showing this in action: https://github.com/laurentpetit/stackoverflow-12689605
HTH,
--
Laurent


Q: Implement fold with for-comprehension How can a fold be implemented as a for-comprehension in Scala? I see the only way is to use some recursive call? This is a try that is failing, not sure how to do this? What is the best way to implement fold as a for-comprehension
  val nums = List(1,2,3)
  nums.fold(0)(_+_)
  def recFold(acc: Int = 0): Int = {
    (for {
        a <- nums
        b = recFold(a + acc)
    } yield b).head
  }
    recFold(0) //Stack overflow

A: If you really want to use for, you don't need recursion, but you would need a mutable variable:
val nums = List(1,2,3)

def recFold(zero: Int)(op: (Int, Int) => Int): Int = {
  var result: Int = zero
  for { a <- nums } result = op(result, a)
  result
}

recFold(0)(_ + _) // 6

Which is pretty similar to how foldLeft is actually implemented in TraversableOnce:
def foldLeft[B](z: B)(op: (B, A) => B): B = {
  var result = z
  this foreach (x => result = op(result, x))
  result
}

A: Fold can be implemented both ways right to left or left to right. No need to use for plus recursion. Recursion is enough.
  def foldRight[A, B](as: List[A], z: B)(f: (A, B) => B): B = {
    as match {
      case Nil => z
      case x :: xs => f(x, foldRight(xs, z)(f))
    }
  }

  @annotation.tailrec
  def foldLeft[A, B](as: List[A], z: B)(f: (A, B) => B): B = {
    as match {
      case Nil => z
      case x :: xs => foldLeft(xs, f(x, z))(f)
    }
  }


Q: Scala/Spark Apriori implementation extremely slow We are trying to implement the Apriori algorithm in Scala using Spark (you don't need to know the algorithm to answer this question).
The function computing the itemsets of the Apriori algorithm is freq(). The code is correct but it gets slower after each iteration in the while in the freq() function, up to the point of taking several seconds to perform a cross join on a table with 1 row with itself.
import System.{exit, nanoTime}
import scala.collection.mutable.WrappedArray
import org.apache.spark.sql.{Column, SparkSession, DataFrame}
import org.apache.spark.sql.functions._
import spark.implicits._

object Main extends Serializable {
  val s = 0.03

  def loadFakeData() : DataFrame = {
    var data = Seq("1 ",
                   "1 2 ",
                   "1 2",
                   "3",
                   "1 2 3 ",
                   "1 2 ")
                .toDF("baskets_str")
                .withColumn("baskets", split('baskets_str, " ").cast("array<int>"))
      data
  }

  def combo(a1: WrappedArray[Int], a2: WrappedArray[Int]): Array[Array[Int]] = {
    var a = a1.toSet
    var b = a2.toSet
    var res = a.diff(b).map(b+_) ++ b.diff(a).map(a+_)
    return res.map(_.toArray.sortWith(_ < _)).toArray
  }
  val comboUDF = udf[Array[Array[Int]], WrappedArray[Int], WrappedArray[Int]](combo)

  def getCombinations(df: DataFrame): DataFrame = {
    df.crossJoin(df.withColumnRenamed("itemsets", "itemsets_2"))
      .withColumn("combinations", comboUDF(col("itemsets"), col("itemsets_2")))
      .select("combinations")
      .withColumnRenamed("combinations", "itemsets")
      .withColumn("itemsets", explode(col("itemsets")))
      .dropDuplicates()
  }

  def countCombinations(data : DataFrame, combinations: DataFrame) : DataFrame = {
    data.crossJoin(combinations)
      .where(size(array_intersect('baskets, 'itemsets)) === size('itemsets))
      .groupBy("itemsets")
      .count
  }

  def freq() {
    val spark = SparkSession.builder.appName("FreqItemsets")
      .master("local[*]")
      .getOrCreate()

    // data is a dataframe where each row contains an array of integer values
    var data = loadFakeData()
    val basket_count = data.count

    // Itemset is a dataframe containing all possible sets of 1 element
    var itemset : DataFrame = data
                                .select(explode('baskets))
                                .na.drop
                                .dropDuplicates()
                                .withColumnRenamed("col", "itemsets")
                                .withColumn("itemsets", array('itemsets))
    var itemset_count : DataFrame = countCombinations(data, itemset).filter('count > s*basket_count)
    var itemset_counts = List(itemset_count)

    // We iterate creating each time itemsets of length k+1 from itemsets of length k
    // pruning those that do not have enough support
    var stop = (itemset_count.count == 0)
    while(!stop) {
      itemset = getCombinations(itemset_count.select("itemsets"))
      itemset_count = countCombinations(data, itemset).filter('count > s*basket_count)
      stop = (itemset_count.count == 0)
      if (!stop) {
        itemset_counts = itemset_counts :+ itemset_count
      }
    }

    spark.stop()
  }
}

A: Since Spark retains the right to regenerate datasets, at any time, that may be what's happening, in which case caching the results of expensive transformations can lead to dramatic improvements in performance.
In this case, it looks at first glance like itemset is the heavy hitter, so
itemset = getCombinations(itemset_count.select("itemsets")).cache

May pay dividends.
It should also be noted that building up a list by appending in a loop is generally a lot slower (O(n^2)) than building it by prepending.  If correctness isn't affected by the order of itemset_counts, then:
itemset_counts = itemset_count :: itemset_counts

will produce at least a marginal speed-up.


Q: Enable :active state in IE7 with jQuery? I've searched for a simple jQuery plugin to enable the active state in IE7, but I've only been able to find IE7-js, which doesn't play well with my current javascript.
I think I could build this myself, but I figure someone else has already done a better job of it than I would. Is there a solid jQuery plugin that does this already?
Thanks in advance!

A: IE7 should work just fine with :active on anchors (<a>), as long as the anchor has the href attribute (source).


Q: Android launchin thridparty intent not working I 'm trying to launch the camera app on button click but I don't want to hav the fot
I want it to behave like it is launched by the lauc´ncher but when I call my code the application simply closes and the camera isn't starting.There isn't even an error code.
Code :
if(v == camera)
    {

        //Intent in=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            // this.startActivity(in);

        Intent startupIntent = new Intent();
        ComponentName distantActivity = new ComponentName("com.android.camera","com.android.camera/.Camera");
        startupIntent.setComponent(distantActivity);
        startupIntent.setAction(Intent.ACTION_MAIN);
        startActivity(startupIntent);

        finish();
    }

A: use android.intent.action.VIEW instead of Intent.ACTION_MAIN as:
    Intent startupIntent = new Intent();

    ComponentName distantActivity= new ComponentName("YOUR_CAMRA_APP_PACKAGE","YOUR_CAMRA_APP_PACKAGE.ACTIVTY_NAME");

// LIKE IN LG  DEVICE WE HAVE AS

//ComponentName distantActivity= new //ComponentName("com.lge.camera","com.lge.camera.CameraApp");

    startupIntent .setComponent(distantActivity);

    startupIntent .setAction("android.intent.action.VIEW");

    startActivity(startupIntent);


Q: Why does Terminals.tokenizer() tokenize unregistered operators/keywords? I've just discovered the root cause of some very confusing behavior I was observing. Here is a test:
@Test
public void test2() {
    Terminals terminals = Terminals.caseInsensitive(new String[] {}, new String[] { "true", "false" });
    Object result = terminals.tokenizer().parse("d");
    System.out.println("Result: " +  result);
}

This outputs:
Result: d

I was expecting the parser returned by terminals.tokenizer() not to return anything because "d" is not a valid keyword or operator.
The reason I care is because I wanted my own parser at a lower priority than that returned by terminals.tokenizer():
public static final Parser<?> INSTANCE =
        Parsers.or(
                STRING_TOKENIZER,
                NUMBER_TOKENIZER,
                WHITESPACE_TOKENIZER,
                (Parser<Token>)TERMINALS.tokenizer(),
                IDENTIFIER_TOKENIZER);

The IDENTIFIER_TOKENIZER above is never used because TERMINALS.tokenizer() always matches.
Why does Terminals.tokenizer() tokenize unregistered operators/keywords? And how might I get around this?

A: In the upcoming jParsec 2.2 release, the API makes it more clear what Terminals does:
http://jparsec.github.io/jparsec/apidocs/org/codehaus/jparsec/Terminals.Builder.html
You cannot even define your keywords without first providing a scanner that defines "words".
The implementation first uses the provided word scanner to find all words, and then identifies the special keywords on the scanned words.
So, why does it do it this way?

*

*If you didn't need case insensitivity, you could have passed the keywords as "operators". Yes, you read it right. One can equally use Terminals.token(op) or Terminals.token(keyword) to get the token level parser of them. What distinguishes operators from keywords is just that keywords are "special" words. Whether they happen to be alphabet characters or other printable characters is just by convention.

*Another way to do it, is to define your word scanner precisely as Parsers.or(Scanners.string("keyword1"), Scanners.string("keyword2"), ...). Then Terminals won't try to tokenize anything else.

*The above assumes that you want to do the 2-phase parsing. But that's optional. Your test shows that you weren't feeding the tokenizer to a token-level parser using Parser.from(tokenizer, delim). If two-phase parsing isn't needed, it can be as simple as:        or(stringCaseInsensitive("true"), stringCaseInsensitive("false"))
More on point 3. The 2-phase parsing creates a few extra caveats in jParsec that you don't find in other parser combinators like Haskell's Parsec. In Haskell, a string is no different from a list of character. So there really isn't anything to gain by special casing them. many(char 'x') parses a string just fine.
In Java, String isn't a List or array of char. It would be very inefficient if we take the same approach and box each character into a Character object so that the character level and token level parsers can be unified seamlessly.
Now that explains why we have character level parsers at all. But it's completely optional to use the token level parsers (By that, I mean Terminals, Parser.from(), Parser.lexer() etc).
You could create a fully functional parser with only character-level parsers, a.k.a scanners.
For example: Scanners.string("true").or(Scanners.string("false")).sepEndBy1(delim)

A: From the documentation of Tokenizer#caseInsensitive:

org.codehaus.jparsec.Terminals
public static Terminals caseInsensitive(String[] ops,
                                          String[] keywords)
Returns a Terminals object for lexing and parsing the operators with names specified in
  ops, and for lexing and parsing the keywords case insensitively. Keywords and operators
  are lexed as Tokens.Fragment with Tokens.Tag.RESERVED tag. Words that are not among
  keywords are lexed as Fragment with Tokens.Tag.IDENTIFIER tag. A word is defined as an
  alphanumeric string that starts with [_a - zA - Z], with 0 or more [0 - 9_a - zA - Z]
  following.

Actually, the result returned by your parser is a Fragment object which is tagged according to its type. In your case, d is tagged as IDENTIFIER which is expected.
It is not clear to me what you want to achieve though. Could you please provide a test case ?

A: http://blog.csdn.net/efijki/article/details/46975979
The above blog post explains how to define your own tag. I know it's in Chinese. You just need to see the code. Especially the withTag() and patchTag() part.


Q: Screenshot comes out black on Wayland I found this code to take a screenshot on Ted Mielczarek's website.
/*
 * gdk-screenshot.cpp: Save a screenshot of the root window in .png format.
 *  If a filename is specified as the first argument on the commandline,
 *  then the image will be saved to that filename. Otherwise, the image will
 *  be saved as "screenshot.png" in the current working directory.
 *
 * Compile with:
 * g++ -o gdk-screenshot gdk-screenshot.cpp `pkg-config --cflags --libs gdk-x11-2.0`
 */

#include <gdk/gdk.h>
#include <gdk/gdkx.h>

int main(int argc, char** argv)
{
  gdk_init(&argc, &argv);
  GdkWindow* window = window = gdk_get_default_root_window ();
  GdkPixbuf* screenshot = gdk_pixbuf_get_from_drawable (NULL, window, NULL,
                            0, 0, 0, 0,
                            gdk_screen_width(),
                            gdk_screen_height());
  GError* error = NULL;
  const char* filename = (argc > 1) ? argv[1] : "screenshot.png";
  return TRUE == gdk_pixbuf_save (screenshot, filename, "png",
                  &error, NULL);
}

I compiled it as described and it appears to work, in that it produces an image with the correct dimensions, but the screenshot is entirely black.

This appears to be a common issue on systems running Wayland (I'm running Archlinux with Wayland), so my question is:
What modifications need to be made to this code to get it to produce a proper screenshot on Wayland (and X)?

A: I had a similar problem.
I use Xlib to take screenshots, but this method can't work on Wayland. Every time I run to xgetimage, I report an error. After looking up the data, I find Wayland doesn't allow such screenshots. However, in this way, I can still get the correct screen size.
Now I use DBUS to call the session bus of the system to take a screenshot, which I learned from reading the source code of Gnome screenshot.
This is a simple summary code:
    method_name = "Screenshot";
    method_params = g_variant_new ("(bbs)",
                                     TRUE,
                                     FALSE, /* flash */
                                     filename);

    connection = g_application_get_dbus_connection (g_application_get_default ());
    g_dbus_connection_call_sync (connection,
                               "org.gnome.Shell.Screenshot",
                               "/org/gnome/Shell/Screenshot",
                               "org.gnome.Shell.Screenshot",
                               method_name,
                               method_params,
                               NULL,
                               G_DBUS_CALL_FLAGS_NONE,
                               -1,
                               NULL,
                               &error);

The document link is here:
https://developer.gnome.org/references
The GitHub of Gnome screenshot is here:
https://github.com/GNOME/gnome-screenshot


Q: How to query a document with the highest value of a field Let's say I have a collection of documents. To make this simpler, let's say all these documents have just 2 fields, name and id, like below.
I want to get the document with the greatest value of "id". Can I use the .find({}) with some parameters? If so, I can't figure out which parameter would find me the max value of a certain field.
[
  {
    name: "name1",
    id: 1
  }
  {
    name: "name2",
    id: 2
  }
  {
    name: "name1",
    id: 3
  }
  {
    name: "name1",
    id: 0
  }
]

A:

let documents = [
  {
    name: "name1",
    id: 1
  },
  {
    name: "name2",
    id: 2
  },
  {
    name: "name1",
    id: 3
  },
  {
    name: "name1",
    id: 0
  }
];

let max = documents.sort( (a, b) => a.id > b.id ? -1 : 1)[0]
console.log( max );

How about
let maxIdDocument = documents.sort( (a, b) => a.id > b.id ? 1 :  -1)[0]

A: First, sort in descending order, then get the first one:

const arr = [{
    name: "name1",
    id: 1
  },
  {
    name: "name2",
    id: 2
  },
  {
    name: "name1",
    id: 3
  },
  {
    name: "name1",
    id: 0
  }
];

const [greatest] = arr.sort(({ id: a }, { id: b }) => b - a);

console.log(greatest);

A: You can sort that array and with the function pop get the object with the greatest id.
arr.slice() // This is to avoid a mutation on the original array.

let arr = [   {     name: "name1",     id: 1   },   {     name: "name2",     id: 2   },   {     name: "name1",     id: 3   } ,  {     name: "name1",     id: 0   } ],
    greatest = arr.slice().sort(({id: a}, {id: b}) => a - b).pop();

console.log(greatest);
.as-console-wrapper { min-height: 100%; }


Q: ADB2C - How to change UI for password confirmation screen(In reset password flow) I have created sign-in user flow with reset password user flow.
I have updated UI with custom UI in both the flows. When user click on 'Forgot password' link then user is seeing new UI for 'Reset password' user flow, but after email verification when user click on continue then user is seeing default UI as below.
Any one know how can I change this UI as well with custom UI.

A: You have to add Custom page for Change password page also. I thin you have added Custom Page only for Forgot password page.


Q: Resolve @RegisteredOAuth2AuthorizedClient with the token obtained outside of spring server of Spring Security 5.2.x I have a controller method that has an argument OAuth2AuthorizedClient with annotation @RegisteredOAuth2AuthorizedClient.
ResponseEntity<String> getFoo(
            @RegisteredOAuth2AuthorizedClient("custom") OAuth2AuthorizedClient client) {
OAuth2AccessToken token = client.getAccessToken();
 ....
}

In order to resolve this, spring look for OAuth token on OAuth2AuthorizedClientService which actually stores the previously authenticated tokens in memory.
Now, I have a scenario where I obtain JWT token from OAuth server outside of this spring resource server, and trying to authenticate this server by passing token using Authorization header.
But when spring trying to resolve OAuth2AuthorizedClient it is looking for token in-memory with the principle of JWT (which will obviously not found since token is not obtained on this server). Hence send new login redirection for new token.
Overall question would be, is it possible to resolve   OAuth2AuthorizedClient with the JWT token (obtained ourside of the server) passed in Authorization header?


Q: Importing python packages, nested packages... going up, traversing, etc... doesn't appear to work - what am I doing wrong? I'm having an issue. I'm porting a lot of code to Python from various other languages of things I've coded over the years and turning it into a large package.
Because not everything fits under a single package - I am nesting packages within. The main package is AcecoolLib, which has init, all of the nested packages have it too.
Because I want to be able to import AcecoolLib - and have everything imported beneath it, all of my init files import everything within their respective folder, and any packages beneath. I only nest 1 deep at the moment - I am not sure whether or not this will change. Probably not.
I have tried absolute imports, and I have tried relative. I have tried modifying sys.modules, and sys.path. I have tried adding paths and I don't know where I can map a name to the path. I end up with a lot of the package loading properly, and some areas I end up with errors where Acecool.X doesn't exist. I fix one, and another one pops up.
One I fixed was - I thought, because I had a few packages named list / tuple / dict that since these are referenced to data-types, that changing them may be beneficial. so I put them into a nested package called array and renamed all of them to include an s on the end. lists, tuples, dicts. not a fan of this - but the error went away.
I'm getting an error in my steam directory now but I don't know of steam being a protected name.
I am using the package, right now, in Sublime Text. I will be using it there for plugins I'm writing - to replace the current system I use which is a single file Acecool.py imported as AcecoolLib in another plugin... It's ugly, hard to maintain, etc.. so I moved some of the code into packages.
In short - I am running into a lot of issues.
This is the first main attempt: https://bitbucket.org/Acecool/acecoollib/src/master/
And this is where I'm at currently: https://www.dropbox.com/s/xvaubq78hlhym9o/AcecoolLib.7z?dl=0
I have tried a lot of variation....
I have looked over other packages which import through nested packages and I haven't found anything which shows me doing anything different ( before I started adding a bunch of crap to the start to find a solution )...
There must be something which lets me set up the paths for each package, and then define they all get added to the AcecoolLib namespace, with nested namespaces within...
I want to be able to go into AcecoolLib/tests/ dir and run tests throughout by running the scripts directly from tests. I also want to be able to import from external / internal sources to have access to everything if I need it.
I also want to be able to import just nested packages or the entire. ie: import AcecoolLib means I should be able to get to Acecool.util.accessors - and so on... or if I import Acecool.util then I don't see AcecoolLib.math - but I could import it.
Right now I'm testing importing everything as my current project uses almost every single function, etc... I added a few as tests..
I have read quite a lot on the subject of importing and I have come across countless 'this is the right way' 'no this' 'nope, this', and so on... none of which work. I have come across articles which say never use this type of import, or this... etc.. most of the articles aren't very useful and are plagued with personal opinions instead of covering the material of the title. Or they cover the basic 101 level variants, or show the directory tree ( which looks identical to mine ) and say that it just works as is...
Maybe that's right - maybe Sublime Text does something differently - ie: I do know that the package is being added to sys.modules, and All of the nested ones are too - so I'm just lost....
Any help is appreciated. Thank you!


Q: "__NSAutoreleaseFreedObject(): release of previously deallocated object" out of the blue I'm not sure if this is an error or not. The code compiles fine (no warnings), but when I enter a method, a local's value (an NSMutableString) displays this content in the debugger:
__NSAutoreleaseFreedObject(): release of previously deallocated object

I'm not getting an exception, it looks like the contents of the string (which is not even allocated at that time) is that NSAutoReleaseFreedObject warning.
What's going on?

A: it (likely) means that your app has executed different from usual, and exposed a bug in your ref counting of the object. this type of issue can also be related to improper multithreading.
executing your app to trigger the problem with zombies enabled should help you locate it.

A: If you don't initialize a normal local variable to anything, its value is undefined — it could be anything. In practice, it will interpret the bit pattern that happens to lie on the stack where the variable is allocated as a value of the variable's type. In this case, the "anything" that the variable contains happens to be the address of that string.


Q: CSV -> JSON -> PostgreSQL "Token invalid" I have a CSV file containing 1 column ("json_doc") with many rows of JSON data. I want to collect this json data and upload it to a Postgres database. The rows are in the format:
{"id": "0436d9b9305d", "base": {"ateco": [{"code": "46.11.03", "rootCode": "G", "description": "Agenti e rappresentanti di animali vivi"}], "founded": "1972-07-10", "legalName": "COBEM - S.R.L.", "legalForms": [{"name": "Società Di Capitale", "level": 1}, {"name": "Società A Responsabilità Limitata", "level": 2}]}, "name": "COBEM - S.R.L.", "people": {"items": [{"name": "45808b0b5b5affa871c8e91169bb10c6930fac56", "givenName": "64e4393f477394f11f6477ca76395ed469548865", "familyName": "68ee44f14dc54d664dffe63195d42a14988b69bb"}]}, "country": "it", "locations": {}}

There are millions of rows, and not all of the formatting is consistent i.e. some nested dictionaries are structurally different to others.
I've taken 5 of these rows, and applied the following Python:
import pandas as pd

df = pd.read_csv('samplecol.csv')
df = df.to_json('data.json')

I then use https://jsonlint.com to check the JSON and all is good.
I have a JSON file, data.json, and a PostgreSQL database, and want to get data.json into Postgres.
I run the following to create a table :
SN_ITA_test=# CREATE TABLE jsons(ID serial NOT NULL PRIMARY KEY, info jsonb NOT NULL);

When I try to upload the file to Postgres using :
SN_ITA_test=# \copy jsons (info) FROM 'data.json';

I get the error:
ERROR:  invalid input syntax for type json
DETAIL:  Token "id" is invalid.
CONTEXT:  JSON data, line 1: {"json_doc":{"0":"{"id...
COPY jsons, line 1, column info: "{"json_doc":{"0":"{"id": "0436d9b9305d", "base": {"ateco": [{"code": "46.11.03", "rootCode": "G", "d..."


Q: Getting Pending Request on HTTP Client Response while ataching multiple files I am facing an issue while sending API requests to by HTTP Client. I am getting a Pending Request. How to fulfill the response and get the response data from $response->collect()
here is my code:
public function postMultipleFiles($url, $files, $params)
{
    $response = Http::withHeaders([
        'Authorization' => auth()->check() ? 'Bearer '.auth()->user()->api_token:''
    ]);

    foreach($files as $k => $file)
    {
        $response = $response->attach('images['.$k.']', $file);
    }

    $response->post($this->base_url.$url, $params);

    return response()->json($response->collect());
}

The error I am getting
message: "Method Illuminate\\Http\\Client\\PendingRequest::collect does not exist."


Q: Security: Sending email address in a url parameter Is it considered bad security practice to include somebody's email address in a url as a parameter over http? The email address belongs to a client, and they may not want anybody to see it. The url points to my own domain, I'm just creating unique urls with email addresses as a parameter so I can detect who visited the url. Can anybody sniff http traffic to extract that info?

A: Yes, it's bad practice to put any personal information in the URL. A URL can be cached and viewed in so many ways. Even if you use SSL, URLs are still saved in your browser's history, so it just makes me cringe to pass non-public data in the URL. Usually it's not any more work to pass information in the body of a POST request, so that's what I would do.

A: Not if you do it over https, as the URL path and querystring will be encrypted along with the body.
It's not a problem for the URL to be stored in the browser history, as that is private to the user.