text:
Q: i am trying to implement a pair of AWS servers that use SSL to create self-signed certificates to communicate some data between them i am able to create a hello world sample program which simply communicating using AWS servers.
but now i am trying to use self signed certificates for communication over secure RSA 2048 connection. Can someone guide me how i can create self signed certificates in Ada and use it with in my server program.
------------------------------------------------------------------------------
--                              Ada Web Server
------------------------------------------------------------------------------
Com_1.adb
                            --
First launch Com_1 then Com_2.
--
--  Let's say that you will launch com_1 on computer1 and com_2 on
--  computer2. Then the commands to launch the demo are:
--
--  on computer1:
--    $ com_1 computer2
--
--  on computer2:
--    $ com_2 computer1
--

with Ada.Command_Line;
with Ada.Strings.Unbounded;
with Ada.Text_IO;

with AWS.Communication.Client;
with AWS.Communication.Server;
with AWS.Response;
with AWS.Utils;

procedure Com_1 is

   use Ada;
   use Ada.Strings.Unbounded;
   use AWS;

   type String_Access is access all String;

   N    : Natural := 0;
   Wait : Boolean := True;

   Last_Message_Received : Boolean := False;

   function Receive
     (Server     : String;
      Message    : String;
      State      : not null access String;
      Parameters : Communication.Parameter_Set
        := Communication.Null_Parameter_Set)
     return Response.Data;
   --  Communication callback

   -------------
   -- Receive --
   -------------

   function Receive
     (Server     : String;
      Message    : String;
      State      : not null access String;
      Parameters : Communication.Parameter_Set
        := Communication.Null_Parameter_Set)
     return Response.Data is
   begin
      Wait := False;

      Text_IO.Put_Line ("Server " & Server
                        & " send me the message " & Message);
      Text_IO.Put_Line ("State " & State.all);

      Text_IO.New_Line;

      --return Response.Build ("text/html", "Ans [" & Utils.Image (N) & ']');
      return Response.Build ("text/html", "Hello");
   end Receive;

   Name : aliased String := "com_1, local server1";

   package Local_Server is
      new Communication.Server (String, String_Access, Receive);

   Answer : Response.Data;
