text:
Q: Styling ListViewItem in WPF I am trying to remove background color for ListViewItem on hover event as well as when element selected.
I was able to remove background color when item is selected by <Setter Property="Focusable" Value="False"/> but for some reason <Style.Trigger> does not work and background color is not changed when mouse is on ListViewItem.
Here is my code
<ListView x:Name="EmergencySectionsListView" MinHeight="210" BorderThickness="0" BorderBrush="White" ItemsSource="{Binding .}"
                      ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Auto">

                <ListView.ItemTemplate>
                    <DataTemplate>
                        <local:EmergencySectionsControl/>
                    </DataTemplate>
                </ListView.ItemTemplate>
                <ListView.ItemsPanel>
                    <ItemsPanelTemplate>
                        <WrapPanel Orientation="Horizontal"/>
                    </ItemsPanelTemplate>
                </ListView.ItemsPanel>
                <ListView.ItemContainerStyle>
                    <Style TargetType="{x:Type ListBoxItem}">
                        <Setter Property="Focusable" Value="False"/>
                        <Style.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Background" Value="{x:Null}"/>
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </ListView.ItemContainerStyle>

</ListView>

I read that triggers in standard ControlTemplate may override triggers in ItemContainerStyle so i tried code below but it didnt work.
<ListView x:Name="EmergencySectionsListView" MinHeight="210" BorderThickness="0" BorderBrush="White" ItemsSource="{Binding .}"
                      ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Auto">

                <ListView.ItemTemplate>
                    <DataTemplate>
                        <local:EmergencySectionsControl/>
                    </DataTemplate>
                </ListView.ItemTemplate>
                <ListView.ItemsPanel>
                    <ItemsPanelTemplate>
                        <WrapPanel Orientation="Horizontal"/>
                    </ItemsPanelTemplate>
                </ListView.ItemsPanel>

                <ControlTemplate TargetType="{x:Type ListViewItem}">
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="{x:Null}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
</ListView>

Please let me know if more info is needed or question is not clear.
I would appreciate any ideas on how to fix this issue.


text:
Q: Calculation of virtual resources I virtualized a server using VMware ESXi. My virtual machine has 8 vCPU, while the real processor is an Intel Xeon E5-2620 v3 (6 core) @ 2,4 GHz. In order to estimate virtual resources needed for running that virtual machine, is it correct the following calculation?
Total amount of GHz = # of vCPU * clock CPU = 8 * 2,4 = 19,2 GHz
Thanks in advance.
Andrea

A: The VMware vSphere documentation (https://pubs.vmware.com/vsphere-60/index.jsp#com.vmware.vsphere.monitoring.doc/GUID-FB4C372B-49AC-4A0F-8573-D8E23241570A.html), about CPU charts said:

Amount of CPU actively used by the host, resource pool, or virtual machine in the cluster.
  ■
  Counter: usagemhz
  ■
  Stats Type: Rate
  ■
  Unit: MegaHertz (MHz)

So, it seems in the chart representing CPU usage of virtual machine, it gives informations about consumption; therefore, as I said in the previous comment, in that chart, a 5% CPU usage corresponds to 961 MHz, meaning that 100% corresponds to 19,2 GHz.
On the other hand, from the same type of chart applied to the host I can see a 6,96% usage corresponds to 1000 MHz used, which means 100% corresponds to 14,4 GHz.
And 14,4 GHz is also the result of the calculation:
Total amount of GHz = # of CPU * clock CPU = 6 * 2,4 GHz= 14,4 GHz, where 6 is the number of cores of the real processor.
I think the answer is in the CPU usage charts.

redpajama_set_name: RedPajamaStackExchange


text:
Q: 'Browse' button in HTML form not working in IE 7 or 8 (ietester) I have a really straight forward image upload form in a website of mine. For some reason, when I load up ieTester and use IE 8 or IE7, the 'Browse' button to locate the file has no text on it, and it also doesn't open a file selection dialogue.
Does anybody know why this might be? Could it be because I'm using IE Tester?
Here's the code for my form:
<form action="edit-profile.php" method="post" enctype="multipart/form-data">
    <input name="file" id="file" type="file" />
    <input type="hidden" name="uploaded" value="true" />
    <input type="submit" value="Upload" />
</form>

Thanks in advance for any help.

A: This appears to be a bug in the current version of IETester/DebugBar.  It has been reported, although not yet acknowledged or dealt with.

A: I am using this approach and it is working in IE8,9. Please check if redesign of browse button is the issue. Consider demo first.
HTML Campus


text:
Q: NodeRed how to return an array of msg object In NodeRed I have this function:
var payload = msg.payload;
  if(payload && payload.length > 10) {
    var data = payload.match(/\d+/ig);
    var string = "vcc:"+data[1]+",temp:"+data[2]/100+",hum:"+data[3]/100;
    return [[{payload: string}, {nodegroup: data[0]}]];
  } else {
    return null;
  }

I need the object msg.payload AND the msg.nodegroup for the EmonCMS node. How can I return an object containing msg.payload and msg.nodegroup?

A: You seam to returning a 2 dimensional array which will send 2 messages to the first output of the function node.
Assuming you want to send just one message to only one output then the following should do what I think you want.
var payload = msg.payload;
if(payload && payload.length > 10) {
   var data = payload.match(/\d+/ig);
   var string = "vcc:"+data[1]+",temp:"+data[2]/100+",hum:"+data[3]/100;
   return {payload: string, nodegroup: data[0]};
} else {
   return null;
}


text:
Q: Maxifs and Sumifs to newest date I have a sheet Balance History with account balances my date/time, along with account name, month and year text fields.
I'm trying to show the most recent balance by account for a specific month and year on a separate (AssetsDebts).  The sumifs &
maxifs formula below does find newest balance by account name and the
Sumifs formula below will sum all rows where the name, month and year
match.  However the combination of the two always results in zero.  My
thought was I could add the 4th criteria ( maxifs ) within the sumifs
and have it work but no luck.
Any help would be great, i am not married to sumifs/maxifs as long as I can reach the above goal.
Balance History'!H:H = Balance Total
Balance History'!D:D = Account Name
Balance History'!O:O = Date/Time ( date )
Balance History'!M:M = Month ( text )
Balance History'!N:N = Year ( text )

AssetsDebts Sheet
E2 = Account Name
B2 = Month ( text )
C2 = Year ( text )

Sumifs & Maxifs
sumifs('Balance History'!H:H,'Balance History'!D:D,E2,'Balance History'!O:O,(maxifs('Balance History'!O:O,'Balance History'!D:D,E2)))

Sumifs
sumifs('Balance History'!H:H,'Balance History'!D:D,E2,'Balance History'!M:M,B2,'Balance History'!N:N,C2)

Combined (results zero )
sumifs('Balance History'!H:H,'Balance History'!D:D,E2,'Balance History'!M:M,B2,'Balance History'!N:N,C2,'BalanceHistory'!O:O,(maxifs('Balance History'!O:O,'Balance History'!D:D,E2)))

Sheet LINK.

A: The Query function is probably your best bet. If you put the below formula into a cell on you AssetsDebts sheet, and have it reference some respective inputs for date/, you'll what you need. Note that there are quotes around the year because the way you've setup your array functions in the history tab has it structured that way.
Functional sheet here.
Actual formula: =Query('Balance History'!B:O,"Select H WHERE G = '"&J4&"' and M = '"&J3&"' and N = '"&J2&"' ORDER BY O DESC Limit 1",0)


text:
Q: C++ sugar syntax for if (!result) return false; When refactoring some code, I often encounter this :
bool highLevelFunc foo()
{
  // ...
  bool result = LesserLevelFunc();
    if (!result) return false;
  // ... Keep having fun if we didn't return
}

Is there any way to make this a little more sexy and less verbose ? Without any overhead or pitfall of course.
I can think of a macro
#define FORWARD_IF_FALSE(r) if (!r) return r;

bool highLevelFunc foo()
{
  // ...
  FORWARD_IF_FALSE(LesserLevelFunc());
  // ...
}

Anything better, i.e without preprocessor macro?

A: Because you might be continuing if LesserLevelFunc returns true, I suggest keeping it pretty close to how it is now:
if (!LesserLevelFunc())
    return false;

A: To me, "readable" code is sexy. I find the original code more readable than your proposal, since the original uses standard C++ syntax and the latter uses a macro which I'd have to go and look up.
If you want to be more explicit, you could say if (result == false) (or better yet, if (false == result) to prevent a possible assignment-as-comparison bug) but understanding the ! operator is a fairly reasonable expectation in my opinion.
That said, there is no reason to assign the return value to a temporary variable; you could just as easily say:
if (!LesserLevelFunc()) return false;

This is quite readable to me.
EDIT: You could also consider using exceptions instead of return values to communicate failure. If LesserLevelFunc() threw an exception, you would not need to write any special code in highLevelFunc() to check for success. The exception would propagate up through the caller to the nearest matching catch block.

A: First of all introducing the macro you are making the code unsafe. Moreover your macro is invalid.
The expression after the negation operator shall be enclosed in parentheses.
#define FORWARD_IF_FALSE(r) if (!( r ) ) return r;

Secondly the macro calls r twice. Sometimes two calls of a function is not equivalent to one call of the same function. For example the function can have some side effects or internal flags that are switched on/off in each call of the function.
So I would keep the code as is without introducing the macro because the macro does not equivalent to the symantic of the original code.


text:
Q: When I run my Asp.net MVC application over IIS Express It works fine but when i switch it to Local IIS it gives me this error When I run my Asp.net MVC application over IIS Express It works fine but when i switch it to Local IIS it gives me this error
System.Data.Entity.Core.EntityException:
'The underlying provider failed on Open.'
enter image description here
enter image description here

A: So there may be you should check connectionstring and also please check below link
An exception of type 'System.Data.Entity.Core.EntityException' occurred in EntityFramework.SqlServer.dll but was not handled in user code


text:
Q: How do I make https://twitter.com/intent/tweet?text= working without letting me login again when I'm already in Twitter web view When I open a link, say example.com/1.html in Twitter app, there would be a webview. And in that 1.html page, I have a link:
Tweet
Clicking on that link, Twitter would guide me to post this tweet.
However, if the link was opened by window.location.href="https://twitter.com/intent/tweet?text=hello", then Twitter would ask me to login again in the webview, which is very weird because I'm already logged in.
So I guess it's the window.location.href problem so I tried another way:
Object.assign(document.createElement('a'), { target: '_blank', href: $b.attr('https://twitter.com/intent/tweet?text=hello')}).click();

This time the click() trigger would never fired.
So, is it impossible for me to invoke a tweet action with pure JavaScript?

A: What I'm noticing is that the $b.attr(<url>) in the href property should just be like this: href: '<url>'.  That looks like jQuery syntax to me, which is saying, "Get the value for the attribute url that's in the element $b.".
It'd be something like '$b.attr("href") or $b.attr("url") if you have an element of <element href="<url>" url="<url>"><element/>".
I think that should fix your problem.
I can't tell if you want to have the user click to open the tweet, or if you want to auto-click for them.  Because that is what the .click() function does, is emulate a click on an element.
If you want the user to click, get rid of the .click().
If you want to auto-open without a click, use window.open('<url>').
That said, if you really want the anchor element, you can execute a click like this:
var body = document.getElementsByTagName("BODY")[0];
var $b = $("#link"); // has an attribute of 'url' with the twitter link
var a = Object.assign(document.createElement('a'), { target: "_blank", innerHTML: "Tweet", href: $b.attr('url')})
body.appendChild(a);
a.click();


text:
Q: While i tried to convert this to json using *json.loads* it throws this error,i need to remove the additional char after the curly and convert to json "{
  "order_currncy": "INR",
  "order_ship_country": "India",
  "order_ship_email": "",
  "order_notes": "",
  "order_status": "Successful",
  "order_capt_amt": 0.0,
  "order_delivery_details": "",
  "order_fee_flat": 0.0,
  "order_discount": 0.0,
  "order_TDS": 0.0,
  "error_desc": "",
  "status": 0,
  "error_code": ""
}\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b"

