text:
Q: Include file exe into Project Netbeans Java i want to include a file into my project in Netbeans, i'm developping an application for PC with the language Java. I searched almost on the Net, but i have found nothing. When i compile the application if i go into path where there is /dist the file exe aren't here.
Thank you so much.
String exec [] = {getClass().getClassLoader().getResource("inc_volume.exe").getPath() };
                System.out.println(exec[0]);
                Runtime.getRuntime().exec(exec);

Update on 20/08/2014 15.29
I have found this source to extract from jar, but i don't know how to use:
    java.util.jar.JarFile jar = new java.util.jar.JarFile(jarFile);
java.util.Enumeration enumEntries = jar.entries();
while (enumEntries.hasMoreElements()) {
    java.util.jar.JarEntry file = (java.util.jar.JarEntry) enumEntries.nextElement();
    java.io.File f = new java.io.File(destDir + java.io.File.separator + file.getName());
    if (file.isDirectory()) { // if its a directory, create it
        f.mkdir();
        continue;
    }
    java.io.InputStream is = jar.getInputStream(file); // get the input stream
    java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
    while (is.available() > 0) {  // write contents of 'is' to 'fos'
        fos.write(is.read());
    }
    fos.close();
    is.close();
}

Here Image:

A: To include an exe file to your project, copy this exe file via filesystem to the src folder of your Netbeans project.

when you have built your project, then this exe file will be packaged into the project jar file.

At runtime to run this exe, you will need to extract this exe file from your jar file.
And as this exe file is extracted you can execute it.
To launch an external application from your java code I recommend to use Apache Commons Exec: http://commons.apache.org/proper/commons-exec/

UPDATE
Below there's sample class to demonstrate how to extract all exe files from the current running jar file. I used these SO posts to make this class: the first and the second ones.
import java.io.File;
import java.io.IOException;

/**
 *
 */
public class TestClass {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {

        extractExeFiles("C://Temp");

    }