K : Integer := 1;
begin
   if Command_Line.Argument_Count = 0 then
      Text_IO.Put_Line ("Usage: com_1 <computer>");
      return;
   end if;

   Local_Server.Start (1234, Name'Access);

   --  Wait for com_2 to become active
   while Wait loop
      delay 1.0;
   end loop;

   --  Send some messages

   --for K in 1 .. 10 loop
      Answer := Communication.Client.Send_Message
        (Command_Line.Argument (1), 3456, "mesSAGE" & Utils.Image (K),
         Communication.Parameters ("param1." & Utils.Image (K),
                                   "param2." & Utils.Image (K)));

      Text_IO.Put_Line ("< reply " & Response.Message_Body (Answer));
  -- end loop;

   --  Exit when last message received

   loop
      exit when Last_Message_Received;
      delay 3.0;
   end loop;

   Local_Server.Shutdown;

end Com_1;

--------------------------------------------------------------------------
com_2.adb
---------

with Ada.Command_Line;
with Ada.Strings.Unbounded;
with Ada.Text_IO;

with AWS.Communication.Client;
with AWS.Communication.Server;
with AWS.Response;
with AWS.Utils;

procedure Com_2 is

   use Ada;
   use Ada.Strings.Unbounded;
   use AWS;

   type String_Access is access all String;

   N : Natural := 0;

   Last_Message_Received : Boolean := False;

   function Receive
     (Server     : String;
      Message    : String;
      State      : not null access String;
      Parameters : Communication.Parameter_Set
        := Communication.Null_Parameter_Set)
     return Response.Data;
   --  Communication Callback

   -------------
   -- Receive --
   -------------

   function Receive
     (Server     : String;
      Message    : String;
      State      : not null access String;
      Parameters : Communication.Parameter_Set
        := Communication.Null_Parameter_Set)
     return Response.Data is
   begin
      Text_IO.Put_Line ("Server " & Server
                        & " send me the message " & Message);
      Text_IO.Put_Line ("State " & State.all);

      for K in Parameters'Range loop
         Text_IO.Put_Line ("   P" & Utils.Image (K) & " = "
                           & To_String (Parameters (K)));
      end loop;
      Text_IO.New_Line;

      N := N + 1;

      Text_IO.Put_Line ("================== " & Natural'Image (N));

      if N = 10 then
         Last_Message_Received := True;
      end if;

      return Response.Build ("text/html", "HELLO SERVER 1");
   end Receive;

   Name : aliased String := "com_2, local server1";

   package Local_Server is
      new Communication.Server (String, String_Access, Receive);

   Answer : Response.Data;
K: Integer := 1;
begin
   if Command_Line.Argument_Count = 0 then
      Text_IO.Put_Line ("Usage: com_2 <computer>");
      return;
   end if;

   Local_Server.Start (3456, Name'Access);

  -- for K in 1 .. 10 loop
      Answer := Communication.Client.Send_Message
        (Command_Line.Argument (1), 1234, "mes2." & Utils.Image (K));
      Text_IO.Put_Line ("< reply " & Response.Message_Body (Answer));
   --end loop;

   --  Exit when last message received

   loop
      exit when Last_Message_Received;
      delay 4.0;
   end loop;

   Local_Server.Shutdown;

end Com_2;


text:
Q: m2e Embedded Runtime: Global Settings File read from wrong location In Eclipse, I have configured a global settings file under Preferences > Maven > User Settings > Global Settings. This file contains a mirror configuration for repositories.
When Eclipse attempts to download dependencies, the settings in this file are used. When starting a maven build via Run As > Maven build, dependency resolution errors occur. When starting a Maven runtime outside from Eclipse, everything works as expected.
I enabled debug output and found the following line when starting a Maven build inside eclipse.
[DEBUG] Reading global settings from EMBEDDED\conf\settings.xml

Why is the configured global config file not used when starting a build in Eclipse? What confuses me especially is Eclipse does use these settings when downloading dependencies in the workspace.
Interestingly, a configured user settings file is used when starting a build from within Eclipse.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ifelse leaving other observations as is In R and tidy verse, there is a way to use ifelse() such that I can change several of the observations in a variable but then I can leave other observations that I don't want changed as they are but just setting else to that column (so in the example below, "Virginica and "Versicolor" would remain the same. Can't figure out how to do that in pandas.
iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
Minimal reproducible example:
iris\
.assign(new_species = iris['species'].apply(lambda x: "set" if x=="setosa" else species))

This comes up with an error and if I put species in quotes, "species" becomes the actual observation.
Thanks much!
James

A: Use replace:
iris['new_spicies'] = iris['species'].replace('setosa', 'set')

Output:
     sepal_length  sepal_width  petal_length  petal_width    species new_spicies
0             5.1          3.5           1.4          0.2     setosa         set
1             4.9          3.0           1.4          0.2     setosa         set
2             4.7          3.2           1.3          0.2     setosa         set
3             4.6          3.1           1.5          0.2     setosa         set
4             5.0          3.6           1.4          0.2     setosa         set
..            ...          ...           ...          ...        ...         ...
145           6.7          3.0           5.2          2.3  virginica   virginica
146           6.3          2.5           5.0          1.9  virginica   virginica
147           6.5          3.0           5.2          2.0  virginica   virginica
148           6.2          3.4           5.4          2.3  virginica   virginica
149           5.9          3.0           5.1          1.8  virginica   virginica

[150 rows x 6 columns]


text:
Q: RemoveProfile Command not working in mdm RemoveProfile command is not working properly for me.
I am setting the proper profile identifier with below xml
<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE plist PUBLIC '-//Apple//DTD PLIST 1.0//EN' 'http://www.apple.com/DTDs/PropertyList-1.0.dtd'><plist version='1.0'>
                        <dict>
                        <key>Command</key>
                                <dict>
                                    <key>RequestType</key>
                                    <string>RemoveProfile</string>
                                    <key>Identifier</key>
                                    <string>com.apple.mgmt.mdmA3727E23-7914-59A6-FDCE-D79D9B42A209</string>
                                </dict>
                        <key>CommandUUID</key>
                        <string>B733FE25-101E-4959-4FAD-7262D7774169</string>
                        </dict>

                    </plist>

Also when I query for profiles installed on device I get this profile installed with same profile identifier.
Can someone guide me whats wrong with the command.
On IPCU, I get the following error:
The profile "com.apple.mgmt.mdmA3727E23-7914-59A6-FDCE-D79D9B42A209" is not managed by MDM.

If I performed an enterprise wipe i.e. remove the main enrollment profile via the same above command, it removes the enrollment as well as all the associated profiles, so why doesn't it allow me to remove individuals?

A: Two pieces of information:
1) If profile is truely not managed (wasn't installed through MDM), you can't remove it using MDM.
2) I noticed and reported to Apple a bug in which my iOS device lost association between MDM profile and profiles which were installed through MDM. So, you may have seen this bug.


text:
Q: How to allow browsing to subdomain with different IP address - AWS I have an AWS virtual machine, and it's running my CRM system fine. I want to set up a subdomain of my main website to go there instead - so I want www.crm.domain.co.nz to go to a different IP than just www.domain.co.nz
I have added the CRM server's IP address as an a-record of crm.domain.co.nz, but browsing to it gives "403 - forbidden" error, yet browsing to the IP address directly gives normal browsing
What am I doing wrong?
Server: AWS Hosted
OS: Ubuntu 14.04 LTS
CRM: SugarCRM
Thankful for any advice...

A: First check resolving on the PC from which you try to connect B. host crm.domain.co.nz. If you got the IP then is all ok.
Check virtual host directive in Apache.
For example, create a new Apache configuration file named sugar.conf:
touch /etc/apache2/sites-available/sugar.conf
ln -s /etc/apache2/sites-available/sugar.conf /etc/apache2/sites-enabled/sugar.conf
vi /etc/apache2/sites-available/sugar.conf

then, add the following lines:
<VirtualHost *:80>
   ServerAdmin admin@your-domain.com
   DocumentRoot /var/www/html/sugar/
   ServerName your-domain.com
   ServerAlias www.your-domain.com
   <Directory /var/www/html/sugar/>
      Options FollowSymLinks
      AllowOverride All
   </Directory>
   ErrorLog /var/log/apache2/your-domain.com-error_log
   CustomLog /var/log/apache2/your-domain.com-access_log common
</VirtualHost>

You must change your-domain.com with you real domain.
Restart the Apache web server for the changes to take effect:
service apache2 restart

The following files and directories inside the /var/www/html/sugar/ directory need to be writable from your web server:
'config.php'
'config_override.php'
'sugarcrm.log'
'cache' and all subdirectories and files
'custom' and all subdirectories and files
'data' and all subdirectories and files
'modules' and all subdirectories and files

This can easily be accomplished by executing the following command:
chown www-data:www-data -R /var/www/html/sugar/

I guess that you have configured DB for sugar.
Because you have "all" configured, maybe only you can check DocumentRoot in /etc/apache2/sites-enabled
grep -R "DocumentRoot" /etc/apache2/sites-enabled

Output will be something like
sites-enabled/000-default.conf   DocumentRoot /var/www/html

If you do not have your sugar DocumentRoot in output you can change that.


text:
Q: Doing print("Enter text: ", end="") sys.stdin.readline() does not work properly in Python-3 Something weird happened when i did this
import sys

print("Enter text: ", end="")
sys.stdin.readline()

Output:
<input>
Enter text:

(Here, <input> (excluding quotation marks means that input happened on that line))
Why does the code run as though my code was
import sys

sys.stdin.readline()
print("Enter text: ", end="")

(Debian/Ubuntu, Python-3.8.10)
Any reason(s) for this?

A: I think, that stdout hasn't flushed before you enter your input.
Try this
import sys

print("Enter text: ", end="")
sys.stdout.flush()
sys.stdin.readline()

> Enter text: 123

A: When is flushed
This answer explains the reason for flushing as newline:

Normally output to a file or the console is buffered, with text output at least until you print a newline. The flush makes sure that any output that is buffered goes to the destination.

Why this print does not flush
In your statement print("Enter text: ", end="") you neither force the flush, nor print newline - instead end parameter was overridden (default was \n new line). Thus the specified text is printed to buffer only and not yet flushed to console.
How to force flush
Built-in function print() has a parameter named flush which default is False:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
[..]
Whether the output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

See also

*

*How can I flush the output of the print function (unbuffer python output)?

*How to overwrite the previous print to stdout in python?

*What does print()'s `flush` do?

*Delft Stack: Flush Print Output in Python, tutorial


text:
Q: Hashing to Negative Values Pretty much the title: I'm hashing a bunch of names (10000-ish) and some are outputting as negative. (table size is 20011).
The hash function in question is:
public static long hash2 ( String key ){
  int hashVal = 0;
    for( int i = 0; i < key.length(); i++ )
      hashVal = (37 * hashVal) + key.charAt(i);
  return hashVal % 20011;
}

I dug around and I think I have to do something to do with "wrap around." But I don't know how to go about that.

A: This is a clear case of Integer Overflow. As you have mentioned in the question that the String may have upto 10000 characters then the hashValue will definitely overflow because it is needed to store value around 37^10000. Even this will fail in string of length 20.
In number theory,
(A+B)%M = (A%M + B%M) % M;
(A*B)%M = (A%M * B%M) % M;

You should apply modulo operation inside the for loop. However If you do modulo operation at last or in execution of for loop, Both will give the same answer If overflow doesn't happen.
So make changes accordingly,
public static long hash2 ( String key ){
  int hashVal = 0;
    for( int i = 0; i < key.length(); i++ )
    {
      hashVal = (37 * hashVal) + key.charAt(i);
      hashVal%=20011;
    }
  return hashVal;
}

A: hashVal is an Integer. It is most likely that your hash function is causing an Integer overflow.
You can easily resolve this by using Math.abs() to ensure that hashVal is a positive number. e.g.
hashVal = hashVal == Integer.MIN_VALUE ? 0 : Math.abs(hashVal);
return hashVal % 20011;

The mod % is to ensure that the final index computed is within the bounds of the table (i.e. if it's >= 20011, it uses the the remainder of division to as you say 'wrap around').


text:
Q: Is it possible to use System.Net.Mail in a Windows App? I was surprised to not find System.Net.Mail in my Windows App. Is there any way I can use/import that namespace or the SmtpClient class in my Windows App project?

A: No. System.Net.Mail is not available in Windows Store apps. Windows.Store apps can use only the parts of the .Net Framework available in the .Net Framework for Windows Store apps.
Windows Store apps do not have an explicit email API. In most cases you are better off letting the user choose how to share data rather than hard-coding email. For that you can support the sharing contract.
For many other cases (especially feedback forms) you may better off connecting to a dedicated web service rather than detouring through email.
If you do specifically need email then you can launch a mailto: URI.
And if you're writing an email client and specifically need to connect to the mail server then there isn't anything in box so you'll either need to connect to a service specific API (many modern mail services support REST clients) or implement SMTP yourself.


text:
Q: PyQt - PyQtGraph -> QWidget: Must construct a QApplication before a QPaintDevice Currently trying to create a PyQt5 application which embeds a PyQtGraph plot,
I already did it in my Proof of Concept and now try to upgrade it.
I use a GraphicsLayoutWidget to embed my graph into PyQt
But i have an error message :

QWidget: Must construct a QApplication before a QPaintDevice. So i read about it, and it seem that my QApplication isn't created.

But i don't understand, i have my mainWindow running and i try to add the GraphicsLayoutWidget on Button Click event so i don't get why it doesn't work.
This sample is the POC which is working well
if __name__ == "__main__":

# set default pyqtgraph color
pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')

app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)

global LeftPanelContent
LeftPanelContent = QtWidgets.QFrame()
LeftPanelContent.setMinimumSize(QtCore.QSize(200, 0))
LeftPanelContent.setMaximumSize(QtCore.QSize(200, 16777215))
LeftPanelContent.setObjectName("LeftPanelContent")

global PanelInfoPatient
PanelInfoPatient = QtWidgets.QFrame()
PanelInfoPatient.setMinimumSize(QtCore.QSize(250, 0))
PanelInfoPatient.setMaximumSize(QtCore.QSize(350, 16777215))
PanelInfoPatient.setObjectName("PanelInfoPatient")

#ui3 = Ui_MiddlePanel()
#ui3.setupUi(PanelInfoPatient)
ui3 = Ui_Form()
ui3.setupUi(PanelInfoPatient)
ui3.ButtonUpdate.clicked.connect(onUpdatePatientClicked)
ui3.ButtonDelete.clicked.connect(onDeletePatientClicked)

ui2 = Ui_LeftPanelContent()
ui2.setupUi(LeftPanelContent)
ui2.ButtonOrganisation.clicked.connect(showRightPanelCollapsible)
ui2.HideButton.clicked.connect(hideLeftPanels)

PanelRight = QtWidgets.QFrame()
PanelRight.setMinimumSize(QtCore.QSize(700, 0))
PanelRight.setObjectName("PanelRight")

ui4 = Ui_RightPanel()
ui4.setupUi(PanelRight)
ui4.widget_2 = pg.GraphicsLayoutWidget();
ui4.verticalLayout.addWidget(ui4.widget_2)
ui4.ButtonEvent.clicked.connect(onEventClicked);
ui4.ButtonDay.clicked.connect(onDayClicked);
ui4.ButtonWeek.clicked.connect(onWeekClicked);
ui4.ButtonMonth.clicked.connect(onMonthClicked);
ui4.widget_2.hide()

ui.gridLayout_2.addWidget(LeftPanelContent, 0, 0, 1, 1)
ui.gridLayout_2.addWidget(PanelInfoPatient, 0, 1, 1, 1)
ui.gridLayout_2.addWidget(PanelRight,  0, 2, 1, 1)

setMainWindowColor()
#MainWindow.setWindowFlags(QtCore.Qt.FramelessWindowHint)
MainWindow.show()
sys.exit(app.exec_())

Now the new implementation :
Launcher.py :
def launchApp(app):
    appController = ApplicationController()
    appController.showMainWindow()
    return app.exec_()

if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    setLangage()
    result = launchApp(app)
    sys.exit(result)

The MainWindows View :
class MainWindow(QMainWindow, Ui_MainWindow, IMainWindows):

def __init__(self, parent=None):
    super(MainWindow, self).__init__(parent)
    self.setupUi(self)

    self.LeftPanelContent = None
    self.PanelInfoPatient = None
    self.PanelRight = None
    self.collaspedLeftPanel = None

    self.leftPanelUi = None
    self.panelInfoPatientUi = None
    self.rightPanelUi = None
    self.collaspedLeftPanelUi = None
    self.dialog = None
    self.lastDir = None

def guiAssemblage(self):

    pg.setConfigOption('background', 'w')
    pg.setConfigOption('foreground', 'k')

    self.LeftPanelContent = QtWidgets.QFrame()
    self.LeftPanelContent.setMinimumSize(QtCore.QSize(200, 0))
    self.LeftPanelContent.setMaximumSize(QtCore.QSize(200, 16777215))
    self.LeftPanelContent.setObjectName("LeftPanelContent")

    self.PanelInfoPatient = QtWidgets.QFrame()
    self.PanelInfoPatient.setMinimumSize(QtCore.QSize(250, 0))
    self.PanelInfoPatient.setMaximumSize(QtCore.QSize(350, 16777215))
    self.PanelInfoPatient.setObjectName("PanelInfoPatient")

    self.PanelRight = QtWidgets.QFrame()
    self.PanelRight.setMinimumSize(QtCore.QSize(700, 0))
    self.PanelRight.setObjectName("PanelRight")

    self.collaspedLeftPanel = QtWidgets.QFrame()
    self.collaspedLeftPanel.setMinimumSize(QtCore.QSize(75, 0))
    self.collaspedLeftPanel.setMaximumSize(QtCore.QSize(75, 16777215))
    self.collaspedLeftPanel.setObjectName("collaspedLeftPanel")

    self.leftPanelUi = Ui_LeftPanelContent()
    self.leftPanelUi.setupUi(self.LeftPanelContent)

    self.panelInfoPatientUi = Ui_Form()
    self.panelInfoPatientUi.setupUi(self.PanelInfoPatient)

    self.rightPanelUi = Ui_RightPanel()
    self.rightPanelUi.setupUi(self.PanelRight)

    self.collaspedLeftPanelUi = Ui_LeftPanelCollapsed()
    self.collaspedLeftPanelUi.setupUi(self.collaspedLeftPanel)

    self.gridLayout_2.addWidget(self.LeftPanelContent, 0, 0, 1, 1)
    self.gridLayout_2.addWidget(self.PanelInfoPatient, 0, 1, 1, 1)
    self.gridLayout_2.addWidget(self.PanelRight,  0, 2, 1, 1)

    self.dialog = QDialog()
    self.dialog.ui = Ui_popupDelete()
    self.dialog.ui.setupUi(self.dialog)
    self.dialog.setWindowTitle("Suppresion patient")

The controlleur :
class MainWindowController(object):

def __init__(self, appController):
    self.appController = appController
    self.model = None
    self.view = None

def run(self):
    self.view = MainWindow()
    self.view.show()
    self.view.guiAssemblage()

    self.connectSignals()

def createPlot(self):
    self.view.rightPanelUi.ContentRightPanel = pg.GraphicsLayoutWidget();
    self.view.rightPanelUi.verticalLayout.addWidget(self.view.rightPanelUi.ContentRightPanel)
    self.view.rightPanelUi.ContentRightPanel.hide()

def connectSignals(self):
    self.view.leftPanelUi.HideButton.clicked.connect(self.onHideLeftPanelClicked)
    self.view.panelInfoPatientUi.ButtonUpdate.clicked.connect(self.onUpdatePatientClicked)
    self.view.panelInfoPatientUi.ButtonDelete.clicked.connect(self.onDeletePatientClicked)
    self.view.rightPanelUi.ButtonEvent.clicked.connect(self.onEventClicked);
    self.view.rightPanelUi.ButtonDay.clicked.connect(self.onDayClicked);
    self.view.rightPanelUi.ButtonWeek.clicked.connect(self.onWeekClicked);
    self.view.rightPanelUi.ButtonMonth.clicked.connect(self.onMonthClicked);

I Also tried to create the GraphicsLayoutWidget  in the guiAssemblage method but i have the same error
Please what i'm i missing ?

A: So i solved my problem.
my pyqtgraph wasn't up to date.
Do not use the PyPy package it's not up to date.
I upgraded numpy then downloaded and replaced my pyqtgraph module with the GitHub sources.
i also removed PyQt5 / PyQt4 and PySide from my computer then reinstall PyQt5
i tried few solution until this stack :
C:\Users\Nicolas\Desktop\GitRepository\e-servicing\src (master)
λ pip install --upgrade pyqtgraph
Requirement already up-to-date: pyqtgraph in c:\python34\lib\site-packages
Requirement already up-to-date: numpy in c:\python34\lib\site-packages (from pyqtgraph)

C:\Users\Nicolas\Desktop\GitRepository\e-servicing\src (master)
λ python launcher.py
Traceback (most recent call last):
 File "C:\Python34\lib\site-packages\pyqtgraph\Qt.py", line 25, in <module>
import PyQt4
ImportError: No module named 'PyQt4'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Python34\lib\site-packages\pyqtgraph\Qt.py", line 29, in <module>
import PySide
ImportError: No module named 'PySide'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "launcher.py", line 9, in <module>
    import pyqtgraph as pg;
  File "C:\Python34\lib\site-packages\pyqtgraph\__init__.py", line 13, in <module>
from .Qt import QtGui
 File "C:\Python34\lib\site-packages\pyqtgraph\Qt.py", line 32, in <module>
raise Exception("PyQtGraph requires either PyQt4 or PySide; neither package could be imported.")
Exception: PyQtGraph requires either PyQt4 or PySide; neither package could be imported.

just get the PyQtGraph source from github
It worked.


text:
Q: iframe issue with jQuery mobile , frame is reloading I am developing a hybrid application using jQuery mobile and phonegap , In my application I am loading a page that contains an iframe. But what really happening is when I am loading it in the  android emulator the page is loading and the frame is overlapping the page (Kinda second loading),when I click the back button and restarting the app then it will work fine .. I have seen some solutions regarding modifying cordova.plist but it didn't work with me , Can anybody help me?  I am using cordova 2.4.0
Giving my HTML below,  I am getting the output right but the frame is overlapping first time.
<!DOCTYPE html>

<title>My Account</title>
<meta charset="utf-8">
<meta name="viewport"
    content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">

<link rel="stylesheet" href="css/jquery.mobile-1.4.2.min.css">

BANK NAME

Back

ATM
BRANCH
NEAR ME


text:
Q: userscripts for greasemonkey to disable meta refresh html tag (function() {

var allMetas, thisMeta, content, timeout, timeout_ms, url;

timeout = -1;
url = 'none';

allMetas = document.getElementsByTagName('meta');
for (var i = 0; i < allMetas.length; i++) {
    thisMeta = allMetas[i];

    if (thisMeta.httpEquiv.match(/refresh/i)) {
        if (thisMeta.content.match(/[\D]/)) {
            content = thisMeta.content.split(';');
            timeout = content[0];

            url = thisMeta.content.match(/url=['"]?([^'"]+)['"]?$/i);
            url = RegExp.lastParen;
        }
    }
}

if (timeout >= 0) {
    var stopTimer = window.setTimeout("window.stop();", timeout_ms);
    window.addEventListener("load", function() {
        try {
            window.clearTimeout(stopTimer);
        } catch (ex) {}
        window.stop();
    }, true);
}

})();

This user script to use with greasemonkey/tampermonkey writed to disable meta refresh html tag.

*

*works on "htmlcodetutorial.com/document/autoforwardexample.html"

*not works on "moviesvids.blogspot.co.uk/" (onely getting blank page).

Need some help to know what wrong?
Thank you.


text:
Q: i want to update values of one column on the basis of values of other column i want to do it using case when statement......but my code isnt working......want correction i am writing it on sql server express edition,,,,,plz reply with correct sql query and reason for why my code is wrong...
MY CODE IS :-
update originals set LOYAL_TO = case when last_name = 'Mikelson'
then LOYAL_TO = 'KLAUS'

when first_name = 'KOL' then LOYAL_TO = 'NO ONE'

when first_name = 'DAVINA' then LOyal_to = 'MARCEL'

when first_name = 'camille' then loyal_to = 'MARCEL'

when first_name = 'vincent' then loyal_to = 'EVERYONE'

when first_name = 'josh' then loyal_to = 'MARCEL'

when FIRST_NAME = 'JACKSON' then loyal_to = 'HAYLEY'

when FIRST_NAME = 'Hollow' then loyal_to = 'DEMON'

end case from originals;

A: Your syntax is all over the place. Something like this is what you are looking for.
update originals
set LOYAL_TO =
case last_name
    when 'Mikelson' then 'KLAUS'
    when 'KOL' then 'NO ONE'
    when 'DAVINA' then 'MARCEL'
    when 'camille' then 'MARCEL'
    when 'vincent' then 'EVERYONE'
    when 'josh' then 'MARCEL'
    when 'JACKSON' then 'HAYLEY'
    when 'Hollow' then 'DEMON'
end


text:
Q: How to initialize a very long array? I am just trying to initialize a huge array. My code is given below:
#include<iostream>
using namespace std;

int main()
{
    int T;
    cin >> T;
    while (T--)
    {
        int d;
        cin >> d;
        int arr[d + 1];
        for (int i = 0; i <= d; i++)
            arr[i] = 0;
    }
    return 0;
}

Now when I input
1 502334160

then I got error Runtime Error - SIGSEGV.
I want to know how to initialize this type of array.

A: The array may be too big to fit in your program's stack address space. If you allocate the array on the heap you should be fine.
int* arr = new int[d + 1];
But remember that this will require you to delete[] the array. A better solution would be to use std::vector<int> and resize it to d + 1 elements.

A: First: Variable length arrays (VLA) are illegal in C++. It might be an extension (as it is in gcc), but it won't build on all compilers.
Second: You can initialize an array with brace initialization. If you don't specify all elements, the others will get default value of 0 (in case of int). So:
int arr[SIZE] {} //specify 0 elements -> all initialized to value 0

Third thing: you allocate your array on stack, so when you create an array of length 1502334160 than it's stack overflow. This amount of ints (assuming 4 bytes each) is almost 6GB of memory while stack is usually 1-2MB.


text:
Q: Vue + Laravel + tinymce upload image blocked by CORS policy I want to upload images insinde the TinyMCE editor but i has been blocked by CORS policy.
I had setting the CORS on my Laravel project. Other function is OK to get the data from this Laravel project
These are my Javascript settings:
uploadImg(blobInfo, success, failure) {
      let formData = new FormData();
      formData.append("file", blobInfo.blob(), blobInfo.filename());
      this.axios({
        method: "post",
        url: "/test2",
        headers: {
          "Content-Type": "multipart/form-data"
        },
        withCredentials: false,
        data: formData
      }).then(res => {
        console.log(res.data);
      });
    }

These are my CORS settings:
public function handle(Request $request, \Closure $next)
    {
        $this->headers = [
            'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE',
            'Access-Control-Allow-Headers' => $request->header('Access-Control-Request-Headers'),
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Max-Age' => 1728000
        ];

        $this->allow_origin = [
            'http://localhost',
            'http://localhost:8080',
            'http://localhost:8000',
        ];

        $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';

        if (!in_array($origin, $this->allow_origin) && !empty($origin)){
            return new Response('Forbidden', 403);
        }

        if ($request->isMethod('options'))
            return $this->setCorsHeaders(new Response('OK', 200), $origin);

        $response = $next($request);
        $methodVariable = array($response, 'header');

        if (is_callable($methodVariable, false, $callable_name)) {
            return $this->setCorsHeaders($response, $origin);
        }
        return $response;
    }

    /**
     * @param $response
     * @return mixed
     */
    public function setCorsHeaders($response, $origin)
    {
        foreach ($this->headers as $key => $value) {
            $response->header($key, $value);
        }
        if (in_array($origin, $this->allow_origin)) {
            $response->header('Access-Control-Allow-Origin', $origin);
        } else {
            $response->header('Access-Control-Allow-Origin', '');
        }
        return $response;
    }

this is the error message:
error message
Can anyone tell me where did i make a mistake? Thanks

A: You could start Chrome or chromium with cors policy disabled.
This would be helpful for debugging
check this answer on how to do that here
 check ths answer on how to do it in laravel here


text:
Q: How do I implement a yes/no into a text box in VB.net? I am looking for when a button is pressed the user is asked yes or no if they want the button to continue it's function if yes it will, if no it will close the text box and nothing will happen.
Here is my current code (reset button for text fields):
Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click
    txtDistanceInp.Clear()
    txtOwnerInp.Clear()
    txtRegInp.Clear()
    txtSpeedLimitInp.Clear()
    txtTimeInp.Clear()
    txtTimeInp2.Clear()
End Sub

Any help offered is useful, thanks.

A: You can use following approach:
 Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
    Dim result As MessageBoxResult = MessageBox.Show("Do you want to continue?", "test", MessageBoxButton.YesNo)

    If result = MessageBoxResult.Yes Then
        MessageBox.Show("Go Ahead")
    Else
        MessageBox.Show("Dont go")
    End If
End Sub


text:
Q: Can't download file with open bootstrap Modal I have an AngularJS front-end that opens a Bootstrap Modal that has a button on it.  When this button is clicked it calls a Web API method on the server that generates an OPEN XML Word Document as a stream and returns the file to the client.  I have several files downloading successfully in IE where I see this:

However, for the file I'm trying to download with the open Modal I never see the above image.  It's not the file itself because it downloads successfully when I try it without the open Modal.  Also, I don't see any errors reported in IE Dev Tools.  I don't think it's the code that generates the streams because the same code generates other files successfully.  I also tried closing the Modal before downloading but that didn't work either.  It's almost like the Modal is "blocking" the download.
Here is the Modal definition:
    var isOUOModal;
    var isSubmitItem = false;
    var openSignificanceModal = function () {

        return $modal.open({
            scope: $scope,
            templateUrl: './app/oa/significance_modal.html',
            controller: SignificanceModalCtrl,
            keyboard: false,
            backdrop: 'static',
            resolve: {
                item: function () {
                    return $scope.item;
                }
            }
        });
    };

    var SignificanceModalCtrl = function ($scope, $modalInstance, item, $window) {
        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };

     };

I seem to be out of ideas at the moment so any assistance is much appreciated.
Thanks,
Pete

A: I was able to determine the cause of the problem here. It had to do with the way I was calling the Web API Method. I was using an AJAX JQuery GET call. Instead I had to do something like this:
var url = url;
window.location.href = url;

When I changed the way I was calling the Web API method I saw the stream returned to the client as expected.


text:
Q: At which of the following lines does reading data happen in SQLite android? 1    Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null);
2    String password1 = resultSet.getString(1);
3    String password2 = resultSet.getString(1);

