text:
Q: add value to form array on click I have the below code working onclick.
<form action="" name="testform" method="post" id="testform">
<input type="hidden" value="" name="a">
<input type="hidden" value="" name="b">
<input type="hidden" value="" name="c">
<select>
    <option value=""></option>
    <option value="" onclick="document.testform.a.value='12'; document.testform.b.value='111'; document.testform.c.value='123'">1</option>
    <option value="" onclick="document.testform.a.value='21'; document.testform.b.value='222'; document.testform.c.value='232'">2</option>
    <option value="" onclick="document.testform.a.value='32'; document.testform.b.value='333'; document.testform.c.value='233'">3</option>
    <option value="" onclick="document.testform.a.value='43'; document.testform.b.value='444'; document.testform.c.value='344'">4</option>
    <option value="" onclick="document.testform.a.value='54'; document.testform.b.value='555'; document.testform.c.value='345'">5</option>
</select>

When you select 1 the hidden fields of a,b,c get the value of 1.
This works fine however I have a larger project in mind here where the user can select multiple values for 'a' throughout the form.  Without onclick I can get this working well eg
<input type="hidden" name="a[]" value="1">

But when I do
<form action="" name="testform" method="post" id="testform">
<input type="hidden" value="" name="a[]">
<input type="hidden" value="" name="b[]">
<input type="hidden" value="" name="c[]">
<select>
    <option value=""></option>
    <option value="" onclick="document.testform.a[].value='12'; document.testform.b[].value='111'; document.testform.c[].value='123'">1</option>
    <option value="" onclick="document.testform.a[].value='21'; document.testform.b[].value='222'; document.testform.c[].value='232'">2</option>
    <option value="" onclick="document.testform.a[].value='32'; document.testform.b[].value='333'; document.testform.c[].value='233'">3</option>
    <option value="" onclick="document.testform.a[].value='43'; document.testform.b[].value='444'; document.testform.c[].value='344'">4</option>
    <option value="" onclick="document.testform.a[].value='54'; document.testform.b[].value='555'; document.testform.c[].value='345'">5</option>
</select>

I get nothing inserted into my hidden value.
Why is this?
Is there a better way of doing what I am trying to do with jQuery?

A: Here is the modified jsfiddle link for your problem.
http://jsfiddle.net/et3r7/12/ Please check if this helps you. I've made hidden to text in order to display the result you can make it them to hidden.
I had cleaned up your code little bit. Removed all the onClick code.

A: I don't think that .value is a property of an array. (Actually, I'm a derp, it may be a property of an array element - I'll look it up) I would also look at the push() method of an array for adding elements.
There are a couple other ways you could approach this task. With JS, you could abstract this a little, and  make a single function to do the work that each click is doing, which would make your code much more succinct.
This is easily done if jQuery, too, but I would be evaluating whether this bit of functionality is worth the additional download (jQuery is 32KB minified and zipped).


text:
Q: Reusable model AngularJS I am in a scenario where I need to be able to reuse a model. Basically, a user selects a dynamic amount of items on one view, and then they need to input various data for each of the items they selected in the following view.
For example, on view #1, I choose, "A, D, G".
Then on view #2, I have to fill out the following for A, D, G:
A: Name, Color, Age
D: Name, Color, Age
G: Name, Color, Age
Originally, I had it set up like this but realized that it wasn't very reusable:
angular.module('itemApp')
  .directive('itemInfo', function () {
    return {
      templateUrl: 'views/directives/item-info.html',
      restrict: 'E',
      controllerAs: 'item',
      scope: {
       myItems: '='
      },
      controller: function ($scope) {
        var vm = this;
        vm.myItems = $scope.myItems;
        vm.hideNextItem = false;
        vm.hidePrevItem = false;
        vm.currentItem = vm.myItems[0];
        vm.itemStep = '1';
        vm.itemInfo = {
          name: '',
          color: '',
          age: ''
        }
        ...
      }
    };
  });

Then I would use ng-repeat in the view to retrieve the information for the first item, push it into an array in the service, reset the model, use a function to select the next item, change the item step, and then repeat. Is there some way I can set up the itemInfo model in a service, somehow create a copy of it for each item, and store the info for each item in an array in the service? That way I would have all three item info available in the service and I wouldn't have to worry about resetting models etc. in a directive. Ultimately, I want to take the array of all three items and make a call to a webservice once this step is completed which would be much easier if all of the data was in one place.

redpajama_set_name: RedPajamaStackExchange


text:
Q: UIStackView with multiline label in a UITableViewCell incorrect height I have a table view where each cell displays an optional title and a multiline subtitle. I want the cell to be self-sizing (i.e grow along with the subtitle but stay as compact as possible). For that I use tableView.rowHeight = UITableView.automaticDimension
The problem I have is that there is quite a lot of vertical spacing around the subtitle in the cells that do have a title.
Cells without title are compressed correctly. Also when I reload the table view, all the layout becomes correct.
Expected behaviour:

Actual behaviour:

The cell has basically a UIStackView pinned to the cell's contentView.
import UIKit

public class TableViewCellSubtitle: UITableViewCell {

    private lazy var labelStack: UIStackView = {
        let labelStack = UIStackView()
        labelStack.alignment = .fill
        labelStack.distribution = .fillProportionally
        labelStack.axis = .vertical
        return labelStack
    }()

    private lazy var titleLabel: UILabel = {
        let titleLabel = UILabel()
        titleLabel.backgroundColor = UIColor.blue.withAlphaComponent(0.3)
        return titleLabel
    }()

    private lazy var subtitleLabel: UILabel = {
        let subtitleLabel = UILabel()
        subtitleLabel.numberOfLines = 0
        subtitleLabel.backgroundColor = UIColor.green.withAlphaComponent(0.3)
        return subtitleLabel
    }()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        setupUI()
        setupConstraints()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {

        contentView.addSubview(labelStack)
        labelStack.translatesAutoresizingMaskIntoConstraints = false
        labelStack.addArrangedSubview(titleLabel)
        labelStack.addArrangedSubview(subtitleLabel)

    }

    private func setupConstraints() {
        NSLayoutConstraint.activate([
                labelStack.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
                labelStack.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 12),
                contentView.bottomAnchor.constraint(equalTo: labelStack.bottomAnchor, constant: 12),
                contentView.trailingAnchor.constraint(equalTo: labelStack.trailingAnchor, constant: 16)
            ])
    }

    public func setup(title: String?, subtitle: String) {
        titleLabel.text = title
        if title == nil {
            labelStack.removeArrangedSubview(titleLabel)
            titleLabel.removeFromSuperview()
        }
        subtitleLabel.text = subtitle
    }
}

I tried setting the content hugging on the subtitle
subtitleLabel.setContentHuggingPriority(.required, for: .vertical)

but that makes the title to grow:

If I set it to both:
titleLabel.setContentHuggingPriority(.required, for: .vertical)
subtitleLabel.setContentHuggingPriority(.required, for: .vertical)

it becomes

In all the cases, if I reload the cell or the table view, the layout becomes correct (here on cell tap):

I'm aware that I could layout the cell without using the stack view but my real implementation is a bit more complex

A: *

*Try with fill instead of fill proportional

*Or try to set label.sizeToFit() to collapse label to its content size


text:
Q: Model XOR check into unique constraint I am modeling a reactions table with columns user_id, post_id, reaction. I want to have entries in this row to be unique which can be easily achieved with a unique index.
reactions can be like, dislike, viewed, applauded
Now the problem is, I also want to model a XOR relationship for like and dislike, meaning, when there is already a row with like for a given pst and user, it shoudn't be possible to add another row with dislike.
Since there are other optional reactions I don't know to write the constraint check for this. Is this even possible?

A: You only want the (user_id, post_id) uniqueness to apply when the reaction is 'like' or 'dislike'. That's a partial index:

When the WHERE clause is present, a partial index is created. A partial index is an index that contains entries for only a portion of a table, usually a portion that is more useful for indexing than the rest of the table. [...] Another possible application is to use WHERE with UNIQUE to enforce uniqueness over a subset of a table.

You want an index like this:
create unique index INDEX_NAME
on TABLE_NAME (user_id, post_id)
where reaction in ('like', 'dislike')

where you'd supply values for INDEX_NAME and TABLE_NAME of course.


text:
Q: PIC (dsPIC33EP 512MU810) : High Speed PWM module
*

*I'm trying to generate a 10% duty cycle-1kHz PWM with a clock at 80Mhz (F_osc) using the inbuilt (Hardware) high speed PWM.

*According to the documentation,
Base Period (number for the PTPER) is calculated by
PTPER = F_osc / [(F_pwm) x (PWM_Clk_Prescale)]
Substituting F_osc = 80Mhz, F_pwm = 1khz and Prescale = 8, I'm getting a count of PTPER=10,000.
However, from my output on an oscilloscope, I can see that I have PWM frequency of ~2khz..
Am I doing anything wrong? Below is my code --
#include<p33EP512MU810.h>
#include<p33Exxxx.h>

//---------------- compiler directives------------------
_FOSCSEL(FNOSC_FRC);
_FOSC(FCKSM_CSECMD & OSCIOFNC_OFF  & POSCMD_XT);    // Clock Switching Enabled and Fail Safe Clock Monitor is disabled
                                                    // OSC2 Pin Function: OSC2 is Clock Output
                                                    // Primary Oscillator Mode: XT Crystal
_FWDT(FWDTEN_OFF);                                  // Watchdog Timer Enabled/disabled by user software
//------------------------------------------------------

//function to initialise oscillator and set up clock
void Init_Oscillator(void)
{
   // Configure Oscillator to operate the device at 40Mhz
    // Fosc= Fin*M/(N1*N2), Fcy=Fosc/2
    // Fosc= 12M*40/(3*2)=80Mhz for 12M input clock
    // 0.5M < Fin/N1 < 8MHz
    // 100M < Fin*M/N2 < 200M
    // Fcy  = Fosc / 2 = 40 MIPS
    PLLFBD       = 38;  // M=80
    CLKDIVbits.PLLPOST = 0;   // N2=2
    CLKDIVbits.PLLPRE  = 1;   // N1=3
    OSCTUN             = 0;   // Tune FRC oscillator, if FRC is used
    RCONbits.SWDTEN=0;     // Disable Watch Dog Timer

    // Clock switch to incorporate PLL
    __builtin_write_OSCCONH(0x03);              // Initiate Clock Switch to
                                                                                // Primary Oscillator with PLL (NOSC=0b011)
    __builtin_write_OSCCONL(0x01);              // Start clock switching
    while (OSCCONbits.COSC != 0b011);           // Wait for Clock switch (to XT w/ PLL) to occur
    while(OSCCONbits.LOCK!=1) {}; // Wait for PLL to lock
}