    /**
     * Gets running jar file path.
     * @return running jar file path.
     */
    private static File getCurrentJarFilePath() {
        return new File(TestClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
    }

    /**
     * Extracts all exe files to the destination directory.
     * @param destDir destination directory.
     * @throws IOException if there's an i/o problem.
     */
    private static void extractExeFiles(String destDir) throws IOException {
        java.util.jar.JarFile jar = new java.util.jar.JarFile(getCurrentJarFilePath());
        java.util.Enumeration enumEntries = jar.entries();
        String entryName;
        while (enumEntries.hasMoreElements()) {
            java.util.jar.JarEntry file = (java.util.jar.JarEntry) enumEntries.nextElement();
            entryName = file.getName();
            if ( (entryName != null) && (entryName.endsWith(".exe"))) {
                java.io.File f = new java.io.File(destDir + java.io.File.separator + entryName);
                if (file.isDirectory()) { // if its a directory, create it
                    f.mkdir();
                    continue;
                }
                java.io.InputStream is = jar.getInputStream(file); // get the input stream
                java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
                while (is.available() > 0) {  // write contents of 'is' to 'fos'
                    fos.write(is.read());
                }

                fos.close();
                is.close();
            }
        }
    }
}


text:
Q: Best way to take screenshot in windows 10 Fast screenshot
How to easily take screenshot of my screen in windows 10?
I would like to have option to select a part of my screen to take the screenshot.

A: You can take screensort by following ways:
1. Snipping Tool : Start > All Programs > Windows Accessories > Snipping Tool.
2. Windows Key + Print Screen : Windows Key + PrtScn.
3. Windows Key + H : Windows Key + H
4. Alt + Print Screen : Alt + PrtScn.
5. Windows Logo + Volume Down :hold down the Windows Logo touch button at the bottom of your Surface screen

A: I accidently found a easy way to take screenshot of my screen in windows 10.
Just hold Windows Logo Key + Shift Key + S

Than you can select what part of the screen you want to take the screenshot.
This will copy of a selected part to your clipboard and than you can simply past it in Paint, photoshop or any image app you want.
Thanks @Abhi
There are many other ways to do this as well:
1. Snipping Tool : Start > All Programs > Windows Accessories > Snipping Tool.
2. Windows Key + Print Screen : Windows Key + PrtScn.

A: Or you can easily use Windows key+fn+printscreen keys

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to subclass System.ComponentModel.GroupDescription? Can anyone explain how to use the GroupDescription class of the .NET library to implement anything else than (a class like) the PropertyGroupDescription class?
In other words: What other kinds of grouping are possible by subclassing GroupDescription?  Can you give a concrete example of how to implement the GroupNameFromItem(...) method of GroupDescription?


text:
Q: Android GridView slow scroll, then very fast scroll I have a GridView with thumbnail images loaded in a separate thread. After all the thumbnails are done loading, if I scroll the grid view it's consistently slow (~5fps), until I scroll a few rows down, then it immediately scrolls extremely fast (~30fps) even if I scroll all the way up again.
If I then repopulate the gridview, it's slow again until I scroll down some more. It's not an issue of recycling the views as I am already doing that.
(Update: uploaded the correct slow trace image)
I tracked the issue to an internal view draw call. Here is the Android Studio trace for when it's slow:

And here is the trace for when it's fast:

It's clear the guilty method is android.view.ThreadedRenderer.draw(), but this is an internal call and I can't test further. From the trace, my understanding is that it's not the drawing that is slow, as the android.view.ThreadedRenderer.updateRootDisplayList() which eventually calls android.widget.AbsListView.draw() finishes just as quickly in both traces. So it must be the rest of the android.view.ThreadedRenderer.draw() that is causing this.
Looking online I found the ThreadedRenderer.java class
Things I've tried:

*

*Forcing hardware rendering on the gridview made no difference.

*Forcing software rendering on the gridview made the list always scroll very slowly.
Any ideas why this could be happening?

A: Well, the reason that it's a lot faster to scroll after the first time is that Android is recycling views. This means that it's taking the most time to construct the views initially.
I think you're going a bit too deep. You should check to make sure you're not downloading the thumbnails synchronously during draw. Try removing the code that downloads the images, or set the URLs to "". Essentially, try stripping down your thumbnail view until you can pinpoint what the issue is. This should help set you on the right track.

A: I had a similar problem recently.
You need to check the number of  Layouts in your xml file.
The more relative or linear layouts you have on your scroll view the more slow it gets.
Post your xml file less see.


text:
Q: Change background color on li:visited I have a tab page for which I want to apply a different background color when a tab was visited. How can I do that?
Here is the code:
HTML:

Tab One

Tab Two

Tab Three

This is first tab

This is second tab

This is third tab

CSS:
ul.tabs>li {float: left; padding: 10px; background-color: lightgray;
          margin-right:5px; border-radius:10px 10px 0 0;
      }

ul.tabs li a{text-decoration:none;}

ul.tabs li a:visited{color:red;}

ul.tabs li:visited{background:lime;}

p{padding:40px;}

jQuery:
$(document).ready(function() {
    $("ul.tabs a").click(function() {
        $(".pane div").hide();
        $($(this).attr("href")).show();
    });
})

fiddle: http://jsfiddle.net/uFALn/63/

A: try this code:
$(document).ready(function() {
    $("ul.tabs a").click(function() {
        $(".pane div").hide();
        $(this).parent().addClass('visited')
        $($(this).attr("href")).show();
    });
})

and css for it:
ul.tabs li.visited{
background:lime;
}

Demo
:visited is applied to references only. At the same time -code above will not work after page reload (as it should be for links). You may additionally test links color on document.ready and set corresponding class on LIs
Another option: form tab headers with links, not with LIs (main css changes):
ul.tabs>li {
     float: left;

}
ul.tabs>li a {
    padding: 10px;
          display:block;
          background-color: lightgray;
          margin-right:5px;
          border-radius:10px 10px 0 0;
      }

demo

A: The visited pseudo-class won't work on lis, because they're not links and there's no way to "visit" a li element.
So, what you can do is to set as to display:block; and give them the background color.
This will work even after page change/refreshes.
Your new CSS:
ul.tabs>li {
    float: left;
    margin-right:5px;
}

ul.tabs li a { /* padding, background and border-radius goes here now */
    display:block;
    padding: 10px;
    background-color: lightgray;
    text-decoration:none;
    border-radius:10px 10px 0 0;
}

ul.tabs li a:visited{color:red;}

ul.tabs li a:visited { /* li a:visited instead of li:visited */
    background:lime;
}

p{padding:40px;}

Demo

A: The HTML element li does not have a :visited selector. You need to apply all your CSS to the anchor.
Change the ul.tabs>li to ul.tabs a and set the background for
ul.tabs li a:visited {
    color:red;
    background: lime;
}

See this fiddle for working code.

A: HTML

Tab One

Tab Two

Tab Three

This is first tab

This is second tab

This is third tab

CSS
ul.tabs>li {
  float: left;
  padding: 10px;

  margin-right:5px;
  border-radius:10px 10px 0 0;
}
li{
background: lightgray;
}
ul.tabs li a{
text-decoration:none;
}

ul.tabs li a:visited{
color:red;
}

ul.tabs li:visited{
background:lime;
}

p{
padding:40px;
}

.active{
    background:blue;
}

JQUERY
$(document).ready(function() {
    $("ul.tabs a").click(function() {
        $("ul.tabs li").removeClass('active');
        $(this).parent().addClass('active');
        $(".pane div").hide();
        $($(this).attr("href")).show();
    });
})

DEMO


text:
Q: Get the reference of all commandbuttons which are inside datatable cell in JQuery I am having a datatable with id employeeDataTable and inside that I have commandbuttons as column like below
<p:commandButton value="Me" update=":#{p:component('primaryEmployeeDetails')}" id="ajax"
     actionListener="#{userPreferenceBean.saveEmployee}" styleClass="ui-priority-primary">
     <f:param name="employeeName" value="#{employee.name}" />
</p:commandButton>

I want to get the control of all commandbuttons so that I can do operation on those inside Jquery.
This is what I am doing --
 $(document).ready(function() {
        $(".ui-priority-primary").click(function() {
        //Getting all rows to iterate through them
        var row = $(document.getElementById("myForm:employeeDataTable")).find("tbody:first").children("tr");
        row.each(function() {
            alert('inside row');
            $(this).find('td').each(function(){
                   alert('inside each cell')
            });
        });
     });

Both alert's are working fine. But can you tell me how to get all commandbutton references in the second loop? Thanks.

A: Finally able to achieve the functionality with below code. A special thanks to @BalusC for guiding me. Sharing the answer here.
$(document).ready(function() {
        $(".ui-priority-primary").click(function() {
            var buttons = $(".ui-priority-primary");
            var rows = $(document.getElementById("myForm:employeeDataTable")).find("tbody:first").children("tr");
                rows.each(function() {
                      alert('Inside Row Loop');
                });

                $(buttons).each(function(){
                      $(this).doUserOperation();
                });
        });
});


text:
Q: Store data locally using HTML and JavaScript I have a small LAN with some computers.
I'm looking for a way to build a dynamic HTML webpage that uses JavaScript to store some data locally (can't use server side - only client side).
The webpage will be stored on a network drive shared with all the computers.
I wish to do that using a file, maybe an XML file or something similar that will be loaded using JavaScript and then saved again after some changes.
The data must be shared with all the computers on the LAN.
How can I do this?

A: You have the following options :
1.LocalStorage : You can store data in variables. There would be a limit as to how much data you can store.
Refer : http://en.wikipedia.org/wiki/Web_storage.
Eg:
// Store
localStorage.setItem("sample", "test");
// Retrieve
var sample = localStorage.getItem("sample");

2.WebSQL : This should be the most easy way of storing in client side. WebSQL is supported in almost all current browsers(HTML5). However there is no longer official support for WebSQL as its depreciated and no future updates.
Refer : http://en.wikipedia.org/wiki/Web_SQL_Database
3.IndexedDB : This is also another way to store data in local database. However this is not yet supported in all browsers.
4.XML
If you are going forward with storing data in local DB, then you can utilize PersistenceJS.
Refer : https://github.com/zefhemel/persistencejs

A: HTML5 localStorage
//Set
localStorage.setItem("lastname", "Smith");

//Get
var lastName = localStorage.getItem("lastname");

A: Try like this:
store a value :
localStorage.setItem("lastname", "amir");

get a value:
localStorage.getItem("lastname");

A: You can use HTML 5 LocalStorage

A: Depending on the flavor of data you're storing, simple cookies might work, accessed with plain old JS.

A: finally I found a solution for it!
I am using a jQuery plugin called: twFile (http://jquery.tiddlywiki.org/twFile.html).
It uses an activeX FileSystemObject - it works great on IE9.


text:
Q: DML exception on seemingly not involved object?
Apex trigger TF_UserTrigger caused an unexpected exception, contact
  your administrator: TF_UserTrigger: execution of AfterUpdate caused
  by: System.DmlException: Insert failed. First exception on row 0;
  first error: MIXED_DML_OPERATION, DML operation on setup object is not
  permitted after you have updated a non-setup object (or vice versa):
  WorkflowQueue__c, original object: User: []:
  Class.TF_WorkflowQueue.Add: line 25, column 1

This quite clear alert. I somehow tried to alter the original User object and thus I got such ugly message. But how? There is load of code so I will try to explain it by word firstly:
I tried to deactivate User. This started chain of events. At first my apex look for all Contacts owner by this User, do some additional checks and then it queue it up into WorkflowQueue__c. Items from this queue are taken by scheduler and sent into my system. Important is, the whole process doesn't affect original User in any means.
Moment of crash is on insert line:
public void Add(string data, boolean multimessage)
{
    if(data == null || String.isEmpty(data))
    {
        this.logger.Debug('Variable \'Data\' should not be null.');
        throw new MoraviaArgumentException('Variable \'Data\' should not be null.');
    }

    WorkflowQueue__c item = new WorkflowQueue__c(Data__c = data, Multimessage__c = multimessage);

    insert item;
}

How the object looks like:

And still the exception tells me I tried to change the User somehow. I would be grateful for any hint of what I am missing or misunderstanding.

A: You cannot create/update  setup and non-setup object records inside the same method. as in your case WorkflowQueue__c is a non-setup object.please see whether you are creating  other setup or non-setup objects in the same transaction

A: When you tried to deactivate a user, the code in your post ran, and since it's part of the same transaction, you got a mixed DML error message, because while you were updating the user, you tried to insert another object.
The key word here is "Transaction" - defined as:

An Apex transaction represents a set of operations that are executed as a single unit.
All DML operations in a transaction either complete successfully, or if an error occurs in one operation, the entire transaction is rolled back and no data is committed to the database.
The boundary of a transaction can be a trigger, a class method, an anonymous block of code, a Visualforce page, or a custom Web service method.

Your transaction started when you updated the user. Your trigger executes in the same transaction. During this trigger, you insert a non-setup object- causing your exception, since your mixing setup & non-setup objects.
Instead of calling this method in the same context, use the @future annotation. Itll cause the method to be executed a few minutes after the trigger runs, and will be in its own context, allowing you to insert a non-setup object without incurring an exception.


text:
Q: How to cause an infinite loop in JPanel class DrawPane extends JPanel
{
  //size is the size of the square, x and y are position coords
  double size = 1, x = 0, y = 0;
  double start = (-1) * size;
  public void paintComponent(Graphics shape)
  {
    for(x = start; x <= scWidth; x += size)
    {
      shape.drawRect((int)x, (int)y , (int)size, (int)size);

      //When a row is finished drawing, add another
      if(x >= scWidth)
      {
        x = start; y += size;
      }

      //Redraws the entire grid; makes the for loop infnite
      else if(y >= scHeight)
      {
        x = start; y = start;
      }
    }
  }
}

I'm confused as to why JPanel refuses to work with the loop once I make it infinite. How would I go about allowing it to do so?

A: When you make the loop "infinite" you effectively tie up and freeze the Swing event thread preventing Swing from doing anything. Instead use a Swing Timer to drive your animation.
e.g.,
class DrawPane extends JPanel {
  //size is the size of the square, x and y are position coords
  double size = 1, x = 0, y = 0;
  double start = (-1) * size;

  public DrawPane() {
    int timerDelay = 200;
    new Timer(timerDelay, new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            x += size;
            if (x >= scWidth) {
                x = start;
                y += size;
            }
            if (y >= scHeight) {
                x = start;
                y = start;
            }
            repaint();
        }
    }).start();
  }

  public void paintComponent(Graphics g)   {
    super.paintComponent(g); // Don't forget to call this!
    g.drawRect((int)x, (int)y , (int)size, (int)size);
  }
}

A: The paint function is supposed to update the Paint and get out of the way. You really shouldn't be putting in complex logic and definitely not infinite loops there.
Just do what you have (except get rid of the reset stuff that makes your loop infinite) and put repaint() in an infinite loop (preferably with some timer logic) somewhere else in your program.

A: It will never break out of the paintComponent loop and update the GUI. The GUI will only update once the paintComponent method finishes. If you want to make the loop infinite, you need to take the code out of your event handler and be calling repaint() from elsewhere, possibly using a timer to do so.


text:
Q: Checking middleware is called from http call How would one test that a piece of custom middleware is actually called from a standard HTTP event?
ie. The middleware is called from:
MyController.js
router.get('/some/endpoint', [myMiddleware()], (req, res, next) => {
    // Code to do whatever here
});

The middleware itself can be defined as:
MyMiddleware.js
module.exports = () => {
    // Middleware code in here
}

My quest is to check that the middleware is called once from my unit test, but I cannot find documentation around this.
MyTest.test.js
it('Should return whatever from GET call', () => {
    return request(app).get('/some/endpoint')
        .expect(200)
        .expect(res => {res.body.should.deep.equal(bodyValue)});
    // How would I place code in here to check that MyMiddleware is called?
    // ie. sinon.assert.calledOnce(MyMiddleware)
});

I have thought about using Sinon's spy, but I can't think of how to hook into the middleware... My attempt was this:
const mwSpy = sinon.spy(require('path to middleware file'));

sinon.assert(calledOnce(mwSpy));

A: The usual way of going about this is splitting this into two tests, an integration test and a unit test.

*

*Will the middleware I specified in the router.get call end up being called when someone hits this endpoint?

*Does my middleware do the right thing?

The first part is basically testing that the Express API is doing what the documentation says. That's not what unit tests are for (this was tagged unit-testing), but since you are already using HTTP requests to test the endpoint, I guess that's not what you are after anyway: you are basically creating verification tests for your system.
You could still test the Express routing without HTTP, though, as I detail in the answer to this question, concerning how to test the router programmatically (faster tests, no http), but less just stick to what you have.
So the basic question is: "My quest is to check that the middleware is called once from my unit test". You don't seem to concern yourself with whether the middleware is doing the right thing or not, just that it's called, which calls for the question on whether we should test the middleware or the layer using the middleware.
In both cases, you need to find a way of injecting a test spy. Either you write a small utility method that will inject that spy: function setMiddleware(module){ middleware = module; } or you use some tooling like proxyquire. See this tutorial on Sinon's homepage for background.
I would just do this (in the test code):
it('Should return whatever from GET call', () => {
  var middlewareFake = sinon.fake();
  // I am assuming it's the actual app object you are referencing below in the request(app) line
  var app = proxyquire('../app/index.js', { './my-middleware': middlewareFake });

  //
  return request(app).get('/some/endpoint')
    .expect(200)
    .expect(res => {
      res.body.should.deep.equal(bodyValue)

      expect(middlewareFake).was.called;
    });
});


text:
Q: What does a client side javascript templating framework offer? What is the use of frameworks like PURE or jQote etc. I can do dynamic things in plain javascript or JQuery using AJAX calls or an advanced library like DWR.
What new stuff do these templating frameworks bring to the table? I need to know since I have been asked to use a browser side templating framework without being explained why :(

A: I guess it depends on what you're using as your server code; it could be that the recommendation came from someone who hasn't heard about N/Velocity for example.
I think the main reason for client templating is that it removes the weight of transformation from the web-server.
It might also allow you to send your JSON from a dedicated box, and serve the template and client code from a different box.
To my mind, both of these 'bonuses' override the fact, that you're putting Data into the DOM that shouldn't be there. Firstly you'll have the JSON that is parsed by the template generator and then you'll have the HTML that is created.
Sure, viewing page source will look neat, but in terms of memory consumption for the browser it's bad,  especially if you're in the UK and have Government contracts who mandate IE6 support.


text:
Q: how to text a clickable phone number including extension on android messages How do I text a clickable phone number that includes the wait to dial extension on android messages?
on iOS I would simply type 8008008000; 123456# and I can even text that to iOS from android and it works, but when I text that to other android phones, the full link gets broken and android only dial the number from the message, requiring going back to the message to copy the extension for paste into dialer of active call.
I want the wait functionality, not the pause function.
I can create contacts in android like 8008008000; 123456# and they operate as desired, the solution I am after will not include creating the contact then sharing the contact.
I need to know what to type in and hit send, and it work for the recipient as desired.

A: typically it would be a comma (8008008000,123456#  with NO spaces.) but its been my experience that .5 seconds (,) is insufficient for the number to be picked up and the IVR to register. a full second is more common, (8008008000,,123456# ) however, Android doesnt seem to parse a double-comma.


text:
Q: How to programmatically create Kafka broker instance? Is there any Java Kafka API available to create Kafka server Instance.
I searched Apache Kafka, but it doesn't have any method to create broker instance

A: No there isn't. Servers (brokers) are expected to be independent jvms so you'd want to use some orchestration that can manage jvms.


text:
Q: How to add more than one dataframe in python email body I want to insert two data frames in my email body and I am able to get one but not both.
Here is my code
import smtplib
import teradata
import pandas as pd

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

table =[{'account': 'Jones LLC', 'Jan': 150, 'Feb': 200, 'Mar': 140}, {'account': 'Alpha Co',  'Jan': 200, 'Feb': 210, 'Mar': 215},{'account': 'Blue Inc',  'Jan': 50,  'Feb': 90,  'Mar': 95 }]

table1 =[{'account': 'fgsdgd LLC', 'Jan': 150, 'Feb': 200, 'Mar': 140}, {'account': 'fsdgsd Co',  'Jan': 200, 'Feb': 210, 'Mar': 215},{'account': 'Blue Inc',  'Jan': 50,  'Feb': 90,  'Mar': 95 }]
sql_canc_hour = pd.DataFrame(table)
sql1 = pd.DataFrame(table1)

 me = "xxx@gmail.com"
 you = "xxxxxx@gmail.com"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Account Details"
msg['From'] = me
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
text = " "
html = """\

Hi Team,\n

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

   {sql_canc_hour}

"""
html1 = """

Hi Team,\n

<link rel="stylesheet"   href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

{sql1}

 """

 html= html.format(sql_canc_hour = sql_canc_hour.to_html())
 html1= html1.format(sql1 = sql1.to_html())
 # Record the MIME types of both parts - text/plain and text/html.
 part1 = MIMEText(text, 'plain')
 part2 = MIMEText(html, 'html')
 part3 = MIMEText(html1, 'html')

 # Attach parts into message container.
 # According to RFC 2046, the last part of a multipart message, in this case
 # the HTML message, is best and preferred.
 msg.attach(part1)
 msg.attach(part2)
 msg.attach(part3)

 # Send the message via local SMTP server.
 s = smtplib.SMTP('XXXX@gmail.com')
 # sendmail function takes 3 arguments: sender's address, recipient's   address
 # and message to send - here it is sent as one string.
 s.sendmail(me, you, msg.as_string())
 print ("Successfully sent email")

Output is
screen shot
My objective is to add as many data frames as possible into email body and send email

A: Just having a quick look at this, I think your issue is less caused by your code and more a result of using two sets of html and head tags.
Some browsers / clients might not interpret this well and only accept the first occurrence. HTML documents are only supposed to have one set. This is true of body tags too.
Adjust your strings to reflect this and see if that resolves your issue.


text:
Q: validate fields from diffrent models in a single form I have the form
TblRegistration/_form.php
<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'tbl-registration-form',
    // Please note: When you enable ajax validation, make sure the corresponding
    // controller action is handling ajax validation correctly.
    // There is a call to performAjaxValidation() commented in generated controller code.
    // See class documentation of CActiveForm for details on this.
    'enableAjaxValidation'=>true,
)); ?>

Fields with * are required.