Do all the rows get read from DB and stored in resultSet when the 1st line is executed(in other words do 2nd and 3rd lines simply output the already retreived values)?
Or is data that will be stored in password2 read from the database at line 3

A: None of the above.
Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null);

At this point, the query has not been executed. It is stored inside the Cursor.
String password1 = resultSet.getString(1);

At this point, the query is executed. You then crash, as the Cursor is not positioned on a row, because you have not called moveToFirst() or any other moveTo...() method.
String password2 = resultSet.getString(1);

This statement will never be executed, due to the aforementioned crash.
In other words, the query is lazy-executed. Only when you perform an operation on the Cursor that needs the result set will the query actually be executed. This is a pain for multi-threaded development.


text:
Q: Segmentation fault: while simulating tournament branch predictor I have a tournament branch predictor simulation as an assignment. This program simulates the tournament branch predictor in the microprocessors. I guess I did everything right. I cannot trace the problem. I am stuck in segmentation fault.
/* Shreyas Kale Computer Architecture Homework 3 Problem 1 */
/*
 * for global index, at first considered not taken, gi[0] --> MSB
 * 0 --> not taken
 * 1 --> taken
 *
 */
#include<stdio.h>
#include<unistd.h>
#include<strings.h>

struct tables{
char msb;
char lsb;
}local[10],global[64],selector[10];