void Init_PWM(void)
{
    /**** PTCON: PWM Time Base Control Register ****/
    PTCONbits.PTEN   = 0;   // Timer Enable bit:    DISABLE MCPWM

        //---------------------------------------------------------------
        //Prescaler 1:8
        PTCON2bits.PCLKDIV = 0b011; // PCLKSEL: 1,2,4,8,16,32,64
        //mode selection
        PWMCON1 = 0x0000;          //PTPER holds period count of PWM
        //Independent mode enable
        IOCON1 = 0xCC00; //fig 14-35 of PWM manual
        // 0xCC00 => PENH high, PENL high, PMOD: 11- True Independent PWM o/p

        //---------------------------------------------------------------
        /**** PTPER: PWM Time Base Period Register ****/
    PTPER = 10000; // Period Value bits
        //Enable PWM timer
        PTCONbits.PTEN   = 1;   // Timer Enable bit:    ENABLE MCPWM
}
//--- extra settings:
// 1) Stop in IDLE MODE :: PTCONbits.PTSIDL = 1 (yes)
// 2) Setting a particular pin as output ==> IOCONxbits.PENH(/L) = 1(enabled)
// 3) MDC,PDC,SDC et al depend on the PWM MODE.
//    Resp, selection of PTPER,PHASE,SPHASE.
//---

int main(void)
{
        Init_Oscillator();
    Init_PWM();// Initialize PWM module
        PDC1 = 1000; // This sets the duty cycle.
    while(1); //loop forever //while

return 0;
}

A: Despite your comments, I believe you have
PLLDIV = 78 // M = 80

So,
FOSC = FIN * PLLDIV / ((PLLPRE + 2) * 2 * (PLLPOST + 1))

FOSC = 8MHz * 80 / ((1 + 2) * 2 * (0 + 1))

FOSC = 8MHz * 80 / 6

FOSC = ~ 107 MHz

A: your pwm CONFIG for 80MHZ is right but make sure that your input frequency is 12MHZ ...i already test pwm for 80mhz with the same config of PWM and its generating proper output as you need 1KHZ. so check your PLL and Fcrystal config. i think you are generating pll 160MHZ.if you are using M=80 then you have to replace it with M=40 (PLLFBD = 38;),correct your comment or code.


text:
Q: Triple DES encryption Please note that the issue I am having here is with the key size. At first, based on the comments included in the below code, I figured that my key needed to be 24 bytes (192 bits). This didn't work so I gave 16, 32, and 8 byte keys a shot - nothing seems to be working. By "not working" I mean that after my text has been encrypted and decrypted it does not hold the same value as my original text.

Example:

Original Text: 'Example test this should work '
Encrypted Text: ¸¹pÕô6
Decrypted Text: 'Example '
Here are the two functions I am using (Encrypt / Decrypt functions). Also I will include how I am calling each function.
        // 168-bit (three-key) 3DES (Triple-DES) encrypt a single 8-byte block (ECB mode)
        // plain-text should be 8-bytes, key should be 24 bytes.
        public byte[] TripleDesEncryptOneBlock(byte[] plainText, byte[] key)
        {
            // Create a new 3DES key.
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();

            // Set the KeySize = 192 for 168-bit DES encryption.
            // The msb of each byte is a parity bit, so the key length is actually 168 bits.

            des.KeySize = 192;
            des.Key = key;
            des.Mode = CipherMode.ECB;
            des.Padding = PaddingMode.None;

            ICryptoTransform ic = des.CreateEncryptor();

            byte[] enc = ic.TransformFinalBlock(plainText, 0, 8);

            return enc;
        }

        public byte[] TripleDesDecryptBlock(byte[] plainText, byte[] key)
        {
            // Create a new 3DES key.
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();

            // Set the KeySize = 192 for 168-bit DES encryption.
            // The msb of each byte is a parity bit, so the key length is actually 168 bits.
            des.KeySize = 192;
            des.Key = key;
            des.Mode = CipherMode.ECB;
            des.Padding = PaddingMode.None;

            ICryptoTransform ic = des.CreateDecryptor();

            byte[] dec = ic.TransformFinalBlock(plainText, 0, 8);

            return dec;
        }

// Encrypt Text
textBox5.Text = ByteToString(TripleDesEncryptOneBlock(StringToByte(textBox5.Text), StringToByte("1 2 3 4 5 6 7 8 9 1 1 2 ")));

// Decrypt Text
textBox5.Text = ByteToString(TripleDesDecryptBlock(StringToByte(textBox5.Text), StringToByte("1 2 3 4 5 6 7 8 9 1 1 2 ")));

Thank you for any help,
Evan

A: The clue is in the name of the function you're using:  TripleDesEncryptOneBlock
This method only encrypts one block of the input string (8 bytes or 64 bits).  To encrypt the entire string you need to chain multiple calls to this method.

A: Use this:
byte[] enc = ic.TransformFinalBlock(plainText, 0, plainText.Length);
I hope it will encrypt/decrypt your whole string. Also you will need not to call this method multiple times

A: Your problem is here:
byte[] dec = ic.TransformFinalBlock(plainText, 0, 8);
                                                  ^

you only encode the first 8 characters of your array So when you decode, there are only those 8 characters to decode, which results in 'Example '.
if you want to encode all your text, you have to increase that value. But be carefull, if you use PaddingMode.None it will fail if the lenght of the array-to-be-encoded is not a multiple of 8.
I added some padding to my text like this:
int length = plainText.Length / 8;
if(plainText.Length%8 > 0)
{
    length++;
}
byte[] paddedText = new byte[length * 8];
plainText.CopyTo(paddedText, 0);
byte[] enc = ic.TransformFinalBlock(paddedText, 0, length * 8);


text:
Q: Using ADAL with SharePoint Framework I've setup a web part with SharePoint framework that requires access to the Microsoft Graph for displaying the recently used files.
I've followed the instruction here: https://github.com/SharePoint/sp-dev-docs/blob/master/docs/spfx/web-parts/guidance/call-microsoft-graph-from-your-web-part.md
I am not using the latest version of adal-angular because it was having timeout issues, it is also said in the guide above to use version 1.0.12 so I am using that version. For doing the component, I inspired myself from the Implicit Flow example: https://github.com/SharePoint/sp-dev-fx-webparts/tree/master/samples/react-aad-implicitflow
My component works fine on the local workbench.
On the SharePoint workbench, I get the following error

Token renewal operation failed due to timeout

When deployed, I ask for a Sign In, which opens a popup window but instead of coming back to the page I was, this popup stays open and that is where I see my recent files.
Am I doing anything wrong? I would like this to work as it does on the local workbench.

A: I have been facing the same issue while working and got a work around which is "We can you please try changing Redirect URL to any Classic page".
The problem is while requesting the Access Token from Modern Page, it throws an error. So, I changed the Redirect URL to one of my Classic Page.
I hope, this might work for you as well.


text:
Q: Vue v-on:click.native in JSX? How to write vue syntax v-on:click.native in JSX?
For example v-on:click in JSX is onClick.

A: Answer was in the documentation for babel-plugin-transform-vue-jsx and it is nativeOnClick:
<el nativeOnClick={this.nativeOnClickHandler} />

A: Accepted answer is wrong.
When using JSX (render function) you'd do this:
{
  components: {someComp},
  functional: true,
  render:function (h, c){
    return h(someComp, {
      nativeOn: {
        click: function(){
          //stuffs
        }
      },
    }, []);
  }
}

import SomeComp from '...'
return default {
  functional: true,
  render: (h, c) => <SomeComp nativeOn={{ click: e => { /* ... */} }} />
}

A: In vue/jsx latest version: https://github.com/vuejs/jsx
v-on:click.native => vOn:click_native


text:
Q: Set and Get attributes in Bunch type object For simplicity to parse/create JSON, machine learning applications usually uses the Bunch object, e.g. https://github.com/dsc/bunch/blob/master/bunch/__init__.py
When getting, there's a nested EAFP idiom that checks through the dict.get() function and then trying to access it with dictionary square bracket syntax, i.e.
class Bunch(dict):
    def __getattr___(self, k):
        try:
            return object.__getattribute__(self, k)
        except AttributeError:
            try:
                 return self[k]
            except KeyError:
                 raise AttributeError

And when trying to set an attribute,
    def __setattr__(self, k, v):
        try:
            # Throws exception if not in prototype chain
            object.__getattribute__(self, k)
        except AttributeError:
            try:
                self[k] = v
            except:
                raise AttributeError(k)
        else:
            object.__setattr__(self, k, v)

Seems like the sklearn implementation follows the same train of thought but has lesser checks https://github.com/scikit-learn/scikit-learn/blob/2beed5584/sklearn/utils/__init__.py#L61
class Bunch(dict):
    def __init__(self, **kwargs):
        super().__init__(kwargs)

    def __setattr__(self, key, value):
        self[key] = value

    def __dir__(self):
        return self.keys()

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(key)

    def __setstate__(self, state):
        # Bunch pickles generated with scikit-learn 0.16.* have an non
        # empty __dict__. This causes a surprising behaviour when
        # loading these pickles scikit-learn 0.17: reading bunch.key
        # uses __dict__ but assigning to bunch.key use __setattr__ and
        # only changes bunch['key']. More details can be found at:
        # https://github.com/scikit-learn/scikit-learn/issues/6196.
        # Overriding __setstate__ to be a noop has the effect of
        # ignoring the pickled __dict__
        pass

The nested EAFP seems a little hard to maintain, my questions here are:

*

*Is there a simpler way to handle get and set functions for Bunch data objects?

*Are there any other Dict like object that allows mutability between attributes and keys?

*How should Bunch object's .update() function work, shallow or deep copying? Or just let the default dict.update() do what it does?  Understanding dict.copy() - shallow or deep?

A: Lucky for you, all objects have an internal dict-like object that manages the attributes of the object (this is in the __dict__ attribute).  To do what you're asking, you just need to make the class use itself as the __dict__ object:
class Bunch(dict):
    def __init__(self, *args, **kwargs):
        self.__dict__ = self
        super().__init__(*args, **kwargs)

Usage:
>>> b = Bunch()
>>> b.foo = 3
>>> b["foo"]
3
>>> b["foo"] = 5
>>> b.foo
5
>>> b["bar"] = 1
>>> b.bar
1


text:
Q: Is there a way to use pygtex files without rerunning pygmentize? I have written a document describing a Python module and used minted with pygmentize. I have now hit an unexpected roadblock, as I need to hand control of the document to my company's publishing department for final formatting. That department has LaTeX but not Python and so I do not think they can install pygmentize, which requires Python.
Before abandoning minted and formatting a different way, I'm wondering if there's a way I can prepare the document so that they can compile it (assuming no changes to the code).
For example, if I had a .pygtex file for an inline compilation that said something like \mintedinline{python}|hello_world|:
\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{hello\PYGZus{}world}
\end{Verbatim}

Is there a way to put that into my document instead?
What about something like,
\begin{minted}{python}
print(p.__dict__())
#{
# 'lat': 90.0,
# 'lon': 0.0
}
\end{minted}

which creates the file
\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n+nb}{print}\PYG{p}{(}\PYG{n}{p}\PYG{o}{.}\PYG{n+nv+vm}{\PYGZus{}\PYGZus{}dict\PYGZus{}\PYGZus{}}\PYG{p}{())}
\PYG{c+c1}{\PYGZsh{}\PYGZob{}}
\PYG{c+c1}{\PYGZsh{} \PYGZsq{}lat\PYGZsq{}: 90.0,}
\PYG{c+c1}{\PYGZsh{} \PYGZsq{}lon\PYGZsq{}: 0.0}
\PYG{c+c1}{\PYGZsh{}\PYGZcb{}}
\end{Verbatim}

I believe that the list as ordered in the .aux file gives the order that they are used in the document (some are used more than once), so I could identify the.pygtex file that needs to be used at each location, but I can't figure out how to insert and compile the information.