in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 1462 (char 1461)

A: This works:
import json

j = """{
  "order_currncy": "INR",
  "order_ship_country": "India",
  "order_ship_email": "",
  "order_notes": "",
  "order_status": "Successful",
  "order_capt_amt": 0.0,
  "order_delivery_details": "",
  "order_fee_flat": 0.0,
  "order_discount": 0.0,
  "order_TDS": 0.0,
  "error_desc": "",
  "status": 0,
  "error_code": ""
}"""

x = json.loads(j)
print(x)

result is a dict x


text:
Q: How to use RF24 to talk to nRF24L01+ on regular PC (Linux) over USB? As I do not have RPi I would love to use my regular PC to talk to nRF24L01+ (connected to Arduino and then to PC with USB). Something like IP over serial.
PC -> USB -> Arduino + nRF24L01+
Is it possible or I need RPi?
I have tried to compile tmrh20 RF24 on Ubuntu x86:
make -B RF24_SPIDEV=1
but it gives me error:
RF24_config.h:58:23: fatal error: Arduino.h: No such file or directory
(they are in regular Ubuntu place).

A: I'm trying to do the same thing with not much luck. However, I can tell you that you'll need to run
./configure --driver=SPIDEV

This should get you past your error. However, I'm still having issues when trying to run make:
[Linking]
arm-linux-gnueabihf-gcc -pthread -shared -Wl,-soname,librf24.so.1 -Ofast -Wall -pthread  -o librf24.so.1.1.7 RF24.o spi.o gpio.o compatibility.o interrupt.o
RF24.o: file not recognized: File format not recognized
collect2: error: ld returned 1 exit status
make: *** [librf24.so.1.1.7] Error 1


text:
Q: How to break the text of long text area field in vf page enter image description here
I have fetched the data of long text area field on my vf page how can i break the text in vf page

A: It's not really a Visualforce-specific question, consider changing the tags to CSS and you'll attract experts. Lots of options you can experiment with, have you seen these?

*

*https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

*https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-wrap

*https://developer.mozilla.org/en-US/docs/Web/CSS/word-break
if the text contains <br> or newlines you could even wrap it in <pre> tags...
What's your VF page structure? Do you use <apex:outputField> for that or <apex:pageBlockSectionItem>? these should enforce some wrapping too. If you have raw {!myField} in the page then well, wrapping (and protecting from XSS injection!) is on you...


text:
Q: Regarding defining input_placeholder to predict over a given image In the following function, author aims to run prediction over a downloaded image based on vgg model.
with tf.Graph().as_default():

url = ("https://upload.wikimedia.org/wikipedia/commons/d/d9/First_Student_IC_school_bus_202076.jpg")

image_string = urllib2.urlopen(url).read()
image = tf.image.decode_jpeg(image_string, channels=3)

image_float = tf.to_float(image, name='ToFloat')

# Subtract the mean pixel value from each pixel
processed_image = _mean_image_subtraction(image_float,
                                          [_R_MEAN, _G_MEAN, _B_MEAN])

input_image = tf.expand_dims(processed_image, 0)

with slim.arg_scope(vgg.vgg_arg_scope()):

    logits, _ = vgg.vgg_16(input_image,
                           num_classes=1000,
                           is_training=False,
                           spatial_squeeze=False)
pred = tf.argmax(logits, dimension=3)

init_fn = slim.assign_from_checkpoint_fn(
    os.path.join(checkpoints_dir, 'vgg_16.ckpt'),
    slim.get_model_variables('vgg_16'))

with tf.Session() as sess:
    init_fn(sess)
    segmentation, np_image, np_logits = sess.run([pred, image, logits])

I have been trying to predict over an existing image read via opencv, the only modification I made is to read image via cv2, add input_placeholder, and modify sess.run correspondingly. However, I got the following error message:
segmentation, np_image, np_logits = sess.run([pred,logits],feed_dict={input_placeholder:image})
ValueError: need more than 2 values to unpack

Would you like to let me know which modification I made is wrong?
with tf.Graph().as_default():

image = cv2.imread('/data/cat.jpg',cv2.IMREAD_UNCHANGED)
input_placeholder = tf.placeholder(tf.float32,shape = [image.shape[0],image.shape[1],image.shape[2]])
image_float = np.float32(image)

# Subtract the mean pixel value from each pixel
processed_image = _mean_image_subtraction(image_float,[_R_MEAN, _G_MEAN, _B_MEAN])

input_image = tf.expand_dims(processed_image, 0)

with slim.arg_scope(vgg.vgg_arg_scope()):

    logits, _ = vgg.vgg_16(input_image,
                           num_classes=1000,
                           is_training=False,
                           spatial_squeeze=False)

pred = tf.argmax(logits, dimension=3)

init_fn = slim.assign_from_checkpoint_fn(
    os.path.join(checkpoints_dir, 'vgg_16.ckpt'),
    slim.get_model_variables('vgg_16'))

with tf.Session() as sess:
    init_fn(sess)
    segmentation, np_image, np_logits = sess.run([pred,logits],feed_dict={input_placeholder:image})

A: For reference first take a look to the official documentation: https://www.tensorflow.org/api_docs/python/tf/Session#run
For each graph element passed to the fetches parameter of sess.run() you get one value returned. In your case you are passing the following list as fetches: [pred,logits] so sess.run([pred,logits], ...) will return 2 values: the result of running the pred op and the logits op.
Citing the documentation

The value returned by run() has the same shape as the fetches
  argument, where the leaves are replaced by the corresponding values
  returned by TensorFlow.

However in this line
segmentation, np_image, np_logits = sess.run([pred,logits],feed_dict={input_placeholder:image})
you are trying to assign these 2 values to 3 different python variables (segmentation, np_image, np_logits) hence you get the ValueError.
If you look at the original example you provided, the final line is:
segmentation, np_image, np_logits = sess.run([pred, image, logits])
To mimic the original example try removing the np_image declaration from your code like so:
segmentation, np_logits = sess.run([pred,logits],feed_dict={input_placeholder:image})

A: is a python error:
segmentation, np_image, np_logits = sess.run([pred,logits],feed_dict={input_placeholder:image})

should be
np_image, np_logits = sess.run([pred,logits],feed_dict={input_placeholder:image})

you are only passing two fetches to the run function


text:
Q: Event receiver and handler without SharePoint Server/Foundation I need to use some event receiver and handler functionalities into my SharePoint sites, but unfortunately I can't install SP Server or SP Foundation on my computer. I tried to use Visual Studio but this application do not allow create such features without having installed SP Server or Foundation. Is this the only way to get access to event handler and receiver?
If it won't be possible I will just change approach and I will try to create my funcionalities in other way.

A: Your only option to create Event Receivers in SharePoint Online is to create a Remote Event Receiver. You do not need SharePoint installed to develop this, but you do need a web site to deploy it to. Azure Web Apps work really well for this, but you can use a regular server or another cloud provider if you wish.
Setting up an RER is really simple, but the tooling and documentation are really poor. You do not necessarily need to create an app, but some of the app tooling is pretty helpful.
Because I've written so many Remote Event Receivers, and because the tooling is inadequate, I've released a "Starter Project" on Github that eliminates a lot of the setup. Feel free to use it and provide feedback.
https://github.com/dgusoff/RemoteEventReceiver.Starter

A: You have a few options in SharePoint online, but traditional event receivers are not one of them. In on-prem environments, event receivers run in memory on the SharePoint box, and as such as disallowed in the cloud environment. So while there are a few options in the cloud, they all have the same attribute of not running directly on sharepoint, but rather run somewhere else.

*

*As derek mentioned, there are remote event receivers. This is one of the original options. These work, but there are now better options.

*Webhooks. This is the new version of remote event receivers. These have a few advantages, and I think these should be used for new development over RERs. The basic intro to these is here.

*Workflow. I know workflow is not the same as an event handler, but certainly there are cases where event handlers could be built out as workflow instead. Workflow options include SharePoint Designer, Flow, and Azure Logic Apps.


text:
Q: How to Perform the following query using Greendao ? I have 2 tables A and B.
Table A contains names and table B contains selected names.
Now I would like to perform the following query on these tables using greendao, Please let me know if it is possible and if it is not are there any alternatives (maybe a raw query).
select *
from A inner join B
on A.nameid = B.nameid

Also, Table A columns: id, nameid, name
and Table B columns: id, nameid, name, rating