//6 bits = 64

struct global_index{
    unsigned int i : 6; //bitfield, to index global predictor
}gi = {0};
int pc = 0, correct = 0;
    //here I mean instruction address
char localdec, globaldec, selected;

void initialise()
{
    int i,res;

    for(i=0;i<10;i++)
    {
        local[i].lsb = 'n';
        selector[i].lsb = 'n';
        local[i].msb = 'n';
        selector[i].msb = 'n';
    }
    for(i=0;i<64;i++)
    {
        global[i].lsb = 'n';
        global[i].msb = 'n';
    }
}

void main()
{
    char *sbs, *sbo, *myfile;
    FILE *fd_sbs, *fd_sbo, *fd_myfile;
    char *seq_in, *fout; // for input and output to file
    int g = 0;
    int k = 0, res;

        sbs = "sample_branch_sequence.txt"; //sample branch sequence filename
        sbo = "sample_branch_output.txt"; //sample branch output filename
        myfile = "myout.txt"; // my output filename

    initialise();
    fd_sbs = fopen(sbs,"r");
    fd_sbo = fopen(sbo,"r");
    fd_myfile = fopen(myfile,"a+");

    /* Check whether files are opened */
    if((fd_sbs == NULL) || (fd_sbo == NULL) || (fd_myfile == NULL))
    {
        printf("\n files are not opened properly, bye bye!");
        return;
    }
    /*Actual algorithm*/
    for(k=0;k<10000;k++)
    {
        fgets(seq_in,4,fd_sbs);
        //printf("%s\n",seq_in);
        pc = atoi(seq_in[0]);
        //now branch

        //look up local
        if(local[pc].msb == 'n')
            localdec = 'n';
        else if(local[pc].msb == 't')
            localdec = 't';

        //lookup global
        g = (int)gi.i;
        if(global[g].msb == 'n')
            globaldec = 'n';
        else if(global[g].msb == 't')
            globaldec = 't';

        //look up selector
        if(selector[pc].msb == 'n')
            selected = 'g';
        else if(selector[pc].msb == 't')
            selected = 'l';
        // final decision and program direction updation of output string
        fout[0] = seq_in[0];
        fout[1] = localdec;
        fout[2] = globaldec;
        fout[3] = selected;
        fout[4] = ((selected == 'g') ? globaldec : localdec);
        fout[5] = seq_in[1];
        fout[6] = '\n';
        fout[7] = '\0';
        //put it in file

        //calculate correct predictions
        if(fout[4] == seq_in[1])
            correct += 1;

        res = fputs(fout,fd_myfile);

        if(res == EOF){
            printf("Something erroneous!!");
        }
        //update global counter
        if(seq_in[1] == 't')
        {
            gi.i = gi.i << 1;   //pust a 0 from left
            gi.i += 1;      //add 1 now so, lsb becomes 1
        }
        else if(seq_in[1] == 'n')
        {
            gi.i = gi.i <<1;    //push a 0 from left
        }
        //NOW UPDATION OF THE PREDICTORS
        if(fout[4] == seq_in[1])
        {
            //decision correct update selector accordingly
            if(selected == 'g')
            {
                // decrement slector
                if((selector[pc].lsb == 't')&&(selector[pc].msb == 't'))
                    selector[pc].lsb = 'n';
                else if((selector[pc].lsb == 'n')&&(selector[pc].msb == 't'))
                {
                    selector[pc].msb = 'n';
                    selector[pc].lsb = 't';
                }
                else if((selector[pc].lsb == 't')&&(selector[pc].msb == 'n'))
                    selector[pc].lsb = 'n';
                else if((selector[pc].msb == 'n')&&(selector[pc].lsb == 'n'))   //cant be deremented
                    return;
            }
            else if(selected == 'l')
            {
                //increment selector

                if((selector[pc].lsb == 'n')&&(selector[pc].msb == 'n'))
                    selector[pc].lsb = 't';
                else if((selector[pc].lsb == 't')&&(selector[pc].msb == 'n'))
                {
                    selector[pc].msb = 't';
                    selector[pc].lsb = 'n';
                }
                else if((selector[pc].lsb == 'n')&&(selector[pc].msb == 't'))
                    selector[pc].lsb = 't';
                else if((selector[pc].msb == 't')&&(selector[pc].lsb == 't'))   //cant increment
                    return;
            }
            //now update other tables : local first increment
            if((local[pc].lsb == 'n')&&(local[pc].msb == 'n'))
                local[pc].lsb = 't';
            else if((local[pc].lsb == 't')&&(local[pc].msb == 'n'))
            {
                local[pc].msb = 't';
                local[pc].lsb = 'n';
            }
            else if((local[pc].lsb == 'n')&&(local[pc].msb == 't'))
                local[pc].lsb = 't';
            else if((local[pc].msb == 't')&&(local[pc].lsb == 't')) //cant increment
                return;
            //now update global : increment
            if((global[gi.i].lsb == 'n')&&(global[gi.i].msb == 'n'))
                global[gi.i].lsb = 't';
            else if((global[gi.i].lsb == 't')&&(global[gi.i].msb == 'n'))
            {
                global[gi.i].msb = 't';
                global[gi.i].lsb = 'n';
            }
            else if((global[gi.i].lsb == 'n')&&(global[gi.i].msb == 't'))
                global[gi.i].lsb = 't';
            else if((global[gi.i].msb == 't')&&(global[gi.i].lsb == 't'))   //cant increment
                return;
        }
        else if(fout[4] != seq_in[1])   //wrong decision
        {
            //decrement local and global
            if((local[pc].lsb == 't')&&(local[pc].msb == 'n'))
                local[pc].lsb = 'n';
            else if((local[pc].lsb == 'n')&&(local[pc].msb == 't'))
            {
                local[pc].msb = 'n';
                local[pc].lsb = 't';
            }
            else if((local[pc].lsb == 't')&&(local[pc].msb == 'n'))
                local[pc].lsb = 'n';
            else if((local[pc].msb == 'n')&&(local[pc].lsb == 'n')) //cant decremet
                return;
            //now update global : decrement
            if((global[gi.i].lsb == 't')&&(global[gi.i].msb == 'n'))
                global[gi.i].lsb = 'n';
            else if((global[gi.i].lsb == 'n')&&(global[gi.i].msb == 't'))
            {
                global[gi.i].msb = 'n';
                global[gi.i].lsb = 't';
            }
            else if((global[gi.i].lsb == 't')&&(global[gi.i].msb == 'n'))
                global[gi.i].lsb = 'n';
            else if((global[gi.i].msb == 'n')&&(global[gi.i].lsb == 'n'))   //cant decrement
                return;

        }
    }

}