text:
Q: JSP Page reloads with form submit - dynamic data not displayed I am new to JSP. I have a JSP page with form (Two text fields) on click of Search button, I am submitting the form and calling a Javascript function with in same JSP and in that function I have a scriptlet which connects to database and retrives user data as Arraylist. Now I am trying to push this array list values into Javascript. When I click on Search I dont see these values in GUI (form) but view source has values. Can anyone help me how to solve this issue? I guess this is because page reload but how to show up that data.
var UIDset = [];
var Nameset = [];
var OrgIDset = [];
<%
String uidValue="";
String orgIDValue="";
int i=0;
if(request.getParameter("UID")!=null)
    uidValue=request.getParameter("UID");
if(request.getParameter("OrgID")!=null)
    orgIDValue=request.getParameter("OrgID");
RetriveUserData rs = new RetriveUserData(uidValue, orgIDValue);
List<UserDetails> l=new ArrayList<>();
l=rs.performSearch();
%>
for(UserDetails ud : l)
{
%>
        UIDset.push(<%=ud.uid%>);
        Nameset.push(<%=ud.gName%>);
        OrgIDset.push(<%=ud.orgVal%>);
<%
}
%>


text:
Q: How to kill active connections based on DB_NAME using SQL? I am currently connected to a customer database via the front end using there application and I run the following query which displays active connections:
SELECT DB_NAME(DBID) AS DBNAME,
       COUNT(DBID)   AS NUMBEROFCONNECTIONS,
       LOGINAME      AS LOGINNAME
FROM   SYS.SYSPROCESSES
WHERE  DBID > 0
GROUP  BY DBID, LOGINAME

I have the ability to run SQL in the front end of the application therefore how can i kill all active connections based on a DB_NAME(DBID) = 'CustomerDB'
using SQL?

A: KILL command may not work for the newly established connection. You can try taking the database to Single_User mode rather using an ALTER statement like
ALTER DATABASE CustomerDB
SET SINGLE_USER WITH ROLLBACK IMMEDIATE

A: USE master
GO

DECLARE @kill varchar(8000) = '';
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), spid) + ';'
FROM master..sysprocesses
WHERE dbid = db_id('MyDB')

EXEC(@kill);

Credits: Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)


text:
Q: MobileVLCKit iOS UniversalBinary Versions Here are precompiled MobileVLCKit Universal Binaries for iOS: http://nightlies.videolan.org/build/iOS/?C=M;O=A
There are a lot of different versions like 0009, 0555, 0622, 1748 and so on.
Can anyone explain what is the difference between them and which should I use?

A: Those are development versions of our library, which we are building up to 3 times per week. Therefore, the newer the date, the newer the build. This is useful if you are waiting for a specific fix or feature to become available without having to compile it yourself.


text:
Q: How do I compare execution time of two queries is SQL Developer? I have two similar queries and I want to compare time they take to execute. However I cant figure out what is the right way to get query execution time and also how do I compare them fairly if each time you run a query its time gets lower?

A: you can get an average execution times from the v$sqlarea view.  Replace with whatever sql text to find your query.  Note that the rows in v$sqlarea are transient. Average times are in units of microseconds.
select sql_text, executions,
       elapsed_time/executions average_exec_time,
       cpu_time/executions  average_cpu_time
from v$sqlarea
where sql_text like 'SELECT blah blah FROM%'

Note that this is just a "ballpark" figure.


text:
Q: specify Asp.net LocalSqlServer connection string in code Normally, we define that connection string in web.config
Is there a way we can specify that connection string in code, like in Application_Start?
That connection string normally used to connect aspnetdb
example:

A: If you're not using entity framework, you can use the SqlConnectionStringBuilder class.
Example from MSDN:
Sub Main()
' Create a new DbConnctionStringBuilder, and add items
' to the internal collection of key/value pairs.
Dim builder As New DbConnectionStringBuilder()
builder.Add("Data Source", "c:\MyData\MyDb.mdb")
builder.Add("Provider", "Microsoft.Jet.Oledb.4.0")
builder.Add("Jet OLEDB:Database Password", "*******")
builder.Add("Jet OLEDB:System Database", _
    "c:\MyData\Workgroup.mdb")
' Set up row-level locking.
builder.Add("Jet OLEDB:Database Locking Mode", 1)

' Display the contents of the connection string, which
' will now contain all the key/value pairs delimited with
' semicolons.
Console.WriteLine(builder.ConnectionString)
Console.WriteLine()

' Clear the DbConnectionStringBuilder, and assign a complete
' connection string to it, to demonstrate how
' the class parses connection strings.
builder.Clear()
builder.ConnectionString = _
    "Data Source=(local);Initial Catalog=AdventureWorks;" & _
    "Integrated Security=SSPI"

' The DbConnectionStringBuilder class has parsed the contents,
' so you can work with any individual key/value pair.
builder("Data Source") = "."
Console.WriteLine(builder.ConnectionString)
Console.WriteLine()

' Because the DbConnectionStringBuilder class doesn't
' validate its key/value pairs, you can use this class
' to store any semicolon-delimited list. The following
' snippet places an arbitrary string into the ConnectionString
' property, changes one of the values, and then displays the
' resulting string.
builder.Clear()
builder.ConnectionString = _
    "Value1=10;Value2=20;Value3=30;Value4=40"
builder("Value2") = 25
Console.WriteLine(builder.ConnectionString)
Console.WriteLine()

builder.Clear()
Try
    ' Assigning an invalid connection string
    ' throws an ArgumentException.
    builder.ConnectionString = "xxx"

Catch ex As ArgumentException
    Console.WriteLine("Invalid connection string.")
End Try

Console.WriteLine()
Console.WriteLine("Press Enter to finish.")
Console.ReadLine()
End Sub

A: If you're using Entity Framework, you can use the Entity ConnectionString builder
            internal static EntityConnectionStringBuilder GetConnectionString()
            {
                // Specify the provider name, server and database.
                string providerName = "System.Data.SqlClient";
                string serverName;
                string databaseName;

                databaseName = "MyDatabase";
                serverName = "localhost";

                // Initialize the connection string builder for the underlying provider.
                SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder()
                {
                    // Set the properties for the data source.
                    DataSource = serverName,
                    InitialCatalog = databaseName,
                    IntegratedSecurity = false,

                    UserID = "sqluser",
                    Password = "password",
                };

                // Build the SqlConnection connection string.
                string providerString = sqlBuilder.ToString();

                // Initialize the EntityConnectionStringBuilder.
                EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder()
                {
                    //Set the provider name.
                    Provider = providerName,

                    // Set the provider-specific connection string.
                    ProviderConnectionString = providerString,

                    // Set the Metadata location.
                    Metadata = "@ENTER META DATA HERE"
                };

                return entityBuilder;
            }
        }

You can then add a constructor to your entity to accept a connection string (borrowed from Here)
public partial class MyEFEntities
{
    public MyEFEntities(string connectionstring)
        : base(connectionstring)
    {
    }
}

Finally, you can call it like this:
using (var connection = DAL.MyEFEntities(GetConnectionString().ToString()))
{
   // Do work here
}


text:
Q: On aws personalize, users and items datasets requires 1 metadata field, why? is it necessary? I am trying to create a recommendation system.
I would like to recommend users to subscribe to topics based on topics they already have subscribed to.
As mentioned in here, there is a requirement of 1 metadata field for the users and items (topics in my case) schemas.
I couldn't find any worthy field to put there.
Why is it a requirement? What should I do then? How impactful is it on the final recommendations score if I leave it blank? Am I missing any other way to solve that issue? Do you think that aws personalize is a good fit for my problem?

A: Seems like it is not mandatory to create all three dataset types. I found it out from aws-personalize-samles. Couldn't figure it out from the docs.
I thought of deleting this question, because it might be a too much of a noob question (seems like it from the downvoting), but heck, if it may shorten someone else time to figure it out by finding the samples, I will leave it as is.
Sorry if I annoyed some people!


text:
Q: Orchard: Creating a user from the register screen NOT dashboard Hey Guys…So im using Orchard CMS 1.6 and instead of creating a user/role from the dashboard, I would like the user to register from the home page.
This is done by leaving the 'username' and 'password' field blank on the home page and clicking 'Sign In'. They are then navigated to a 'Log On' page which displays a 'Register link'.
This allows the user to enter 4 fields to create an account. 'Username, Email, Password, and confirm password'. I would like to add additional fields to this form but am having no luck.
I've tried to install the profile, Users personal Info, and extended Reg modules.
These add additional fields to creating a user, when the user is created from the dashboard. (Users/ Add new user)…but not to the register screen.
Does anyone have any idea how to add fields to the register screen(access from the home page)?
Thanks for any replies…

A: tl;dr:
Check out: Extended Registration
Details:
You can accomplish this with combination of the Profile module and the Extended Registration module. By default, the Registration page  (Found in Orchard.Users) is hard-coded to display only the four fields you mentioned. Extended Registration takes the Profile part from the Profile module and also displays it on the Registration page.
Build out your registration field to however you want by extending the User content type, though it sounds like you have done this since you have access to these fields via New User in the Admin dashboard.
Note: Extended Registration requires the Profile module.


text:
Q: Powershell Script to Find & Highlight Specific Files Based on Creation Date I am trying to write a Powershell Script that checks a certain folder for .zip files. The .zip files contain information from certain backups. These .zip files lie within a folder tree for different plants that our company owns. Every day there is supposed to be a new .zip file in the bottom of this folder tree that is retained for a total of 7 days.
Ideally, each folder should contain 7 consecutive days of backups equaling 7 .zip files in each folder. Sometimes there are more than 7 and sometimes there are 0 depending on the issue the plant is experiencing.
I want (and am having trouble) writing a script that checks these folders for these .zip files and lets me know if there aren't any files in there from the last seven days. (It is okay if there aren't exactly 7).
So far I have the following code:
Get-ChildItem -filter "*.zip" -recurse -path C:\ArcherBackup\ | where {($_.CreationTime -gt ((get-date).AddDays(-7)))}

But this code brings up a list of every file that I have to manually look through.
I would like the script to more or less highlight a directory that does not contain a .zip file that is at least 7 days old.
Any assistance or guidance is appreciated.

A: Your snippet will return all the files created within the last seven days.
$_.CreationTime -gt ((get-date).AddDays(-7))

I think you want to return files that are older than seven days, so change -gt to -lt:
$_.CreationTime -lt ((get-date).AddDays(-7))

When using comparisons, it's a good idea to always use less than operators, that way, the conditional increases from left to right, like an x-axis, and it helps in readability/understanding.
0 -lt x -and x -lt 10

Makes it obvious that x should come between 0 and 10.

A: var 1, command line, sub directory that does not contain a .zip file that is at least 7 days old:
powershell $tm=(get-date).AddDays(-7);ls "C:\ArcherBackup" -fo -r^|?{$_.PSIsContainer}^|%{ls "$($_.FullName)" -fo -fi *.zip}^|?{$_.CreationTime -lt $tm}^|group Directory^|FT -H Name