A: I think this might help.
You can use the raw query as a fake join. And you get all you want in the Query object
Query query = ATableDao.queryBuilder().where(
new StringCondition("nameid IN " +
"(SELECT nameid FROM B_Table )").build();

Since "nameid" doesn't seems to be a unique identifier in your sample. I won't suggest to use Relations to solve this issue. If you are try to use Relations, you can find my previous answer here.

A: Try this:
List<ATableObj> listATableObj = ATableDao.queryRawCreate(", BTable BT
WHERE BT.nameid = T.nameid").list();

A: If you use greendao this works differntly:
Instead of your query you select rows from table a (or b) and if you need a field of b (or a) you call getB() (or getA()) to get the corresponding row of that table.
If you have rows in table a that have no match in table b and you have rows in table b that have no match in a and you onlly want to select everything that has matches uin both tables, you would have to do a raw query to filter the rows of a (or b).


text:
Q: how to export several .xls (Excel) files in a directory into a single .csv file? So I'm looking for a way to export all of the .xls files in a directory into a single .csv file. Any ideas as to how I would approach this?
Specifically:
say my directory contains-
wksht1.xls
wksht2.xls
wksht3.xls
...
wksht1000.xls

how would I merge all of those files into a single .csv (We'll call is aggregate.csv).
Assume each file has the maximum amount of worksheets/rows filled.
All of the files are normalized to a data standard
Thank you very much!

A: Here's the NON .NET solution (it's not clear if your ".NET" tag implies that .NET is mandatory).
I'd write a VBS/WSH script like this one and run it from the command line:
Dim oFSO
Dim oShell, oExcel, oFile, oSheet
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oShell = CreateObject("WScript.Shell")
Set oExcel = CreateObject("Excel.Application")
oExcel.DisplayAlerts = False

For Each oFile In oFSO.GetFolder("C:\").Files
  If LCase(oFSO.GetExtensionName(oFile)) = "xls" Then
    With oExcel.Workbooks.Open(oFile, 0, True, , , , True, , , , False, , False)
      For Each oSheet In .Worksheets
        oSheet.SaveAs ".\" & oFile.Name & "." & oSheet.Name, 6
      Next
      .Close False, , False
    End With
  End If
Next
oExcel.Quit
oShell.Popup "Conversion complete", 10

Mind you, this is directly excerpted from here: http://www.computing.net/answers/programming/script-convert-excel-ss-to-csv/16265.html
But I've used a nearly identical approach many times before to export Access tables to CSV, so I know that VBS scripting is a viable (and probably the simplest) method for this.
Modify the directory name as you see fit (i.e. I don't think your files are in "C:\".  Save this to a file named export_to_csv.vbs, then run with:
cscript export_to_csv.vbs

or
wscript export_to_csv.vbs


text:
Q: Accessing class method without calling the class into a variable php Is it possible to use a classes methods without actually calling the class into a variable. I am sure i have seen this somewhere but i'm not sure if i was dreaming.
Take this example:
<?php
namespace proj;
class beer{
  public function whichIsBest(){
     return 'Not cheap stuff';
  }
}

Include the file start the class but then how can i get to the whishIsBest method without calling the class into a variable first.
<?php
include 'beerClass.php';
new \proj\beer();
echo \proj\beer()->whichIsBest

Or is this just not possible and I was actually dreaming?

A: http://www.php.net/manual/en/language.oop5.static.php
class beer {
public static function whichIsBest() {
 do //
}
}
..

echo beer::whichIsBest();


text:
Q: Writing a Delphi wrapper for P/Invoke & mscorlib.dll  As I have been reading up
I need to get to some foundation to build safely on
When .net takes up a *.dll from within windows it no longer becomes available to .com.
1/ Does this rule mean I loose loadlibray() and GetProcAddress() to load a .net dll like mscorlib.dll.  one developer says no, So I'm asking what boundaries do I have.
Has delphi installed loadlibray() and GetProcAddress() into delphi code?
2/ MSCorEE.dll has a list of methods for wrapping the mscorlib.dll, That I'm about to create a *.pas file to connect to the MSCorEE.dll. Can I use a mscorlib_tbl file as a reference to the mscorlib.dll.
3/ After installing P/Invoke I have no reference to create a Delphi wrapper.
can some suggest something I could use please.
4/ If I could find a copy of mscoree.h & metahost.h & MSCorEE.dll it would save me a lot of work.

A: I guess you want to achieve something like http://www.codeproject.com/KB/COM/simpleclrhost.aspx
Install the Microsoft SDK and you'll get all .h needed files.
Then you can convert the C header file into Delphi. You'll find how in this article of Rudy's Delphi Corner.
But you'll need a lot of understanding about how the low-level managed code works, to interface with Delphi unmanaged code.
I don't exactly understood what you want to do. Take a look at existing solutions like the one call COM interop, instead of sinking into low-level not documented APIs. It may save a lot of time.
More easily, and from my experiment, you can easily call DotNet call from a Delphi application, just by exposing some DotNet objects a COM objects, then call them from Delphi. Even DotNet GUI can be called very easily. You'll just be aware to register the DotNet COM objects for the Wow64 compatibility layer, since Delphi applications are only 32 bit (yet).


text:
Q: why run the gpseginstall utility occured hostfile_exkeys is not accessible as user gpadmin? The GreenPlum version is 4.3.8
when I run the gpseginstall utility to create the Greenplum system user (gpadmin) on all hosts and set the password for that user on all hosts occured a error.
Several steps before installing gpseginstall are correct.
I think the reason should that gpadmin user not competence to read root's file,
so I chmod 777 to the file but the error still occured.
the command is gpseginstall -f hostfile_exkeys -u gpadmin -p gpadmin.
who can help me to solve the error.
Here is the picture.

A: Try moving the hostfile_exkeys file into /tmp and providing the full path to it when invoking gpseginstall:
gpseginstall -f /tmp/hostfile_exkeys -u gpadmin -p gpadmin


text:
Q: How to read the "Report I/O and transfer rate statistics" from sar in sysstat? CONTEXT. Rhel 8.6, sysstat 11.7.3
GOAL. I need to obtain readable statistics in kb, MB or GB, of the data transferred in bandwidth from a website.
WHAT AM I DOING. The server where the website is hosted has sysstat installed and its logs are available in /var/log/sa/. The sysstat sar documentation mentions that the -b option returns a "Report I/O and transfer rate statistics", and displaying information "bread/s". The bread is the "Total amount of data read from the devices in blocks per second. Blocks are equivalent to sectors and therefore have a size of 512 bytes".
I used Sarchart to read the data from the February log, and it returns this graph that I don't understand:

I suspect that I can achieve my goal by reading the information from the bread/s. The problem is that I don't understand two things:

*

*What exactly does "Total amount of data read from the devices" mean? Is that total the number of bytes that have been used in bandwidth?

*If the average transfer number is 200 (as the graph seems to show), does that mean I have to multiply 200 times 512 (bytes) to get the total number of bytes transferred?

Thank you very much in advance!


text:
Q: Dynamically add Vue components to an array I am creating this wizard with a bunch of steps, but the amount of steps depends on what the user selects in step 1 via checkboxes. Step 1 is fixed so it will always be there and so are the last two steps. Between the first and the second last steps are dynamic steps (lets call them components) I get from an array. So on step 1 if I check task 1's checkbox then a tab will appear with task 1's content, but here is my problem I need the tasks I add to the array to be components and not just strings I get from the value property of the checkbox.
Template:
<template>

Setup

          Give this project a name
          <input type="text" placeholder="Title of Project" id="projTitle" />

          <input type="checkbox" v-model="steps" value="Task1" id="addTask1" />
          Task 1

          <input type="checkbox" v-model="steps" value="Task2" id="addTask2" />
          Task 2

          <input type="checkbox" v-model="steps" value="Task3" id="addTask3" />
          Task 3

          <input
            type="checkbox"
            v-model="steps"
            value="Task 4"
            id="addTask4"
          />
          Task 4

{{ step }}

Add Docs

Publish

      <button type="button" class="btn btn-primary">Next</button>

</template>

and here is the script:

I need the steps I add dynamically with the check boxes in step 1 to be components. How can I accomplish it please?

A: To create components dynamically on checkbox selection, You can do that by using :is attribute. Here is the official documentation.

    <component v-bind:is="step"></component>

And you can register these components dynamically by putting a watcher on steps array :
Vue.component('Task1', {
    template: '
Task 1 component
'
})

Live Demo :

new Vue({
  el: '#app',
  data: {
    steps: []
  },
  watch: {
    steps: {
      handler() {
        this.steps.forEach(step => {
          Vue.component(step, {
            template: `<div>${step} component</div>`
          })
        });
      }
    }
  }
})

Setup

        Give this project a name
        <input type="text" placeholder="Title of Project" id="projTitle" />

        <input type="checkbox" v-model="steps" value="Task1" id="addTask1" />
        Task 1

        <input type="checkbox" v-model="steps" value="Task2" id="addTask2" />
        Task 2

        <input type="checkbox" v-model="steps" value="Task3" id="addTask3" />
        Task 3

        <input
               type="checkbox"
               v-model="steps"
               value="Task 4"
               id="addTask4"
               />
        Task 4

      <component v-bind:is="step"></component>

Add Docs

Publish


text:
Q: Migrating sharepoint farm from one domain to another We had Sharepoint farm with domain "ABC". we have moved new domain "XYZ" and domain "ABC" no longer exist now. i want to migrate entire sharepoint farm from "ABC" to "XYZ" now. how do i proceed. please guide step by step

A:
You have a Single Server farm and would like to migrate SharePoint
  server to a new domain
Old Domain: FABRIKA.CONTOSO.COM
New Domain: CONTOSO.COM
Step 1: Preparations before migrating servers:
1.Check if the SharePoint Central Administration's Application Pool is running under Network Service or using a Domain Account
To verify:
a. Open IIS manager –>Expand Web Sites –> Right Click on SharePoint
  Central Administration –> Properties –> Home Directory Tab and then
  locate the Application Pool mapped
b. Right click on the Application Pool and then Click on then Identity
  Tab.
Note: If the Application Pool is running under Network Service then we
  can skip the next step.

*Create a new service account in the new domain (CONTOSO.COM)

*Open SQL Management Studio and backup all the SharePoint related databases including configuration database.
Step 2: Making SharePoint Server a member server of a Different Domain

*

*Right click on My Computer

*Click on Properties

*Under Computer Name click on Change…

*Set it to Workgroup (Restart)
After the restart of the server, join the server back to the domain
  following 1 – 3 section however, pointing it as a member of new domain
  (CONTOSO.COM).
Step 3: Setting up Service Account Rights:
Add the newly created service account to the Local Administrator,
  WSS_WPG, WSS_ADMIN & IIS_WPG group
To do so follow:

*

*Right click on My Computer

*Click on Manage

*Expand Configuration and then expand Local Users and Groups

*Click on Groups and then from the right pane double click on the appropriate group as mentioned above and add the service account.
Step 4: SQL Permissions:
We have to setup appropriate permission for the new service account in
  order to make SharePoint Work.
Follow:

*

*Open SQL Management Studio and then connect to the server

*Expand Security

*Right click on Logins and select new login

*Under Login name specify the new service account

*Click on Server Roles and Check (DBCreator & SecurityAdmin)

*Click on User Mapping and then Check the SharePoint related databases one at a time giving DB_Owner Rights.
Step 5: Updating Service Account:
To update SharePoint with the new service account we have to execute
  following commands on all the SharePoint Servers.
Open CMD and navigate to cd %commonprogramfiles%\Microsoft Shared\Web
  server extensions\12\Bin

*

*stsadm -o updatefarmcredentials -userlogin CONTOSO\ServiceAccount -password NewPassword

*stsadm -o updateaccountpassword -userlogin CONTOSO\ServiceAccount -password NewPassword -noadmin

*stsadm.exe -o spsearch -farmserviceaccount CONTOSO\ServiceAccount -farmservicepassword NewPassword

*stsadm.exe -o spsearch -farmcontentaccessaccount CONTOSO\ServiceAccount –farmcontentaccesspassword NewPassword
5.stsadm.exe -o editssp -title SharedServicesProviderName -ssplogin CONTOSO\ServiceAccount -ssppassword NewPassword

*stsadm.exe -o osearch -farmserviceaccount CONTOSO\ServiceAccount -farmservicepassword NewPassword

  Note: In case of WSS v3 point no. 5 & 6 is not applicable.
Refer: http://support.microsoft.com/kb/934838
Step 6: Confirm Site loads:
Using the new farm service account attempt to load the SharePoint
  Central Administration, once it loads successfully attempt to load the
  Portal Site using the same account.
Step 7: Migrating User Accounts:
Warning: Before you begin ensure that we have migrated all the AD user
  accounts to the new domain.
Note: When a user is migrated in Active Directory, the Security
  Identifier (SID) changes for the user. Additionally, the logon
  information for the user might be changed. Windows SharePoint Services
  and Microsoft SharePoint Portal Server 2003 store user information
  based on both the user SID and the user logon information. When the
  user SID or the user logon information changes in Active Directory,
  Windows SharePoint Services must be updated with the new user
  information before the user can access Windows SharePoint Services
  successfully.
In order to map the old domain account to the new domain account in
  SharePoint execute following.
Open CMD and navigate to cd %commonprogramfiles%\Microsoft Shared\Web
  server extensions\12\Bin
Execute: stsadm -o migrateuser -oldlogin DOMAIN\user -newlogin
  DOMAIN\user -ignoresidhistory
Where OldLogin = User account from the old domain for e.g.,
  FABRIKAM\SUSHRAO
And the Newlogin = Migrated user account CONTOSO\SUSHRAO
Refer:
  http://technet.microsoft.com/en-us/library/cc262141(office.12).aspx
To migrate the Security Group
stsadm –o migrategroup –oldlogin Domain\group –newlogin Domain\group
Where OldLogin = security group from the old domain for e.g.,
  FABRIKAM\HR
And the Newlogin = Migrated group CONTOSO\HR

Check this blog http://blogs.technet.com/b/sushrao/archive/2011/12/02/sharepoint-migrating-sharepoint-server-from-one-domain-to-another.aspx
It contain a detailed steps to migrate SharePoint server to new domain.
Hope that will help you!

A: I am assuming you are talking about Farm Migration not one server migration.
Migrating SharePoint farm from one domain to another is not easy process. You have to build new Farm on new Domain then restore the SharePoint farm backup. You can Move the SQL Server to different domain without any issue.
There are hard coded references, so that is not supported(farm's domain migration)
Here are the steps which should be perform in order to complete the migration.

*

*Backup your current farm(sharepoint farm backup).

*Disjoin the existing servers from current domain.

*Join the servers(Including the SQL Server) to the new domain.

*Re-create a configuration database in the new SQL location.(means rebuild the farm)

*Restore the farm from farm's backup.

*Restore any customizations (Customized web.config for forms
authentication may apply.)

*Run the Migrate User to move all users from old domain to new.


text:
Q: jgit repository browser I would like to create a git repository browser with jgit. But i don't know how to get the last modified date and the last commit message for a file. Here is my current code for the browser:
File directory = new File("/Users/sdorra/.scm/repositories/git/scm-git");
Repository repository =
  RepositoryCache.open(RepositoryCache.FileKey.lenient(directory,
    FS.DETECTED), true);

try
{
  ObjectId revId = repository.resolve(Constants.HEAD);
  DirCache cache = new DirCache(directory, FS.DETECTED);
  TreeWalk treeWalk = new TreeWalk(repository);

  treeWalk.addTree(new RevWalk(repository).parseTree(revId));
  treeWalk.addTree(new DirCacheIterator(cache));

  while (treeWalk.next())
  {
    System.out.println("---------------------------");
    System.out.append("name: ").println(treeWalk.getNameString());
    System.out.append("path: ").println(treeWalk.getPathString());

    ObjectLoader loader = repository.open(treeWalk.getObjectId(0));

    System.out.append("directory: ").println(loader.getType()
                      == Constants.OBJ_TREE);
    System.out.append("size: ").println(loader.getSize());
    // ???
    System.out.append("last modified: ").println("???");
    System.out.append("message: ").println("???");
  }
}
finally
{
  if (repository != null)
  {
    repository.close();
  }
}

It is possible to get the last commit of a file?
Note: My git repository is a bare repository without working copy.

A: You're using lower level JGit API, why don't you use LogCommand via the org.eclipse.jgit.api package? Then use addPath(...), call()...
After that, you should get a list of RevCommit's for the specified path.


text:
Q: When should one de facto use try-except in Python? I usually use try-except blocks when I eg need input data from the user or try to start a thread. But is there some rule of thumb telling when one should definitely use a try-except block? As technically speaking nothing prohibits you of doing something as "clever" as:
try:
    print("Hello world")
except:
    print("Bye bye world")

Should I implement a try-except block whenever I for example feel like one of the following errors could arise?
$ python -m pydoc builtins

BaseException
    Exception
        ArithmeticError
            FloatingPointError
            OverflowError
            ZeroDivisionError
        AssertionError
        AttributeError
        BufferError
        EOFError
        ImportError
            ModuleNotFoundError
        LookupError
            IndexError
            KeyError
        MemoryError
        NameError
            UnboundLocalError
        OSError
            BlockingIOError
            ChildProcessError
            ConnectionError
                BrokenPipeError
                ConnectionAbortedError
                ConnectionRefusedError
                ConnectionResetError
            FileExistsError
            FileNotFoundError
            InterruptedError
            IsADirectoryError
            NotADirectoryError
            PermissionError
            ProcessLookupError
            TimeoutError
        ReferenceError
        RuntimeError
            NotImplementedError
            RecursionError
        StopAsyncIteration
        StopIteration
        SyntaxError
            IndentationError
                TabError
        SystemError
        TypeError
        ValueError
            UnicodeError
                UnicodeDecodeError
                UnicodeEncodeError
                UnicodeTranslateError
        Warning
            BytesWarning
            DeprecationWarning
            FutureWarning
            ImportWarning
            PendingDeprecationWarning
            ResourceWarning
            RuntimeWarning
            SyntaxWarning
            UnicodeWarning
            UserWarning
    GeneratorExit
    KeyboardInterrupt
    SystemExit

A: It really should only be used when there are errors that might happen in a program that you want to handle a certain way. There might be errors you know could potentially happen, such as a memory error, but unless you want your program to react a certain way, you shouldn't use a try-except block.
For a smooth user experience, it might also be good to catch certain exceptions that are out of your control (like a Connection Error) so that you can tell your user what happened and they can try to remedy it.

A: Exceptions are raised when called code encounters a problem that it cannot solve itself. For example when arguments are invalid, or when resources it attempts to access are not responding properly. Exceptions are generally meant to be exceptional and while they may occur when performing things, the normal control flow would be without exceptions.
You should catch exceptions, whenever called code could potentially raise an exception which you can recover from. That part is very important: There is no use catching an exception when you cannot work around that failure. Only catch exceptions that you expect to be raised.
That may seem counter intuitive after I having said that exceptions are exceptional, so expecting them seems weird. But the point is that code could raise any exception. For example, there are a lot of different external factors that could cause perfectly working code to suddenly raise an exception that it would usually never do. So you don't just catch any exception. Instead you catch those exceptions explicitly that you expect to be eventually raised from the code and that you can work with without affecting your overall program.
I go into a lot more detail about this in my answer to another question: Why is "except: pass" a bad programming practice?
So basically, catch a specific exception when the code you are calling could raise that one and you could recover from it. Asking the user for input and want to parse this? Catch the exception from the parser and ask the user to correct it. Performing a network request to some API? Catch a network exception and maybe retry it. Writing a library for consuming an API that then performs a network request? Do not catch the network exception but let the consumer of your code decide how to recover from it.
Also, if you don't know what exceptions code could raise, check the documentation. Usually the relevant exceptions are documented. There's always a possibility that some exceptions may occur outside of the control of the called code, e.g. MemoryError, but those are usually neither to be expected nor really recoverable anyway, so you shouldn't really check for those.


text:
Q: Understanding projective space as fibrations of tori over spaces with boundaries The toric manifold $\mathbb{CP}^1$ can be understood as a circle fibration over an interval $I$, with the circles having zero radius at the boundaries of the interval. How does one generalize this viewpoint to higher-dimensional projective spaces, i.e., $\mathbb{CP}^N$?
Can we interpret, e.g., $\mathbb{CP}^2$ as the fibration of the torus $T^2$ over a square $I^2$ or disk? References would be appreciated.


text:
Q: Trouble solving $\int\sqrt{1-x^2} \, dx$ I am trying to learn how to solve integrals and I've got the hang out of a lot of examples, but I haven't got the slightest idea how to solve this example, this is how far I've got:
$$
\int\sqrt{1 - x^2} \, dx = x\sqrt{1-x^2} - 2\int\frac{x^2}{\sqrt{1-x^2}} \, dx
$$
Can you please help me solve it, and also some tips concerning the integration are welcome.
Thank you

A: Using Trigonometric substitution, $\arcsin x=\phi$
$\implies (i)x=\sin\phi$ and
$(ii)-\frac\pi2\le \phi\le\frac\pi2$ based on principal value of inverse sine ratio,
$\implies\cos\phi\ge0$
$$\int\sqrt{1-x^2}dx=\int|\cos\phi|\cos\phi d\phi = \int\cos^2\phi d\phi$$
$$= \frac12\int(1+\cos2\phi) d\phi$$
$$=\frac12\left(\phi+\frac{\sin2\phi}2\right)+K=\frac{\phi+\sin\phi\cos\phi}2+K$$

A: $\newcommand{\cos}{\sin}$
Let's try $$\int_0^{x}\sqrt{1-a^2}\text da$$ You can generalize from that.  Now, $\sqrt{1-x^2}$ describes a semicircle.  Consider the following image:
So we have $\int_0^x\sqrt{1-a^2}\text da=A_1+A_2$.  $A_2$ is a right triangle with base $x$ and height $\sqrt{1-x^2},$ so $A_2=\frac12x\sqrt{1-x^2}$.  Meanwhile, $A_2$ is a sector of the circle.  Note that the angle $$\theta=\angle (0,1)O(x,\sqrt{1-x^2})=\frac{\sin^{-1}x}1=\sin^{-1}x$$
Since the angle from the center is proportional to the area, $A_2=\frac{\theta}{2\pi}\cdot \pi r^2=\frac{\sin^{-1}x}{2}$
Thus $$ \int_0^x\sqrt{1-a^2}\text da=\frac{\sin^{-1}x+x\sqrt{1-x^2}}{2} $$

A: subsititute $ x =sin\theta $, this gives,
$ dx = cos\theta d\theta$
hence, $ \int \sqrt{(1-x^2)} dx  = \int (\sqrt{1 - sin^2\theta} ). cos\theta d\theta = \int cos^2 \theta d\theta $
Remember that, $cos(\alpha + \beta) =  cos \alpha .cos \beta - sin \alpha . sin \beta $,
substituting, $\alpha = \beta = \theta$,

*

*$ (cos^2\theta - sin^2\theta) = cos(2\theta)$, as well

*$ (cos^2\theta + sin^2\theta) = 1  $
Adding equation 1. and 2. yields,
$2 cos^2 \theta = 1 + cos2\theta ~ \implies ~ cos^2\theta = \frac{1}{2}(1+cos2\theta)$
hence going  back to integral,
$\int cos^2\theta d\theta = \frac{1}{2}\int (1+cos2\theta) d\theta  = \frac{1}{2}(\theta + \frac{sin2\theta}{2}) + C$
By reverse substitution, $\theta = cos^{-1}x = arccos(x) $  and $sin2\theta = 2.sin\theta . cos\theta$
The solution of indefinite integral is ,
$ \int \sqrt{(1-x^2)} dx =  \frac{1}{2} ( \theta + \frac{2.sin\theta.cost\theta}{2} )+ C \implies \frac{1}{2}(\theta + sin\theta. cos\theta) + C $
$ \int \sqrt{(1-x^2)} dx \implies  \frac{1}{2}(arccos(x) + x\sqrt{1-x^2}) + C $

A: I, personally, suggest @lab's way because it is general and suitable for students, but you may use this strange substitution as well: $$1-x^2=x^2t^2$$

A: Your idea of integrating by parts is good (but you did it wrong):
\begin{align}
\int\sqrt{1 - x^2} \, dx
&= x\sqrt{1-x^2} - \int x\frac{-2x}{2\sqrt{1-x^2}} \, dx \\
&= x\sqrt{1-x^2} + \int\frac{x^2}{\sqrt{1-x^2}}\,dx\\
&= x\sqrt{1-x^2} + \int\frac{x^2-1+1}{\sqrt{1-x^2}}\,dx\\
&= x\sqrt{1-x^2} - \int\sqrt{1-x^2}\,dx+\int\frac{1}{\sqrt{1-x^2}}\,dx\\
&= x\sqrt{1-x^2} + \arcsin x - \int\sqrt{1-x^2}\,dx
\end{align}
Therefore
$$
2\int\sqrt{1 - x^2} \, dx = x\sqrt{1-x^2} + \arcsin x
$$
and
$$
\int\sqrt{1 - x^2} \, dx = \frac{1}{2}x\sqrt{1-x^2} + \frac{1}{2}\arcsin x + c
$$


text:
Q: Backbone model.destroy() limited I'm attempting to bulk delete a collection of backbone models like so...
collection.each(function(model, i){
  model.destroy();
});

I'm finding that when the each loop contains model.destroy(), it stops after a count of 10. If  I run it again, it stops a 5. The times after 3.. 2.. and then 1.
If I replace the model.destroy() with console.log(i), the loop runs the length of the collection.
Is this an intentional limitation within Backbone to keep you from deleting 1000 records in one shot or a browser limitation on the number of relatively simultaneous DELETE methods?

A: Is this an intentional limitation within Backbone to keep you from deleting 1000 records in one shot or a browser limitation on the number of relatively simultaneous DELETE methods?
No.
The problem is you are munging the collection on each iteration. Consider the following.
Say you start off with a collection of 10 models:
// pretend this collection has 10 models [m0,m1,m2,m3,m4,m5,m6,m7,m8,m9]
collection.each(function(model,i) {
  model.destroy();
});

On your first iteration, your collection.length === 10 and the arguments to collection.each will be m0 and 0. So you call, m0.destroy() which lives at index 0.
At the end of the first iteration your collection contains the following models
[m1,m2,m3,m4,m5,m6,m7,m8,m9]

The following is where the problem starts:
Now for your second iteration your collection.length === 9 . The each function is now on its second iteration and grabbing the model at index of 1, and that's where model 2 lives. So the arguments into each are m2,1. You then call m2.destroy() and remove that from the collection.
At the end of the second iteration your collection contains the following:
[m1,m3,m4,m5,m6,m7,m8,m9]

The third iteration, your index will be 2 and m4.destroy() will be called. leaving you with:
 [m1,m3,m5,m6,m7,m8,m9].

This happens until the index is greater than collection.length and then stops. Leaving you with unwanted models in your collection.
The following should work for you:
while ( (model=collection.shift()) ) {
  model.destroy()
}

A: Agree to previous answers, you are not allow to do that.
Very quickly, what I would do in that case:
collection.map(function (model) {
  return model.id;
}).each(function (id) {
  collection.get(id).destroy();
});

A: Have you tried removing the model first from the collection using Backbone.Collection.remove? I think by calling model.destroy() you are breaking the internal array of models handled by the collection.
Try it like this:
collection.each(function(model, i) {
    collection.remove(model);
    model.destroy();
});


text:
Q: CMS existing HTML5/CSS3 website I build HTML5/CSS3 websites that are cross-browser compliant and responsive. My clients want the ability to edit text areas and upload new stories into the news section and images to the photo gallery. What is my best option to continue building (clean, SEO friendly) websites while giving my clients the option to update the website themselves?
I have looked into the likes of a CMS like joomla and drupal and they seem heavily dependent on templates which scares me. Is it just a case of pasting my php-includes and css files into system that builds my unique 'template'? Other CMS options; cushycms and pagelime seem more along the lines of what I'm looking for but appear to edit existing text only?
In a nutshell; I want to keep my existing designs and simply make them editable.

A: Sorry for the blatant self-promotion, but feel I have to chime in.
I'm the CEO of Webpop, a fully hosted CMS that's made with frontend developers and web designers in mind.
We built Webpop exactly for solving this problem and have done a lot of work on making sure that you can keep your HTML/CSS and javascript exactly as it appears in your static mockup when building a site with Webpop.
We have two completely separate UIs, one for you, where we've done our best to make it as easy as we can to let you work directly with the HTML, CSS and javascript. And one for your clients, that's just a simple on-site editor where they can update the part of the site that's dynamic content.

A: I would opt for a MVC framework. You can find all information about all different frameworks here.
The advantage of this is that you can keep your HTML5/CSS3 as the "views" while moving the business logic to controllers and models of your MVC framework. I personally used CakePHP and CodeIgniter. The latter is very easy to use and will be very simple to set up.

A: I have found Get Simple CMS http://get-simple.info/ to be great for this.  It PHP based but doesn't require a database.  It comes with a few templates, but it's not too tricky to edit or create your own template from your CSS and HTML.

A: I always liked Perch for exactly this kind of stuff. Editable fields, real simple stuff. However I eventually did migrate to Wordpress, simply because my clients started demanding more blog-life features. If the sites you build are going to remain simple, Perch is quite wonderful.
http://grabaperch.com/

A: Well basically i always use wordpress , it's not so hard to learn... you slice your site up into the areas you need ... the menu's are generated automatically as you add pages to your site . Wordpress also has lots of plug-ins wich are easy to implement . Wordpress is not only a blog , major sites use it for contentmanaging their website.
check it out at Wordpress.org for learning to slice up your website there's a very nice guide, find it here : Theming and CSS


text:
Q: find a match and copy lines after in perl I have the following data..
interface 123
 item1
 item2
 item3
interface 456
 item5
 item6
 item7
card 477
 something foo
 somethig bar

Each interface starts at the very beginning of the line, where the detail of each interface has a space before the actual item. This is the only thing that can distinguish when the config detail of a ended.
I need to search each interface, and copy it and it's detail until the next line that does not start with a space.
So I would need to separate each interface with it's content detail, but not card. I was helped in a previous question with this, but the 2 loops are throwing me out and I would want to run 1 loop only as I do alot more later like deduplication, so 2 loops are becoming very confusing me.
my @idx = grep { $lines[$_] =~ /^interface/ } 0..$#lines;

for my $i (0..$#idx-1) {
say "Interface:";
say "\t$_" for @lines[$idx[$i]..$idx[$i+1]-1];
}

# The last interface section stops at the first unindented line
say "Interface:";
for my $i ($idx[-1] .. $#lines) {
    last if $lines[$i] =~ /^\S/ and $lines[$i] !~ /^interface/;
    say "\t$lines[$i]";
}

Can someone kindly help me do the same thing in a single loop?

A: use strict; use warnings;

my $interface_line;
while(<DATA>) {
  if( /^interface/ ) { # start of new interface-section
    $interface_line = 1;
  }elsif( $interface_line && /^[ \t]/ ) { # interface-section followup
    $interface_line++;
  }elsif( $interface_line ) { # end of interface-section
    $interface_line = undef;
  }

  if( $interface_line ) {
     print "Interface:\n" if $interface_line == 1;
     print "$interface_line: $_";
  }
}

__DATA__
interface 123
 item1
 item2
 item3
interface 456
 item5
 item6
 item7
card 477
 something foo
 somethig bar


text:
Q: How to parse Nested JSON Array into Codable struct I want to parse the JSON nested array into my decodable struct but the issue is there is no Key values how can i set into my decodable struct. I am also using SwiftJSON to parse object in my project...
Here is my Decodable struct:
struct PlayerData: Decodable {
    let playerID: Int?
    let platIDRef: Int?
    let EnrolledDateTime: String?
    let PlayerType: String?
    let LastCheckIn: Double?
    let SerialNo: Int?
    let Offered: Double?
    let PlayerReferralCode: Int?
    let PlayerStats: Double?
    let PlayerUpstream: Int?

}

here is the server response JSON object in console:
you check the below json response at JSON VIEWER
[[1,1,1532890155915,0,7618.37,1,8047.76,1,0.01197066,0],[2,1,1532890155915,0,7618.37,1,8046.87,1,0.27672821,0],[3,1,1532890155915,0,7618.37,1,8045.26,1,0.27672821,0],[4,1,1532890155915,0,7618.37,1,8038.04,1,0.11222798,0],[5,1,1532890155915,0,7618.37,1,8037.94,1,0.09222818,0],[6,1,1532890155915,0,7618.37,1,8036.3,1,0.1994227,0],[7,1,1532890155915,0,7618.37,1,8035.4,1,0.44272289,0],[8,1,1532890155915,0,7618.37,1,8034.52,1,0.04333567,0],[9,1,1532890155915,0,7618.37,1,8034.51,1,0.40587824,0],[10,1,1532890155915,0,7618.37,1,8032.3,1,0.10256018,0],[11,1,1532890155915,0,7618.37,1,8031.13,1,0.00637662,0],[12,1,1532890155915,0,7618.37,1,8031.12,1,0.46122825,0],[13,1,1532890155915,0,7618.37,1,8030.34,1,0.12184043,0],[14,1,1532890155915,0,7618.37,1,8030.08,1,0.01381566,0],[15,1,1532890155915,0,7618.37,1,8028.18,1,0.01001035,0],[16,1,1532890155915,0,7618.37,1,8028.16,1,0.37072738,0],[17,1,1532890155915,0,7618.37,1,8028.14,1,0.13835319,0],[18,1,1532890155915,0,7618.37,1,8027.71,1,0.4302254,0],[19,1,1532890155915,0,7618.37,1,8026.13,1,0.002,0],[20,1,1532890155915,0,7618.37,1,8025.71,1,0.04610317,0],[21,1,1532890155915,0,7618.37,1,8379.29,1,0.00301798,1],[22,1,1532890155915,0,7618.37,1,8379.3,1,0.0698277,1],[23,1,1532890155915,0,7618.37,1,8380.3,1,0.32028728,1],[24,1,1532890155915,0,7618.37,1,8380.63,1,0.04697547,1],[25,1,1532890155915,0,7618.37,1,8382.57,1,0.01067624,1],[26,1,1532890155915,0,7618.37,1,8385.38,1,0.01161041,1],[27,1,1532890155915,0,7618.37,1,8385.4,1,0.16014364,1],[28,1,1532890155915,0,7618.37,1,8385.52,1,0.1241647,1],[29,1,1532890155915,0,7618.37,1,8386.13,1,0.12978041,1],[30,1,1532890155915,0,7618.37,1,8386.82,1,0.36803144,1],[31,1,1532890155915,0,7618.37,1,8387.9,1,0.06358541,1],[32,1,1532890155915,0,7618.37,1,8387.94,1,0.56588357,1],[33,1,1532890155915,0,7618.37,1,8389.71,1,0.10676243,1],[34,1,1532890155915,0,7618.37,1,8390.52,1,0.05338121,1],[35,1,1532890155915,0,7618.37,1,8390.61,1,0.64999101,1],[36,1,1532890155915,0,7618.37,1,8393.96,1,0.00368495,1],[37,1,1532890155915,0,7618.37,1,8393.97,1,0.32669303,1],[38,1,1532890155915,0,7618.37,1,8394.6,1,0.01363635,1],[39,1,1532890155915,0,7618.37,1,8395.11,1,0.53381214,1],[40,1,1532890155915,0,7618.37,1,8395.79,1,0.07345255,1]]

A: To decode an array you need to get the unkeyedContainer() and decode each value separately
let jsonString = """
[[1,1,1532890155915,0,7618.37,1,8047.76,1,0.01197066,0],[2,1,1532890155915,0,7618.37,1,8046.87,1,0.27672821,0],[3,1,1532890155915,0,7618.37,1,8045.26,1,0.27672821,0],[4,1,1532890155915,0,7618.37,1,8038.04,1,0.11222798,0],[5,1,1532890155915,0,7618.37,1,8037.94,1,0.09222818,0],[6,1,1532890155915,0,7618.37,1,8036.3,1,0.1994227,0],[7,1,1532890155915,0,7618.37,1,8035.4,1,0.44272289,0],[8,1,1532890155915,0,7618.37,1,8034.52,1,0.04333567,0],[9,1,1532890155915,0,7618.37,1,8034.51,1,0.40587824,0],[10,1,1532890155915,0,7618.37,1,8032.3,1,0.10256018,0],[11,1,1532890155915,0,7618.37,1,8031.13,1,0.00637662,0],[12,1,1532890155915,0,7618.37,1,8031.12,1,0.46122825,0],[13,1,1532890155915,0,7618.37,1,8030.34,1,0.12184043,0],[14,1,1532890155915,0,7618.37,1,8030.08,1,0.01381566,0],[15,1,1532890155915,0,7618.37,1,8028.18,1,0.01001035,0],[16,1,1532890155915,0,7618.37,1,8028.16,1,0.37072738,0],[17,1,1532890155915,0,7618.37,1,8028.14,1,0.13835319,0],[18,1,1532890155915,0,7618.37,1,8027.71,1,0.4302254,0],[19,1,1532890155915,0,7618.37,1,8026.13,1,0.002,0],[20,1,1532890155915,0,7618.37,1,8025.71,1,0.04610317,0],[21,1,1532890155915,0,7618.37,1,8379.29,1,0.00301798,1],[22,1,1532890155915,0,7618.37,1,8379.3,1,0.0698277,1],[23,1,1532890155915,0,7618.37,1,8380.3,1,0.32028728,1],[24,1,1532890155915,0,7618.37,1,8380.63,1,0.04697547,1],[25,1,1532890155915,0,7618.37,1,8382.57,1,0.01067624,1],[26,1,1532890155915,0,7618.37,1,8385.38,1,0.01161041,1],[27,1,1532890155915,0,7618.37,1,8385.4,1,0.16014364,1],[28,1,1532890155915,0,7618.37,1,8385.52,1,0.1241647,1],[29,1,1532890155915,0,7618.37,1,8386.13,1,0.12978041,1],[30,1,1532890155915,0,7618.37,1,8386.82,1,0.36803144,1],[31,1,1532890155915,0,7618.37,1,8387.9,1,0.06358541,1],[32,1,1532890155915,0,7618.37,1,8387.94,1,0.56588357,1],[33,1,1532890155915,0,7618.37,1,8389.71,1,0.10676243,1],[34,1,1532890155915,0,7618.37,1,8390.52,1,0.05338121,1],[35,1,1532890155915,0,7618.37,1,8390.61,1,0.64999101,1],[36,1,1532890155915,0,7618.37,1,8393.96,1,0.00368495,1],[37,1,1532890155915,0,7618.37,1,8393.97,1,0.32669303,1],[38,1,1532890155915,0,7618.37,1,8394.6,1,0.01363635,1],[39,1,1532890155915,0,7618.37,1,8395.11,1,0.53381214,1],[40,1,1532890155915,0,7618.37,1,8395.79,1,0.07345255,1]]
"""

struct PlayerData: Decodable {
    let playerID: Int
    let platIDRef: Int
    let enrolledDateTime: Int
    let playerType: Int
    let lastCheckIn: Double
    let serialNo: Int
    let offered: Double
    let playerReferralCode: Int
    let playerStats: Double
    let playerUpstream: Int

    init(from decoder: Decoder) throws {
        var arrayContainer = try decoder.unkeyedContainer()
        playerID = try arrayContainer.decode(Int.self)
        platIDRef = try arrayContainer.decode(Int.self)
        enrolledDateTime = try arrayContainer.decode(Int.self)
        playerType = try arrayContainer.decode(Int.self)
        lastCheckIn = try arrayContainer.decode(Double.self)
        serialNo = try arrayContainer.decode(Int.self)
        offered = try arrayContainer.decode(Double.self)
        playerReferralCode = try arrayContainer.decode(Int.self)
        playerStats = try arrayContainer.decode(Double.self)
        playerUpstream = try arrayContainer.decode(Int.self)
    }
}

The JSON can be decoded as [PlayerData].self
let data = Data(jsonString.utf8)
do {
    let result = try JSONDecoder().decode([PlayerData].self, from: data)
    print(result)
} catch { print(error) }


text:
Q: Unanswered questions have accepted answer with upvote in Android app I see some of the questions in the Unanswered section having an accepted answer and the accepted answer having upvote also in the Android app.
In the blog post it is defined as

Unanswered questions have no answers with upvotes (or accepted)

But the accepted answer with upvote also still list in the Unanswered questions. Is my understanding is wrong or is it a bug?
Screenshot for reference:


text:
Q: Use Jenkins container to build Dockerfile and deploy Flask app I have a Flask-Nginx app that I made using Flask and Nginx Docker containers and used docker-compose to make them run. Now I want to use a Jenkins container to clone this code from a repository upon a Web-hook trigger. This means I have to build and run my Flask app container inside a container (Docker in Docker). Is this a correct approach(It feels messy to me)? Or is there anyway to build and run the Flask app container outside the Jenkins container? Please let me know of any other possible and proper ways.

A: yes, There is an option that's Kaniko.
You wouldn't need docker to build a docker image from a Dockerfile.
Sounds impossible then check out Kaniko.
One more bonus of using kaniko is that the images built by it are identical to the images built by Docker.
Check out
https://medium.com/@sebgoa/building-docker-images-with-kaniko-6e2421b018


text:
Q: Mapping columns programmatically during migration We have a source farm which is Moss 2007 and try to migrate it to Sharepoint 2010.
on the source farm we have two Information Lists on the top web site (category1 and category2), so in every sub web sites we have a document library which contains two custom columns col1 and col2 (among others). the data for these columns comes from category1 and category2 (for all sub web sites) which are showen as dropdownlist and every field (file) in these documnt libraries get a value form the dropdownlists.
On the target farm's Managed Metadata we have created two lists (same as source farm) targetCat1 and targetCat2.
Now I want to create an application which goes through all sub sites and goes through all Document libraries and creates new target document Library, gets data (file) from source sub site, moves it to target docuemtn library on target sub site and mapps Category1 to targetCat1, Category2 to targetCat2 for every file.
Thank you very much for your answer.

A: You should look at partner solutions rathen than reinventing the wheel. Search for SharePoint migration to find options


text:
Q: Как установить картинку с firebase storage? Я написал код, который передает фото и имя пользователя. На данный момент они видны только в активити передачи.
Как сделать так, чтобы во всех imageview этого пользователя были картинки, загруженные им и видные другим пользователям на java?
Надо, чтобы когда заходит определенный пользователь, он видел в своем профили именно ту информацию, которую он загрузил, и чтобы другие тоже соответственно.
Изменение: я небольшой код написал для пользователя. Я прописал в профиль активити, чтобы он получал имя и фото со storage. Но он почему то не работает. Фото и имя не меняется. Возможно, дело в том, что при вводе имени там стоит edittext, а в моем изменении просто textview, но фото тоже не грузится. Как это можно исправить?
private void GetuserInfo()
    {
        DatabaseReference reference= FirebaseDatabase.getInstance().getReference().child("Users");
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (snapshot.exists()&&snapshot.getChildrenCount()>0)
                {
                    String name=snapshot.child("name").getValue().toString();
                    textVusername.setText(name);
                    if (snapshot.hasChild("image")) {
                        String image = snapshot.child("image").getValue().toString();
                        Picasso.get().load(image).into(image_user_sett);
                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }

Вот мой код активити:
private ImageView imageprof, plusphoto;
    private EditText nick_edit;
    private Button savenick_button;
    private StorageReference storageprofilpicsRef;
    private FirebaseStorage storage;
    private Uri imageUri;
    private String myUri = "";
    private String checker = "";
    private StorageTask uploadTask;
    private FirebaseAuth mAuth;
    private DatabaseReference databaseReference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settingacc);
        imageprof = (ImageView) findViewById(R.id.imageprof);
        plusphoto = (ImageView) findViewById(R.id.plusphoto);
        storageprofilpicsRef = FirebaseStorage.getInstance().getReference().child("ProfileImage");
        storage = FirebaseStorage.getInstance();
        mAuth = FirebaseAuth.getInstance();
        databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
        savenick_button=(Button) findViewById(R.id.savenick_button);
        nick_edit=(EditText) findViewById(R.id.nick_edit);

        savenick_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (checker.equals("clicked")) {
                    ValidateControlers();

                } else {
                    ValidateAndSaveOnlyInfo();

                }

            }
        });

        plusphoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checker = "clicked";
                CropImage.activity().setAspectRatio(1, 1).start(SettingaccActivity.this);
            }
        });
        getUserInfo();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            imageUri = result.getUri();

            imageprof.setImageURI(imageUri);
        } else {
            Toast.makeText(this, "Произошла ошибка", Toast.LENGTH_SHORT).show();
        }

    }

    private void ValidateControlers() {
        if (TextUtils.isEmpty(nick_edit.getText().toString()))
            Toast.makeText(this, "Введите ние", Toast.LENGTH_SHORT).show();

        else if (checker.equals("clicked")) ;
        {

            uploadProfilImage();
        }
    }
    private void uploadProfilImage() {
    final ProgressDialog progressDialog=new ProgressDialog(this);
    progressDialog.setTitle("Идет загрузка");
    progressDialog.setMessage("Пожалуйста подождите");
    progressDialog.show();
    if (imageUri !=null){
        final StorageReference fileRef= storageprofilpicsRef.child(mAuth.getCurrentUser().getUid()+"jpg");
        uploadTask=fileRef.putFile(imageUri);
        uploadTask.continueWithTask(new Continuation() {
            @Override
            public Object then(@NonNull Task task) throws Exception {
                if (!task.isSuccessful()){
                    throw  task.getException();
                }
                return fileRef.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task <Uri>task) {
                if (task.isSuccessful()){
                    Uri downloadUri=task.getResult();
                    myUri=downloadUri.toString();
                    HashMap<String,Object> userMap=new HashMap<>();
                    userMap.put("uid",mAuth.getCurrentUser().getUid());
                    userMap.put("name",nick_edit.getText().toString());
                    userMap.put("image",myUri);

                    databaseReference.child(mAuth.getCurrentUser().getUid()).updateChildren(userMap);
                    progressDialog.dismiss();

                    startActivity(new Intent(SettingaccActivity.this,HomeActivity.class));
                }
            }
        });
    }
    else {
        Toast.makeText(this, "Изображение не выбрано", Toast.LENGTH_SHORT).show();
    }
    }
    private void ValidateAndSaveOnlyInfo() {
        if (TextUtils.isEmpty(nick_edit.getText().toString()))
            Toast.makeText(this, "Введите ние", Toast.LENGTH_SHORT).show();

else {
            HashMap<String, Object> userMap = new HashMap<>();
            userMap.put("uid", mAuth.getCurrentUser().getUid());
            userMap.put("name", nick_edit.getText().toString());

            databaseReference.child(mAuth.getCurrentUser().getUid()).updateChildren(userMap);

            startActivity(new Intent(SettingaccActivity.this, HomeActivity.class));
        }
    }
    private void getUserInfo() {
    databaseReference.child(mAuth.getCurrentUser().getUid()).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if (snapshot.exists()&&snapshot.getChildrenCount()>0)
            {
                String name=snapshot.child("name").getValue().toString();
                nick_edit.setText(name);
                if (snapshot.hasChild("image")) {
                    String image = snapshot.child("image").getValue().toString();
                    Picasso.get().load(image).into(imageprof);
                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
    }
    }


text:
Q: MVC - Run different areas under different application pools I need to run different areas in the code under different appPools.
I tried converting the admin area (MVC C#) to application and assign a different appPool but the binaries still run's under to main appPool.
Is there other way to do it?
I thought about making an applications that pointing to the same folder but I'm not sure what will be the consequent. also, if possible I prefer a cleaner solution.


text:
Q: (help still needed) How to make a playvideo function that returns when video is over? So I am using JavaFX and want to set up an experiment where I have to play many videos and interact with the user. For this setup I would like to write a function that receives a filename and plays the video with that name. But it should only return when the video is over, and not before. So something like this:
private void play(URI name){
    MediaPlayer mediaPlayer = new MediaPlayer(new Media(name));
    mediaPlayer.setAutoPlay(true);
    view.setMediaPlayer(mediaPlayer);
}

However this function returns before the video is over, making the execution of the program a complete mess. I know MediaPlayer has a setOnEndOfMedia(Runnable) function but I am not sure how I could potentially use that to achieve my goal.
This is the code I have at the moment. But it does not work. The problem being that both videos are played at the same time, likely because the play function returns as soon as it has started the video. I have also tried just adding a while(true) loop at the end of the play function so that it gets stuck there until the return; in .setOnEndOfMedia is callled, that prevented any video's from being played at all.
CODE:
static MediaView view;

@Override
public void start(Stage stage) throws IOException, URISyntaxException, InterruptedException {
    // Create full screen scene
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    stage.setFullScreen(true);
    Scene scene = new Scene(new Group(), dim.getWidth(), dim.getHeight());
    stage.setScene(scene);
    stage.show();

    // Create the view and add it to the Scene.
    view = new MediaView();
    ((Group)scene.getRoot()).getChildren().add(view);

    play("videol");
    play("video2");
}

private static void play(String name) throws InterruptedException {
    Media media = new Media(uri(name));
    MediaPlayer player = new MediaPlayer(media);
    player.setOnReady(() -> {
        player.play();
        player.setOnEndOfMedia(() -> {
            player.dispose();
            return;
        });
    });
    view.setMediaPlayer(player);
}

private static String uri(String name) {
    return Paths.get("clips/" + name + ".mp4").toUri().toString();
}

public static void main(String[] args) {
    launch(args);
}

A: Keeping my original stuff since it is useful for others.
Anyways the problem with your code is that you are calling the method twice, right after itself. You need to call the method from within the EndOfMedia part. If you wish you can create a list and for the parameter when using recursion you can use list.poll() to take and remove the first string in the list. Then when the list is null you can just return to the interface. Just some ideas.
What I would suggest you use is to create a method for playing your music which takes a String as a parameter, this string would be then used to find its equivalent in a hashmap, say HashMap<String, MediaPlayer>. Then to the part where you actually need help. I suggest you write something like this:
    mediaPlayer.setOnReady(() -> {
        mediaPlayer.play();
        mediaPlayer.setOnEndOfMedia(() -> {
            mediaPlayer.dispose();
            MusicPlayer();
        });
    });

Basically, you are playing the media when ready and then at the end disposing of it and calling the method again and in where my code uses recursion and calls the method MusicPlayer you can instead 'return'. Sorry if this is poorly explained, if you need further help just comment below.


text:
Q: How to get Microsoft Edge handling my css for 3D in perspective correctly for mouse hovering? I am using the css properties perspective and transform to create a 3D world in html. In Google Chrome everything works without problems, but in Microsoft Edge there is something buggy in it... I narrowed it down using this jsfiddle: https://jsfiddle.net/uke8bsvk/12/
The third variant in the fiddle is where it goes wrong. It is working fine in Google Chrome, but in Microsoft Edge somehow the red div does not respond well to hovering it with the mouse by changing its color to green. It only responds to hovering it with the mouse close to the bottom of the red div.
In the fourth variant I removed transform-style: preserve-3d for the red div and everything works fine again.
Does anyone have an idea what's going on here and how to solve it?
PS. In my real case, I sometimes have a child div for which preserving 3d is necessary and sometimes I do not have a child div. It is not really an option to use the obvious dirty work around of setting and removing transform-style: preserve-3d dependent on the presence of a child div.

A: I found a relatively clean trick/work around to 'solve' the problem: just add an extra child div, make it invisible and rotate it out of plane with transform: rotateX( 1deg ). See jsfiddle: https://jsfiddle.net/uke8bsvk/13/

A: You need to prefix the 3d properties in your css, using Autoprefixer. You can do it on the site itself or add it as an extension to your code editor of choice.
It will add some of these prefixes to your code as so:
-webkit-transform-origin: bottom left;
      transform-origin: bottom left;
-webkit-transform: rotateX( 30deg );
      transform: rotateX( 30deg );
      background: red;
-webkit-transform-style: preserve-3d;
      transform-style: preserve-3d;

Here is an updated Fiddle.
You should prefix each and every one of your projects for the web.


text:
Q: How to check if a php array value is in js array? First of all I get all the values from a php array:
<?php
  $user_id = get_current_user_id();
  $userPostsInternal = get_user_meta( $user_id, 'save_post_internal', TRUE );
  $userPostsExternal = get_user_meta( $user_id, 'save_post_external', TRUE )
?>

I then get those arrays and convert them in a JS array
var savedInternal = "<?php echo $userPostsInternal; ?>";
var savedExternal = "<?php echo $userPostsExternal; ?>";

savedInternal = savedInternal.split(',');
savedExternal = savedExternal.split(',');

I then need to check if current id value is in the js array and proceed accordingly:
if($.inArray(this.id, savedInternal) !== -1) {
    console.log("yes");
} else {
    console.log("no");
}

This is happening on a mouse over an element, if I place the following the id is correct, so it isn't about this.id
console.log(this.id);

I get 128545 and it is correct.
Full code:
google.maps.event.addListener(circle, 'mouseover', function(e) {

  <?php
    $user_id = get_current_user_id();
    $userPostsInternal = get_user_meta( $user_id, 'save_post_internal', TRUE );
    $userPostsExternal = get_user_meta( $user_id, 'save_post_external', TRUE )
  ?>

  var savedInternal = "<?php echo $userPostsInternal; ?>";
  var savedExternal = "<?php echo $userPostsExternal; ?>";

  savedInternal = savedInternal.split(',');
  savedExternal = savedExternal.split(',');

  $("#timeSearch").removeClass("fadeIn").addClass("fadeOut");
  $(".infoBox").removeClass("fadeOut").addClass("fadeIn");
  if(this.currSite == "curr" ) {
    var linkGo = this.linkToPost;
    var whatSite = this.currSite;
    if($.inArray(this.id, savedInternal) !== -1) {
      var contentString = '

' + this.site + '

'+this.title+'

<button data-whatSite="'+whatSite+'" data-id="'+this.id+'" type="button" class="btn-site btn btn btn-outline-dark btn-block">Già nella box</button>

Vedi contenuto

';
    } else {
      var contentString = '

' + this.site + '

'+this.title+'

<button data-whatSite="'+whatSite+'" data-id="'+this.id+'" type="button" class="btn-site btn btn btn-dark btn-block">Salva nella box</button>

Vedi contenuto

';
    }
  } else {
    var linkGo = linkExternal+this.linkToPost;
    var whatSite = this.currSite;
    if($.inArray(this.id, savedExternal) !== -1) {
      var contentString = '

' + this.site + '

'+this.title+'

<button data-whatSite="'+whatSite+'" data-id="'+this.id+'" type="button" class="btn-site btn btn btn-outline-dark btn-block">Già nella box</button>

Vedi contenuto

';
    } else {
      var contentString = '

' + this.site + '

'+this.title+'

<button data-whatSite="'+whatSite+'" data-id="'+this.id+'" type="button" class="btn-site btn btn btn-dark btn-block">Salva nella box</button>

Vedi contenuto

';
    }
  }
  infoWindow = new google.maps.InfoWindow({content: contentString});
  infoWindow.setPosition(this.getCenter());
  infoWindow.open(map);
  btnBoxSave(infoWindow, whatSite);
});

A: $.inArray(...) uses strict comparison.
From the code that you've posted it seems that the arrays contain strings (they were created using .split(...) which returns an array of strings) and the value you're checking to see if it is in the arrays (this.id) is a number.
To fix that, use:
$.inArray(this.id.toString(), savedInternal) and $.inArray(this.id.toString(), savedExternal)


text:
Q: How to install PHRETS 2.0? What are all the step by step process to install phrets in ubuntu?
I tried the following, but then unable to run phrets

*

*First I got installed composer.

*Then I ran composer require troydavisson/phrets

*Now I have two files composer.json and composer.lock, and a folder named "vendor"

*Inside vendor folder, I can see autoload.php file and some other folders
Now I tried the sample code from phrets git
But then am getting the following error,

PHP Fatal error:  Class 'Monolog\Logger' not found in /var/www/testing/newphrets.php on line 7

Please advice what am missing here. Am planning to switch my project from old version to phrets 2.0.
Thanks

A: According to Troy's PHRETS 2.0 Logging video on YouTube and looking at PHRETS' composer.json, you can see that you need to do one of two things. Either,
(a) Add monolog to your project's composer.json,
{
    "require": {
        "troydavisson/phrets": "2.*",
        "monolog/monolog": ">=1.10"
    }
}

and run composer update in your project's root directory.
or,
(b) Since monolog is in PHRETS' composer.json file but in the require-dev section, run composer install --dev or composer update --dev to indicate you're currently in development and would like to use the development libraries.


text:
Q: Latter Delivery Ack. from GCM to App server? I am using GCM for Chat App. If User is Offline(not Connected to App but internet is active)  then i Send push notification to devices It receive perfectly.
But when Device is totally offline(neither connected to App and nor active internet) at that time GCM send me response like { id: XXXXXXXX,success: 3,failure: 2{message_id:xxxxx,ect:..}} on my App server.
two device are totally offline they don't have active internet connection..
when device will connect to internet GCM Send them message.
but how can my App server will Know that Message is delivered by GCM.
I Search a lot but can't get any satisfied answer.
I tried that on messageRecive at client device(Android device) i will send httpRequest to my App server but it not suitable for my app it makes App very slow.
So Question is how Can i know that my failure 2 message are delivered.

A: First of all, you do not need to update your app server in case of a downstream message after it is sent to GCM Server. As explained here, GCM server stores the message in case of an offline device and delivers it once the device is online.
(Now assuming that what you want is to handle network tasks on the client)
You can use GcmNetworkManager to batch network discovery and connectivity related tasks across the system through Play Services. Go through the documentation.
You can use GCM Statistics and Diagnostics from Google Play Developer Console, too. This gives you details of messages handled by a particular app (through Registration token) down to status of specific messages (through message IDs). More explanation here.
(However I am not too clear exactly what you want)
EDIT

but how can my App server will Know that Message is delivered by GCM.

Sorry, reading through again I realised this is the real question. Answer is pretty straight forward here.
.


text:
Q: Fixed Nav Menu - How to animate in and out using javascript? I am trying to created a fixed navigation menu that appears when the user scrolls past 500px, and disappears as the user scrolls back up the page.
However, I don't want it to just appear and disappear, but to animate in and out in a sliding motion.
I found part of the answer to this question on Stackoverflow (link). JSFiddle solution: http://jsfiddle.net/k3AHM/1/
var nav = $('.nav');
var scrolled = false;

$(window).scroll(function () {

if (500 < $(window).scrollTop() && !scrolled) {
    nav.addClass('visible').animate({ top: '0px' });
    scrolled = true;
}

if (500 > $(window).scrollTop() && scrolled) {
    nav.removeClass('visible').css('top', '-30px');
    scrolled = false;
}

The above code works to the extent that the fixed nav menu animates into view when user goes past 500px. However, I need the menu to animate out again as the user scrolls back up the screen instead of just disappearing instantly.
I would be very grateful if anyone can suggest changes to the javascript which allow the menu to animate both in and out?
Thank you!

A: Animate have different overload that can help you to animate the way you want with slide from left or from right with delays.
Please refer http://www.w3schools.com/jquery/jquery_animate.asp
In your case just animate while removing the visible class so that it will not disappear instantly.
var nav = $('.nav');
var scrolled = false;

$(window).scroll(function () {

 if (500 < $(window).scrollTop() && !scrolled) {
    nav.addClass('visible').animate({ top: '0px' });
    scrolled = true;
 }

 if (500 > $(window).scrollTop() && scrolled) {
    nav.animate({ top: '-30px'}, 500);
    scrolled = false;
 }
});

Above you can see I have specified 500 for delay to make it invisible slowly. Please use any value based on your delay requirement.

A: You could do something like:
http://jsfiddle.net/k3AHM/4/
 if (500 > $(window).scrollTop() && scrolled) {
   //animates it out of view
   nav.animate({ top: '-30px' });
   //sets it back to the top
    setTimeout(function(){
       nav.removeClass('visible');
    },500);
    scrolled = false;
}

A: There is not need to use any javascript or its libraries you can achieve this using bootstrap build in data attribute and with some css.
LOL. It will look weird while you run in mobile width.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

Basic Topnav

Page 1

Page 2

Page 3

test


text:
Q: gcloud pubsub publish message issue I am trying to publish the message on topic but I am not able to publish the message. I am using laravelframework. My subscription is push type.

I have used $ composer require google/cloud-pubsub from  https://github.com/googleapis/google-cloud-php-pubsub link
I have followed this link: (https://cloud.google.com/pubsub/docs/publisher#php)
**use Google\Cloud\PubSub\PubSubClient;**
function publish_message($projectId, $topicName, $message)
{
    $pubsub = new PubSubClient([\[][1]
        'projectId' => $projectId,
    ]);
    $topic = $pubsub->topic($topicName);
    $topic->publish(['data' => $message]);
    print('Message published' . PHP_EOL);
}

I am getting this error (open this link : https://i.stack.imgur.com/XXHZ5.png.

  [1]: https://i.stack.imgur.com/XXHZ5.png

A: Your question would benefit from a more detailed explanation.
As it is, the code you show is the same code as published by Google.
Assuming (!?) Google's code works (probable but not certain), your code should work.
Since we know your code doesn't work, it's probably something else.
I suspect you've missed one or more of the following possibly the last steps:

*

*created a Google Cloud Platform project ($projectId)?

*enabled the Pub/Sub API?

*created a Pub/Sub topic [and >=1 subscriber] ($topicName)?

*created (service account) credentials permitted to publish to this topic?

*set GOOGLE_APPLICATION_CREDENTIALS to point to the account's key?

How are you running the code?
If possible please also print the ClientException that you show in the image.
Update
I tested Google's code and it works for me:
BILLING_ID=[[YOUR-BILLING]]
PROJECT_ID=[[YOUR-PROJECT]]
TOPIC_NAME=[[YOUR-TOPIC-NAME]]

gcloud projects create ${PROJECT}
gcloud beta billing projects link ${PROJECT} \
--billing-account=${BILLING}

# Enabled Pub/Sub and create topic=subscription=${TOPIC_NAME}

gcloud services enable pubsub.googleapis.com \
--project=${PROJECT}

gcloud pubsub topics create ${TOPIC_NAME} \
--project=${PROJECT}

gcloud pubsub subscriptions create ${TOPIC_NAME} \
--topic=${TOPIC_NAME} \
--project=${PROJECT}

# Create service account ${ROBOT} and key `./${ROBOT}.json`
# Grant the account `publisher` permissions

ROBOT=[[YOUR-ACCOUNT-NAME]]

gcloud iam service-accounts create ${ROBOT} \
--project=${PROJECT}

gcloud iam service-accounts keys create ./${ROBOT}.json \
--iam-account=${ROBOT}@${PROJECT}.iam.gserviceaccount.com \
--project=${PROJECT}

gcloud projects add-iam-policy-binding ${PROJECT} \
--member=serviceAccount:${ROBOT}@${PROJECT}.iam.gserviceaccount.com \
--role=roles/pubsub.publisher

Then -- and apologies, I'm no PHP developer -- here's what I did:
composer.json:
{ "require": { "google/cloud-pubsub": "1.24.1" } }

pubsub.php:
<?php

require_once 'vendor/autoload.php';

use Google\Cloud\PubSub\PubSubClient;

// Expects Env PROJECT_ID, TOPIC_NAME **and** GOOGLE_APPLICATION_CREDENTIALS
$projectId = getenv("PROJECT_ID");
$topicName = getenv("TOPIC_NAME");

$pubsub = new PubSubClient([
        "projectId" => $projectId
]);

$topic = $pubsub->topic($topicName);
$topic->publish(["data"=>"Hello Freddie!"]);
print("Message published" . PHP_EOL);

?>

Then:
export GOOGLE_APPLICATION_CREDENTIALS=./${ROBOT}.json
export PROJECT_ID
export TOPIC_NAME
php pubsub.php

NOTE the code implicitly assumes GOOGLE_APPLICATION_CREDENTIALS to authenticate against the service, see Application Default Credentials

yields:
Message published

And:
gcloud pubsub subscriptions pull ${TOPIC_NAME} \
--project=${PROJECT} \
--format="value(message.data)"
Hello Freddie!

A: I am guessing the issue you are faced is because of you must have missed the authentication step. Have you created a SA and downloaded the json file to authenticate? If so, double check that you have this line in your filesystem:
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-credentials.json


text:
Q: How to remove all classes except one I'm trying to remove the class 'fa-minus' unless its part of the element being triggered. Everything else is working great, however, I'm having trouble targeting all the spans that have the class 'fa-minus' without affecting the dropdown being clicked. Any help is appreciated, thanks.
HTML

Do you lease to individuals and corporations?

Cornerstone leases to all people who are in need of short term furnished housing:  business travelers, human resource/relocation departments, government personnel, and vacation travelers.  We also serve the insurance industry for displaced home owners in need of temporary furnished housing.

Are you the same as an extended stay hotel?

No. We offer a full sized furnished apartment that is much larger than a hotel room and is fully equipped with all the comforts of home.

Is there a minimum stay?

Yes, most locations have a 30 day minimum length of stay.

Can I bring my family pet?

Yes you can, as we offer pet friendly properties in every city and area.  Most properties have a pet weight limit and breed restrictions, and require an additional pet deposit and/or pet fee.

How do I Pay?

We accept Visa, MasterCard and American Express.  For companies paying by check, a major credit card is required on file.

Is there a fee for internet access?

No, our apartments include high speed internet and Wi-Fi service at no additional charge.

Is phone service included?

We have found that most of our guest use their cell phones and do not require land lines.  For additional questions please speak with a Cornerstone representative.

How do I get the keys to my apartment and check in?

Once your reservation is confirmed we will send you your address and easy directions from the airport or major highway.  Typically guest should plan to arrive during office hours.  Late check in can be arranged but may require an additional fee.

What are the check in and check out times?

Typically check in is at 2pm and check out is at 11am.

JS
$(document).ready(function($) {
 $('#accordion').find('.accordion-trigger').click(function(){

 //Expand or collapse this panel

 $(this).next().slideToggle('fast');
 $(this).find('span').toggleClass('fa-minus');

 //Hide the other panels

 $(".accordion-content- container").not($(this).next()).slideUp('fast');

 // remove classes 'fa-minus' unless its part of the accordion being triggered

 });
});

A: Something like this should get you started:
jsFiddle Demo
$(".accordion-content-container").hide();

$('.accordion-trigger').click(function() {
   //Expand or collapse this panel
   $(this).next().slideToggle('fast');
   $(this).find('span').toggleClass('fa-minus');

   //Hide the other panels
   $(".accordion-content-container").not($(this).next()).slideUp('fast');

   // remove classes 'fa-minus' unless its part of the accordion being triggered
    $('span').removeClass('fa-minus');
   $(this).find('span').addClass('fa-minus');
});

Notes:
(1) You can just use $('.accordion-trigger').click instead of $('#accordion').find('.accordion-trigger').click
(2) I added $(".accordion-content-container").hide(); in javascript to initially hide all content divs.

A: Thanks, for all the help. I ended up wrapping each section of the accordion in a container to better utilize the available JQuery methods. I appended, .parent().find('span').removeClass('fa-minus'); to $(".accordion-content-container").not($(this).next()).slideUp('fast'). This is what I was trying to do in the first place, I just didn't read the documentation close enough and was trying to use 'parent()' in the wrong way.

*

*$(".accordion-content-container").not($(this).next()).slideUp('fast')

This line of code was already where I needed to be to remove the 'fa-minus' class, I was just having a hard time traversing back up the DOM to the span with the class of 'fa-minus'.

*Wrapping each section of the accordion in a 'acccordion-container' div gave the ability to use parent(). This way when this line of code was executing:
$(".accordion-content-container").not($(this).next()).slideUp('fast');
I could traverse up the DOM to the closest parent which was .accordion (but is now .accordion-container).

*$(".accordion-content-container").not($(this).next()).slideUp('fast').parent().find('span').removeClass('fa-minus');

Finally, in the instance when 'accordion-content-container' was being closed, 'parent()' looks back to 'accordion-container', then finds the  and removes the class 'fa-minus'.
I hope that makes sense, as usual, every day I'm learning something new.