</code></pre>

A: You have seq_in as
char * seq_in;

To be used later in a fgets call.  Your variable must have its memory allocated properly or you program will raise a segmentation fault.  You can solve this issue:
char seq_in[200];  /* or the size you want */

Or
char * seq_in = malloc (200, sizeof(char));  /* or the size you want */

Same issue happens with your fout variable.


text:
Q: Visual Basic - how to force event to fire I'm new to VB (using VBA, actually) and I would like to force an event to fire.  Specifically, I am updating the value in a textbox and I would like to call that textbox's AfterUpdate() event.
Private Sub cmdCreateInvoice_Click()
  Me.txtInvDate = '11/01/10'
  Me.txtInvDate.AfterUpdate
End Sub

During run time, I get an error that says "Compile Error: Invalid Use of Property".  If I try something similar, but with the click event (ex: cmdCreateInvoice.Click), which does NOT have a property that shares the name, I get an error that says "Compile Error: Method or Data member not found".
I know there must be a way to fire one event from another.  But what is the proper syntax?
Thanks!

A: Call

txtInvDate_AfterUpdate()

A: AFAIK, there is no way to "fire an event manually" in VB(A). What you can do is call the event handler manually, and for this, rdkleine has given you the answer already:
Call txtInvDate_AfterUpdate()

This will have exactly the same effect as if the event had fired (though it does not give you the whole chain of events that may also fire along with it--unless you Call their handlers as well).
IgorM has another valid point, in comments on his answer--it's "cleaner" to write a different Sub to do the work you want done, then call it from both the event handler & wherever you're trying to do it now (button click?). So:
Private Sub txtInvDate_AfterUpdate()
    DoWhatever
End Sub

Private Sub button_Click()
    DoWhatever
End Sub

Private Sub DoWhatever
    'your desired effect
End Sub

You could even make DoWhatever a Public Sub in a Module.
Edit
And no, in VB(A) it doesn't matter what order you define your Sub (or Function) routines.

A: Try to use something like this:
Private Sub TextBox1_LostFocus()
  TextBox1.Value = "5"
End Sub

Use LostFocus event if you change value manually.
Or you can use another way:
Private Sub CommandButton1_Click()
   TextBox1.Value = "new value"
End Sub

Private Sub TextBox1_Change()
   MsgBox TextBox1.Value
End Sub

Try to use Change event.

A: Some code apparently will (regretfully) force events to fire:
    Me.Dirty = False

forces BeforeUpdate and AfterUpdate to fire, as I understand it. There are probably more cases too. Any secret hooks which attach to your code in that manner reflect bad design in my view and will inevitably lead to inadvertant & frustrating loops being created.

A: Is there a way to keep a textboxes event firing until I click on another text box? I'm needing to stay "in" the text box which has Do While loop for a selection. Once the selection is made, I want the user to be able to replace the selection without having to click on the text box again. If the user is satisfied with the select, they can click on a different text box.


text:
Q: Error attaching to process: sun.jvm.hotspot.debugger.DebuggerException: cannot open binary file When I use jmap to get the heap info about a process, I got error like that:
$jmap -heap process_id

Attaching to process ID process_id, please wait...
Error attaching to process: sun.jvm.hotspot.debugger.DebuggerException: cannot open binary
file
sun.jvm.hotspot.debugger.DebuggerException: sun.jvm.hotspot.debugger.DebuggerException:
cannot open binary file

OS: Ubuntu 14.04
I have solved another error (DebuggerException: Can't attach to the process) by updating kernel.yama.ptrace_scope = 0.
See: https://bugs.openjdk.java.net/browse/JDK-7050524

A: This will also happen if you attempt to attach to an ineligible process so it's a good idea to reconfirm your pid.
For example, a friend of mine got this when they attempted to attach to the jps process they used to search for eligible pids ;).

A: I faced the same issue, however when I su'd to the correct user having the relevant permissions the issue went away.

A: In our case, the java process was using .../JAVA_HOME/jre/bin/java binary and the jmap process was using .../JAVA_HOME/bin/jmap binary.
Once we changed java process to use .../JAVA_HOME/bin/java binary, then the issue got resolved. We were able to run the jmap successfully.
Key is to use run the java process using JDK java binary instead of JRE java binary.

A: Not directly related to the question asked. But, I encountered a similar error while using the jstack command while taking the thread dump of a java process. Let's say the pid of the java process for which I wanted thread dump is 1234.
I had used the command jstack -l 1234 /home/users/a/thread-dump.txt
What I missed in the above command is the redirection operator(>). The correct version of the command is
jstack -l 1234  > /home/users/a/thread-dump.txt

Maybe it helps someone :)

A: I had the same issue with jstack. It turned out that I wasn't using Oracle JRE but OpenJDK as runtime for the process, but had only Oracle's JDK installed. Oracle's jstack cannot access an OpenJDK process. See also Does OpenJDK have a tool similar to jstack (Oracle Java)?


text:
Q: BSD has 58 more builtins I read the builtins from bsd builtin(1) and gnu version from Ubuntu Manpage: bash-builtins - bash built-in commands, see bash(1)
In [25]: print(bsd_bins)
['!', '%', '.', ':', '@', '{', '}', 'alias', 'alloc', 'bg', 'bind', 'bindkey', 'break', 'breaksw', 'builtins', 'case', 'cd', 'chdir', 'command', 'complete', 'continue', 'default', 'dirs', 'do', 'done', 'echo', 'echotc', 'elif', 'else', 'end', 'endif', 'endsw', 'esac', 'eval', 'exec', 'exit', 'export', 'false', 'fc', 'fg', 'filetest', 'fi', 'for', 'foreach', 'getopts', 'glob', 'goto', 'hash', 'hashstat', 'history', 'hup', 'if', 'jobid', 'jobs', 'kill', 'limit', 'local', 'log', 'login', 'logout', 'ls-F', 'nice', 'nohup', 'notify', 'onintr', 'popd', 'printenv', 'pushd', 'pwd', 'read', 'readonly', 'rehash', 'repeat', 'return', 'sched', 'set', 'setenv', 'settc', 'setty', 'setvar', 'shift', 'source', 'stop', 'suspend', 'switch', 'telltc', 'test', 'then', 'time', 'times', 'trap', 'true', 'type', 'ulimit', 'umask', 'unalias', 'uncomplete', 'unhash', 'unlimit', 'unset', 'unsetenv', 'until', 'wait', 'where', 'which', 'while']

In [26]: print(gnu_bins)
[':', '.', '[', 'alias', 'bg', 'bind', 'break', 'builtin', 'case', 'cd', 'command', 'compgen', 'complete', 'continue', 'declare', 'dirs', 'disown', 'echo', 'enable', 'eval', 'exec', 'exit', 'export', 'fc', 'fg', 'getopts', 'hash', 'help', 'history', 'if', 'jobs', 'kill', 'let', 'local', 'logout', 'popd', 'printf', 'pushd', 'pwd', 'read', 'readonly', 'return', 'set', 'shift', 'shopt', 'source', 'suspend', 'test', 'times', 'trap', 'type', 'typeset', 'ulimit', 'umask', 'unalias', 'unset', 'until', 'wait', 'while']

In [32]: len(set(bsd_bins) - set(gnu_bins))
Out[32]: 58

In [28]: print(set(bsd_bins) - set(gnu_bins))
{'elif', 'end', 'setenv', 'login', 'nohup', 'done', 'glob', 'notify', 'echotc', 'alloc', 'then', 'which', 'endsw', 'stop', 'switch', 'default', 'builtins', 'false', 'setty', 'printenv', '@', 'uncomplete', 'fi', 'do', 'nice', 'bindkey', 'ls-F', 'unhash', '!', 'unlimit', 'limit', 'foreach', 'hup', 'telltc', 'log', 'where', 'jobid', 'repeat', 'unsetenv', 'chdir', 'settc', 'setvar', '%', 'filetest', 'sched', 'endif', 'goto', 'hashstat', 'rehash', 'breaksw', 'onintr', 'for', '}', '{', 'time', 'true', 'else', 'esac'}

BSD has 58 more builtins, what's the cause of the difference?

A: To quote from bsd builtins link you referenced:

Only builtin commands for the csh(1) and sh(1) shells are listed here.

IIRC /bin/sh on FreeBSD is ash. So the page you reference contains built-in commands for two shells. The Ubuntu page you reference contains only one shell's -  bash - built-ins.


text:
Q: No JsonAdapter for java.util.LinkedHashMap using moshi Running this code
val itemsInCart = viewModelScope.async {
    cartItemRepository = CartItemRepository()
    cartItemRepository?.getItemsInCartBySellerSuspend(email, sellerPK)
}
val setItems = arrayListOf<JSONObject>()
val getItemsInCart = itemsInCart.await()
if (getItemsInCart != null) {
    for (items in getItemsInCart){
        val newCartItem = CartItem()
        newCartItem.id = items.id
        newCartItem.email = items.email
        newCartItem.productId = items.productId
        setItems.add(newCartItem.toJSON())
    }
}

val params = HashMap<String, Any>()
params["PK"] = userPK
params["items"] = setItems
val getSubmitStatus = EarthlingsApi.retrofitService.userOrderSubmit(params)

will throw the error No JsonAdapter for java.util.LinkedHashMap<java.lang.String, java.lang.Object>, you should probably use Map instead of LinkedHashMap (Moshi only supports the collection interfaces by default) or else register a custom JsonAdapter.
Here's how I build my Moshi and Retrofit
private val moshi = Moshi.Builder()
    .add(LinkedHashMapAdapter())
    .add(BigDecimalAdapter)
    .add(KotlinJsonAdapterFactory())
    .build()
private val retrofit = Retrofit.Builder()
    .addConverterFactory(ScalarsConverterFactory.create())
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .addCallAdapterFactory(NetworkResponseAdapterFactory())
    .baseUrl(BASE_URL)
    .client(client)
    .build()

@POST("/user/order/submit")
suspend fun userOrderSubmit(@Body params: Map<String, Any>?): NetworkResponse<OrderSubmitResponse, ErrorResponse>