var 2, command line, sub directory that does not contain a .zip file that is at least 7 days old;
except hiden files and directory:
powershell $tm=(get-date).AddDays(-7);ls "C:\ArcherBackup" -r^|?{$_.PSIsContainer}^|%{ls "$($_.FullName)" -fi *.zip}^|?{$_.CreationTime -lt $tm}^|group Directory^|FT -H Name

empty sub folders without files:
powershell $d=ls -r^|?{$_.PSIsContainer};$d^|?{$_.GetFiles().Count -eq 0}^|FT -H FullName

sub folders without zip-files:
powershell $d=ls -r^|?{$_.PSIsContainer};$d^|?{$_.GetFiles('*.zip').Count -eq 0}^|FT -H FullName

sub folders without zip-files;
sub directory that does not contain a .zip file that is at least 7 days old:
powershell $d=ls "C:\ArcherBackup" -fo -r^|?{$_.PSIsContainer};$tm=(get-date).AddDays(-7);$d^|%{ls "$($_.FullName)" -fo -fi *.zip}^|?{$_.CreationTime -lt $tm}^|group Directory^|FT -Au -H Name, Count;$d^|?{$_.GetFiles('*.zip').Count -eq 0}^|FT -H FullName|findstr [/s]| more

|findstr [/s]| - delete empty string in pipe
FT- alias Format Table
FT -H FullName - output format, select only FullName
-Au alias -Autosize
-H -hide header,
? - alias where - alias Where-Object
% - alias foreach - alias ForEach-Object
-fo - alias -force, fi - alias -filter,-r - alias -recurse
^ - escape character | - current shell is not processed as a pipeline-command
group - alias Group-Object