 <?php echo $form->errorSummary(array($model,$model1)); ?>

        <?php echo $form->labelEx($model,'director'); ?>
        <?php echo $form->textField($model,'director',array('size'=>50,'maxlength'=>50)); ?>
        <?php echo $form->error($model,'director'); ?>

        <?php echo $form->labelEx($model,'experience'); ?>
        <?php echo $form->textField($model,'experience'); ?>
        <?php echo $form->error($model,'experience'); ?>

        <?php echo $form->labelEx($model,'language'); ?>
        <?php echo $form->textField($model,'language',array('size'=>50,'maxlength'=>50)); ?>
        <?php echo $form->error($model,'language'); ?>

        <?php echo $form->labelEx($model1,'email'); ?>
        <?php echo $form->textField($model1,'email'); ?>
        <?php echo $form->error($model1,'email'); ?>

        <?php echo $form->labelEx($model1,'password'); ?>
        <?php echo $form->textField($model1,'password'); ?>
        <?php echo $form->error($model1,'password'); ?>

        <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

<?php $this->endWidget(); ?>

My actioncreate  create contain
public function actionCreate()
    {
        $model=new TblRegistration;
        $model1=new TblLogin();

        // Uncomment the following line if AJAX validation is needed
        //$this->performAjaxValidation($model1);

        if(isset($_POST['TblRegistration']) && isset($_POST['TblLogin']))
        {
            $model->attributes=$_POST['TblRegistration'];
                        $model1->attributes=$_POST['TblLogin'];
            $model->save();
            if($model->save())
            {

                    $model1->reg_id=$model->reg_id;

                    $model1->save();
            }
            if(($model->save() )&& ($model1->save()))
                $this->redirect(array('view','id'=>$model->reg_id));
        }

        $this->render('create',array(
            'model'=>$model,
        ));
    }

my fields email and password is from the model TblLogin.I want to validate those fields before iam saving the data.how can i achive this?

A: After:
$model->attributes=$_POST['TblRegistration'];
$model1->attributes=$_POST['TblLogin'];

Add:
if($model->validate() && $model1->validate()){
$model->save();
...


text:
Q: Admins can't edit each other's posts After I imported content from another wordpress site using the WXR export/import tools, my admins can't edit each other's posts.  This is really aggravating because I can't figure out how to change this.  And it doesn't just related to imported content.  I can create two brand new admins, each one creates an entry, but neither one can edit the other's posts.
On the post listing page, it doesn't even show an Edit link on or below the title, and there's no checkbox for bulk editing, if the logged-in user isn't the author.  I don't have this problem with pages, but it does effect any Custom Post Types set as 'capability_type' => 'post'
I have no idea how this happened or how to undo it. Please help before I pull all my hair out.

A: Ok, I got it figured out.  For some reason, current_user_can was returning false when an admin went to edit other user's posts... I have no idea how admins lost the ability to do this, but putting this into functions.php is a workable bandaid that restores admin edit capabilities;
$administrator = get_role('administrator');
$administrator->add_cap('edit_others_posts');


text:
Q: How to setup the react native navigation on android? I have some issue with WIX react native navigation when I installed them,
I'm doing the steps in the documentation correctly but when running the app and Configure the libs and when up to Configure react native vector icon,
I have " Build Failed ".
> Configure project :react-native-vector-icons
The CompileOptions.bootClasspath property has been deprecated and is scheduled to be removed in Gradle 5.0. Please use the CompileOptions.bootstrapClasspath property instead.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
> java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex Unable to merge dex

so I don't Know what's wrong,
please if you have the same issue and fixed them, help me

A: For navigation between screens and Routing and navigation for your React Native apps you can switch to React Navigation 3x https://reactnavigation.org/. Its an extensible yet easy-to-use navigation solution written entirely in JavaScript (so you can read and understand all of the source), on top of powerful native primitives.
If you're already familiar with React Native then you'll be able to get moving with React Navigation quickly!
Install the react-navigation package in your React Native project.
yarn add react-navigation
or with npm
npm install --save react-navigation
Next, install react-native-gesture-handler. If you're using Expo you don't need to do anything here, it's included in the SDK. Otherwise:
yarn add react-native-gesture-handler
or with npm
npm install --save react-native-gesture-handler
Link all native dependencies:
react-native link react-native-gesture-handler
No additional steps are required for iOS.
To finalise installation of react-native-gesture-handler for Android, be sure to make the necessary modifications to MainActivity.java:
package com.reactnavigation.example;

import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;

public class MainActivity extends ReactActivity {

  @Override
  protected String getMainComponentName() {
    return "Example";
  }

  @Override
  protected ReactActivityDelegate createReactActivityDelegate() {
    return new ReactActivityDelegate(this, getMainComponentName()) {
      @Override
      protected ReactRootView createRootView() {
       return new RNGestureHandlerEnabledRootView(MainActivity.this);
      }
    };
  }
}

You're good to go!


text:
Q: GNUPLOT: how to use a header row from CSV-file as plot header in a loop? I have  CSV file with the following structure:
headerString1;headerString2;...;headerStringN
doubleNumber1;doubleNumber2;...;doubleNumberN
... many other doubleNumberRows

I want to plot histograms from each of the columns in individual files - this is something that works - and I want to take the title for each individual plot from the CSV-file, first row. I searched a lot, but could find a solution. Up to now this is my gnuplot code:
set datafile separator ";"
set style data histogram

binwidth=20
set boxwidth binwidth-2
bin(x,width)=width*floor(x/width)

# No legends!
unset key

do for [COL=1:10] {
    set title sprintf("%d", columnheader(COL)) <--- This always tells me it is a number, "%s" does not work
    FILE = sprintf("%s%02d%s","Histogram",COL,".png")
    set term png giant font helvetica 24 size 1440, 1080
    set output FILE
    plot "myCSVFile.CSV" using (bin(column(COL),binwidth)):(1.0) smooth freq with boxes lc 1
}

columnheader(COL) is a number (?), at least I can convert it via sprintf("%d", columnheader(COL)) to a number string which is "-2147483648" for all plots. The output looks like this:

How do I retrieve the headerString# strings and use it as title in my individual plot?

A: You have access to the columnhead string only in very specific contexts, for example within a plot command. Setting the plot title is not one of them (set title doesn't even know which data file you are going to be using), but creating legend entries is. So you could position the legend where the title usually appears.
For example, given the datafile test.csv
First Column;Second Column
-900;-700
-1100;-800
-1000;-650

you could use
set term push

set datafile separator ";"
set style data histogram
set style fill solid 1

binwidth=20
set boxwidth binwidth-2
bin(x,width)=width*floor(x/width)

set key outside top center samplen 0

do for [COL=1:2] {
    FILE = sprintf("%s%02d%s","Histogram",COL,".png")
    set term pngcairo
    set output FILE

    plot "test.csv" using (bin(column(COL),binwidth)):(1.0) smooth freq notitle with boxes lc 1, \
         NaN title columnhead(COL) with lines lc rgb "white"

    set output
}

set term pop

and get

Here I separated the plot that displays the histogram from the plot that generates the legend entry so that the sample picture does not show up in the legend.
Alternatively, if you know the possible column titles beforehand you could also use
do for [name in '"First Column" "Second Column"'] {
   set title name
   plot "test.csv" using (bin(column(name),binwidth)):(1.0) smooth freq notitle with boxes lc 1
}

A: I found a workaround for my problem:
Instead of extracting the column header from the file (which were desirable), I create a title array which I have to copy from the csv file :(
Code:
titles = "columnHeader1 ... columnHeaderN"

do for [COL=1:N] {
    FILE = sprintf("%s%02d%s","Histogram",COL,".png")
    set term png giant font helvetica 24 size 1440, 1080
    set output FILE
    set title word(titles, COL)
    plot "InputFileName.CSV" using (bin(column(COL),binwidth)):(1.0) smooth freq with boxes lc 1
}

This works, but is a couple of clicks more than desired...


text:
Q: New PC build and Linux + WIn10 independet boot I recently assembled a new RIG (specs below) because I needed more power for my work.
I also needed to move back to windows to use certain programs that didn't run well (or didn't run at all) on playonlinux. However I'd like to run Ubuntu as a second OS, because I like its DE a lot more.
I've been using ubuntu for several years, but I'm in no way an expert, I can follow a tutorial but I'm unable to solve my problem on my own, tbh I recall when I started using and dual booting linux (way back in the early 2000's) I had a similar issue and I followed a tutorial on some magazine I used to read (that was about the only way to get a linux distro with 56k modem).
I should've gotten to the point by now... well, what I'd like to do is to install linux on a separate HDD (from the old rig) and put GRUB on a USB stick.
That way when the USB stick is not inserted Win10 would boot normally, but if I insert the USB drive then Grub will boot and I'd be able to boot linux (or even better get dual boot options).
Back then I used a floppy drive to achieve this result, but a lot has changed ever since (also BIOS was replaced by UEFI).
My specs:
CPU Intel core i5 7500 (also I'm using the iGPU HD630)
MB Asrock H270 Pro4 (intel LAN and Realtek ALC892 audio)
RAM Crucial DDR4 2400 2x4GB
SSD (WIN10) Crucial MX300 525GB
HDD (for Ubuntu) some old WD Blue 500GB

So if you can point me to some tutorial I'd be very grateful, because I couldn't find anything at all (for UEFI systems).
PS I think I should specify that considering the architecture of my CPU/GPU probably I will install 16.10 x64 (unity), although I will try 16.04 firstly.


text:
Q: Retrieving check box name (value) from a table in SQL database into ascx file I have tab names stored in a table named 'Importtabs' in my SQL database. Instead of hard coding the name of tabs i am importing i want to retrieve the names from the above mentioned table and set them as values for my checkbox list on the ascx side. Here is the hardcoded version that i was earlier using:
<div style="overflow: auto;">
<asp:CheckBoxList ID="CheckBoxList1" BorderStyle="None" runat="server" RepeatColumns="3">
<asp:ListItem>All Temporary Differences</asp:ListItem>
<asp:ListItem>All Permanent Differences</asp:ListItem>
<asp:ListItem>All BS Only Differences</asp:ListItem>
<asp:ListItem>RTA Temp</asp:ListItem>
<asp:ListItem>RTA Perm</asp:ListItem>
<asp:ListItem>RTA Temp Other</asp:ListItem>
<asp:ListItem>RTA Perm Other</asp:ListItem>
<asp:ListItem>RTA Other Expense</asp:ListItem>
</div>

How can i do a similar thing as shown above but using the names ( 'All Temporary Differences', 'All Permanent Differences' etc ) from the 'Importtabs' table in my Database. Please help.

A: Assuming you already know how to retrieve data from a database, this code can be used to put that data into the CheckBoxList
protected void Page_Load(object sender, EventArgs e)
{
    // do not rebind the list if this is a postback; user input would be lost
    if (this.IsPostBack)
    {
        return;
    }
    CheckBoxList1.DataSource = GetValues();
    CheckBoxList1.DataBind();
}

private string[] GetValues()
{
    // get data from database, with 'select <columnName> from Importtabs'
    // populate array
    // return values as a string[]
}

That will result in a lot of hits to your database, so you might want to run the GetValues() method once and then cache the results.

Links for Caching and SqlConnection


text:
Q: Moving Focus to GridView's first item view In my activity i have two fragments 1st one contains a linearlayout and second one contains a gridview and i have to support D-pad navigation in my app.
now when user press key to movetowards grid view i want to show the 1st item of gridview as selected view

so every time when focus moves from linearlayout to gridview , gridview's first item should get selected/focused
any leads on these is highly appreciated

A: on keypress towards gridview you can call:
firstItem.requestFocus();

replace "firstItem" by your element name, such as button, edittext, etc
OR
you can implement OnFocusChangeListener to your activity and do this:
gridView.setOnFocusChangeListener(this);

and then
@Override
public void onFocusChange(View v, boolean hasFocus) {

    if(hasFocus){
        firstItem.requestFocus();
    }
}


text:
Q: How do I change self-made themes of my app in Flutter in real time I have my own made dark theme in my current app. Now, I also want to add light theme to it. I have seen some answers, but I have a condition that, my MaterialApp is already inside a ChangeNotifierProvider for API Data. Now, as I saw in some examples, I need another change notifierprovider for changing theme real time. Also, my theme button is on another page, far away from main. So, how should I implement this functionality.
Here is my MyApp -
return ChangeNotifierProvider(
      create: (context) => APIData(),
      child: MaterialApp(
        title: 'Testing',
        theme: ThemeData(
          fontFamily: 'Nunito Sans',
          brightness: Brightness.dark,
          textTheme: TextTheme(
            headline1: headingStyle1,
            headline2: headingStyle2,
            headline3: headingStyle3,
            headline4: headingStyle4,
            headline6: bodyText3,
            bodyText1: bodyText1,
            bodyText2: bodyText2,
            button: buttonTextStyle,
            caption: linkStyle,
          ),
        ),
        //themeMode: _themeMode,
        // home: SplashScreen(),
        initialRoute: isViewed==0 || isViewed==null ? 'splash' : 'home',
        navigatorObservers: <NavigatorObserver>[observer],
        routes: {
          'home': (context) => AuthenticationWrapper(),
          'splash' : (context) => SplashScreen(),
        },
        scaffoldMessengerKey: scaffoldMessengerKey,
        navigatorKey: navigatorKey,
      ),
    );

theme_manager.dart -
import 'package:flutter/material.dart';

import '../styles.dart';
import 'storage_manager.dart';

class ThemeNotifier with ChangeNotifier {
  final darkTheme = ThemeData(
    fontFamily: 'Nunito Sans',
    brightness: Brightness.dark,
    textTheme: TextTheme(
      headline1: headingStyle1,
      headline2: headingStyle2,
      headline3: headingStyle3,
      headline4: headingStyle4,
      headline6: bodyText3,
      bodyText1: bodyText1,
      bodyText2: bodyText2,
      button: buttonTextStyle,
      caption: linkStyle,
    ),
  );

  final lightTheme = ThemeData(
    primarySwatch: Colors.grey,
    primaryColor: Colors.white,
    brightness: Brightness.light,
    backgroundColor: const Color(0xFFE5E5E5),
    accentColor: Colors.black,
    accentIconTheme: IconThemeData(color: Colors.white),
    dividerColor: Colors.white54,
  );

  ThemeData _themeData = ThemeData.light();
  ThemeData getTheme() => _themeData;

  ThemeNotifier() {
    StorageManager.readData('themeMode').then((value) {
      print('value read from storage: ' + value.toString());
      var themeMode = value ?? 'light';
      if (themeMode == 'light') {
        _themeData = lightTheme;
      } else {
        print('setting dark theme');
        _themeData = darkTheme;
      }
      notifyListeners();
    });
  }

  void setDarkMode() async {
    _themeData = darkTheme;
    StorageManager.saveData('themeMode', 'dark');
    notifyListeners();
  }

  void setLightMode() async {
    _themeData = lightTheme;
    StorageManager.saveData('themeMode', 'light');
    notifyListeners();
  }
}

storage_manager.dart -
import 'package:shared_preferences/shared_preferences.dart';

class StorageManager {
  static void saveData(String key, dynamic value) async {
    final prefs = await SharedPreferences.getInstance();
    if (value is int) {
      prefs.setInt(key, value);
    } else if (value is String) {
      prefs.setString(key, value);
    } else if (value is bool) {
      prefs.setBool(key, value);
    } else {
      print("Invalid Type");
    }
  }

  static Future<dynamic> readData(String key) async {
    final prefs = await SharedPreferences.getInstance();
    dynamic obj = prefs.get(key);
    return obj;
  }

  static Future<bool> deleteData(String key) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.remove(key);
  }
}

And, from here I have to change my theme, which is in settings.dart, which is navigated after at least 3-4 pages -
                          CustomSwitch1(
                                value: status,
                                onChanged: (bool val) {
                                  setState(() {
                                    status = val;
                                    print(status);

                                  });
                                },
                              ),


text:
Q: Django fails to process get request properly with a misconfiguration in the project's main urls.py I've got a website I'm writing using Django which is a very basic, rudimentary CMS. For now the feature I am trying to implement involves when a web user enters their fake 12-digit chuckee cheese membership card number, Django should redact the first 8 digits and present it back to the user. All of this takes place on the main landing page with blog post text content.
Here is the urlspatterns variable declared inside my project's parent urls.py:
urlpatterns = [
   path('admin/', admin.site.urls),
   path('', include('redactors.urls')),
   path('', include('posts.urls')),
   path('', include('counters.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

With that exact urlspatterns, the result is this.
As you can see in that image, when the web user enters their membership card number, on the  webpage to the right, the card number (below the green heading elements) renders and is processed as intended (which is at this web address location, http://127.0.0.1:8000/?ccEntry=111111111111. The problem is the landing page (as depicted on the left at http://127.0.0.1:8000/), renders the template with the blog post content missing.
One solution would be to swap the order in which path('', include('redactors.urls')), and path('', include('posts.urls')), as they appear inside urlpatterns list. With that change, the result is this. As you can see in this second image, the blog post content renders with and without the card number entered but then below the green heading element doesn't process in the webpage to the right, it's just blank. I'm expecting to see: 'xxxx xxxx 1111'.
My question is: How do I get the ccEntry get request to process so that the blog post content text is rendered when the user lands on the home page and when the web user enters their 12-digit card number?
It's also worth noting that I'm not getting a trace back and my server is not crashing so I don't have many leads in terms of searching on Google for other developers resolving similar or related issues.
Here are the views, the template and the urls.py in play.
Main project urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
   path('admin/', admin.site.urls),
   path('', include('redactors.urls')),
   path('', include('posts.urls')),
   path('', include('counters.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Take note of the positioning of path('', include('redactors.urls')), and path('', include('posts.urls')), When I the two positions, I get a different result but still does not achieve my goal (as described above).
redactors.views:
from django.shortcuts import render
from posts.models import Posts

def home(request):
   if 'ccEntry' in request.GET:
       number = request.GET['ccEntry']
       redacted_num = 'xxxx xxxx {}'.format(number[-4:])
       posts = Posts.objects.all().order_by('-pub_date')
       # context = {'posts':posts}
       return render(request, 'alls/landings.html', {'number':number, 'redacted_num':redacted_num, 'posts':posts, })
   else:
       return render(request, 'alls/landings.html')

posts.views:
from django.shortcuts import redirect, render, get_object_or_404
from posts.models import Posts

def posts(request):
  posts = Posts.objects.all().order_by('-pub_date')
  context = {'posts':posts}
  return render(request, 'alls/landings.html', context)

templates/alls.html:

Enter your fake Chuckee Cheese Neptune membership card number!

   <form action="{% url 'home' %}" method="get">

       Enter Card Number:
       <input type="text" id="password" name="ccEntry" pattern="[0-9]{12}" maxlength="12"/>

Must be a 12 digit number and no letters.

       <input type="submit" value="Redact!" class="button"/>

   </form>

Here is your fake Chuckee Cheese Neptune membership card number!

This was the original number that you entered:

{{ number }}

Here it is redacted:

{{ redacted_num }}

Again? Click here!

 {% for post in posts %}

 Blog post title: {{ post.title }}

Publication Date: {{ post.pub_date_preference }}

{{ post.body|safe }}

 {% endfor %}

The above three files I think is where my problem is. But in case you people need to explore some of my other project files, here is a static snapshot (tagged as v0.9.0) of the full source code repo on my GitHub.

A: Strange: Moments ago I merged my redactors branch into master. There were two minor merge conflicts.
My urlpatterns list variable inside my redactor app's urls.py used to look like this:
urlpatterns = [
    path('', views.home, name='home'),
]

Basically, when I passed in 'home'` to the first path argument like this:
urlpatterns = [
    path('home', views.home, name='home'),
]

...everything seems to run as intended. The blog post content is present with or without form input and the POST request processes as expected. Hooray!


text:
Q: Firebase authentication does not work after publishing After publishing the application i cannot use firebase authentication i get an error saying : this app is not authorized to use firebaseauthentication check sha1 or package name
I went and got the sha1 that is in the jks file and added it to firebase but the problem remains what should i do?

A: Solved by updating the app bundle after adding the SHA1 to firebase thanks


text:
Q: How do I connect PHP to mysql to my website's Database? This is the error I'm getting

PHP Warning:  mysqli::__construct(): (HY000/1130): Host 'ip98-436-9-183.dc.dc.cox.net' is not allowed to connect to this MySQL server in /home/ahmadarsalann/php/edit.php on line 7
Connection failed: Host 'ip72-205-1-229.dc.dc.cox.net' is not allowed to connect to this MySQL server

Down below is the code I'm using
<?php
$servername = "umw3.reclaimhosting.com";
$username = "username";
$password = "password";

// Create connection
 $conn = new mysqli($servername, $username, $password);

// // Check connection
 if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}
   echo "Connected successfully";
?>

I'm using wordpress, and I'm trying to connect to the backend of the database in the code to edit data on there. The password and username isn't real for security reasons. But so far this is what I got to connect to the database using php, because that's the language it's using.
The database is in the php my admin
I'm trying to access wp post. It is in php myAdmin, wp post is used by wordpress.
The picture of the info needed here :


text:
Q: Members table with one instead of three unique fields In almost each code example by creating mysql joinUs table, there is the code like this:
CREATE TABLE `members` (
`id` int(10) unsigned NOT NULL auto_increment,
`username` text, //unique
`email` text, //unique
`pass` text,
PRIMARY KEY  (`id`)

So, if username and/or email is set as unique, what is then the purpose of id field?
Can I simply set username as primary key and exclude the id from the table?

A: Id is a nice convention because it will never change. That lets other tables reference users via their id, and enables you to let users change their usernames and emails. Having said that, yes, you could use username as a primary key.


text:
Q: How to update two data tables back to db using OleDb and DataAdapter in c# I got two datatables from a mdb file using oledb and modified it.
accessConnection.Open();

string selectQuery = "SELECT * FROM Students";
DataAdapter = new OleDbDataAdapter(selectQuery, accessConnection);
DataAdapter.Fill(StudentsDataTable);

DataAdapter.SelectCommand.CommandText = "SELECT * FROM Teachers";
DataAdapter.Fill(TeachersDataTable);

// modified the two datatables
// ...

However, I have a problem in updating the two tables back into the mdb file. I can't update StudentsDataTable because the DataAdapter select command was already changed to select TeachersDataTable. When I handle only one DataTable, I don't have this kind of problem.
DataAdapter.UpdateCommand = new OleDbCommandBuilder(DataAdapter).GetUpdateCommand();
DataAdapter.Update(StudentsDataTable); <-- exception error occur that columns don't match.
DataAdapter.Update(TeachersDataTable);

Do you have any ideas for updating two datatables using one DataAdapter? or Should I have separate DataAdapters for the two tables?

A: Essentially you have to create two instances.
DataAdapter.UpdateCommand = new OleDbCommandBuilder(DataAdapter).GetUpdateCommand();
DataAdapter.Update(TeachersDataTable);

DataAdapter.SelectCommand.CommandText = "SELECT * FROM Students";
DataAdapter.UpdateCommand = new OleDbCommandBuilder(DataAdapter).GetUpdateCommand();
DataAdapter.Update(StudentsDataTable);

The main issue is your DataAdapter is set to Teachers table as it was the last command set on it.


text:
Q: Arch os-prober won't find Windows 10 on different disk Ok so I have read similar questions but I haven't been able to solve my problem so far.
I have just installed an Arch in a SSD (located on /dev/sdc) and I have a Windows 10 on another SSD (/dev/sda).
My problem is that when executing grub config (grub-mkconfig -o /boot/grub.d/grub.cfg) and having enabled os-prober, it still won't find the Windows 10 entry.
The output of fdisk -l is:
Disk /dev/sda: 223.57 GiB, 240057409536 bytes, 468862128 sectors
Disk model: INTEL SSDSCKKW24
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xd67b45de

Device     Boot     Start       End   Sectors   Size Id Type
/dev/sda1  *         2048   1026047   1024000   500M  7 HPFS/NTFS/exFAT
/dev/sda2         1026048 467744983 466718936 222.5G  7 HPFS/NTFS/exFAT
/dev/sda3       467746816 468856831   1110016   542M 27 Hidden NTFS WinRE

Disk /dev/sdb: *Omitted*

Disk /dev/sdc: 465.76 GiB, 500107862016 bytes, 976773168 sectors
Disk model: Samsung SSD 870
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: E2F762F9-0255-497D-934E-0B8DF1009AD8

Device        Start       End   Sectors   Size Type
/dev/sdc1      2048   1050623   1048576   512M EFI System
/dev/sdc2   1050624  34605055  33554432    16G Linux swap
/dev/sdc3  34605056 976773134 942168079 449.3G Linux filesystem

How could I fix it so that os-prober detects my Windows 10 system?
Edit
As some answers to similar questions suggested, I already tried installing ntfs-3g, mounting the Windows partitions and re-running grub-mkconfig but it still won't detect the system.


text:
Q: Straight paths Dijkstra's Algorithm implementation I have recently been trying to implement Dijkstra's Algorithm in Javascript using the tutorial here. I'm able to make it go around obstacles successfully, but the paths it makes are simply not optimal, usually coming off as very straight. I think the problem is with how he implemented finding the neighbors. His code seems to pick the neighbors in a near-random order while mine always picks them in a set order, so that's probably a good place to look. I couldn't for the life of me figure it out. I tried everything I could think of.
My filling implementation is this:
function floodFill(array,sx,sy,dx,dy){
    var frontier=[[sx,sy]];
    array[sy][sx].visited=true;
    var look=[[-1,0],[0,-1],[1,0],[0,1]];
    var looks=0;
    while(frontier.length>0){
        if(frontier.length>0){
            var current=frontier[0];
            frontier.splice(0,1);
            if(current[0]==dx && current[1]==dy){
                console.log("Broke early!");
                break;
            }
            for(var i=0;i<look.length;i++){
                var y=current[0]+look[i][0];
                var x=current[1]+look[i][1];
                if((y>=0 && y<array[current[0]].length) && (x>=0 && x<array.length)){
                    if(array[y][x].visited==false && array[y][x].type==0){
                        frontier.push([y,x]);
                        looks++;
                        array[y][x].visited=true;
                        array[y][x].origin=[current[0],current[1]];
                        array[y][x].order=looks;

                    }
                }
            }
        }
    }
}

You can find a demo here (you need to open up your javascript console to see it)
Thank you very much for your time.
Here's an image of my problem

A: Figured out the answer. To put it simply, I wasn't checking diagonals when I was finding the neighbors.
You can find a working version here
The part that I changed
var look=[[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]];


text:
Q: How to convert Mupad symbol 'I' {sqrt(-1)} to 'i' in matlab I am trying to evaluate this integral in matlab

matlab is treating 'ans' as a symbol because of 'I'. How to convert this 'I' into 'i' so that ans becomes a complex number.
much appreciated!

A: The symbolic math toolbox has an overloaded double function that can be used to convert from sym to double representation (if the expression is a symbolic constant or is a constant expression).
For example:
ans_sym = vpa(1+1*i);
ans_double = double(ans_sym);

Look here for more information: http://www.mathworks.se/help/toolbox/symbolic/double.html.


text:
Q: Change SpatialLinesDataFrame coordinates to fit into a shapefile I have a SpatialLinesDataFrame of streets in Malawi and  Shapefile of Malawi country. The problem is that the coordinates of some parts of one of the streets are located in the Malawi lake (and it's clearly not possible in the reality), so I think there are some problems between the shapefile and the SpatialLinesDataFrame. How can I correct the coordinates of the SpatialLinesDataFrame so that they can overlap correctly? The shapefile I am using for Malawi can be found here : mwi_adm_nso_20181016_SHP.zip (the name of the file I am using is mwi_admbnda_adm3_nso_20181016.shp).
Here the code to create the SpatialLinesDataframe of the street that has segments in the lake.
# download the shapefile of Malawi
mySHPM <-
  shapefile(
    paste(
      path,
      "/mwi_admbnda_adm3_nso_20181016.shp",
      sep = ""
    )
  )
# subset to focus on the area where the street is
mySHP <- mySHPM[mySHPM$ADM2_EN %in% c("Karonga", "Rumphi"), ]

# define the SpatialLinesDataframe for the street that goes in the lake
Xline <- c(34.21031,34.21031,34.21027,34.21026,34.21023,34.21022,34.21006,34.20951,34.20848,34.20763,
           34.20712,34.20624,34.20524,34.20443,34.20412,34.20409,34.20409,34.20421,34.20418,34.20414,
           34.20403,34.20437,34.20503,34.20548,34.20598,34.20625,34.20589,34.20493,34.20467,34.20449,
           34.20376,34.20349,34.20377,34.20444,34.20598,34.20694,34.20912,34.20978,34.20999,34.20985,
           34.20950,34.20864,34.20822,34.20820,34.20838,34.20890,34.20905,34.20876,34.20798,34.20697,
           34.20599,34.20399,34.20219,34.20074,34.19889,34.19631,34.19428,34.19126,34.18883,34.18757,
           34.18614,34.18343,34.18179,34.17895,34.17602,34.17429,34.17208,34.17101,34.16972,34.16955,
           34.16949,34.16944,34.16954,34.16986,34.16973,34.16935,34.16908,34.16896,34.16874,34.16783,
           34.16684,34.16574,34.16509,34.16471,34.16463,34.16445,34.16422,34.16420,34.16399,34.16386,
           34.16358,34.16319,34.16275,34.16217,34.16153,34.16145,34.16154,34.16207,34.16210,34.16196,
           34.16145,34.16095,34.16044,34.15993,34.15940,34.15889,34.15835,34.15780,34.15720,34.15652,
           34.15592,34.15546,34.15524,34.15497,34.15463,34.15426,34.15387,34.15335,34.15306,34.15270,
           34.15222,34.15185,34.15141,34.15107,34.15080,34.15071,34.15080,34.15120,34.15137,34.15167,
           34.15143,34.15091,34.15038,34.14988,34.14946,34.14922,34.14899,34.14851,34.14815,34.14800,
           34.14762,34.14732,34.14697,34.14715,34.14691,34.14640,34.14608,34.14568,34.14541,34.14543,
           34.14590,34.14617,34.14634,34.14649,34.14670,34.14647,34.14623,34.14614,34.14628,34.14649,
           34.14633,34.14608,34.14591,34.14556,34.14515,34.14494,34.14472,34.14444,34.14414,34.14378,
           34.14354,34.14322,34.14309,34.14320,34.14355,34.14380,34.14419,34.14451,34.14485,34.14522,
           34.14538,34.14530,34.14525,34.14522,34.14522,34.14520,34.14521,34.14487,34.14455,34.14419,
           34.14378,34.14341,34.14304,34.14306,34.14355,34.14411,34.14461,34.14485,34.14480,34.14468,
           34.14448,34.14448,34.14438,34.14445,34.14449,34.14443,34.14419,34.14395,34.14341,34.14293,
           34.14259,34.14268,34.14319,34.14367,34.14371,34.14401,34.14402,34.14379,34.14326,34.14281,
           34.14225,34.14182,34.14130,34.14082,34.14021,34.14002,34.13975,34.13975,34.14023,34.14068,
           34.14111,34.14147,34.14145,34.14144,34.14097,34.14035,34.13982,34.13912,34.13863,34.13819,
           34.13769,34.13761,34.13751,34.13746,34.13699,34.13661,34.13670,34.13716,34.13736,34.13718,
           34.13663,34.13655,34.13655,34.13662,34.13683,34.13707,34.13728,34.13741,34.13740,34.13761,
           34.13824,34.13843,34.13842,34.13796,34.13723,34.13716,34.13718,34.13709,34.13689,34.13702,
           34.13744,34.13761,34.13754,34.13755,34.13722,34.13682,34.13665,34.13634,34.13631,34.13623,
           34.13625,34.13639,34.13652,34.13656,34.13695,34.13717,34.13716,34.13694,34.13683,34.13632,
           34.13584,34.13532,34.13487,34.13437,34.13384,34.13348,34.13303,34.13258,34.13235,34.13206,
           34.13204,34.13173,34.13134,34.13130,34.13102,34.13098,34.13089,34.13066,34.13052,34.13049,
           34.13005,34.13001,34.12955,34.12952,34.12938,34.12859,34.12828,34.12784,34.12704,34.12610,
           34.12483,34.12405,34.12284,34.12198,34.12105,34.11939,34.11927,34.11853,34.11828,34.11751,
           34.11658,34.11550,34.11403,34.11364,34.11339,34.11303,34.11240,34.11173,34.11087,34.11034,
           34.10987,34.10982,34.11021,34.11024,34.11016,34.10976,34.10923,34.10895,34.10898,34.10904,
           34.10887,34.10870,34.10847,34.10803,34.10774,34.10691,34.10652,34.10620,34.10544,34.10540,
           34.10547,34.10630,34.10641,34.10682,34.10677,34.10665,34.10664,34.10727,34.10819,34.10943,
           34.11040,34.11054,34.11062,34.11087,34.11081,34.11079,34.11079)

Yline <-
c(-10.45258, -10.45259, -10.45294, -10.45369, -10.45489, -10.45648, -10.45859, -10.46091, -10.46452, -10.46747,
-10.46972, -10.47282, -10.47625, -10.47942, -10.48181, -10.48305, -10.48489, -10.48688, -10.49033, -10.49375,
-10.49606, -10.49860, -10.50286, -10.50589, -10.50926, -10.51182, -10.51374, -10.51642, -10.51806, -10.52037,
-10.52250, -10.52405, -10.52527, -10.52634, -10.52831, -10.52905, -10.53041, -10.53148, -10.53272, -10.53478,
-10.53576, -10.53710, -10.53811, -10.53825, -10.53968, -10.54224, -10.54315, -10.54454, -10.54563, -10.54692,
-10.54783, -10.54895, -10.54994, -10.55071, -10.55176, -10.55325, -10.55491, -10.55747, -10.55951, -10.56054,
-10.56163, -10.56337, -10.56472, -10.56799, -10.57132, -10.57269, -10.57448, -10.57609, -10.57886, -10.58046,
-10.58276, -10.58438, -10.58613, -10.58850, -10.59053, -10.59210, -10.59307, -10.59355, -10.59357, -10.59333,
-10.59312, -10.59287, -10.59279, -10.59252, -10.59238, -10.59253, -10.59336, -10.59393, -10.59408, -10.59396,
-10.59353, -10.59313, -10.59288, -10.59271, -10.59255, -10.59260, -10.59274, -10.59306, -10.59316, -10.59317,
-10.59296, -10.59305, -10.59316, -10.59342, -10.59353, -10.59358, -10.59341, -10.59330, -10.59337, -10.59367,
-10.59402, -10.59435, -10.59463, -10.59494, -10.59532, -10.59560, -10.59559, -10.59548, -10.59519, -10.59497,
-10.59484, -10.59461, -10.59478, -10.59503, -10.59486, -10.59503, -10.59509, -10.59530, -10.59564, -10.59584,
-10.59583, -10.59578, -10.59600, -10.59620, -10.59639, -10.59614, -10.59587, -10.59588, -10.59584, -10.59549,
-10.59499, -10.59452, -10.59414, -10.59381, -10.59365, -10.59368, -10.59346, -10.59331, -10.59317, -10.59330,
-10.59354, -10.59390, -10.59430, -10.59461, -10.59489, -10.59503, -10.59519, -10.59505, -10.59496, -10.59479,
-10.59466, -10.59449, -10.59425, -10.59387, -10.59365, -10.59346, -10.59352, -10.59341, -10.59355, -10.59355,
-10.59316, -10.59312, -10.59314, -10.59323, -10.59332, -10.59374, -10.59384, -10.59372, -10.59391, -10.59422,
-10.59455, -10.59488, -10.59493, -10.59490, -10.59490, -10.59477, -10.59437, -10.59416, -10.59399, -10.59421,
-10.59427, -10.59405, -10.59378, -10.59391, -10.59426, -10.59459, -10.59435, -10.59452, -10.59462, -10.59500,
-10.59540, -10.59564, -10.59566, -10.59519, -10.59477, -10.59469, -10.59481, -10.59492, -10.59478, -10.59458,
-10.59454, -10.59468, -10.59489, -10.59522, -10.59558, -10.59608, -10.59612, -10.59612, -10.59556, -10.59541,
-10.59550, -10.59559, -10.59540, -10.59518, -10.59522, -10.59529, -10.59534, -10.59547, -10.59551, -10.59564,
-10.59592, -10.59610, -10.59623, -10.59621, -10.59598, -10.59587, -10.59586, -10.59580, -10.59568, -10.59572,
-10.59554, -10.59546, -10.59492, -10.59453, -10.59403, -10.59389, -10.59357, -10.59333, -10.59308, -10.59286,
-10.59283, -10.59279, -10.59239, -10.59197, -10.59184, -10.59131, -10.59120, -10.59101, -10.59062, -10.59048,
-10.59021, -10.59022, -10.59011, -10.59019, -10.59054, -10.59093, -10.59098, -10.59106, -10.59102, -10.59058,
-10.59023, -10.59009, -10.59001, -10.59002, -10.59028, -10.59057, -10.59101, -10.59129, -10.59150, -10.59152,
-10.59151, -10.59108, -10.59072, -10.59039, -10.59010, -10.58976, -10.58972, -10.58904, -10.58882, -10.58845,
-10.58838, -10.58833, -10.58859, -10.58851, -10.58845, -10.58817, -10.58790, -10.58771, -10.58768, -10.58799,
-10.58799, -10.58738, -10.58720, -10.58723, -10.58757, -10.58774, -10.58812, -10.58875, -10.58917, -10.58920,
-10.58930, -10.58927, -10.58915, -10.58919, -10.58933, -10.58968, -10.58981, -10.58970, -10.58913, -10.58871,
-10.58863, -10.58875, -10.58869, -10.58857, -10.58840, -10.58776, -10.58771, -10.58709, -10.58688, -10.58693,
-10.58698, -10.58680, -10.58643, -10.58626, -10.58621, -10.58628, -10.58687, -10.58748, -10.58799, -10.58860,
-10.58908, -10.58929, -10.59015, -10.59142, -10.59176, -10.59204, -10.59191, -10.59216, -10.59234, -10.59253,
-10.59294, -10.59297, -10.59298, -10.59285, -10.59288, -10.59313, -10.59308, -10.59325, -10.59455, -10.59463,
-10.59521, -10.59622, -10.59643, -10.59773, -10.59809, -10.59836, -10.59890, -10.60086, -10.60199, -10.60337,
-10.60447, -10.60461, -10.60458, -10.60432, -10.60430, -10.60432, -10.60433)

coords <- as.data.frame(cbind(x = Xline, y = Yline))
Slo1 <- Line(coords)

Sli1 <- Lines(list(Slo1),ID="ID")
HMline <- SpatialLines(list(Sli1))
class(HMline)
proj4string(HMline) <- proj4string(mySHP)
plot(mySHP)
plot(HMline, add = T, col = "red")
# you can notice a small segment going outside the shapefile. if you can't, look at this:

# crop the street to save in "cropped" just the segments that are not overlapping the shapefile
cropped <- gDifference(HMline, mySHP)
plot(HMline)
plot(cropped, add = T, col = "red", lwd = 4)

Thanks for your help!


text:
Q: Explain sufficient statistic for Poisson distribution The Wikipedia entry on this topic is, to me, very confusing. It states that:

If X1, ...., Xn are independent and have a Poisson distribution with parameter λ, then the sum T(X) = X1 + ... + Xn is a sufficient statistic for λ.

I know that $T(X)$ is the "sufficient statistic" function, but I am lost as to what "sum T(X)" means in this context. The sum of my iid observations? What does that even mean if they are N-dimensional?
The demonstration below this line is also confusing (to me) and even mentions a function "h(x)" which is never explained as far as I can see.
Could you explain the concept of "sufficient statistic" for a Poisson distributed sample better?


text:
Q: Combinatorial proof involving sum of factorials I need help with this combinatorial proof:
$1\cdot1!+2\cdot2!+\cdots+n\cdot n!=(n+1)!-1$
So far I came up with this:
Let S be a set of numbers $1, 2, \ldots, n+1$
So LHS could be: How many permutations of length $k$ there is over set $S$ such that number $1$ is not the first in permutation. $k$ can be $2, 3,\ldots, n+1$. But the RHS gives me trouble...
Thanks.
(Sorry for the poor formating, I am not good with HTML)

A: $n\cdot n!$ counts the number of ways to order $\{1,2,3,\ldots,n+1\}$ without $n+1$ being first.
$(n-1)\cdot (n-1)!$ counts the number of ways to order $\{1,2,3,\ldots,n+1\}$ with $n+1$ being first and $n$ not second.
$(n-2)\cdot (n-2)!$ counts the number of ways to order $\{1,2,3,\ldots,n+1\}$ with $n+1$ being first and $n$ second and $n-1$ not third.
Etc...
The RHS is all the ways to order $\{1,2,3,\ldots,n+1\}$ without all the elements in descending order.

A: We want to show that the permutations of $n+1$ elements, except for one of them, are in bijective correspondence with the pairs $(j,\tau)$ where $\tau$ is a permutation of $k\le n$ elements and $1\le j\le k$, for some $k$.
Here's a correspondence. We start with a permutation $\sigma$ of $\{1,2,3,\ldots,n+1\}$, for example
 i        1 2 3 4 5 6 7 8 9 10
sigma(i)  1 6 3 2 7 5 4 8 9 10

If the permutation is the identity, then it doesn't map anywhere! Otherwise let $k+1$ be the largest index such that $\sigma(k+1)\ne k+1$. In the example $k+1=7$. We have $k\ge 1$ because index $1$ can't be the latest difference between $i$ and $\sigma(i)$.
Let the first output $j$ be the number such that $\sigma(k+1-j)=k+1$. In other words, $j$ is the number of elements to the right of the $k+1$ in the lower line of the permutation, before the trailing sequence of unchanged positions. In the example above we have $j=2$ because the two elements 5 4 come between 7 and the final 8 9 10.
The second output $\tau$ is now defined by $\tau(i) = \begin{cases} \sigma(i) & i < j \\ \sigma(i+1) & i \ge j \end{cases}$
 i      1 2 3 4 5 6
tau(i)  1 6 3 2 5 4

This correspondence is bijective -- we can do it in reverse starting with $(j,\tau)$. First write down $\tau$, then insert the number $k+1$ before the $j$th-to-last element, and finally append the numers $k+2, k+3, \ldots, n+1$ at the end of the permutation.

A: hint: $n\cdot n! = (n+1)!-n!$. Can you continue?

A: Proof by induction works here. This is not a combinatorial proof though (sorry!).
At $n=1$, the statement $1\cdot 1!=2!-1$ is true; both sides equal $1$.
Assume the statement for $n=k$ is true: $$1\cdot 1!+2\cdot 2!+\cdots+k \cdot k!=(k+1)!-1$$
For $n=k+1$, we have
\begin{align}
1\cdot 1!+2\cdot 2!+\cdots+(k+1) \cdot (k+1)!&=1\cdot 1!+2\cdot 2!+\cdots+k\cdot k!+(k+1) \cdot (k+1)! \\
&=(k+1)!-1+(k+1)\cdot(k+1)! \\
&=(k+1)!(1+(k+1))-1 \\
&=(k+1)!(k+2)-1 \\
&=(k+2)!-1
\end{align}


text:
Q: Hard drive causing BSOD I've come across a problem after building my new PC and installing a clean Windows 7.
I originally planed on a RAID 1 or 0 but after further research I decided against it.
So I was left with two 1TB Western Digital Black SATA 6Gb/s hard drives. My plan now was to use my second hard drive as a backup (using Windows Backup or 3rd party software). I set both hard drives to AHCI in the BIOS and installed Windows 7. I went through the lengthy process of downloading and installing each driver manually (latest versions), using the motherboard disk for a list of what I need. After a few restarts and before installing any software, I took an image backup onto DVD and the second hard drive.
First witnessed the problem during the first scheduled Windows backup. The progress bar froze at about 70% (doc backup done, image backup in progress). It stayed still for 2 hours until it blue screened. Next time the backup froze, I tried shutting down. It logged me out and got stuck at the last step ("Shutting down" and blue spinner) for an hour, until I hard shutdown.
I later realised this hasn't got anything to do with the backup. I ended up blue screening on almost every shut down (same place). Turns out, it's because of the second hard drive spinning down or turning off. The computer will now shutdown properly, as long as I remember to read or write to the second drive before executing shutdown.
I've now set "Turn off hard disk after: Never" - No problems, so far.
Do I have dodgy hard drive(s) or should I investigate the POWER_STATE_DRIVER_FAILURE BSOD - can it be a driver issue? AHCI?


text:
Q: RabbitMQ getting unacknowledged messages I have a RabbitMQ server which has around 100 of queues having around 100 messages in each. All the queues has same exchange and individual routing keys.
I am using Spring's amqp framework to interact with the RabbitMQ server. I have multiple applications using the same RabbitMQ server (i.e multiple consumers).
The problem I'm facing is that for some particular consumers though the
messages are received , the ack is failing i.e I can see some unacknowledged messages in some queues. Now the pickle is that if my application even accidentally receives a duplicate (unacked message i.e a message which has been received previously) message it throws exception and that's what I have started getting for those unacked messages.
But I'm not even sure that when and why I will get an unacked (i.e duplicate)message as I not sure about the priority of the unacked messages. So, can you guys give the solutions for the following problem :

*

*Even After getting the messages properly why for sometimes only the ack is  not successful.

*Even if there is no solution of the first problem 1 how I should configure my application so that it should never ever receive an unacked (duplicate) message.
BTW the behavior has not been seen from the very beginning of the creation
of the application, it started behaving in this way lately.

A: Take a look at the following:

*

*Semaphore queue implemented in Rabbit. ( optionally you can use zookeeper or etcd to achieve this)

*When you receive a message, it has a flag redelivered which is set  when the message was already consumed by other consumer, but went back to the queue for some reason. So you can simply check for that and if it's set, then drop the message.


text:
Q: Why is sbt quitting when using fish? I'm trying to get sbt running using the fish shell.
#!/usr/local/bin/fish
java -Xmx512M -jar (dirname (status -f))/sbt-launch-0.7.4.jar "$argv"

When I call sbt I get the following
[info] Building project MyProject 1.0 against Scala 2.8.1
[info]    using MyProject with sbt 0.7.4 and Scala 2.7.7
[info]
[info] Total session time: 1 s, completed Dec 19, 2010 4:29:46 PM
[success] Build completed successfully.

Then sbt quits.  Why?  Shouldn't it just wait for commands?
On a possibly related note, I'm sure I didn't used to have to do #![shell] on the first line when I was using bash.  What's changed?
UPDATE:
When writing the equivalent script to use bash everything works fine, sbt doesn't do a build then quit
#!/bin/bash
java -Xmx512M -jar `dirname $0`/sbt-launch-0.7.4.jar "$@"

A: If you don't use a shebang (#!/usr/local/bin/fish in your example), a script will run with the default shell on your system, which is likely /bin/sh.
If you run your script using #!/bin/sh or #!/bin/bash does it work the way you expect it to?
There's nothing in your script that should affect how things work differently from other shells. I don't understand how your script relates to what you're doing (mostly because I'm unfamiliar with sbt). What is the name of your script? How is it called? How are you calling sbt?

A: Looks like you're running the shell as a script, not a shell. Fish will just run your java command and then exit.
Take the bang out of that script and make it executable and you can just run it as
/path/to/fish /path/to/script
I believe.


text:
Q: region - date & time question in my C# program i receive date & time like this: DateTime.Now
and i get: 19/09/2010 20:10:30 because my region is: Hebrew (Israel)
but What happens if I'll install my program on computer with region English (united states)
I'll probably get an error because the format is MM/dd/yyyy hh:mm:ss
my question is, How to ensure that i Always get the date in dd/MM/yyyy hh:mm:ss format ?
in any type of region ?
thank's in advance

A: DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");

Output just generated:

19/09/2010 19:31:20

Just so you know "HH" is 24 hour clock hours, so from 0-23 and "hh" is 12 hour clock hours, so from 1-12. So with "hh" you'd need a "tt" after it. You also generally don't have the "0" in front of any hours < 10 when using a 12 hour clock.
Like:
DateTime.Now.ToString("dd/MM/yyyy h:mm:sstt");

19/09/2010 7:34:25PM

All of the format specifiers (so "h", "mm", "MM", etc) can be found here: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx


text:
Q: Lightning recordData - Namespace in Managed Package We are using lightning:recordData to create new records from a lightning component.  In my dev org I can so something like:
        cmp.find("myRecordCreator").getNewRecord(
        "MyObject__c", // sObject type (objectApiName)
        null,      // recordTypeId
        false,     // skip cache?
        $A.getCallback(function() {
            var rec = cmp.get("v.newRecord");
            var error = cmp.get("v.newRecordError");
            if(error || (rec === null)) {
                helper.showToastErrorMessage("Error initializing record template: " + error);
                return;
            }
        })
    );

When packed and deployed this fails with an error:

You don't have access to this record. Ask your administrator for help or to request access.

I'm pretty sure this is because MyObject__c is a custom object that has a namespace after being deployed.
What is the recommended method of getting the namespace so that I can have a conditional in my code to prepend this object name with a namespace when its running in a managed package?  The namespace of this object will be the same namespace of the component itself.


text:
Q: Strange problem with differential amplifier for current sensing with TL084 I have a problem with the circuit below:

I'm using the op-amp as differential amplifier for low-side current sensing with gain of 100. All resistors are 0.1% and the load is just a variable resistor for testing the circuit.
The problem is no matter what load I have and how much current is going through the sense resistor the output of the op-amp is around 23 - 24 volts. I tried switching all of the components checked all the connections and even rebuilt the circuit on a bread board with no avail. I feel like there is something obvious that I'm missing.
I have the same circuit in simulator and it works just fine.
Update: As I mentioned I did miss something obvious and didn't check the datasheet fully.

A:
You can't drive the input common mode voltage to 0V.
Have you tried to connect the load to GND and the shunt to 24v?
TL084 Datasheet


text:
Q: MySql Updating boolean value When I try to test manually updating the boolean value in my MySql table before implementing it into a ruby script, I get a match but no changes :

UPDATE calls SET ended = NOT ended WHERE incoming_Cid = '1234567890';
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1  Changed: 0  Warnings: 0

Unless I'm mistaken, this looks like correct syntax to me.
I looked at other threads concerning this issue (flipping boolean values) like here.
What would be a better way to accomplish this?

A: Would this work :
UPDATE calls set ended = !ended WHERE incoming_Cid = '1234567890';

A: Most likely your ended value was an SQL NULL value. The logical not of a null value is still null, so the DB is properly reporting "no changes", because the value in ended didn't change - it started out as null, and was still null:
mysql> create table foo (x boolean);
mysql> insert into foo values (null);
Query OK, 1 row affected (0.04 sec)

mysql> update foo set x=not x;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1  Changed: 0  Warnings: 0

mysql> update foo set x=not x;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1  Changed: 0  Warnings: 0

Note the Changed: 0. But once you reset x to a non-null value:
mysql> update foo set x=true;
Query OK, 1 row affected (0.06 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> update foo set x=not x;
Query OK, 1 row affected (0.04 sec)
Rows matched: 1  Changed: 1  Warnings: 0

rows start changing immediately.


text:
Q: Redux store not updating after dispatch (async data load) I've got a weird problem. I call a the dispatch method to load some data from a server. That works great, I manage to fetch my data and update the reducer state. But the redux store state does not seem to be updated. The useSelector constant is never updated. Any idea? Thanks for your help!
Here is the code...
App.tsx
function App(): ReactElement {

    //* Init *//
    const alertPopupRef = useRef(null);
    const [dataLoaded, setDataLoaded] = useState<boolean>(false);

    const applicationPreferences = useSelector<RootState, ApplicationPreferences>(state => state.applicationPreferences);

    const dispatch = useDispatch();

    useEffect(() => {
        // This code is only triggered once, when the component is mounted.
        console.log(applicationPreferences);
    }, [applicationPreferences]);

    dispatch(loadApplicationPreferences(showError));

    // Just for test.
    setTimeout(() => {
        // The 'ApplicationPreferences' variable is still empty.
        console.log(store.getState());
    }, 3000);

    //* Component Functions *//
    function showError(err: ApiBusinessLayerError): void {
        alertPopupRef.current.show(AlertsTypes.Error, err.error, err.description, true);
        console.log("showAlert is triggered.");
    }

    return (
        dataLoaded ?
            <AlertContext.Provider value={{ showError }}>
                <Alert ref={alertPopupRef} />
                <Router>
                    <Switch>
                        <Route exact path="/" component={public_welcome_page} />
                        <Route path="/signup" component={public_signup_page} />
                    </Switch>
                </Router>
            </AlertContext.Provider>
            :

                <Alert ref={alertPopupRef} />

                    Language: {applicationPreferences.language}

    );
}

application_preferences_reducer.ts
import produce from "immer";
import { ApiBusinessLayerError, ApiDataTypes, get } from "../api_business_layer";
import ApplicationPreferences from "../models/application_preferences";
import { RootState } from "../store";

//* ┌──────────────────┐
//* │ ETI DECLARATIONS │
//* └──────────────────┘
export interface ApplicationPreferencesState {
    language: string;
    server: string;
    isInDevelopement: boolean;
}

export enum ApplicationPreferencesActionsTypes {
    SET_PREFERENCES = "SET_PREFERENCES"
}

export type ApplicationPreferencesAction = {
    type: ApplicationPreferencesActionsTypes,
    payload: ApplicationPreferences[]
}

//* ┌─────────┐
//* │ ACTIONS │
//* └─────────┘
export function loadApplicationPreferences(errorCallback: (err: ApiBusinessLayerError) => void): Function {
    return async (dispatch: (action: ApplicationPreferencesAction) => RootState, getState: () => RootState): Promise<void> => {
        get<ApplicationPreferences>(ApiDataTypes.ApplicationPreferences, null, null)
            .then(data => { dispatch({ type: ApplicationPreferencesActionsTypes.SET_PREFERENCES, payload: data }); })
            .catch((err: ApiBusinessLayerError) => { errorCallback(err); });
    }
}

//* ┌─────────┐
//* │ REDUCER │
//* └─────────┘
const initialState: ApplicationPreferencesState = {
    language: "",
    server: "",
    isInDevelopement: false
}

const routes: { [actionType: string]: (state: ApplicationPreferencesState, action: ApplicationPreferencesAction) => ApplicationPreferencesState } = {
    [ApplicationPreferencesActionsTypes.SET_PREFERENCES]: _setApplicationPreferences,
}

function applicationPreferencesReducer(state: ApplicationPreferencesState = initialState, action: ApplicationPreferencesAction): ApplicationPreferencesState {
    if (!routes[action.type]) { return state; }
    return routes[action.type](state, action);
}

function _setApplicationPreferences(state: ApplicationPreferencesState, action: ApplicationPreferencesAction): ApplicationPreferencesState {
    return produce(state, state => {
        // The state is correctly set here.
        state = JSON.parse(JSON.stringify(action.payload[0]));
    });
}

export default applicationPreferencesReducer;

store.ts
import { applyMiddleware, CombinedState, combineReducers, createStore } from "redux";
import thunk from "redux-thunk";
import applicationPreferencesReducer, { ApplicationPreferencesState } from "./reducers/application_preferences_reducer";
import languagesReducer, { LanguagesState } from "./reducers/languages_reducer";
import signInReducer, { SignInState } from "./reducers/signin_reducer";
import userPrivilegesReducer, { UserPrivilegesState } from "./reducers/user_privileges_reducer";
import userTypesReducer, { UserTypesState } from "./reducers/user_types_reducer";

export type RootState = CombinedState<{
    applicationPreferences: ApplicationPreferencesState;
    language: LanguagesState;
    signIn: SignInState;
    userTypes: UserTypesState;
    userPrivileges: UserPrivilegesState;
}>

export const rootReducer = combineReducers({
    applicationPreferences: applicationPreferencesReducer,
    language: languagesReducer,
    signIn: signInReducer,
    userTypes: userTypesReducer,
    userPrivileges: userPrivilegesReducer
});

const store = createStore(rootReducer, applyMiddleware(thunk));

export default store;

index.tsx
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import "bootstrap/dist/css/bootstrap.min.css";
import "bootstrap/dist/js/bootstrap.min.js";
import App from "./App";
import { Provider } from 'react-redux';
import store from "./data/store";

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>
    , document.getElementById('root')
);

A: Not sure why you are using produce in the reducer since you don't actually change any subset of the state and instead return a completely newly created state. I think you can do the following:
//don't you hate code that wanders off the right side of the screen so you can't see what's going on, when someone sets their editor/formatter to a line length over 80
function _setApplicationPreferences(state: ApplicationPreferencesState, action: ApplicationPreferencesAction): ApplicationPreferencesState {
    return JSON.parse(JSON.stringify(action.payload[0]));
}


text:
Q: CSS animation working on Chrome but not on Safari and IOS I have a website where the content changes automatically as shown below.
But it doesn't work on IOS and safari.
Does spin not work here? or am i doing something wrong?
If it's an issue with IOS and Safari, How can i have a fallback text so that it doesn't look empty

#spin {
  color: red;
}

#spin:after {
  content: "";
  animation: spin 12s linear infinite;
}

@keyframes spin {
  0% {
    content: "Hello 1";
  }
  25% {
    content: "Hello 2";
  }
  50% {
    content: "Hello 3";
  }
  75% {
    content: "Hello 4";
  }
  100% {
    content: "Hello 5";
  }
}

  Say a warm

A: Safari has issues when it comes to animate the content property. Do this instead:

#spin {
  color: red;
  line-height: 1.2em;
  height: 1.2em;
  overflow: hidden;
  display: inline-block;
}

#spin:after {
  content: "Hello 1\A Hello 2\A Hello 3\A Hello 4\A Hello 5";
  display: block;
  white-space: pre;
  animation: spin 4s infinite steps(5);
}

@keyframes spin {
  100% {
    transform: translateY(-100%)
  }
}

  Say a warm

A: Replace this:
#spin {
  color: #red;
}

With this:
#spin {
  display: block;
  color: #red;
}

I´ve read it also works using:
display: inline-block;


text:
Q: Accessing a protocol's associated type in SwiftUI view produces compilation error I have a protocol with an associated type and a property. When I try to access the property in a SwiftUI View using an if let statement, I get the compilation error 'Command CompileSwift failed with a nonzero exit code' (Xcode 14.1) without any more error information. Why does this not compile?
Minimum reproducible example:
protocol MyProtocol {
    associatedtype MyAssociatedType
    var myAssociatedType: MyAssociatedType { get set }
}

struct MyView: View {
    @Binding var myProtocol: (any MyProtocol)

    var body: some View {
        Group {
            if let string = $myProtocol.myAssociatedType as? Binding<String> {
                TextField("", text: string)
            } else {
                EmptyView()
            }
        }
    }
}


text:
Q: Solution of $2{{I}_{xy}}={{I}_{x}}+{{I}_{y}}$ How i can find  the general solution of the following partial differential equation:
$$\frac{{{\partial }^{2}}I}{\partial x\partial y}=\frac{1}{2}\left( \frac{\partial I}{\partial x}+\frac{\partial I}{\partial y} \right)$$
I made a guess $I\left( x,y \right)={{e}^{x+y}}$

A: Hint:
Let $\begin{cases}p=x+y\\q=x-y\end{cases}$ ,
Then $\dfrac{\partial I}{\partial x}=\dfrac{\partial I}{\partial p}\dfrac{\partial p}{\partial x}+\dfrac{\partial I}{\partial q}\dfrac{\partial q}{\partial x}=\dfrac{\partial I}{\partial p}+\dfrac{\partial I}{\partial q}$
$\dfrac{\partial I}{\partial y}=\dfrac{\partial I}{\partial p}\dfrac{\partial p}{\partial y}+\dfrac{\partial I}{\partial q}\dfrac{\partial q}{\partial y}=\dfrac{\partial I}{\partial p}-\dfrac{\partial I}{\partial q}$
$\dfrac{\partial^2I}{\partial x\partial y}=\dfrac{\partial I}{\partial y}\left(\dfrac{\partial I}{\partial p}+\dfrac{\partial I}{\partial q}\right)=\dfrac{\partial I}{\partial p}\left(\dfrac{\partial I}{\partial p}+\dfrac{\partial I}{\partial q}\right)\dfrac{\partial p}{\partial y}+\dfrac{\partial I}{\partial q}\left(\dfrac{\partial I}{\partial p}+\dfrac{\partial I}{\partial q}\right)\dfrac{\partial q}{\partial y}=\dfrac{\partial^2I}{\partial p^2}+\dfrac{\partial^2I}{\partial p\partial q}-\dfrac{\partial^2I}{\partial p\partial q}-\dfrac{\partial^2I}{\partial q^2}=\dfrac{\partial^2I}{\partial p^2}-\dfrac{\partial^2I}{\partial q^2}$
$\therefore\dfrac{\partial^2I}{\partial p^2}-\dfrac{\partial^2I}{\partial q^2}=\dfrac{1}{2}\left(\dfrac{\partial I}{\partial p}+\dfrac{\partial I}{\partial q}+\dfrac{\partial I}{\partial p}-\dfrac{\partial I}{\partial q}\right)$
$\dfrac{\partial^2I}{\partial p^2}-\dfrac{\partial^2I}{\partial q^2}=\dfrac{\partial I}{\partial p}$
Similar to Can I combine the wave and heat equations?


text:
Q: Maximization algorithm for ball preferences I'm trying to devise the most efficient algorithm for a problem, but I'm having some difficulty. If someone could lend a hand, either by proposing an algorithm or classifying the problem so I can do some further research, I would be very appreciative.
The problem is as follows:
There are n (an integer) number of distinct red balls, each of which has its own number, and m number of distinct green balls, each of which has its own corresponding number as well. For example, if n = 3, then there are three red balls named Red Ball 1, Red Ball 2 and Red Ball 3.
There are also two boxes in which the balls can be placed.
Before the balls are placed in the boxes however, x number of people make predictions as to which balls will be placed in which box (either box 1 or box 2). Each person gets one prediction and for each prediction they can guess one ball to be in each box. The only condition is that the ball they guess in box 1 cannot be the same color as the ball they guess to be in box 2. An example prediction would be: "I think that Red Ball 2 will be in box 1 and Green Ball 3 will be in box 2"
After everyone has made their predictions, the balls will be placed in the boxes the maximize the number of predictions that are correct.
The code I must write will be prompted with n, m, and x as well as the predictions and then be asked to return the maximum number of predictions that are correct.
Once again, I am looking for either algorithmic help or help to identify the type of problem this is. I currently have a recursive algorithm running on (n^2), but I need something a little more efficient.
Thanks for your help! Cheers, Mates!