As you can see, I have already created the LinkedHashMapAdapter (below is the code), but it will still return the above error. So either I made something wrong in my LinkedHashMapAdapter code below or somewhere else
class LinkedHashMapAdapter {
    @ToJson
    fun arrayListToLinkedHashMap(list: LinkedHashMap<String,Any>): LinkedHashMap<String,Any> = list

    @FromJson
    fun arrayListFromLinkedHashMap(list: LinkedHashMap<String,Any>): LinkedHashMap<String,Any> = list
}


text:
Q: How many endings does Cultist Simulator have? I recently started playing Cultist Simulator and I got the "Evening falls" ending. How many endings does the game have in total?

A: Right now there are around five possible endings, I believe. There are also four legacies. There are plans to add in additional endings and legacies in future DLC (which you will get for free if you bought the Perpetual Edition, which if you bought the game today you certainly have). And there are different ways of getting the three main endings, depending on your cult choices, expedition results, and mistakes.


text:
Q: Are Riemann surfaces toric? For a smooth toric projective variety $X$, I'm able to use the result
$H^0(X,\mathcal{O}(D)) \cong \bigoplus_{m \in \Delta_D \cap M} \mathbb{C}\cdot \chi^m$
to understand global sections of a given sheaf on $X$, subject to the choice of a torus-invariant divisor $D = \sum_{\rho\in \Sigma(1)} a_\rho D_\rho$, based on the corresponding polytope $\Delta_D = \{m\in M\text{ }|\text{ }\left<m,u_\rho\right>\geq -a_i\}$ for $u_\rho$ a primitive ray generator of $\rho\in \Sigma(1)$.
This helps me understand $H^0(\mathbb{P}^n, \mathcal{O}(D))$ for instance, for a given $D$.
If we identify $\mathbb{P}^1_\mathbb{C}$ with a genus 0 Riemann surface, then I can understand global sections of a genus 0 Riemann surface via this correspondence with a toric variety. I am wondering: Are any positive genus Riemann surfaces toric, so that I can understand the global sections of a given sheaf in the same way? If they are not toric, why are they not toric?


text:
Q: grep files with pattern A but exclude files with pattern B I want to grep files which include pattern A (iwant) but I want to exclude files which contain pattern B (idontwant).
Example:
read -p "...what are you looking for: " iwant
read -p "...what should not be included: " idontwant

iwant="blue car"
idontwant="red car"

Just assume I have the following files:
-rw-rw-r--.  1 terpentin terpentin  45 Jun  8 16:04 blue.car
-rw-rw-r--.  1 terpentin terpentin  44 Jun  8 16:05 mixed.car
-rw-rw-r--.  1 terpentin terpentin  40 Jun  8 16:04 red.car

find . -type f -print -exec cat {} \;

./mixed.car
blue car
red car
blue car

./red.car
red car
red car
red car

./blue.car
blue car
blue car
blue car

How is it possible to get only the file "./blue.car" as a result?
The original content includes hundreds of long text files, which makes it important to be as resource-efficient as possible.

A: Use
find . -type f ! -exec grep -q "$idontwant" {} ';' -exec grep -q "$iwant" {} ';' -print

or
find . -type f -exec grep -q "$iwant" {} ';' ! -exec grep -q "$idontwant" {} ';' -print

*

*The terms (sometimes called "predicates") in a find
command are characterized as tests (e.g., -type f)
and actions (e.g., -print and -delete).
It might be hard to figure out from the man page
that -exec is both an action and a test.
So, just asfind . -type f -mtime -30 -name '*.txt' -readable -size +5 test6 test7 test8 …
successively narrows the search to files that meet all the criteria
(satisfy all the specified tests), sofind . -exec cmd1 {} ';' -exec cmd2 {} ';' -exec cmd3 {} ';' …
finds files for which all the commands succeed.

*Any find test can be negated (inverted) by preceding it with !.
So find . ! -type d finds plain files, symbolic links, named pipes, sockets, and device files — everything except directories.

*Note that ! -exec grep … is not equivalent to -exec grep -v ….
-exec grep -v … will find files
that have at least one line that doesn't match.
! -exec grep … will find files where no lines match.

*The -q option to grep is officially a synonym for --quiet,
but it also means quick.
It writes no output (except perhaps for error messages, as applicable),
but also it exits as soon as it finds a match —
it doesn't read every file to the end to find every match.
(Of course, if a file doesn't contain any matches,
then grep must read it in its entirety to determine that.)

*So (TL;DR) the commands find the files for which
grep -q "$iwant"     filesucceeds and
grep -q "$idontwant" filefails
(because we preceded it with !).

*The two commands are functionally equivalent,
but may have different performance
(i.e., may take different amounts of time to run).
If only a few files contain the search strings,find . -type f -exec grep -q "$iwant" {} ';' ! -exec grep -q "$idontwant" {} ';' –print
will be faster,
because the grep "$iwant" will eliminate most of the files.
If many of the files contain both strings, thenfind . -type f ! -exec grep -q "$idontwant" {} ';' -exec grep -q "$iwant" {} ';' –print
will be faster,
because the ! grep "$idontwant" will eliminate most of the files.

A: With GNU grep we can perform the filename extraction with a judicious choice of regex and grep options:
$ grep -lzPsr '(?s:(?=.*blue)(?!.*red))' .

We are operating grep in slurp mode (-z) wherein the whole file is treated as one big line.
The -l will list the filenames of file(s) matching the regex.
The -r will run recursively on all files in current dir nd below.
The -s will silence the grep to not emit any warnings.
The regex will look for the presence of blue and absence of red in a file for it to say yes.
The -P invokes the Perl regex engine in grep so that we can get the advantage of pcre regexes.


text:
Q: Phonegap, Lawnchair and Cookie in Android I'm using Lawnchair with in my Android Phonegap App. For most of my users, Lawnchair works well. But for some reasons, some of my users say that the settings are not saved (i use Lawnchair with DOM Adapter to save settings). Are there any other adapters that i can use with phonegap for Android? I saw Cookie Adapter but it is for the previous version of Lawnchair
Thanks

A: There are many adapters in lawnchair to store stuff.
http://westcoastlogic.com/lawnchair/adapters/

The way lawnchair works is, if an adapter is specified, it will use that, or if no adapter is specified and if the code of all adapters is appended to lawnchair.js file, then lawnchair checks which one to use in the order of they are appended and picks the first one it finds suitable.
Moreover the dom adapter works fine for my android app. Update your code to the latest lawnchair on github. So i guess the problem could be somewhere else too, maybe the data u are storing. Check out.


text:
Q: List of resources not used on Slurm? Is it possible to show the list of nodes that are not used by any jobs as well as the resources availaible (number of CPUs, momory) ?
Thx

A: Yes, this is possible with the sinfo command.
What I like to use is for example:
$ sinfo -O cpusstate
CPUS(A/I/O/T)
0/4/0/4

It prints the amount of total CPUs and shows which are currently allocated, idle or in other state.
You have also options for memory (e.g. sinfo -O freemem) and other metrics, visit the official documentation about sinfo for a full list.


text:
Q: I want to divorce vs I want divorce Is there a difference between

I want divorce

and

I want to divorce.

And concerning the second one should I rather say

I want to divorce my wife

And is "to divorce" A verb here or  or object of the verb "want"?

A: Divorce can be either a noun or a verb.
In your first sentence, it is used as a noun, but it needs an indefinite article.

I want a divorce.

In the second sentence, to divorce is a verb form, an infinitive, but it is used as a noun phrase.
Because divorce is almost always transitive, it almost always needs an object. Your alternative suggestion. I want to divorce my wife would sound much more natural than I want to divorce.  However, the latter would not be wrong, especially if the context made it clear, but would sound stilted.

A: You would say

I want to divorce my wife.

and

I want a divorce from my wife.

Here, in the first example "divorce" is a verb (thus the infinitive) and the second is a noun (thus the indefinite article).

A: Nothing wrong with both the sentences, but "I want to Divorce", sounds more correct to use.


text:
Q: UnboundLocalError: local variable 'ix' referenced before assignment I tried to run dis code (its a little game and now im adding the graphics but it gives me the 'UnboundLocalError:' and i dont realy know what im doing wrong
from graphics import *

import time

import random

a = 5

c = 0

ix = 1001

x = 2

def main():

while int(ix) != int(a):

win = GraphWin('Game', 500, 500)
shape = Rectangle(Point(499,499), Point(0,0))
shape.setOutline("red")
shape.draw(win)

shape = Rectangle(Point(200, 100), Point(300, 0))
shape.setOutline("black")
shape.draw(win)

    input = Entry(Point(250, 450), 10)
    input.draw(win)

    win.getMouse()

    ix = input.getText()
    testText = Text(Point(250, 50), ix)
    testText.draw(win)
    time.sleep(1)
    testText.setText('')
main()

As result i expect a loop in the graphic window where when the input ix = a the loop ends.

A: The problem is that ix is a local variable in your main() function that shadows your global ix defined outside main(). To fix it you have several options:

*

*Define ix inside main()

*Make ix global with global ix

*Pass ix to the function as parameter: main(ix)

*Remove the main() function entirely and just put everything to the global scope


text:
Q: Set strikeout for specific value only in Crystal Report I am sorry before if the title is not too descriptive.
My goal is to create report like this (ignore the red line):
sample
In the Height (m) field, I create formula in the Formula Fields to check two values of height.
If IsNull({stored.RevisedHeight}) or {stored.RevisedHeight} = "" then
    {stored.Height}
Else
    {stored.Height} + ChrW(13) + {stored.RevisedHeight}

I need to set strikeout style for value {stored.Height} only in the Else condition.
Thanks in advance.

A: Use
If IsNull({stored.RevisedHeight}) or {stored.RevisedHeight} = "" then
    {stored.Height}
Else
    "<Strike>" + {stored.Height} + "</Strike>" + ChrW(13) + {stored.RevisedHeight}

Right-click the formula object on the report canvas,
Format Field...  select Paragraph tab, set Text Interpretation option to 'HTML Text'.


text:
Q: Ruby delete keys from hash only while printing without modifying the hash I am a newbie to ruby. I am trying to delete keys which are passwords from the hash while printing the hash, with/without modifying the original hash
 request = {"name"=>"test-2",
            "dns_zone_status"=>"valid",
            "certificate_status"=>"valid",
            "db_password"=>"GS*8qLiU",
            "af_pass"=>"rk*pp2",
            "master_password"=>"sfvrere",
            "db_user"=>"testuser2"}
puts "request : #{request}"
puts "request : #{request.except("db_password","af_pass","master_password")}"

The first puts print the whole hash and the 2nd one errors undefined method 'except' for #<Hash:0x00000001dbcd00> (NoMethodError)

A: Use Hash#reject, which is non-destructive and returns a hash.
puts "request : #{
  request.reject do |k,_|
    ["db_password","af_pass","master_password"].include?(k)
  end
}"
#request : {"name"=>"test-2", "dns_zone_status"=>"valid", "certificate_status"=>"valid", "db_user"=>"testuser2"}