text:
Q: How to extract only the integer value instead of the Double value when reading data from Excel using Java I need a code which should get data from Excel as int values instead of String values.
It is displaying the value 2.0 which was originally saved in sheet as 2`
Try 1:
HSSFCell number = sheet.getRow(1).getCell(26);
Integer result =Integer.valueOf(number);
System.out.println(result);

Try 2:
int L = Integer.parseInt(getRow(1).getCell(26));

Error:The method parseInt(String) in the type Integer is not applicable for the arguments (Cell)

Code:
System.out.println(+sheet.getRow(1).getCell(26));

Output: 2.0
Expected output : 2

A: I recommend the following way, which does not try to cast an HSSFCell to an Integer/int:
// get the cell as object (this is NOT a number, instead, it contains one)
HSSFCell numberCell = sheet.getRow(1).getCell(26);
// get the cell value as double (there is no direct integer version)
double cellValue = numberCell.getNumericCellValue();
// cast the value to an int
int number = (int) cellValue;

A: Once you read the Double values from the excel instead of displaying the values as 2.0, to print it as 2 you can use the DecimalFormat Class methods and you can use the following solution:
HSSFCell number = sheet.getRow(1).getCell(26);
Double result =Double.valueOf(number);
DecimalFormat format = new DecimalFormat();
format.setDecimalSeparatorAlwaysShown(false);
System.out.println(format.format(result));

Incase your usecase is to print the String format you can add String.valueOf() and you can use the following solution:
HSSFCell number = sheet.getRow(1).getCell(26);
Double result =Double.valueOf(number);
DecimalFormat format = new DecimalFormat();
format.setDecimalSeparatorAlwaysShown(false);
System.out.println(String.valueOf(format.format(result)));

A: You could try
int L = Integer.parseInt(getRow(1).getCell(26).getStringCellValue());


text:
Q: Divide by zero error(stored procedure) I have stored procedure with the following lines,
DECLARE @DateRun as datetime
Select @DateRun=LastRunDate from tblBatchRun where JobId = 1
INSERT INTO tblRawTestScore
select * from vwOverallTestScores where TimeCompleted > @DateRun

I now get an error like the one shown below,

Msg 8134, Level 16, State 1, Procedure
  sp_CopyTestScoresRun, Line 9 Divide by
  zero error encountered.

When I modify the above stored procedure lines like,
INSERT INTO tblRawTestScore
select * from vwOverallTestScores where TimeCompleted > (Select LastRunDate from tblBatchRun where JobId = 1)

my stored procedure now executes fine.
Can anybody help me on this pls?

A: Looks to me like select lastrundate from tblbatchrun where jobid = 1 gets no rows.
In the first scenario you are getting a NULL result in your variable, which cannot be compared (it'll have problems casting things around as well), while in your second version the SP is not getting any results back from the subselect, therefore no comparison is made and no error is thrown.

A: What value are you getting from this statement:
Select LastRunDate from tblBatchRun where JobId = 1


text:
Q: Get the Child Class Propert in Parent class I had a two controllers in my application with database first approach

SampCutReqMaster.CS

public partial class SampCutReqMaster
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public SampCutReqMaster()
        {
            this.SamCutAssignmentMasters = new HashSet<SamCutAssignmentMaster>();
        }

        public decimal SampCutreqID { get; set; }
        public Nullable<decimal> BuyerID { get; set; }
        public Nullable<decimal> PatternRefID { get; set; }
        public Nullable<decimal> PatternStyleID { get; set; }
        public Nullable<decimal> SampleTypeID { get; set; }

        public virtual BuyerMaster BuyerMaster { get; set; }
        public virtual PatternStyle PatternStyle { get; set; }
        public virtual PatterRefMaster PatterRefMaster { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<SamCutAssignmentMaster> SamCutAssignmentMasters { get; set; }
        public virtual SampleType SampleType { get; set; }
    }

and The next is

SamCutAssignmentMaster

 public partial class SamCutAssignmentMaster
    {
        public decimal CutAssignID { get; set; }
        public decimal SampCutreqID { get; set; }
        public System.DateTime ReceivedDate { get; set; }
        public string ReceivedBy { get; set; }
        public Nullable<decimal> PatternMasterID { get; set; }

        public virtual PatternMaster PatternMaster { get; set; }
        public virtual SampCutReqMaster SampCutReqMaster { get; set; }
    }

I had created a controller with a index view for  SampCutReqMaster
public class SampCutReqMastersController : Controller
    {
        private ArtEntities db = new ArtEntities();
    // GET: SampCutReqMasters
    public ActionResult Index()
        {
            var sampCutReqMasters = db.SampCutReqMasters.Include(s => s.BuyerMaster).Include(s => s.PatternStyle).Include(s => s.PatterRefMaster).Include(s => s.SampleType).Include(s=>s.SamCutAssignmentMasters);

            var sampCutReqMasterssort = sampCutReqMasters.ToList().OrderByDescending(a => a.AddedDate);
            return View(sampCutReqMasterssort.ToList());
        }
}

I want to get the "receivedBy" of SamcutAssignmentMaster(child class) in my  view of SamCutReqMaster (Parent).But there may be no data in SamcutAssignmentMaster relavant to  SamCutReqMaster (FK is SamCutReqID)
In Index view Below I need to access SamcutAssignmentMaster.receivedBy
   @model IEnumerable<WebArtSampler.Models.SampCutReqMaster>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Index

    @Html.ActionLink("Create New", "Create")

            @Html.DisplayNameFor(model => model.ReqNum)

            @Html.DisplayNameFor(model => model.Fabric)

            @Html.DisplayNameFor(model => model.SampleRequiredDate)

            @Html.DisplayNameFor(model => model.AddedDate)

            @Html.DisplayNameFor(model => model.AddedBy)

            @Html.DisplayNameFor(model => model.BuyerMaster.BuyerName)

            @Html.DisplayNameFor(model => model.PatternStyle.StyleName)

            @Html.DisplayNameFor(model => model.PatterRefMaster.PatterRefNum)

            @Html.DisplayNameFor(model => model.SampleType.SampleType1)

            @Html.DisplayNameFor(model => model.SizeDetail)

            @Html.DisplayNameFor(model => model.Qty)

@foreach (var item in Model) {

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

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

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

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

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

            @Html.DisplayFor(modelItem => item.BuyerMaster.BuyerName)

            @Html.DisplayFor(modelItem => item.PatternStyle.StyleName)

            @Html.DisplayFor(modelItem => item.PatterRefMaster.PatterRefNum)

            @Html.DisplayFor(modelItem => item.SampleType.SampleType1)

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

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

            @Html.ActionLink("Edit", "Edit", new { id=item.SampCutreqID }) |
            @Html.ActionLink("Details", "Details", new { id=item.SampCutreqID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.SampCutreqID })

}

A: Ok. You can't access the properties whilst your type is still as the interface ICollection. You need to cast it to a concrete type before you can access the properties of the collection via an index.
 @for (var adCounter = 0; adCounter <= (Model.SamCutAssignmentMasters.Count - 1); adCounter++)
 {
    @Html.DisplayFor(x => ((List<SamCutAssignmentMaster>)x.SamCutAssignmentMasters)[adCounter].ReceivedBy)
 }

Cast the type to a list as per the above and you should see the properties.
NOTE: You are using DisplayFor in your view. If you intend to post the contents of this view the model will not bind unless you have a hidden control for each item or you switch to TextBoxFor. You will also need the for (Counter) syntax as well to bind to items in collections.
Hope that helps.


text:
Q: How can I display the response of a MailChimp form submit in a modal box instead of redirecting? I currently have a standard form for users on my site to signup for our mailing list:
<form class="form-stacked" action="http://coworkDF.us2.list-manage.com/subscribe/post" method="post">
<input class="span3" id="MERGE0" name="MERGE0" type="email" autocapitalize="off" autocorrect="off" placeholder="e-mail">
<input type="submit" class="btn float-right mail-send" value="Enviar">
</form>

Instead of redirecting them to the confirmation page, I'd love to display that confirmation in a modal box without leaving the page. I'm using the Twitter Bootstrap toolkit to build the site... they have a nice modal box utility but I'm not sure how to combine that with the MailChimp form.
Any thoughts? Thanks in advance

A: Just in general terms, you need to submit the signup request via ajax so that you stay on the current page, then extract relevant pieces from the response and use them to populate your modal.


text:
Q: Creating a VBA loop to validate results of two nested functions across a range I have been racking my brain trying to figure out how to nest a function inside a for each loop in order to run the same validation against each result and add it to a list if it meets the criteria.
So the base function I am using grabs 2 lat/long sets and gets distance in KM between the two. Listed below:
Public Function getDistance(latitude1,longitude1,latitude2,longitude2)
earth_radius = 6371
Pi = 3.14159265
deg2rad = Pi / 180

dLat = deg2rad * (latitude2 - latitude1)
dLon = deg2rad * (longitude2 - longitude1)

a = Sin(dLat / 2) * Sin(dLat / 2) + Cos(deg2rad * latitude1) * Cos(deg2rad * latitude2) * Sin(dLon / 2) * Sin(dLon / 2)
c = 2 * WorksheetFunction.Asin(Sqr(a))

d = earth_radius * c

getDistance = d

End Function

So what I want to do with this is run it against a two lists of locations and do a for loop where, in pseudocode, it would be: For each location in list A; create a list of each location within 5km (getDistance result).
I have a second block of code from extendoffice that seems to be close as it is a multi parameter vlookup listed below:
Function MYVLOOKUP(pValue As String, pWorkRng As Range, pIndex As Long)
'Update 20150310
Dim rng As Range
Dim xResult As String
xResult = ""
For Each rng In pWorkRng

    If rng = pValue Then
        xResult = xResult & " " & rng.Offset(0, pIndex - 1)
    End If
Next
MYVLOOKUP = xResult
End Function

I cant seem for the life of me nest that function inside the vlookup to loop I know I have to call in the get distance function inside the for each loop but I think it might need to be a nested loop inside of that for loop.
Am I completely off here with my thinking? I am rather new to VBA, so what I am really having trouble is figuring out the syntax on this double nested loop...
Update:
So I thing I have gotten a bit further with what I need. I dont think I am going to try to compare the two ranges, rather just bring in the latitude and longitude of the lookup variable into the function. So this is where I  got picture of what I am trying to achieve:
spreadsheet snip with columns and results i am trying to achieve
The actual code of the two functions, the geographical distance query listed before and the function I tried to create:
Public Function getDistance(latitude1, longitude1, latitude2, longitude2)
earth_radius = 6371
Pi = 3.14159265
deg2rad = Pi / 180

dLat = deg2rad * (latitude2 - latitude1)
dLon = deg2rad * (longitude2 - longitude1)

a = Sin(dLat / 2) * Sin(dLat / 2) + Cos(deg2rad * latitude1) * Cos(deg2rad * latitude2) * Sin(dLon / 2) * Sin(dLon / 2)
c = 2 * WorksheetFunction.Asin(Sqr(a))

d = earth_radius * c

getDistance = d

End Function

Function findCloseStores(basesitelat As Double, basesitelong As Double, storeRange As Range)
    Dim xResult As String
    xResult = ""
    Dim rw As Range
    Dim worker As Double
    For Each rw In storeRange.Rows
        worker = getDistance(basesitelat, storeRange.Cells(rw.Row, 2), basesitelong, storeRange.Cells(rw.Row, 3))
        If worker <= 9.77 Then
            xResult = xResult & "," & storeRange.Cells(rw.Row, 1)
        End If
    Next rw
    findCloseStores = xResult
End Function

What I actually get as results is just blank. It is processing the function I gave it, but It isnt reading something right/i wrote something wrong in the findCloseStores function that is making it assume no parameters are met.
Any idea on what I am doing wrong on the findCloseStores function?

A: You're right that it's a nested loop. In outline, it can go like this: for each A, for each B, if the getDistance from A to B is short, then add B to a list, next B, save the list, next A.


text:
Q: Extern enum between different source files - C I am having trouble with accessing an enum defining the state of a program between multiple source files.
I define my enum in my header main.h
    typedef enum{
    STATE_HOME,
    STATE_SETUP,
    }STATE;

extern enum STATE state;

I declare it in my main.c
#include "main.h"
STATE state = STATE_HOME;

but when I try and use it in another source file, example.c, it says 'undefined reference to state':
#include "main.h"
void loop ()
{
UART(state);
}

A: The quickest solution to your problem is to change your enum to this:
typedef enum STATE {
    STATE_HOME,
    STATE_SETUP,
} STATE;

But personally, I hate typedef-ing things in the C language, and as you have already noticed: naming confusion.
I think a more preferable method is merely this:
-- main.h:
enum STATE {
    STATE_HOME,
    STATE_SETUP,
};

extern enum STATE state;

-- main.c:
enum STATE state = STATE_HOME;

This avoids the entire conversation about different C language namespaces for typedef.
Apologies for a terse answer without more explanation...

A: An alternative method to share the constant values (of enum members) among multiple source files:
enums.h:
enum { STATE_HOME, STATE_SETUP }; // anonymous enum (no name tag)

main.c:
#include "enums.h"

example.c:
#include "enums.h"

Access to the enum members is as if they were defined using preprocessor "#define" statements; so use the member names alone, like int variables.
printf ("values of STATE_HOME: %d and STATE_SETUP: %d \n", STATE_HOME, STATE_SETUP);

How it works:
The enum members are cloned versions, replicated and made available in each source file that includes the enums.h header file. This is possible using the static specifier. This works when only static declarations or definitions populate the header file.

A: Extern is a way to use global variable in multiple files.
Simple approach of extern is:

*

*Declare extern varaible: This should be done in header file. For ex: in STATE_Declaration.h:

typedef enum{
    STATE_HOME,
    STATE_SETUP,
} STATE;

extern STATE state; /*Extern Declaration (NOTE:enum is not needed )*/

*

*Extern variable definition: in STATE_definition.c
    #include "STATE_Declaration.h"
    STATE state = STATE_HOME;

*

*and finally, usage: in STATE_USAGE.c
#include "STATE_Declaration.h"
void loop ()
{
    UART(state);
}

These 3 things should be taken care of, then nothing will fail w.r.t extern.


text:
Q: in eclipse export jar database is not working I have created a Swing application that uses msaccess database.
The application runs fine on Eclipse, but when I run the packaged executable Jar, I get the following error:
java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver

here is my code
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:cs");

please help me


text:
Q: Matching in Perl does not work I'm trying to match a line that starts with >, but does not work...
#!/usr/bin/perl

while ($lines = <>) {
  $count++;
  if (/^\#/) {
    next;
  }
  elsif (/^>/) {
    print "hola";
  }

}

Any idea?

A: you are trying to match $_ and not $lines
change it to
#!/usr/bin/perl

while ($lines = <>) {
  $count++;
  if ($lines =~ /^\#/) {
    next;
  }
  elsif ($lines =~ /^>/) {
    print "hola";
  }

}


text:
Q: HOW to merge table cells with python-pptx lib I have been faced with problem: How to merge some cells into big cell (vertically or horizontally merging) with python-pptx library?
I've found no examples to do this and I need some help.
Any help would be appreciated.

A: Update: Cell Merge was added to python-pptx in version 0.6.14. The method is documented here:
https://python-docx.readthedocs.io/en/latest/api/table.html#docx.table._Cell.merge
Basically, you define a rectangular region to merge by specifying two diagonal corner cells, so something like this:
table.cell(0, 0).merge(table.cell(1, 1))

would merge the top-left four cells, two in each of the first two rows.

Unfortunately, this feature has not yet been implemented in python-pptx.
To accomplish this, you would need to extend python-pptx with some sort of workaround function.
These issues from the GitHub project may provide some useful information if you want to pursue that:
https://github.com/scanny/python-pptx/issues?q=is%3Aissue+is%3Aopen+merge+label%3Atable


text:
Q: Trying to make a simple slideshow in Javascript / HTML I'm trying to make a simple slideshow of images to display on a webpage, but for some reason I'm not getting anything. I'm currently using Mozilla's Thimble WIDE because I'm on a chromebook... So it MIGHT be a limitation of that, but can anyone see any errors in my code?
Currently, I get a box with a relative size of 200x400 (I'm imagining that is the size) that blinks every 2.5 seconds, but never displays an image.
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Slideshow Attempt</title>

    <script>
        var slideimages = new Array()
        slideimages[0] = new Image()
        slideimages[0].src = "cleanhouse1.jpg"
        slideimages[1] = new Image()
        slideimages[1].src = "cleanhouse2.jpg"
        slideimages[2] = new Image()
        slideimages[2].src = "cleanhouse3.jpg"
    </script>
</head>

<body>
    <img src="cleanhouse1.jpg" id="slide" width="200" height="400"/>
    <script>
        var step = 0

        function slideit() {
            if (!document.images)
                return

            document.getElementById('slide').src = slideimages[step].src

            if (step < 2)
                step++
            else
                step = 0

            setTimeout("slideit()", 2500)
        }

        slideit()
    </script>
</body>
</html>

A: Call setTimeout in this way: setTimeout(slideit,2500) This is the working fiddle


text:
Q: how do I call function inside .ajax? I have the following code and I want to call initialize function here with the following;
google.maps.event.addDomListener(window, 'load', initialize);
But I am getting this error; Error: initialize is not defined.
What is wrong here?
$(function CheckinMap() {
        $.ajax({
            type: "GET",
            url: "content/home/index.cs.asp?Process=ViewCheckinMap",
            success:     function initialize(data) {
                var center = new google.maps.LatLng(48.404840395764175, 2.6845264434814453);

                var map = new google.maps.Map(document.getElementById('map'), {
                  zoom: 2,
                  center: center,
                  mapTypeId: google.maps.MapTypeId.ROADMAP,
                  maxZoom: 4
                });

                var markers = [];
                for (var i = 0; i < data.users.length; i++) {
                  var location = data.users[i];
                  var latLng = new google.maps.LatLng(location.latitude,
                      location.longitude);
                  var marker = new google.maps.Marker({
                    position: latLng
                  });
                  markers.push(marker);
                }
                var markerCluster = new MarkerClusterer(map, markers);
            },
            error: function (data) {
                $("#checkinmap").append(data);
            }
        });
    });
google.maps.event.addDomListener(window, 'load', initialize);

A: If you want to use a function for both the jQuery success method and the addDomListener third argument, then you have to store it somewhere when you define it rather than passing it directly to success.
That somewhere also has to be in scope for both your call to ajax and to addDomLister.
Move function initialize(data) so it appears before your current line 1.
Then say success: initialize.

A: You're defining intialize inside CheckinMap scope and then trying to use it outside of that scope in last line of you code. If you really need to have it in both places, define it outside and then reference if in success property value.
function initialize(data) {
    var center = new google.maps.LatLng(48.404840395764175, 2.6845264434814453);

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 2,
      center: center,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      maxZoom: 4
    });

    var markers = [];
    for (var i = 0; i < data.users.length; i++) {
      var location = data.users[i];
      var latLng = new google.maps.LatLng(location.latitude,
          location.longitude);
      var marker = new google.maps.Marker({
        position: latLng
      });
      markers.push(marker);
    }
    var markerCluster = new MarkerClusterer(map, markers);
}

$(function CheckinMap() {
        $.ajax({
            type: "GET",
            url: "content/home/index.cs.asp?Process=ViewCheckinMap",
            success: initialize,
            error: function (data) {
                $("#checkinmap").append(data);
            }
        });
    });
google.maps.event.addDomListener(window, 'load', initialize);


text:
Q: Is it possible to remove URL in popup I have an application where I have used javascript alert popup box.
When I open that in smart device like iPhone then it shows the URL on top as shown below:

So is there a way to remove that URL.?

A: If you could find a way to set the delegate of that UIAlertView you can try to use

*

*(void)willPresentAlertView:(UIAlertView *)alertView

You can then change the title from there if this would work.


text:
Q: Why is my Node.js INSERT giving me a Rethrow non-MySQL errors, Error: ER_PARSE_ERROR: you have an error in your MySQL syntax? All I'm trying to do is INSERT the values from post into my user table. This has worked before but now I'm getting the error in the title. Any help would be appreciated.
var express = require('express');
var router = express.Router();
var db = require('../helpers/db');
var empty = require('is-empty');
var Password = require('node-php-password');

router.post('/', function(req, res, next) {
  var firstName = req.body.first;
  var lastName = req.body.last;
  var username = req.body.username;
  var password = req.body.password;
  var permission = 2;

  db.query('SELECT username FROM user WHERE username = ?', [username], function (err, result) {
    if (err) throw err;
    if (!empty(result)) {
      console.log('Taken');
    } else {
      var hash = Password.hash(password, "PASSWORD_DEFAULT");
      var post = {
          first: firstName,
          last: lastName,
          username: username,
          password: hash,
          permission: permission
      };
      db.query('INSERT INTO user SET = ?', post, function (err, result) {
        if (err) throw err;
        console.log('ok');
      });
    }
    res.redirect('/');
  });

});

module.exports = router;


text:
Q: #define on a specific translation unit from another I would like to ask if it's possible to do this
If it is, how can it be done?
I want to do this because I want to "update" a class but I don't have access to edit that class
(class B simply adds a variable to class A)
A.h
#pragma once
class A
{
public:
int x;
A();
};

A.cpp
#include "A.h"
A::A():x(0){}

update_to_A.h
#pragma once
#include "A.h"
class B: public A
{
public:
int y;
B();
};

update_to_A.cpp
#include "update_to_A.h"
B::B():y(1){}

And the written in main would be like this
main.cpp (written like this)
#include "A.h"
#include "update_to_A.h"
int main()
{
A object; //variables: x (supposed to be x, y)
};

But I want it to act like this
main.cpp (act like this)
#include "A.h"
#include "update_to_A.h"
int main()
{
B object; //variables: x, y
};

A: This is not a good idea for many reasons. In order of increasing importance:

*

*It is confusing to read. Why does A suddenly mean B?

*It most likely breaks single responsibility. A is supposed to do a specific thing, so wanting it to suddenly be a B is probably making it do things that it's not originally supposed to.

*If other code also uses A (the old one) and wants to interact with your code, it wouldn't know about this change in meaning, which will quickly lead to problems. For example, each B needs more space than an A, so you cannot put them into the same array.

*It is not possible to do this in C++ without resorting to extremely ugly and dangerous tricks. You can #define A B in update_to_A.h and work from there, but I must stress that this is the wrong way. You are headed for pain and suffering if you try that.
Let me be abundantly clear: Any way in which you achieve what you described in the question will be a dirty hack. It's not maintainable, very brittle and will most likely cause unsolveable issues before it does whatever you wanted to really achieve.
If you want to have a B in your main, why not use B? Why abuse A like that?


text:
Q: How to find X509SerialNumber I'm building soap message which requires wse security and for some reason, the client requires KeyInfo, subject and serial #. but the serial # displayued for the x509 is hex and doesn't fit the xsd requirements for X509SerialNumber node which is integer. I've read that this needs to the the issuer serial # but it isn't part of the cert. This is a self signed certificate. How can I determine what the serial # is?
Please DO NOT tell me to use WCF. If I could use it, I would. I know WCF would make it easier, I hold an MCTS for WCF.

A: There's only one serial number field of the certificate and it's is binary data. The issuer can put anything there. In fact, serial number is treated as a very large integer number, but such number will look like a binary if you just inspect the byte array that holds the number. So you need to treat this value as a huge number and convert it to "readable" form. Eg. If you have 4-byte-long byte array that contains FF 00 FF 00 (4 bytes), the string representation will be "4278255360"
Update: my above explanation applies to XMLDSig and XMLEnc standards. In other standards (or just for display purposes) other formats can be used (such as base64, base16 encoding etc.).

A: I found what I needed.  http://www.dotnetmonster.com/Uwe/Forum.aspx/dotnet-security/2875/Manually-computing-sha1-digest-of-reference-containing
Just needed to add some code. the X509ChainElement.Certificate.GetSerialNumberString() gives me what I need and I don't have to calc anything.
Here is the code I'm now using
public static XmlElement GenerateSignature(XmlElement xmlToSign, StoreName storeName, StoreLocation storeLocation, X509Certificate2 certificate, string referenceID)
    {
        SignedXml signedXml = new SignedXml(xmlToSign);

        signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
        signedXml.SigningKey = certificate.PrivateKey;

        Reference tRef = new Reference(referenceID);
        XmlDsigExcC14NTransform env = new XmlDsigExcC14NTransform();

        tRef.AddTransform(env);
        signedXml.AddReference(tRef);

        KeyInfo keyInfo = new KeyInfo();
        X509Chain x509Chain = new X509Chain();
        x509Chain.Build(certificate);

        foreach (X509ChainElement element in x509Chain.ChainElements)
        {
            KeyInfoX509Data x509Data = new KeyInfoX509Data(element.Certificate);
            string issuer = element.Certificate.Issuer;
            x509Data.AddIssuerSerial(issuer, element.Certificate.GetSerialNumberString());
            keyInfo.AddClause(x509Data);
        }

        signedXml.KeyInfo = keyInfo;
        signedXml.ComputeSignature();

        XmlElement xmlDsig = signedXml.GetXml();
        return xmlDsig;
    }


text:
Q: Is it possible not to output relation column when using APOC.export? MATCH (m:computer)

WITH collect(DISTINCT m) AS M
CALL apoc.export.csv.data( M, [], null, {stream:true, batchSize:100}) YIELD data as mdata

For such a query, even if just for export nodes, without relationships, it still gives the following field with all empty values:
 _start
  _end
  _type

And it's hard to filter out them in the process. Is there a parameter to control this?
ADDITIONS:
MATCH (m:SportsTeam)-[r:hasMember]-(n)
WITH collect(DISTINCT m) AS M, collect(DISTINCT n) AS N, collect(r) as R
CALL apoc.export.csv.data( M, [], null, {stream:true}) YIELD data
WITH apoc.text.replace(data, '(?:,"_start","_end","_type"|,,,)(?=\n)', '') AS mdata
CALL apoc.export.csv.data( N, [], null, {stream:true}) YIELD data as ndata
WITH apoc.text.replace(data, '(?:,"_start","_end","_type"|,,,)(?=\n)', '') AS ndata
CALL apoc.export.csv.data( [], R, null, {stream:true}) YIELD data as rdata
RETURN mdata, ndata, rdata

What I am doing here is to output the node M, node N and relation R into 3 different files. After I added the 2 replace functions to get rid of the last 3 columns, it reports this error:
neobolt.exceptions.CypherSyntaxError: Variable `N` not defined (line 5, column 28 (offset: 282))
"CALL apoc.export.csv.data( N, [], null, {stream:true}) YIELD data as ndata"

Does the CALL and WITH can't be used in a row like this?

A: You can use the APOC function apoc.text.replace to modify the CSV string to remove the unwanted rows:
MATCH (c:computer)
WITH COLLECT(DISTINCT c) AS cs
CALL apoc.export.csv.data(cs, [], null, {stream:true, batchSize:100}) YIELD data
WITH apoc.text.replace(data, '(?:,"_start","_end","_type"|,,,)(?=\n)', "") AS newData
... // use newData, which does not have the last 3 columns

Since the 3 columns you don't want are at the end of each row, the regular expression (?:,"_start","_end","_type"|,,,)(?=\n) matches the unwanted text at the end of each row (whether the header row or a data row).
[UPDATE]
With respect to the ADDITIONS issues: a WITH clause will drop any variables not specified by the clause, so N was not being carried forward. Also, you had other issues. This should fix up all the issues:
MATCH (m:SportsTeam)-[r:hasMember]-(n)
WITH COLLECT(DISTINCT m) AS M, COLLECT(DISTINCT n) AS N, COLLECT(r) as R
CALL apoc.export.csv.data( M, [], null, {stream:true}) YIELD data
WITH apoc.text.replace(data, '(?:,"_start","_end","_type"|,,,)(?=\n)', '') AS mdata, N, R
CALL apoc.export.csv.data( N, [], null, {stream:true}) YIELD data
WITH apoc.text.replace(data, '(?:,"_start","_end","_type"|,,,)(?=\n)', '') AS ndata, mdata, R
CALL apoc.export.csv.data( [], R, null, {stream:true}) YIELD data AS rdata
RETURN mdata, ndata, rdata


text:
Q: IntelliJ community edition not finding existing dependency I have IntelliJ IDEA 2017.1.1 Community edition on Windows 7 and its complaining about Dependencies even if it's there. Please refer the following screenshot:

<dependency>
          <groupId>com.oracle</groupId>
          <artifactId>ojdbc7</artifactId>
          <version>${oracle.jdbc.version}</version>
</dependency>

Here is the screenshot of the file present inside the .m2 folder (full path : D:\Users\myusername\.m2\repository\com\oracle\ojdbc7\12.1.0.1
Do I need to do something like install:install-file by going to the 12.1.0.1 folder from windows command ?
The oracle website has been flaky for the past two weeks ( I have confirmed with few other people as well where they faced the same issue) where I am not able to download the ojdbc7.jar from their website. Hence, I have downloaded the file from the server using FileZilla and placed it manually in the 12.1.0.1 folder, could this be creating problem?

A: You can add another repository.
<pluginRepositories>
  <pluginRepository>
  <id>maven.oracle.com</id>
   <url>https://maven.oracle.com</url>
 </pluginRepository>

Look at http://docs.oracle.com/middleware/1213/core/MAVEN/config_maven_repo.htm#MAVEN9010

A: Yes acoording to that you can use maven repositery
https://mvnrepository.com/search?q=ojdbc7 you can refer this maven repositery


text:
Q: Is there a way to have asynchronous communication between a C++ and C# application through Protobuf? The scenario I'm thinking of is as following: Imagine there's two functions within two different programs, one of which in C++ and the other in C#. For now I'll call these functions cppFunc() and csFunc().
Say cppFunc() requests an identification token from csFunc(), which could normally be obtained through a protobuf generated binary file. cppFunc() however, needs to confirm this token and then return it when confirmed.
This scenario would mean cppFunc() would have to wait for csFunc() to be executed, so it can send a token. Is there any way this can be done? I've had a look at gRPC because this seemed like the most plausible solution, the way I understand it the request respone structure there between the client and server wouldn't really function between two clientside applications. Granted ofcourse this could be a wrong assumption of me to make.
Edit:
For extra context. I'm assuming here these are two different programs/processes (One an entirely seperate C++ based program the other a C# program through the use of the Unity game engine). Ideally the communication here would be possible both between devices and on  a single computer. The programs are basically both frontend applications put on top of an already existing C++ backend. So they would both do the same because they both use the same backend.
Another example of the type of communication here would be that I'd like to have the ability to process a .obj in the C++ program, and send it's data to the C# program. I have already found a way to do this, but only through the means of me compiling and executing the C++ program, manually dragging the binary file to the C# program and reconstructing it there. In the ideal scenario you would process the .obj file on the C++ side and have it available in the C# program right after without having to manually do anything with the generated files.
The issue here being that it's not just merely sending object data from point a to point b, but also needing this multi directional token identification system.


text:
Q: Show that $f\not\in L^1(\mathbb{R})$ but $f\in L^2(\mathbb{R})$. Let $f(x)=\min\{1,1/|x|\}$. Show that $f\not\in L^1(\mathbb{R})$ but $f\in L^2(\mathbb{R})$.
I think I want $||f||_1$ to not be finite and $||f||_2<\infty$, but I'm confused as to how to compute those from a minimum function.  Would I just take $f(x)=\frac{1}{|x|}$ and compute as normal?  Or is there something else I'm missing?
Any help would be greatly appreciated.

A: Set $f(x)=\min\{1,1/|x|\}$.
We may write
$$
\begin{align}
\int_\mathbb{R}|f(x)|dx&=\int_{|x|\leq 1}|f(x)|dx+\int_{|x|> 1}|f(x)|dx\\\\
&=\int_{|x|\leq 1}1\:dx+\int_{|x|> 1}\frac1{|x|}dx\\\\
\end{align}
$$ and the latter integral is divergent, thus $f\not\in L^1(\mathbb{R})$.
Similarly$$
\begin{align}
\int_\mathbb{R}|f(x)|^2dx&=\int_{|x|\leq 1}|f(x)|^2dx+\int_{|x|> 1}|f(x)|^2dx\\\\
&=\int_{|x|\leq 1}1\:dx+\int_{|x|> 1}\frac1{|x|^2}dx\\\\
\end{align}
$$ and both integrals are convergent, thus $f\in L^2(\mathbb{R})$.


text:
Q: Kafka being able to write to a topic beyond retention period What is the behavior of topics that go beyond their retention period? Is it possible to write to them after their retention policy period? I have been trying to write to them on confluent-kafka-dotnet (a .NET library) but when I run a consumer I don't see any messages streaming through. The value of the partition is just an empty string array. Is it possible to write to a topic beyond the retention time or does the topic get disabled?
using (var consumer = new Consumer(config))
{
    consumer.Assign(new List<TopicPartitionOffset> { new TopicPartitionOffset(topicName, 0, 0) });

    while (true)
    {
        Message msg;
        if (consumer.Consume(out msg))
        {
            Console.WriteLine("Topic: {0} Response: P{1},O{1} :{3}", msg.Topic, msg.Partition, msg.TopicPartitionOffset, Encoding.UTF8.GetString(msg.Value));
        }
    }
}

A: Kafka's retention period applies to past events, not event you are writing right now. You should be able to see new messages no matter what your retention policy is.
Example:
A topic with 24h retention is created at midnight, july 1st. On 23:50, July 1st, all the data you wrote during the entire day is still there.
At 01:00, July 2nd, only data that was written after 1:00am, July 1st will be stored (last 24h), earlier events are "purged".
If your consumer can't see new messages, it is one of the two:
1. Are your messages being written at all? (Kafka has a file-dump utility to help check)
2. When does your consumer start reading? If your consumer starts at the end of the topic, it may miss earlier messages. If it starts at the beginning, it will get all messages in topic. "auto.offset.reset" configuration controls this. "--from-beginning" if you are using the console consumer.


text:
Q: Generate a new JUnit test after implementing some methods of a class under test I am newbie in IntelliJ, I used to use NetBeans. My situation is the following:

*

*I create the class and the corresponded test.

*I create some method in the class.
Is there is any feature in IntelliJ for refactoring the test, so that the new method/function created will generate its corresponding test function in the test class? I stress that the test file is already generated.
Edit1: My aim is updating the current test, not generating a new one. I am looking to a feature which implements the new test function into the current test. Here is the situation with snippet code:
src/pack/Foo.java
package pack

class Foo {
     \\ variables
     public Foo (arguments){
         \\ variable initialization
     }

     private void metho1(){ ... }

*

*I generate the test.

Test/pack/FooTest.groovy
package pack

class FooTest {
     private static Foo tmp = new Foo (arguments)

     void testmetho1(){ ... }

*

*So now I create several methods into Foo.java.

src/pack/Foo.java
package pack

class Foo {
     \\ variables
     public Foo (arguments){
         \\ variable initialization
     }

     private void metho1(){ ... }
     private void metho2(){ ... }
     private void metho3(){ ... }

*

*What I want is to update the FooTest.groovy in such a way thatmetho2, metho3 created in Foo.java will generate the functions tests for them.

Test/pack/FooTest.groovy
package pack

class FooTest {
     private static Foo tmp = new Foo (arguments)

     void testmetho1(){ ... }
     void testmetho1(){ ... }
     void testmetho1(){ ... }

A: Please check the documentation:
Create test methods
To create stub test methods in JUnit test classes, you can use the IntelliJ IDEA code generation feature.

*

*Open the corresponding JUnit test class in the editor.

*Place the cursor where you want a new test method to be generated.

*Press Alt+Insert and select Test Method from the Generate menu.

A: I put my cursor on the new method name
press {Generate... (default Alt+Insert I think)}
Select 'Tests...'
select my method(s) I want to generate test scaffolding for
have it use the existing class.


text:
Q: How do I display data from firebase in a flatlist? I've looked at some similar question and tried to change the code but the data still won't show. I've watch a few tutorials and I've got this far.
This is my code.
 export default class HomeScreen extends React.Component {

  state = {
    dateItems: [],
    loading: false,
  }

  unsubscribe = null;

  async getAppointment() {
    const dateList = [];
    var snapshot = await firebase.firestore()
      .collection('appointment')
      .orderBy('createdAt', 'desc')
      .get()

    snapshot.docs.forEach(doc => {
      dateList.push({
        key: doc.id,
        date: doc.data().date,
        createdAt: doc.data().createdAt,
      });
      this.setState({
        dateItems: dateList,
        loading: false,
      });
    });
    console.log(dateList);
  }

  componentDidMount() {
    this.getAppointment();
  }

  render() {
    return (
      <View style={styles.container}>

        <View >
          <View style={styles.header}>
            <Text style={styles.headerTitle}>Appointments</Text>
            <Button
              onPress={() => this.props.navigation.navigate('Booking')} title="Add"
            />
          </View>
          <FlatList
            data={this.state.dateItems}
            renderItem={(item, index) => (
              <View>
                <Text style={styles.item}>{item.date}</Text>
                <Text>Created: {item.createdAt}</Text>
                <View style={styles.hr}></View>
              </View>
            )}
            keyExtractor={item => item.id}
          />
        </View>
      </View>
    );
  }
}

The data shows in an array in the console
Array [
  Object {
    "createdAt": t {
      "nanoseconds": 467000000,
      "seconds": 1591023433,
    },
    "date": t {
      "nanoseconds": 478000000,
      "seconds": 1592740813,
    },
    "key": "Qlaq8Nd5GYaxFYr9M6Iq",
  },
  Object {
    "createdAt": t {
      "nanoseconds": 31000000,
      "seconds": 1591020391,
    },
    "date": t {
      "nanoseconds": 859000000,
      "seconds": 1593327612,
    },
    "key": "ZsP2pBcNNgb4Nj6Jrpce",
  },
]

I need to show the date and not the timestamp for both date and createdAt. i don't know where I can implement this.

A: Formatting dates in Javascript can be very messy since you get into all sorts of complications with timezones, etc.
But in general, to start with, you'll want a new Date object. To get that, you would do:
const date = new Date(doc.data().date.seconds * 1000)

This is because the Date constructor takes (as one option) the number of milliseconds since 1970 as its argument.
However, this will only give you a Date object, and console.log will return a very long string like "Mon Jun 01 2020 07:57:13 GMT-0700 (Mountain Standard Time)". To format it, you want Intl.DateTimeFormat:
const dateObj = new Date(doc.data().date.seconds * 1000)
const date = new Intl.DateTimeFormat('en-US').format(dateObj) // "6/1/2020"

If you want to have more granular control than that over the date format, look at this SO answer or, to make your life much easier, use something like Moment.js.
If you're ok with the default en-US formatting (or any other locale), your code will end up looking something like the following. I'm not sure why you are calling setState inside every loop of the forEach statement, but assuming you can save that until dateList is fully built, you can use map instead, which is more efficient:
const dateFormat = new Intl.DateTimeFormat('en-US')
const dateList = snapshot.docs.map(doc => {
  const dateObj = new Date(doc.data().date.seconds * 1000)
  const createdAtObj = new Date(doc.data().createdAt.seconds * 1000)
  return {
    key: doc.id,
    date: dateFormat.format(dateObj),
    createdAt: dateFormat.format(createdAtObj)
  }
 });

 this.setState({
    dateItems: dateList,
    loading: false,
 })


text:
Q: Set color of alternate row using jQuery? I am trying to use query to set color of alternate rows of a html table. But every time I add a new row query switches the color of the whole table. Here is the Javascript code I am using:
var alternate = true;
function addRow(data) {
    if(alternate){
        $("table.live_feed").find('tbody.main').prepend(data).css("background", "#f1f1f1");
        alternate = false;
    }else{
        $("table.live_feed").find('tbody.main').prepend(data).css("background", "white");
        alternate = true;
    }
}

PS: I looked as some similar questions on Stack Overflow where they change the color of odd or even rows. I do not want to change the color of rows that are already present, I only want to change the color of new rows being added.

A: Your .css is acting on the found item (tbody.main), instead you want it to act on data:
var data = $(data).css("background", "#f1f1f1");
$("table.live_feed").find('tbody.main').prepend(data);

As a side note, for alternating row colours you can utilise the selectors :odd and :even
Example:
$('tr:odd').css('background', 'lightgray');

A: prepend and append and other DOM insertion methods don't return the just created elements, but the jQuery object where you called them.
In your code, the css call is applied to the tbody.main jQuery object.
In this example you can see how the returned element of the append call is the div element with test id.
http://jsfiddle.net/marcosfromero/VUrhZ/
In the same example you can see a workaround to apply css to the just inserted element using first() after prepend.


text:
Q: PLS-00302: component 'SLEEP' must be declared I am getting the error when I use the below command in SQL;
EXEC SYS.DBMS_SESSION.SLEEP(1);
But If I use the DBMS_LOCK then it's working.
EXEC SYS.DBMS_LOCK.SLEEP(1);
ref : https://oracle-base.com/articles/18c/dbms_session-sleep-18c
is there something I am missing while using this command ?

A: DBMS_LOCK is a privileged routine, ie, there is a lot of power in it, and thus it typically was protected from general use.  The problem is, the very useful SLEEP routine was also then not available.
In 18c, we realised this problem and so replicated the SLEEP routine to DBMS_SESSION which is publicly available.  Thus everyone gets to use SLEEP.
Before 18c, you need to grant execute on DBMS_LOCK to those that want it (which is risky), or create a wrapper function and only grant that, eg
create or replace
procedure SYS.SLEEP(n number) is
begin
  dbms_lock.sleep(n);
end;

grant execute on sys.sleep to public;

A: Self made procedure. If you dont have the right to set the grant
CREATE OR REPLACE procedure new_sleep(p_nSekunden  number)

is

  dDate  date := sysdate;
begin

  dDate := dDate + ( (1/24/3600) * p_nSekunden );

  loop

    exit when sysdate > dDate;

  end loop;

end;


text:
Q: postgres logging_collector sending to two directories simultaneously In the course of testing logging for a postgres server we discovered logs were being sent to two different directories simultaneously.
The two locations were:

*

*/var/lib/postgresql/9.6/main/pg_log/ (intended)

*/var/log/postgresql/ (uninteded)

Settings changed in postgresql.conf prior:
logging_collector = on
log_destination = 'csvlog'

Settings in postgresql.conf not changed, but relevant:
log_directory = 'pg_log'
log_truncate_on_rotation = off

I'm aware that both directories are standard for postgres logging, but sending to both simultaneously seems unusual.
We were testing logging for a day, and both sets of logs were created on that day.

A: You must be using the Debian/Ubuntu packages for PostgreSQL.
The packagers have opted to not use PostgreSQL' logging_collector, but rather have the processes write the messages to standard error. These messages are then collected in a log file in /var/log/postgresql, and log rotation is applied to them (see the startup script for how they did it).
Now if you configure logging in PostgreSQL like you did, the log will be written to log_directory, but the startup process hasn't changed: it still creates a file in /var/log/postgresql, but now only the first few messages after the startup end there, then PostgreSQL switches to using its log file.


text:
Q: How do I replace value between xml tag in a file by using shell scripting sed command? I have a configuration file. Ex: config.xml It has following configurations.
    <!-- Admin username for the Authentication manager. -->
    <Username>adminusername</Username>
    <!-- Admin password for the Authentication manager. -->
    <Password>adminpassword}</Password>

I need to change the value "adminusername" and "adminpassword" by running a shell script. How can I achieve this using sed?

A: Sed is not the right tool for the job. Use an XML-aware tool that can really parse the XML.
For example, in xsh I happen to maintain, you can write
open config.xml ;
set /Root/Username "newname" ;
set /Root/Password "newpassword" ;
save :b ;

(Provided the XML's root element is called Root, the mentioned elements are its children, and they aren't repeated.)


text:
Q: Value not reflecting in couchdb using putState in Hyperledger Fabric I am trying to build a chaincode application using fabric-shim in NodeJS. When I use the putState(key,Buffer.from(value)), the value does not reflect in CouchDB, while key and other parameters (stub etc..) can be seen in CouchDB.
Any erason why it does not work?

A: Yes, if you look at CouchDB document, it won't show the value of a respective key. But you can see there is one attachment with a document which has actually byte array or buffer value of a key.
Please check the following image to see example attachment, if you click on it will get download as a binary file.

If you wanna fetch exact value then use the following script to get the database dump
https://github.com/danielebailo/couchdb-dump
So after database dump, you will get to see JSON object with data as one of the key in it as follows
{
  "_id": <<id>>,
  "_rev": <<rev>>,
  "~version": <<version>>,
  "_attachments": {
    "valueBytes": {
      "content_type": "application/octet-stream",
      "revpos": 1,
      "digest": <<key>>,
      "data": "AAAHAQA="  ==> <<value in Base64 format>>
    }
  }
}

Using Base64 decoder you can decode value which will return value in form of byte array or buffer. Then you can convert byte array or buffer to respective object.


text:
Q: How to pass bitmap from one activity to another i have bitmap in ActivityA i want to pass the bitmap from here to ActivityB, i googled for this. when i use this
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", bitmap);

for getting
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");

i am getting this error !!! FAILED BINDER TRANSACTION !!! .
how can i solve this problem.

A: I tried and its working as below using intent.putExtra("name", bitmap)
While passing with intent,
Intent intent = new Intent(Current.this, Next.class);
intent.putExtra("bmp", bitmap);
startActivity(intent);

While fetching,
Bitmap bitmap = getIntent().getParcelableExtra("bmp");

OR
Other option is to use Application class,
You can also use a class that extends Application and have a setter getter for Bitmap and call it from every Acitivity.
((myApplication_class_name)getApplication()).setBitmap(bmp);

and fetch the Bitmap using,
((myApplication_class_name)getApplication()).getBitmap();

A: Your code is correct for putting bitmaps into the extras and works fine for me with small images.
But it seems that there is a limit for the size of the Parcelable extra. See http://groups.google.com/group/android-developers/browse_thread/thread/7322a84adcfee567?pli=1.
You might want to store the image first and only hand over the URI to the store location.
Edit: Using a public static field for the bitmap as suggested by udaykiran  violates so many OO principles I don't even know where to start.

A: I dont think that is the right method... you can use this link for the feature to be implemented. i too have used something like this itself.

A: You can simply name you Bitmap as static first.
then create a method like
public static Bitmap getBitmap(){
return bitmap;
}

then you can simply call from other activities,
bitmapwantedclass.getBitmap();

Hope it helps


text:
Q: what is difference between structure and class
Possible Duplicate:
What are the differences between struct and class in C++

consider that i need to answer this question for interview..

A: in structure, the member access specifier are default to public while on class is private.

A: This is a standard interview question.
The standard (and correct) answer is "A struct's members are public by default while a class' members are private by default."
For bonus points, the full answer is "A struct's members are public by default and inheritance is public by default whereas a class's members and inheritance are private by default."


text:
Q: Prove that this splitting field has degree 4 over $\Bbb{Q}$.
If $m$ and $n$ are distinct square-free positive integers greater than $1$, show that the splitting field $\Bbb{Q}(\sqrt{m}, \sqrt{n})$ of $(X^2-m)(X^2-n)$ has degree 4 over $\Bbb{Q}$.

Proof
$X^2 - m \in \Bbb{Q}$ is irreducible by Eisenstein's criterion since it's square free. So $[\Bbb{Q}(\sqrt{m}: \Bbb{Q}] =2$. Since $m \not= n$, $\sqrt{m}$ cannot be a root of $x^2 - n$. So $[\Bbb{Q}(\sqrt{m}, \sqrt{n}): \Bbb{Q}(\sqrt{m})] \geq 2$. However, since $x^2-n$ is irreducible by Eisenstein $[\Bbb{Q}(\sqrt{m}, \sqrt{n}): \Bbb{Q}(\sqrt{m})] = 2$.
Do you think my proof is correct?
Thank you in advance

A: To complete the proof along your lines, we need to show that $\mathbb{Q}(\sqrt{n})\ne \mathbb{Q}(\sqrt{m})$. We give a number-theoretically oriented argument.
It is enough to show that there do not exist integers $a$, $b$, and $c$, with $c\ne 0$, such that $\sqrt{n}=\frac{a+b\sqrt{m}}{c}$.
Suppose to the contrary that there are such integers. So $c\sqrt{n}=a+b\sqrt{m}$.
It is clear that $b$ cannot be $0$. If $a=0$, we have $c^2n=b^2m$. Without loss of generality we may assume that $b$ and $c$ are relatively prime. But then $b^2$ and $c^2$ are relatively prime, so $c^2$ divides $m$. Since $m$ is square-free, this is only possible if $c^2=1$. Similarly, $b^2=1$. It follows that $m=n$, contradicting the fact that $m\ne n$,
So we have $c\sqrt{n}=a+b\sqrt{m}$, where neither $a$ nor $b$ is equal to $0$. By squaring both sides, we conclude that $2ab\sqrt{m}$ is rational, which is not true.


text:
Q: Debugging child process after fork (follow-fork-mode child configured) I'm developing an application which the parent forks a child to handle certain tasks. I'm having an issue where I've configured gdb to follow-fork-mode child but after fork, after reaching a breakpoint, it sends a SIGTRAP but the child somehow terminates and send SIGCHLD to the parent.
I've configured signal(SIGTRAP, SIG_IGN) before fork so my understanding is that the child should inherit and ignore SIGTRAP when the breakpoint is reached but it's not happening.
Please help me to understand this if I'm incorrect.
How can I successfully debug the child process?

A: The child process inherits signal handlers from the parent, but not the pending signal.
After forking try installing the signal handler for SIGTRAP at a place in code where the child process executes after forking. If you don't handle SIGTRAP, the default action is that the child is terminated.
If you want to debug the child process, you must use follow-fork-mode.
You must set the mode using
set follow-fork-mode child

However, now only the child can be debugged, and the parent runs unchecked.
There is an alternative way of debugging the child process.
After fork() is executed, put a sleep() call in the code where the child executes, get the PID of the child using the ps utility, then attach the PID.
attach <PID of child process>

Now, you can debug the child process, like any other process.
After debugging, you can detach the PID using
detach


text:
Q: Why is yaourt looking in the wrong place (pacman works)? After removing yaourt and package-query, upgrading pacman to v4.0.1 and reinstalling the latest package-query and yaourt from AUR, I can't use yaourt anymore. It tells me:
Unable to open file: /usr/local/etc/pacman.conf

I don't understand why it's looking there now and not in /etc. Meanwhile pacman is working normally. If I create a symlink to pacman.conf, I get the following error instead:
failed to initialize alpm library (could not find or read directory)

My $PATH is:
/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/usr/bin/vendor_perl:/usr/bin/core_perl

I have tried looking in the yaourt PKGBUILD prior to installing, reinstalling it, looking in the yaourt script file, and I can't find anything suspicious. Not sure what to look for, what could have happened?
EDIT: Found the solution: /usr/bin needs to be before /usr/local/bin in $PATH.

A: Yaourt apparently uses the first entry in $PATH, so /usr/bin needs to be before /usr/local/bin there.
Changing this in /etc/profile solved the problem.

A: Reinstall package-query using empty --prefix: ./configure --prefix=

A: I had the same issue. The problem (as mentioned in other answers) is that if you run:
[linux]$ echo $PATH
[linux]$ /usr/local/sbin:/usr/local/bin:/usr/bin .....

Notice that /usr/local/sbin and /usr/local/bin appear first, so the programs searched for will be taken from these locations (if they exist).
Have a look in /usr/local/bin to see if you can see package-query there; if you can, then your issues are being caused by this, it shouldn't be there (unless you installed it there). So. Lets fix it......
Start by removing YAOURT:
sudo pacman -R yaourt
checking dependencies...

Packages (1) yaourt-1.9-1

Total Removed Size:  0.81 MiB

:: Do you want to remove these packages? [Y/n] y
:: Processing package changes...
(1/1) removing yaourt                                                                                [############################################################################] 100%
:: Running post-transaction hooks...
(1/1) Arming ConditionNeedsUpdate...

And then remove package-query:
[linux]$ sudo pacman -R package-query
checking dependencies...

Packages (1) package-query-1.9-3

Total Removed Size:  0.08 MiB

:: Do you want to remove these packages? [Y/n] y
:: Processing package changes...
(1/1) removing package-query                                                                                [############################################################################] 100%
:: Running post-transaction hooks...
(1/1) Arming ConditionNeedsUpdate...

Finally, manually remove the stray package-query binary:
[linux]$ sudo rm -rf /usr/local/bin/package-query

Now, re-install yaourt (and package-query) using the instructions supplied here: https://archlinux.fr/yaourt-en
And you should be good to go.


text:
Q: Making a CakePHP 1.2 page work on localhost So I need to copy a site from a webserver and run it from my localhost.
The site is created with CakePHP 1.2.3.8166 (it says in VERSION.txt).
I am new to CakePHP, so i started with the 2.0 tutorial and i have also a fresh install of 1.2.11 and both work perfectly. (I just had to fix the mod_rewrite issues by enabling AllowOverride All).
However when i tried to run my downloaded site i just got "page not found" error.
With a little searching, the solution was to remove the first "/" in
"RewriteRule    ^$ /app/webroot/    [L]" and other places in the .htaccess files.
So now my page looks wired, like this:
http://pastebin.com/ZMX3RjZG
Clearly the page does't load properly and i don't know what is wrong.
Now i am stuck, anyone have come across similar problem?
I run:
Windows 7 Pro 64bit,
PHP 5.3.6,
Apache 2.2.19
Any help appreciated.

A: Based on the second code sample you've provided and the way the rendered content is garbled I would say that shorthand tags aren't enabled in your version of PHP.
This shorthand notation might be the root of your problem:
<?= //Some PHP script ?>

There are two solutions, either change all the shorthand tags to the full declaration:
<?php //Some PHP script ?>

Which might be quite an undertaking as you're working with an existing project. It all depends on the size of it and if this shorthand notation is present in all of the files (the Cake core uses the full declaration). Or you could enable shorthand in your php.ini and restart the Apache server.
More information on shorthand tags can be found in the PHP manual.