As is commonly done, I've used an underscore for the block variable holding the value associated with the key k to tell the reader that it is not used in the block calculation.

A: Instead of having to bring all of ActiveSupport in as a dependency (which is the gem implementing Hash#except, if you don't need it in other ways you can just inline this tiny method as:
puts "request : #{request.slice(*request.keys - ["db_password","af_pass","master_password"])}"

A: The Hash#except method actually comes from ActiveSupport, which is loaded by default in Rails but not in standalone Ruby.
However, that's easily remedied, all you have to is add the activesupport gem and one of the following requires:
# require everything in active support, the easy/lazy option
# this is what rails does and it's probably fine to do
# unless you really, really care about how much memory you use
require 'active_support/all'

# require only the hash extensions
require 'active_support/core_ext/hash'

# require only this one specific method
require 'active_support/core_ext/hash/except'

Note that the name of the gem (activesupport) and the library you require (active_support) are indeed named differently, which can be a little tricky to remember.


text:
Q: React - Expected an assignment or function call I'm new with reactjs and I got a little problem. I'm getting an error: Expect an assignment or function call.
Is referring to the User function, but I do call that function below when I'm creating a new object.
How can I fix this?
import React from 'react';
import '../css/style.css';

export function Form(){

    let users = [];

    function User(name, surname, age, email, password){
        this.name = name;
        this.surname = surname,
        this.age = age,
        this.email = email,
        this.password = password
    }

    function formValues(){
        let name = document.getElementById("name").value;
        let surname = document.getElementById("surname").value;
        let age = document.getElementById("age").value;
        let email = document.getElementById("email").value;
        let pwd = document.getElementById("password").value;

        var newUser = new User(name, surname,age, email, pwd);

        users.push(newUser);
        console.log(users);
    }

    return(

Sign up today, for free!

            <input type="text" id = "name" placeholder = "Name" required/>
            <input type="text" id = "surname" placeholder = "Surname" required/>
            <input type="number" id = "age" placeholder = "Age" required />
            <input type="email" id = "email" placeholder = "Email" required/>
            <input type="password" id = "password" placeholder = "Password" required/>
            <button id = "sign-up" onClick={() => formValues()}>Sign Up</button>

    )
}

A: Your function isn't using semi-colons to end the expressions.
function User(name, surname, age, email, password) {
  this.name = name;
  this.surname = surname;
  this.age = age;
  this.email = email;
  this.password = password;
}


text:
Q: OpenCL RT errors in kernel How can i find out about the runtime error in kernel code.
For example A[0] == 0:
__kernel void eval(__global float* A, __global float* C) {

    C[0] = 3/A[0];

}

After evaluating C[0] == 3
I tried -Werrer like parameter for clBuildProgram, but he finds error only at compilation stage(C[0] = 3/0 -> 1 error generated: division by zero is undefined)

A: Unfortunately there is no way to have OpenCL serve you runtime errors such as division by zero on a silver platter. A division like 3.0f/A[0] is a perfectly valid operation. It is up to the user to ensure, through algorithm design, that the input A[0] is never zero. For large kernels, this may not be trivial. And if this cannot be ensured, you have to check the results for Inf/NaN and manually throw the error. Alternatively, if A>=0 is distance and A!=0 cannot be ensured, a common trick is to add a tolerance value in the division: 3.0f/(A[0]+1E-9f)
Same with array out of bounds exception: there is no runtime error, but in this case it's likely that the application will crash. You have to make sure by algorithm design that the array index is always valid.


text:
Q: Compile error when using lambda functions in the header file I've seen a (weird) compile error in my code when trying to learn and use lambda functions. I've spent some time debugging it but still don't know what's wrong. So I have a header file named config.h, which is like
namespace config {
    ...
    const int kNumPeriodsPerMove = [&] () {
        const double time_nbr_disc = kSizeSlotHello * kNumSlotsHelloPerNbrDisc;
        const double time_data_tx = kSizeSlotData * kNumSlotsDataPerDataTx;
        const double time_epoch = time_nbr_disc + time_data_tx;
        const int num_periods_per_move = ceil(kTimeBtwMoves / time_epoch);
        return num_periods_per_move;
    };
    ...
}

where variables in the form of k* like kSizeSlotHello are all const variables that have been defined before and also within config. When I compile I have the error messages:
config.h:183:5: error: invalid user-defined conversion from 'config::<lambda()>' to 'int' [-fpermissive]
 };
 ^
config.h:175:41: note: candidate is: config::<lambda()>::operator int (*)()() const <near match>
const int kNumPeriodsPerMove = [&] () {
                                     ^
config.h:175:41: note:   no known conversion from 'int (*)()' to 'int'

I also used lambda functions in other places like const int kNumSlots = [&] (double (*f)(double)) {...} (f); which does not have any compile error. I'm very curious about what the problem is. Thanks.

A: By doing that:
const int kNumPeriodsPerMove = [&] () {
    // your code here
    return num_periods_per_move;
};

You are not actually executing it.
Instead, you are creating a lambda function instance that cannot be converted to int.
So, the error is meaningful.
Instead, you should have:
auto fn = [&] () {
    // your code here
    return num_periods_per_move;
};

int kNumPeriodsPerMove = fn();

Or even that (more concise):
int kNumPeriodsPerMove = ([&] () {
    // your code here
    return num_periods_per_move;
})();

That said, one could argue about the fact that to use the lambda this way does not make much sense and you should maybe revise that part of code.


text:
Q: Save multiple copy of form - Orbeon Is it possible in Orbeon Form Builder to store the multiple copy of same form?
For example I have create one form with 10 fields and also I need another form with 1 more additional field. I want use the copy of existing so that I can add another field and save it.
Thanks
Pradeep Bansal

A: At this point, there is no "save as…" or "create copy of this form" capability in Form Builder. You can simulate this by:

*

*Opening the form you would like to make a copy of, clicking on Edit Source, copying the source of the form.

*Creating a new form, choosing a new app name / form name, again going to Edit Source, and pasting the source you copied.

*Pasting the source will change the app name / form name of your form to be the one of the original form, so after pasting the source, go to Metadata / Edit Metadata and reset the app name / form name.

This technique does not copy attachments you might have to your form, so if you have attachments you also need to reattach them to the target form.


text:
Q: How to automate drag and drop and click in Canvas Element using Selenium Webdriver? I have to create automated tests for automating click and drag and drop in Html canvas.

A: This documentation about Advanced User Actions might be useful.

A: Well long story short we can do this using Actions class. Below code should get you started.
Actions act = new Actions(driver);
act.dragAndDrop(fromLocation, toLocation).perform();

Just ensure both fromLocation and toLocation are webelements. Cheers

A:   Actions act=new Actions(driver);
  act.DragAndDrop(webElement_Source, webElement_Target)).Build().Perform();


text:
Q: React Native FlatList onViewableItemsChanged callback encounter error after state changed rerender I need to set the state to detect which item in the current viewport is visible. for this purpose, I write below code:
const [inViewPort, setInViewPort] = useState(0);

const viewabilityConfig = {
  viewAreaCoveragePercentThreshold: 30,
};

const onViewableItemsChanged = ({viewableItems, changed}) => {
  if (changed && changed.length > 0) {
    setInViewPort(changed[0].index);
  }
};

return (
  <SafeAreaView style={styles.container}>
    <FlatList
      data={myData}
      renderItem={renderItem}
      showsHorizontalScrollIndicator={false}
      keyExtractor={(_, index) => index.toString()}
      horizontal={true}
      onViewableItemsChanged={onViewableItemsChanged}
      viewabilityConfig={viewabilityConfig}
    />
  </SafeAreaView>
);

The onViewableItemsChanged event callback triggers correctly but after I call setInViewPort so the component updated and it rerendered the below error encounter:

Invariant Violation: Changing onViewableItemsChanged on the fly is not supported

A: I was looking for the same answer and there is no clear example anywhere. This is how I solved it.
const [inViewPort, setInViewPort] = useState(0)

const viewabilityConfig = useRef({
  itemVisiblePercentThreshold: 50,
  waitForInteraction: true,
  minimumViewTime: 5,
})

const onViewableItemsChanged = React.useRef(({ viewableItems, changed }) => {
  if (changed && changed.length > 0) {
    setInViewPort(changed[0].index);
  }
})

return (
  <SafeAreaView style={styles.container}>
    <FlatList
      data={myData}
      renderItem={renderItem}
      showsHorizontalScrollIndicator={false}
      keyExtractor={(_, index) => index.toString()}
      horizontal={true}
      onViewableItemsChanged={onViewableItemsChanged.current}
      viewabilityConfig={viewabilityConfig.current}
    />
  </SafeAreaView>
)


text:
Q: how to store the values passed by html form as it is into mysql DB? i wonder how to store the values passed by html form as it is interms of format into mysql table. can anyone help me.
let me clear my question.
when the user enter his address in the text area like,
no:14,cross cut road,

XXX nagar,

Tamilnadu,

india.

and when this value is passed from a form and stored in mysql table, it'll displayed in a single line when i retrieved it in the next time, like
no:14,cross cut road,XXX nagar,Tamilnadu,india.

but i want to display it like the previous one like how they enter, in the same format.
can anyone help how to do this???
thanks in advance.
i've no idea to use any web editors. so i tried n2lbr function and got the same format. New line problem solved but now am facing the space problem. if i leave 10  spaces and wrote a text, it'll display the text only.. not the spaces. how to solve this??

A: You should use a wysiwyg editor like ckeditor.

A: Use
mysql_real_escape_string doesn't remove line breaks, it escapes them.

While displaying use
 nl2br for adding those line breaks.

A: when you press enter in the text area the '\n' character is appended to your text and this character is stored in DB but when you read from the DB and want to visualize your text, you should consider that your component recognize the '\n' character, if it doesn't recognize newline character (i.e. '\n') then you should replace '\n' with html break (i.e. br) tag to show the new line in html.


text:
Q: Running a local Yii2 server with WAMP I am a frontend JS dev and I've begun working on a project that has a PHP backend running with Yii2 framework. The project came with no setup instructions so I'm trying to figure it out as I go, but coming from Node.js... it's pretty confusing.
I downloaded and installed WAMP, created the MySQL DB for the API using MyPHPAdmin, and imported the data from a dump. That worked and I can see the tables and data. Now when I go to localhost I see that WAMP is running. I tried the sample Yii project and that also runs at localhost/yii-test/web.
According to Yii I am to serve this API by moving this entire API directory to the /www directory of the WAMP install. Now if I go to localhost/fania-api I see the directory listing for my server. To me this says that the API is accessible locally.
I have configured the .env of my frontend to point to localhost/fania-api, but when I send any request I get a CORS error, which I am assuming is masking some 404 or 500 error. Now the funny thing is the .env I was given comes with the URL http://fanintelligence.localhost, not the Yii given localhost/fania-api.
So my question is how do these two things fit together? I installed WAMP and setup the MySQL DB at the default port, but how does my API know it's there? How can I know if it's the right port? And what about these two different URLs, how do they match up?
Also the API does not contain a /web folder, not sure if that is an issue or not but I couldn't serve it with php yii serve either. If this was a Node.js server I'd clone, npm install and npm run start which would probably do something like build and serve. I can't believe this is so difficult to setup in comparison.
Any advice or help is greatly appreciated!
EDIT: When I try to reach my server from the frontend at either address I get:
Access to fetch at 'http://localhost/fania-api/oauth2/token?accessToken=undefined' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
/fania-api/oauth2/token?accessToken=undefined:1 Failed to load resource: net::ERR_FAILED
However I do not believe this is an actual CORS error as the previous developer also used the local to test, so the CORS policy will allow for this. My guess is the address I'm pointing to is incorrect or the server is not actually live.
If I try to run php yii serve:
Document root "C:\Users\hesel\dev\repo\eartotheground\fania-api\console/web" doe
s not exist.
But the crux of the erroneous behaviour is the inability to connect to a supposedly live local server (is it even live? how can I tell?).

A: *

*If yii is installed via composer, go to the project,open the terminal and run ./yii serve

*If yii has been downloaded as an archive file:
open terminal/cmd prompt in the folder of the project and
type composer install to ensure all packages in vendor are installed.
got to config/web.php
'request' => [
        'cookieValidationKey' => 'put your random generated string',
],
Access the application via http://localhost/basic/web/
NB: try xammp  for php local development you wont regret

A: I got it working. For hosting with WAMP:

*

*Place entire server code folder in www/ (in WAMP install dir)

*Edit wamp64\bin\apache\apache{version}\conf\httpd.conf:
DocumentRoot "${INSTALL_DIR}/www/{your project}/{optional public folder}"
<Directory "${INSTALL_DIR}/www/{your project}/{optional public folder}">

*Edit wamp64\bin\apache\apache{version}\conf\extra\httpd-vhosts.conf:

<VirtualHost {project name}:80>
 ServerName {project name}.localhost
 ServerAlias {project name}.localhost
 DocumentRoot "${INSTALL_DIR}/www/{your project}/{optional pub"
 <Directory "${INSTALL_DIR}/www/">
   Options +Indexes +Includes +FollowSymLinks +MultiViews
   AllowOverride All
   Require local
 </Directory>
</VirtualHost>

Your server should now be live at {project name}.localhost.


text:
Q: Best practices with HDF5 and Datasets I work with colleagues who rely on HDF5 as their data interchange format (largely exported from Python's Pandas).
Of course we have Import[] available for getting this data in, but I would like to work with it in the Dataset[] idiom. I was disappointed to see that SemanticImport[] doesn't do the job I'd expect here. (You'd sort of hope / expect that importing a "Dataset" would, well, map to a Dataset, but such are the ways of WRI).
I know I can 'assemble' the Dataset from the HDF5 in a straight-forward way, but was just wondering if anyone had already done the 'heavy lifting' here.

A: You can see:
https://github.com/scotmartin1234/HDF5Mathematica
There are some screenshots about compound datatypes, and you could also download the package and use it.
This is version 2.00 (August 2016) of the package that was originally provided as version 1.00 in July 2011.


text:
Q: How to compare String and string in enum I'm new in MVC programming.
So I'm using play framework.
Here is the enum from my model:
public enum Status{
    CREATED,
    MODERATED,
    REJECTED,
    REPLIED,
    REPLY
}

@Column(name="status_")
@Enumerated(EnumType.STRING)
public Status status;

public String getStatus() {
    return status;
}

Now, I need to access the $status from the view (html) and compare the string:
#{if programComment.getStatus()=="MODERATED"}

 ...

#{/if}

but it gives me error:

Getting Uncaught ReferenceError: MODERATED is not defined

A: after long play with quotes, I found the answer:
#{if "${programComment.getStatus()}"=="MODERATED"}

...

#{/if}

So, I wrapped the variable with double quotations.


text:
Q: How to pass NTLM credentials using angular http post call? I am working on localhost where angular and web api using 2 different ports that's causing issue now.
I am trying to call web api c# from angular like this

this.http.post<AccessToken>(`${this.url}/api/Home/Eid/?code=12345sfffs`,{headers:this.httpHeaders})
       .pipe(Response => {
         console.log("hi");
         console.log(Response);
        return Response;
        }); ```

But I am getting below error
Failed to load resource: the server responded with a status of 401 (Unauthorized)
When I tried in postman also I got same 401 error and later I fixed by adding NTLM credentials in postman to get 200 response.
But how to pass NTLM credentials from angular post call?
And why web api expecting for NTLM credentials?
Thanks in advance!

A: I have modified my angular post call to this
  return
 this.http.post<AccessToken>(`${this.url}/api/Home/Eid/?code=12345sfffs`,{headers:this.httpHeaders},{
withCredentials: true })
        .pipe(Response => {
         console.log("hi");
         console.log(Response);
         return Response;
         });

In Web API, I have modified web.config to this
<httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="http://localhost:4200"/>
        <add name="Access-Control-Allow-Credentials" value="true" />
      </customHeaders>
    </httpProtocol>


text:
Q: How can i unit test command line arguments in main Hey I am trying to write unittest to test command line arguments in main. Argparser do not recognize arguments passed
def test_main_local_build(self):
    args = ['python', 'main.py','-b','test', '-d', '-S', '-m', 'el', '-l',
    'Network']
    main.main(args[1:])


text:
Q: How to control the LED on an xbox 360 gamepad using pyusb I'm looking to use pyusb to interact with a wired xbox 360 gamepad. So far I can read just fine but I'd also like to write so I can make the LED stop blinking.
Looking here, I should be able to do it, but no matter what messages I try sending, I'm not having any luck controlling the LED. Below is the code I have thus far, any suggestions?
import usb
dev = usb.core.find(idVendor=1118, idProduct=654)
dev.set_configuration()
readEP = dev[0][(0,0)][0] #endpoint to read from
writeEP = dev[0][(0,0)][1] #endpoint to write to

print readEP #should be: <ENDPOINT 0x81: Interrupt IN>
print writeEP #should be: <ENDPOINT 0x1: Interrupt OUT>

##read the startup messages
for i in range(4): #usually only 4 messages
  data = dev.read(readEP.bEndpointAddress,readEP.wMaxPacketSize,100)
  print len(data) #should be 3

##get initial button/axes state
data = dev.read(readEP.bEndpointAddress,readEP.wMaxPacketSize,100)
print len(data) #should be 20

##Try to set the LED to illuminate just one element (message 0x06).
##Each of the following commented-out attempts fails to leave only the first
##element illuminated and subsequent attempts at reading or writing yields
##"usb.core.USBError: [Errno 5] Input/Output Error"
dev.write(writeEP,'010306',100)
# dev.write(writeEP,'0\x010306',100)
# dev.write(writeEP,'66310',100) #decimal value of 0x010306

##attempt to read again
while True:
  data = dev.read(readEP.bEndpointAddress,readEP.wMaxPacketSize,100)

A: Solved it; just had to try more variants of the string being written. Here's what eventually worked:
dev.write(writeEP,"\x01\x03\x06",0)


text:
Q: How do I set a default color in my box and let the color change depending on input? I am making an easy math-app for my daughter. Right now i have a TextField (with the decorationColor white) that shows a question (like '2+5=') and then she can type in the answer in the same box (displaying '2+5=7').
Below this textField I have another textField. This field puts out the correct answer when the user has tapped a button. If the user has answere correct, the decorationColors turns green, and if the answer is wrong the decorationColors turns red.
The problem is that I'm having trouble letting this box being white before the button for correction is being pressed. At this moment there is no color until it turns green or red.
I have put each box in separate classes right now, so I won't mess up too much if I do something wrong.
Any help putting some color as 'default' to this second box is highly appreciated. Thank you.
   import 'package:flutter/material.dart';

class CorrectionTextField extends StatelessWidget {
  final String text;
  final boxPaint;

  CorrectionTextField({this.text, this.boxPaint = Colors.white});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(right: 10.0, top: 8.0),
      child: Container(
        constraints: BoxConstraints.expand(height: 60.0, width: 150),
        decoration: BoxDecoration(
          color: boxPaint,
          borderRadius: BorderRadius.all(const Radius.circular(15.0)),
          border: Border.all(color: Colors.black54, width: 4.0),
        ),
        child: Center(
          child:
          Text(text, style: TextStyle(color: Colors.white, fontSize:
48.0)),
        ),
      ),
    );
  }
}

Next Class:
  Color correctionColor = Colors.white;
   var correct = Colors.green;
  var incorrect = Colors.red;
....
  body: Column(
      children: <Widget>[
        operationField,
        correctionField,

A: You can specify a default value for any instance variable in the constructor, to add a default color you could write:
CorrectionTextField({
    this.text,
    this.boxPaint = Colors.white,
});

That way, it will be set to white if no color property is specified when instantiating the widget.