text:
Q: Bind part of ViewModel I have the following ViewModel
public class NewCustomerViewModel {
    public long CustomerId {get;set;}
    public NewCustomerFormViewModel NewCustomerForm {get;set; }
}

NewCustomerFormViewModel contains only fields which are part of the form. And only them I would like to validate. So I would like to have the following Action signature:
[HttpPost]
public ActionResult NewCustomer(long battleId,
    NewCustomerFormViewModel newCustomerFormViewModel)

Unfortunately it doesn't work with default ModelBinder. So what is the easiest way to bind properties of NewCustomerViewModel to NewCustomerFormViewModel?
Update. Here is the part of my view:

Title @Html.TextBoxFor(m => m.NewCustomerForm.Title,
  Model.NewCustomerForm.Title)

So ModelBinder looks for NewCustomerForm property which he can't find in NewCustomerForViewModel

A: ASP.NET MVC relies heavily upon naming conventions for resolving Views, Actions, Controllers, and even parameters. The parameters are probably being posted under a NewCustomerForm namespace (e.g. NewCustomerForm.Name=John), because that's how they fit into the model that you're producing inputs for. Try renaming your parameter to newCustomerForm so that the binder actually does find an object by that name.
[HttpPost]
public ActionResult NewCustomer(long battleId,
    NewCustomerFormViewModel newCustomerForm)

A: Maybe i am not 100% sure about your requirements as you didn't provided your controller code and view code. But as I have understood that you want a mechanism to include the 'NewCustomerForm' under validation and binding and exclude 'CustomerId' out.
It this is the case then try the following code.
Code for Model
Exclude the properties you don't want to bind.
[Bind(Exclude = "CustomerId")]
public class NewCustomerViewModel
{
    public long CustomerId { get; set; }
    public NewCustomerFormViewModel NewCustomerForm { get; set; }
}

public class NewCustomerFormViewModel
{
    public string Name { get; set; }
    public string Title { get; set; }
}

Code for Controller
public class TestController : Controller
{
    public ActionResult Index(string username )
    {
        NewCustomerViewModel model = new NewCustomerViewModel();
        model.NewCustomerForm = new NewCustomerFormViewModel();
        return View(model);
    }
    [HttpPost]
    public ActionResult IndexPost(NewCustomerViewModel m)
    {
        UpdateModel(m);
        return View("index",m);
    }
}

Code for View

Index

<% using (Html.BeginForm("indexpost","test")) {%>
<%: Html.TextBoxFor(m => m.CustomerId, Model.CustomerId)%>
<%: Html.TextBoxFor(m => m.NewCustomerForm.Title, Model.NewCustomerForm.Title)%>
<%: Html.TextBoxFor(m => m.NewCustomerForm.Name, Model.NewCustomerForm.Name)%>

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


text:
Q: Is there a way to pass temporary tables across the stored procedures I have 4 stored procedures. I need to take the result of the first stored procedure (2 temp tables) and pass it into the second stored procedure. These temp tables need to be used in the from clause in the  second stored procedure.
Similarity the third and fourth stored procedures need results from the previous stored procedures.
is there a way to pass temporary tables across the stored procedures?

A: Regarding this comment, "it was 1 Sp but we broke it into 4 so its easier to alter if needed", I suggest that you break it up even more.  In other words, implement encapsulation.
Have a separate stored procedure for each time you want to select data from the actual tables.  Do not populate temp tables in these procedures, just return the data.
Then write a stored procedure that creates and populates temp tables from the procs mentioned above, and does the necessary processing.
Here is a simple example:
create procedure GetData1
select Field1, Field2
from blah, blah, blah

create procedure AssembleAllData
create table #temp1 (Field1, Field2)
insert into #temp1
exec GetData1
select Field1, Field2, etc
from #temp1 join anActualTable etc

drop table #temp1

A: In your current SP1, you can create temporary table pass the name to the second stored procedure like below
SP1 code
IF OBJECT_ID('tempdb.dbo.#TempTable1')  IS NOT NULL
        DROP TABLE #TempTable1
EXEC SP2  N'#TempTable1'

Inside the SP2 you can insert the values into #TempTable1 which will be available to the calling SP
SP2 code
CREATE procedure [dbo].[SP2]
  @outTempTable NVARCHAR(128)
AS

  IF @outTempTable IS NOT NULL AND LEN(@outTempTable) > 0
  BEGIN
        EXEC (  'INSERT INTO ' + @outTempTable + ' SELECT  * FROM TableA' )
  END

A: Your question sounds more like an answer than a question. Just do as you described.
You don't need to pass the data in the temp tables from one procedure to the next. The data is just there. In one procedure you write to the temp table and in the next procedure you read from the temp table.
I would also not create temp tables dynamically, just create them and let them wait for data. This assumes that the temp table data is local to a session (in oracle this is the case and in a way the reason why temp tables exist).
Also I would opt against passing table names between procedures. There is almost always a better way and it is a no-no anyways. If you are under the impression that you need variable temp table names, then you really want to add another column to the temp tables (you may even call it "temp_table_name", though it almost certainly means something different). Then you can pass the "temp_table_name" around and the selects would need a where temp_table_name = ... and the inserts would have to populate this extra column.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I use vlookup or match/index to look up data to the left for more than look up value?
This is the data I have.
I want to see if I can look up all the Korean stocks. So the input value should be "SOUTH KOREA" and the result table/array should look like this:

Apparately, I can't use VLOOKUP because 1) the lookup value (country name) is on the right column and 2) it will return the first value (STOCK A) only. I need to return all the values (STOCK A, STOCK B, STOCK E, AND STOCK F). I would really appreciate help!

A: I mean it seems far more logical to utilize the inbuilt filter function, but if you absolutely insist on using formulas / code then:
Just use this simple procedure
Private Sub sort_wares(From As String, toColumn As Integer)

    Dim ws As Worksheet: Set ws = Sheets("Sheet1")
    Dim tbl As ListObject: Set tbl = ws.ListObjects("Table1")
    Dim index As Integer
    index = 2

    For Each Rng In tbl.ListColumns(2).DataBodyRange
        If Trim(LCase(Rng)) = Trim(LCase(From)) Then

            ws.Cells(index, toColumn + 1) = Rng
            ws.Cells(index, toColumn) = Rng.Offset(0, -1)

            index = index + 1
        End If

    Next Rng
End Sub

You can easily invoke the procedure, so for example if we from the following data wanted to look up all the wares from Zimbabwe and print them to the 5th Column (E) we would do the following
Call sort_wares("Zimbabwe", 5)

A: You can use below function. Note that it is array formula which needs to be committed by hitting CTRL+SHIFT+ENTER simultaneously. Excel will wrap formula with {} if done correctly!
=IFERROR(INDEX($A$1:$A$1000,SMALL(IF($B$1:$B$1000="SOUTH KOREA",ROW($B$1:$B$1000)),ROWS($A$1:A1))),"")
You can replace "SOUTH KOREA" by a cell reference.
Adjust the ranges to suit and copy down as much as you need.


text:
Q: How to set SendClaimsIn for azure ad b2c REST call I have  created an AAD B2C custom policy which makes a call  to call our REST API when a new user signs up by creating a custom Azure AD B2C custom policy.But i have to set two values to REST API.  Ocp-Apim-Subscription-Key in header and email id in body.but i have to set SendClaimsIn only as either header or body.
so i added SendClaimsIn as header.But i cdont know how to set both values as inputclaim.My code is
<ClaimsProvider>
  <DisplayName>Signup REST APIs</DisplayName>
  <TechnicalProfiles>
    <TechnicalProfile Id="REST-ValidateProfile">
      <DisplayName>Check loyaltyId Azure Function web hook</DisplayName>
      <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
      <Metadata>
        <Item Key="ServiceUrl">https://myapicall.io/api/</Item>
        <Item Key="SendClaimsIn">Header</Item>
        <Item Key="AuthenticationType">Bearer</Item>
        <Item Key="AllowInsecureAuthInProduction">false</Item>
      </Metadata>
      <CryptographicKeys>
        <Key Id="BearerAuthenticationToken" StorageReferenceId="B2C_1A_RestApiBearerToken" />
      </CryptographicKeys>
      <InputClaims>
        <!-- Claims sent to your REST API -->
        <InputClaim ClaimTypeReferenceId="email" />
        <InputClaim ClaimTypeReferenceId="grant_type"  "DefaultValue"="Ocp-Apim-Subscription-Key"/>
      </InputClaims>
      <UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop" />
    </TechnicalProfile>
  </TechnicalProfiles>
</ClaimsProvider>

its shows validation error while uploading

makes a reference to ClaimType with id "Ocp-Apim-Subscription-Key" but
  neither the policy nor any of its base policies contain such an
  element

i want to set header as Ocp-Apim-Subscription-Key as "12345"

A: Add the following inside of the <ClaimsSchema> tag near the top of the file:
<ClaimType Id="Ocp-Apim-Subscription-Key">
  <DisplayName>OCP APIM Subscription Key</DisplayName>
  <DataType>string</DataType>
</ClaimType>

Change the values inside of the <InputClaims> in your REST-ValidateProfile technical profile to the following:
<InputClaims>
  <!-- Claims sent to your REST API -->
  <InputClaim ClaimTypeReferenceId="email" />
  <InputClaim ClaimTypeReferenceId="Ocp-Apim-Subscription-Key" DefaultValue="12345" />
</InputClaims>

You don't need a grant_type input claim for a static OAuth2 bearer (see here).


text:
Q: Is there any function in Networkx that directly generates adjacency list from a table of nodes Suppose that an Undirected graph neighboring nodes are given in a txt file as below
1 2
1 3
1 4
1 5
2 5
2 6
3 4

can I generate an adjacency matrix by a single function in networkx as  below
[0 1 1 1 1 0 ]
[1 0 0 0 1 0 ]
[1 0 0 1 0 0 ]
[1 0 1 0 0 0 ]
[1 1 0 0 0 0 ]
[0 0 0 0 0 1 ]

A: It is not really one function, but you can read edges from file and then create adjacency matrix like this:
import networkx as nx

G = nx.read_edgelist('list.txt')
A = nx.adjacency_matrix(G)

which gives
matrix([[ 0.,  1.,  1.,  1.,  1.,  0.],
        [ 1.,  0.,  0.,  0.,  1.,  0.],
        [ 1.,  0.,  0.,  1.,  0.,  1.],
        [ 1.,  0.,  1.,  0.,  0.,  0.],
        [ 1.,  1.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  1.,  0.,  0.,  0.]])


text:
Q: Delete using superagent in reactjs im just curious on how should I use delete in superagent, its hard to search for any delete superagent documentation I am currently using asp.net as my api and reactjs as front end i have this button
<button className ="btn btn-danger" onClick={this.deleteEmployee.bind(this,  d.Employee_ID)}>Delete</button>

how will i connect it on superagent using fetch?
im using a localhost
http://localhost:5118/api/employeedetails/DeleteEmployeeDetail/

A: Use del() see the documentation

DELETE can be also called as .del() for compatibility with old IE
  where delete is a reserved word.

npm install superagent
var request = require('superagent');

deleteEmployee(id) {
    request
       .del('/api/employeedetails/DeleteEmployeeDetail')
       .send({ id: id })
       .set('Accept', 'application/json')
       .end(function(err, res){});
}


text:
Q: Best way to store data (single object) in Web API project without database My project group and I are to develop a generic workflow system, and have decided to implement a single Node (a task in the workflow) as a C# Visual Studio Web API project (Using the ASP.NET MVC structure).
In the process of implementing a Node's logic, we've come across the trouble of how to store data in our Node. Our Node specifically consists of a few lists of Uri's leading to other Nodes as well as some status/state boolean values. These values are currently stored in a regular class but with all the values as internal static fields.
We're wondering if there's a better way to do this? Particularly, as we'd like to later apply a locking-mechanism, it'd be prefereable to have an object that we can interact with, however we are unsure of how we can access this "common" object in various Controllers - or rather in a single controller, which takes on the HTTP requests that we receive for ou Node.
Is there a way to make the Controller class use a modified constructor which takes this object? And if so, the next step: Where can we provide that the Controller will receive the object in this constructor? There appears to be no code which instantiates Web API controllers.
Accessing static fiels in some class seems to do the trick, data-wise, but it forces us to implement our own locking-mechanism using a boolean value or similar, instead of simply being able to lock the object when it is altered.
If I am not making any sense, do tell. Any answers that might help are welcome! Thanks!

A: Based on your comments, I would say the persistence mechanism you are after is probably one of the server-side caching options (System.Runtime.Caching or System.Web.Caching).
System.Runtime.Caching is the newer of the 2 technologies and provides the an abstract ObjectCache type that could potentially be extended to be file-based. Alternatively, there is a built-in MemoryCache type.
Unlike a static method, caches will persist state for all users based on a timeout (either fixed or rolling), and can potentially have cache dependencies that will cause the cache to be immediately invalidated. The general idea is to reload the data from a store (file or database) after the cache expires. The cache protects the store from being hit by every request - the store is only hit after the timeout is reached or the cache is otherwise invalidated.
In addition, you can specify that items are "Not Removable", which will make them survive when an application pool is restarted.
More info: http://bartwullems.blogspot.com/2011/02/caching-in-net-4.html


text:
Q: .NET NUnit test - Assembly.GetEntryAssembly() is null When class used Assembly.GetEntryAssembly() run in unit test, the Assembly.GetEntryAssembly() is null.
Is there some option how define Assembly.GetEntryAssembly() during unit testing?

A: Implement the SetEntryAssembly(Assembly assembly) method given in
http://frostwave.googlecode.com/svn-history/r75/trunk/F2DUnitTests/Code/AssemblyUtilities.cs
to your unit test project.
         /// <summary>
        /// Use as first line in ad hoc tests (needed by XNA specifically)
        /// </summary>
        public static void SetEntryAssembly()
        {
            SetEntryAssembly(Assembly.GetCallingAssembly());
        }

        /// <summary>
        /// Allows setting the Entry Assembly when needed.
        /// Use AssemblyUtilities.SetEntryAssembly() as first line in XNA ad hoc tests
        /// </summary>
        /// <param name="assembly">Assembly to set as entry assembly</param>
        public static void SetEntryAssembly(Assembly assembly)
        {
            AppDomainManager manager = new AppDomainManager();
            FieldInfo entryAssemblyfield = manager.GetType().GetField("m_entryAssembly", BindingFlags.Instance | BindingFlags.NonPublic);
            entryAssemblyfield.SetValue(manager, assembly);

            AppDomain domain = AppDomain.CurrentDomain;
            FieldInfo domainManagerField = domain.GetType().GetField("_domainManager", BindingFlags.Instance | BindingFlags.NonPublic);
            domainManagerField.SetValue(domain, manager);
        }

A: You could do something like this with Rhino Mocks:  Encapsulate the Assembly.GetEntryAssembly() call into a class with interface IAssemblyLoader and inject it into the class your are testing. This is not tested but something along the lines of this:
[Test] public void TestSomething() {
  // arrange
  var stubbedAssemblyLoader = MockRepository.GenerateStub<IAssemblyLoader>();
  stubbedAssemblyLoader.Stub(x => x.GetEntryAssembly()).Return(Assembly.LoadFrom("assemblyFile"));

  // act
  var myClassUnderTest = new MyClassUnderTest(stubbedAssemblyLoader);
  var result = myClassUnderTest.MethodToTest();

  // assert
  Assert.AreEqual("expected result", result);
}

public interface IAssemblyLoader {
  Assembly GetEntryAssembly();
}
public class AssemblyLoader : IAssemblyLoader {
  public Assembly GetEntryAssembly() {
    return Assembly.GetEntryAssembly();
  }
}


text:
Q: Windows Waveform Functions - WAVEOUTCAPS for bitdepths other than 8 and 16 The Microsoft documentation for the WAVEOUTCAPS struct lists a number of formats that an audio device can support:

I do not see any 24-bit variables listed here, although through I have confirmed my sound card is capable of opening a 24-bit output with a call to WaveOutOpen (and playing 24bit audio files through that output).
I'm guessing that Microsoft defined additional variables somewhere for 18/20/24/32/48/64 bit output, but I can't find them. I tried searching on the net and nothing came up, and I tried using Visual Studio to search for variables in my current name space that start with "WAVE_FORMAT_" but did not find any additionally defined formats that way.
Is it possible to check for 4/18/20/24/32/48/64 bit output availability on Windows using the function WaveOutGetDevCap(), or any similar function? If so, how?

A: waveOutXxx is legacy API you, generally speaking, should not be used nowadays. This API is an emulation layer on top of real audio API and does not have to support 24-bit scenarios which did not exist at the time of waveOutXxx. There are no specific new constants defined for newer formats and there are so many of them that there cannot be a separate bit for every one.
You can compose a WAVEFORMATEX structure that describes your high bitness format (you would typically use WAVEFORMATEXTENSIBLE variant of it) and check it against waveOutOpen function.
Or, rather, use WASAPI and IAudioClient::Initialize, see Rendering a Stream for details and the way WAVEFORMATEX structure is used there.


text:
Q: PySimpleGUI Attribute Error on Windows XP SP3 with Python 3.4.4 Running a Python program which uses a PySimpleGUI interface on top of TkInter. Program runs well on Windows 10 and CentOS Linux workstations. Unfortunately have a job requirement to also run the program on a Windows XP Service Pack 3 PC in an isolated secret lab area, no internet, so any installations are brought in on a DVD.
Python 3.4.4 was the latest version I could find which supports Windows XP and it installs and runs fine with Tkinter up and running as well.
PC Setup:
Windows XP Service Pack 3
Python 3.4.4
PySimpleGUI 3.39.0
Execution Error:
Traceback (most recent call last):
File "PysharkLiveCapGUI.py", line 9, in <module>
sg.theme('Topanga')
AttributeError: 'module' object has no attribute 'theme'
Path to PySimpleGUI EGG:
Type "help", "copyright", "credits" or "license" for more information.
\>>> import PySimpleGUI as sg
\>>> print(sg)
<module 'PySimpleGUI' from 'C:\\Python34\\lib\\site-packages\\pysimplegui-3.39.0-py3.4.egg\\PySimpleGUI\\_init_.py'>
PySimpleGUI Installation Results:
C:\Python34\Downloads\dist\PySimpleGUI-3.39.0>python setup.py install
C:\Python34\lib\distutils\dist.py:260: UserWarning: Unknown distribution option:
 'long_description_content_type'
  warnings.warn(msg)
running install
running bdist_egg
running egg_info
writing top-level names to PySimpleGUI.egg-info\top_level.txt
writing PySimpleGUI.egg-info\PKG-INFO
writing dependency_links to PySimpleGUI.egg-info\dependency_links.txt
reading manifest file 'PySimpleGUI.egg-info\SOURCES.txt'
writing manifest file 'PySimpleGUI.egg-info\SOURCES.txt'
installing library code to build\bdist.win32\egg
running install_lib
running build_py
creating build\bdist.win32\egg
creating build\bdist.win32\egg\PySimpleGUI
copying build\lib\PySimpleGUI\PySimpleGUI.py -> build\bdist.win32\egg\PySimpleGU
I
copying build\lib\PySimpleGUI\__init__.py -> build\bdist.win32\egg\PySimpleGUI
byte-compiling build\bdist.win32\egg\PySimpleGUI\PySimpleGUI.py to PySimpleGUI.c
python-34.pyc
byte-compiling build\bdist.win32\egg\PySimpleGUI\__init__.py to __init__.cpython
-34.pyc
creating build\bdist.win32\egg\EGG-INFO
copying PySimpleGUI.egg-info\PKG-INFO -> build\bdist.win32\egg\EGG-INFO
copying PySimpleGUI.egg-info\SOURCES.txt -> build\bdist.win32\egg\EGG-INFO
copying PySimpleGUI.egg-info\dependency_links.txt -> build\bdist.win32\egg\EGG-I
NFO
copying PySimpleGUI.egg-info\top_level.txt -> build\bdist.win32\egg\EGG-INFO
zip_safe flag not set; analyzing archive contents...
creating 'dist\PySimpleGUI-3.39.0-py3.4.egg' and adding 'build\bdist.win32\egg'
to it
removing 'build\bdist.win32\egg' (and everything under it)
Processing PySimpleGUI-3.39.0-py3.4.egg
Removing c:\python34\lib\site-packages\PySimpleGUI-3.39.0-py3.4.egg
Copying PySimpleGUI-3.39.0-py3.4.egg to c:\python34\lib\site-packages
PySimpleGUI 3.39.0 is already the active version in easy-install.pth

Installed c:\python34\lib\site-packages\pysimplegui-3.39.0-py3.4.egg
Processing dependencies for PySimpleGUI==3.39.0
Finished processing dependencies for PySimpleGUI==3.39.0

Problem?:
PySimpleGUI installation appeared to run error free. The EGG file looks fine when I inspect it using 7 Zip. Best guess is that Windows XP doesn't know how to read the EGG file although it's within a Python execution where theoretically Python has no problem importing EGG files. Any help with this issue greatly appreciated.
Thanks,
Jeff Stearns

A:
Program runs well on Windows 10 and CentOS Linux workstations.

It should be wrong if you have code like sg.theme and you will get exception, no matter on Windows 10, CentOS Linux workstations.

PySimpleGUI 3.39.0

If nothing wrong, function sg.theme released from 4.14.0 PySimpleGUI 23-Dec-2019.

Python 3.4.4

"Upgrade your PySimpleGUI to the most update version" may not work for this version of python. try to use old method sg.change_look_and_feel.


text:
Q: ping timeout command -W not working for Android In my Android application, I have used the ping command with appropriate option mentioned in below link:
http://linux.about.com/od/commands/l/blcmdl8_ping.htm
All other options are working except -W which is timeout.
I am using this command to ping with 5sec time out: ping 131.107.8.1 -W 5
I believe this should give "Request timed out" after 5sec. I also tested it with "Test Ping" application but it failed there as well.
Where as in my windows machine, I am using this command for same IP: ping 131.107.8.1 -w 7000
And it is properly giving "Request timed out" after 7000msec.
Any pointer where am I missing the concept?

A: I'm not entirely sure on Android's implementation of Ping, but on Linux the flags ping -w and ping -W have very different operations.
In this case, you're using ping -W, which waits for a timeout to happen across the network. According to the man page:

-W timeout
               Time to wait for a response, in seconds. The option affects only
               timeout in absense of any responses, otherwise  ping  waits  for
               two RTTs.

I believe what you're attempting to do is set a deadline for the Ping command, e.g. ping -w as described by the man page again:

-w deadline
               Specify  a  timeout, in seconds, before ping exits regardless of
               how many packets have been sent or received. In this  case  ping
               does  not  stop after count packet are sent, it waits either for
               deadline expire or until count probes are answered or  for  some
               error notification from network.

A:
Ping timeouts only start after the IP address has been determined. If
  your workstation is offline, then ping cannot determine the IP address
  and so appears to wait approximately a default 20 secs before
  returning false.

Source: https://serverfault.com/a/739873/156789


text:
Q: Promise not awaited on geocode So I have the following code that I thought was awaiting correctly, but when I looked into it a little deeper, I found its just reacting very quickly (fast enough to be used in the angular template).
    this.dataService.getSomeData().subscribe(async (res) => {
      this.historyList = res;
      this.historyList.forEach(async (element) => {
        console.log('before')
        let address = await this.geocode(element);
        console.log(address)
        element.address = address
     });
     console.log('after');

and my geocode promise looks like:
 async geocode(item:Location):Promise<string> {
   return await new Promise(async (resolve) => {
    const geocoder = new google.maps.Geocoder();
    const location = new google.maps.LatLng(item.latitude, item.longitude);
    geocoder.geocode({ location: location }, async (results, status) => {
      if (status === 'OK') {
        resolve(results[0].formatted_address);
      }
    });
  });
 }

Right now, the multiple "Before" logs and the one "After" Log will show in the console before any of the addresses come back.  Can anyone see where I might be going wrong?  VS Code doesn't have any issue with my await on the geocode method, so I am a little stumped.
Thanks

A: when you do .forEach(async element=> it is never going to await on the callbacks, if you wanted to do them in sequence you would switch it to a for-of loop:
this.dataService.getSomeData().subscribe(async (res) => {
  this.historyList = res;
  for(const element of this.historyList) {
    console.log('before')
    let address = await this.geocode(element);
    console.log(address)
    element.address = address
  }
  console.log('after');
}

Or to do them in parallel use Promise.all:
this.dataService.getSomeData().subscribe(async (res) => {
  this.historyList = res;
  // use map to get a promise for each.
  await Promise.all(this.historyList.map(async (element) => {
    console.log('before')
    let address = await this.geocode(element);
    console.log(address)
    element.address = address
 }));
 console.log('after');
}


text:
Q: Virtual field does not appear in REST JSON result I have a Model named Users with a virtual field named full_name, and it works fine in the template by calling:
<?= $user->full_name; ?>

But it doesn't automatically come to the REST.

A: Quote from the docs:

By default virtual properties are not exported when converting
  entities to arrays or JSON. In order to expose virtual properties you
  need to make them visible. When defining your entity class you can
  provide a list of virtual properties that should be exposed:
namespace App\Model\Entity;

use Cake\ORM\Entity;

class User extends Entity
{

    protected $_virtual = ['full_name'];

}

This list can be modified at runtime using virtualProperties:
$user->virtualProperties(['full_name', 'is_admin']);

Cookbook > Database Access & ORM > Entities > Exposing Virtual Fields


text:
Q: How to use Apple Pay in NativeScript I'm trying to make Apple Pay in NativeScript app by using native code.
But have some errors with data type (?)
let item = new PKPaymentSummaryItem();
item.label = "iPhone Xs 64 Gb";
item.amount = 39999;

JavaScript error:

file:///app/components/Home.vue:24:0 JS ERROR Error: -[__NSCFNumber decimalNumberByRoundingAccordingToBehavior:]: unrecognized selector sent to instance 0xf549d0dbe6e8cc69

A: As the error message suggests, you need to get the typing conversion right. Installing the tns-platform-declarations packages as a dev dependency to your project will give you handy intellisense which will guide you through such issues. For this particular case, try like that:
item.amount = new NSDecimalNumber({ string: "29999" });


text:
Q: Abuse of notation for infimum and supremum I would like to take the infimum and supremum of two sets  $(\frac{1}{2} e^{8m+4} - 1, e^{8m+4} - 1)$ and $(\frac{1}{2} e^{8m+4}, \frac{3}{2}e^{8m+4})$, but writing

$\sup((\frac{1}{2} e^{8m+4}, \frac{3}{2}e^{8m+4})) < \inf((\frac{1}{2}
e^{8m+4} - 1, e^{8m+4} - 1)) \log(\inf((\frac{1}{2}
e^{8m+4} - 1, e^{8m+4} - 1))) < p_r$ and
  $\inf((\frac{1}{2} e^{8m+4},
\frac{3}{2}e^{8m+4}))\log(\inf((\frac{1}{2} e^{8m+4},
\frac{3}{2}e^{8m+4}))) > e^{8m+4}$ for all $m > \frac{1}{4}$.

looks absolutely terrible. What I would like to write is this:

If we let $k \in (\frac{3}{2} e^{8m+4} - 1, 2e^{8m+4} - 1)$ and $r \in (\frac{1}{2} e^{8m+4} - 1, e^{8m+4} - 1)$ then we have $c = k - r + 1 \in (\frac{1}{2} e^{8m+4}, \frac{3}{2}e^{8m+4})$. We observe that
  $\sup(c) < \inf(r) \log(\inf(r)) < p_r$ and $\inf(c)\log(\inf(c)) > e^{8m+4}$ for all $m > \frac{1}{4}$.

These statements aren't equivalent given that $r$ and $c$ are elements of the respective sets and not the sets themselves. However, I fear that both the first approach and assigning variables to the given sets would make this statement significantly longer than it needs to be.
Would this be considered a meaningful abuse of notation, or should I perhaps rewrite this another way?
Thank you.

A: This isn't a terrible abuse of notation, but it might take some thought for your reader to figure out what you mean.  So I think a better way to do this would be to just give names to the sets themselves, rather than elements of them.  If you define $K=(\frac{3}{2} e^{8m+4} - 1, 2e^{8m+4} - 1)$, $R=(\frac{1}{2} e^{8m+4} - 1, e^{8m+4} - 1)$, and $C=(\frac{1}{2} e^{8m+4}, \frac{3}{2}e^{8m+4})$, then you can write with no abuse of notation:

If we let $k \in K$ and $r \in R$ then we have $k - r + 1 \in C$. We observe that
  $\sup C < (\inf R) \log(\inf R) < p_r$ and $(\inf C) \log(\inf C) > e^{8m+4}$ for all $m > \frac{1}{4}$.

Combined with the definitions of the sets, this is only slightly longer than your proposed version, and it is significantly clearer what it means.
Alternatively, it sounds from context like you might not really care about the sups and infs themselves but, and care only about the relationships between the specific numbers $k$, $r$, and $c$ chosen.  So you could avoid talking about sups and infs at all, and instead write something like:

If we let $k \in (\frac{3}{2} e^{8m+4} - 1, 2e^{8m+4} - 1)$ and $r \in (\frac{1}{2} e^{8m+4} - 1, e^{8m+4} - 1)$ then we have $c = k - r + 1 \in (\frac{1}{2} e^{8m+4}, \frac{3}{2}e^{8m+4})$. We observe that
  $c < r \log(r) < p_r$ and $c\log(c) > e^{8m+4}$ for all $m > \frac{1}{4}$.  The first inequality folows from $c<\frac{3}{2}e^{8m+4}$ and $r>\frac{1}{2} e^{8m+4} - 1$, and the second inequality follows from $c>\frac{1}{2} e^{8m+4}$.


text:
Q: Spring Cloud Stream AggregateApplication with local Data Flow Server I am trying to create Spring Cloud Stream Aggregate Application which runs with Data Flow Web Server to be able to manage application via Web UI.
Application runner class:
@SpringBootApplication
public class Runner {

public static void main(String[] args) {
    new AggregateApplicationBuilder(args).web(true)
            .from(JSONFileSourceApplication.class).args("--fixedDelay=5000")
            .via(ProcessorOne.class)
            .to(LoggingSinkApplication.class).run(args);
}

This works OK. Now trying to add Dataflow Server. Create a class:
@SpringBootApplication
@EnableDataFlowServer
public class WebServer {}

And set it as parent configuration of AggregateApplicationBuilder:
...
    new AggregateApplicationBuilder(WebServer.class, args).web(true)
...

If I run it, the following exception occurs:
BeanCreationException: Error creating bean with name 'initH2TCPServer' ...
Factory method 'initH2TCPServer' threw exception ... Exception opening port "19092" (port may be in use)

Looks like AggregateApplicationBuilder process tries to create another H2 server instead of using one from parent configuration.
If I replace @SpringBootApplication annotation with @Configuration in my JSONFileSourceApplication, ProcessorOne and LoggingSinkApplication classes - stream application starts, web server starts (http://localhost:9393/dashboard), but I don't see my stream components, all tabs in web UI are empty.
How to run Spring Cloud Stream AggregateApplication with Web UI enabled?

A: SCDF as it stands today, it does not support the concept of aggregate applications.
The primary reason to this is the fact that SCDF assumes apps to be of know channel types; it is either input/output or both (for processors). However, when using AggregateApplicationBuilder, there are a variety of ways you can compose the channels and it gets blurry in the DSL/UI to be able to discover and bind to the channels in an automated manner.
That said, in the upcoming release,
1) We are planning to introduce the concept of "function-chaining". This allows composition of "multiple" small functions (e.g., filterNulls, transformToUppercase, splitByHypen, ..) into a single stream application at runtime. As a developer, you'd focus on developing/testing the functions standalone and register them with SCDF. Once available in the registry, you will have new DSL primitives to compose them into a single unit, which internally is chained (at runtime) by SCDF.
2) We have plans to elevate the visibility of queues/topics. There will be DSL primitives to interact and create data pipelines with them directly. Given this flexibility, it will be easier for composition like use-cases.


text:
Q: Execute bash command and capture output I have a bash command I'm executing in perl as follows
 @args = ( "bash" , "-c",  "diff <(ssh  -o \"StrictHostKeyChecking no\" user-db01 'mysql -uuser -ppass --execute=\"show databases\"') <(ssh  -o \"StrictHostKeyChecking no\" user-db02 'mysql -uuser -ppass --execute=\"show databases\"')");
system(@args);

but this doesn't allow me to get the output to a string variable.
If I execute the exact samething with backticks
 $cmd = "bash -c diff <(ssh  -o \"StrictHostKeyChecking no\" user-db01 'mysql -uuser -ppass --execute=\"show databases\"') <(ssh  -o \"StrictHostKeyChecking no\" user-db02 'mysql -uuser -ppass --execute=\"show databases\"')";
 my $res = `$cmd`;

its throwing an error sh: -c: line 0: syntax error near unexpected token('` What can I do to execute the command and get the result in a variable?

A: You can use one of the usual CPAN modules, e.g. IPC::System::Simple that has a capture() method; or a more-likely-to-be-present IPC::Open2.
Your backticsk problem is that you didn't quote the diff command, thus making it an argument to bash:
BREAKS: bash -c diff <( cmd2 ) <( cmd1 )
GOOD  : bash -c "diff <( cmd2 ) <( cmd1 )"

Your code treats every "word" as a separate argument to your system shell (NOT to bash), e.g. it's the same as calling system("bash", "-c", "diff", " <(ssh" ...)


text:
Q: Is my code correct for launching two android apps using android intent? this is my code
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void Smart1(View view){
        Intent Smart1app =getPackageManager().getLaunchIntentForPackage("project.developers.com.demoproject");
        startActivity(Smart1app);

        }

    public void Smart2(View view) {
        Intent Smart2app =getPackageManager().getLaunchIntentForPackage("com.smart.hayat");
        startActivity(Smart2app);

    }}

when i run application using this code, i cant access both apps.What is the the logical error or my logic itself might be wrong

A: ContrainLayout is bit difficult to understand.
In this xml I have used LinearLayout. Inside that I have added two ImagesView On each ImagesView there is onClick property is added.
Please go through the code, If you didn't understand let me know.
Here is your xml file

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context=".MainActivity">

    <ImageView
        android:layout_weight="1"
        android:onClick="Smart1"
        app:srcCompat="@mipmap/ic_launcher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ImageView
        android:layout_weight="1"
        android:onClick="Smart1"
        app:srcCompat="@mipmap/ic_launcher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

And Here your java file

MainActivity.java

public class MainActivity extends AppCompatActivity {

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

    }

    public void Smart1(View view) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setComponent(ComponentName.unflattenFromString("project.developers.com.demoproject"));
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    public void Smart2(View view) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setComponent(ComponentName.unflattenFromString("com.smart.hayat"));
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}


text:
Q: Melt the Upper Triangular Matrix of a Pandas Dataframe Given a square pandas DataFrame of the following form:
   a  b  c
a  1 .5 .3
b .5  1 .4
c .3 .4  1

How can the upper triangle be melted to get a matrix of the following form
 Row     Column    Value
  a        a       1
  a        b       .5
  a        c       .3
  b        b       1
  b        c       .4
  c        c       1

#Note the combination a,b is only listed once.  There is no b,a listing

I'm more interested in an idiomatic pandas solution, a custom indexer would be easy enough to write by hand...
Thank you in advance for your consideration and response.

A: First I convert lower values of df to NaN by where and numpy.triu and then stack, reset_index and set column names:
import numpy as np

print df
     a    b    c
a  1.0  0.5  0.3
b  0.5  1.0  0.4
c  0.3  0.4  1.0

print np.triu(np.ones(df.shape)).astype(np.bool)
[[ True  True  True]
 [False  True  True]
 [False False  True]]

df = df.where(np.triu(np.ones(df.shape)).astype(np.bool))
print df
    a    b    c
a   1  0.5  0.3
b NaN  1.0  0.4
c NaN  NaN  1.0

df = df.stack().reset_index()
df.columns = ['Row','Column','Value']
print df

  Row Column  Value
0   a      a    1.0
1   a      b    0.5
2   a      c    0.3
3   b      b    1.0
4   b      c    0.4
5   c      c    1.0

A: Also buildin on solution by @jezrael, here's a version adding a function to do the inverse operation (from xy to matrix), usefull in my case to work with covariance / correlation matrices.
def matrix_to_xy(df, columns=None, reset_index=False):
    bool_index = np.triu(np.ones(df.shape)).astype(bool)
    xy = (
        df.where(bool_index).stack().reset_index()
        if reset_index
        else df.where(bool_index).stack()
    )
    if reset_index:
        xy.columns = columns or ["row", "col", "val"]
    return xy

def xy_to_matrix(xy):
    df = xy.pivot(*xy.columns).fillna(0)
    df_vals = df.to_numpy()
    df = pd.DataFrame(
        np.triu(df_vals, 1) + df_vals.T, index=df.index, columns=df.index
    )
    return df
df = pd.DataFrame(
    {"a": [1, 0.5, 0.3], "b": [0.5, 1, 0.4], "c": [0.3, 0.4, 1]},
    index=list("abc"),
)
print(df)
xy = matrix_to_xy(df, reset_index=True)
print(xy)
mx = xy_to_matrix(xy)
print(mx)

output:
     a    b    c
a  1.0  0.5  0.3
b  0.5  1.0  0.4
c  0.3  0.4  1.0

  row col  val
0   a   a  1.0
1   a   b  0.5
2   a   c  0.3
3   b   b  1.0
4   b   c  0.4
5   c   c  1.0

row    a    b    c
row
a    1.0  0.5  0.3
b    0.5  1.0  0.4
c    0.3  0.4  1.0

A: Building from solution by @jezrael, boolean indexing would be a more explicit approach:
import numpy
from pandas import DataFrame

df = DataFrame({'a':[1,.5,.3],'b':[.5,1,.4],'c':[.3,.4,1]},index=list('abc'))
print df,'\n'
keep = np.triu(np.ones(df.shape)).astype('bool').reshape(df.size)
print df.stack()[keep]

output:
     a    b    c
a  1.0  0.5  0.3
b  0.5  1.0  0.4
c  0.3  0.4  1.0

a  a    1.0
   b    0.5
   c    0.3
b  b    1.0
   c    0.4
c  c    1.0
dtype: float64


text:
Q: Regular Expression I would like to capture data from the following text by regex:
Test string:
(003) Recoverable salaries and allowances (General)
(700) General non-recurrent, (001) lamslkdf; (999) ajkndsfk

And this is my current regex pattern
[\(|\[](?<code>[0-9]{0,3})[\)|\]]\s?(?<title>[\s\S]+)

This is my expectation and the above regex cannot match.

*

*003 >> Recoverable salaries and allowances (General)

*700 >> General non-recurrent

*001 >> lamslkdf

*999 >> ajkndsfk

How can I achieve this purpose? Please advice. Thanks

A: You can use
(?:\((?<code>\d{1,3})\)|\[(?<code>\d{1,3})])\s*(?<title>.*?)(?=\s*(?:\(\d{1,3}\)|\[\d{1,3}]|\z))

See .NET regex demo. Output:

Details

*

*(?:\((?<code>\d{1,3})\)|\[(?<code>\d{1,3})]) - either (, then one to three digits captures into Group "code", and ), or [, then 1-3 digits captured into Group "code" and ]

*\s* - 0+ whitespaces

*(?<title>.*?) - Group "title"

*(?=\s*(?:\(\d{1,3}\)|\[\d{1,3}]|\z)) - immediately followed with

*

*\s* - 0+ whitespaces

*(?:\(\d{1,3}\)|\[\d{1,3}]|\z) - either ( + one to three digits and ), or [, one to three digits, ] or end of string.


text:
Q: Amazon Fire-Os can't handle stream intent Is it possible to open a stream on Fire-TV using an Intent like you normally do in android?
This code will show no players that can handle the intent:
playerIntent.setAction(android.content.Intent.ACTION_VIEW);
playerIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
playerIntent.setDataAndType("http://localhost/videostream", "video/*");
startActivity(playerIntent);

This wont work either:
//      playerIntent.setComponent(new ComponentName("com.amazon.avod", "com.amazon.avod.playbackclient.EdPlaybackActivity"));

A: FireTV doesn't have a stand-alone video player. Your options would be to either add a MediaElement to your app to display the content or use a WebView with a  element in (though it looks like they recommend the VisualOn SDK for higher quality video where hardware acceleration will make it look better). Not sure if there are any 3rd party video players in the store that would listen to the event if you just want to hand-off playback.
Depending on the app, have you looked at the HTML5 based Web App Starter Kit that's just been added?


text:
Q: NuGet failed installing ImageSharp I have been trying to install the imagesharp package via NuGet, but I am getting an error from the output window below:
Restoring packages for C:\Users\mycomp\Source\Repos\WebApplication\WebApplication1\WebApplication1.csproj...
Package SixLabors.ImageSharp 1.0.0-beta0001 is not compatible with netcoreapp2.0 (.NETCoreApp,Version=v2.0). Package SixLabors.ImageSharp 1.0.0-beta0001 supports:
 - netstandard1.1 (.NETStandard,Version=v1.1)
 - netstandard1.3 (.NETStandard,Version=v1.3)
 Package restore failed. Rolling back package changes for 'WebApplication1'.
Time Elapsed: 00:00:00.9032282
 ========== Finished ==========

And here from the Error List window:
    Error       Package restore failed. Rolling back package changes for 'WebApplication1'.

I tried repairing VS 15.4.0 and also updating to VS 15.4.2, but none of it is fixing my issue....any thoughts?

A: The answer was quite simple in the end. It had nothing to do with the compatibility of the netcoreapp2.0, or either the netstandards1.1/netstandard1.3. That was just a symptom of the real issue. This is how I fixed it:
Tools>Options>NuGet Package Manager>Clear All NuGet Cache/s.
I did get another error while uninstalling from NuGet manager stating access denied to remove the BuildBundlerMinifier package, so I manually deleted it from my .nuget folder, installed SixLabors.ImageSharp package, then reinstalled the BuildBundlerMinifier again, then VOILA! It worked.
Every option that I did try to search for, were either confusing or totally unnecessary.
There is high probability that if you do run into any weird issues like this while installing/uninstalling your NuGet packages, its due to your NuGet cache folder/s.

A: Seems that you are trying to install ImageSharp in a .Net Core 2.0 project which is not supported. See this line of error message:
"Package SixLabors.ImageSharp 1.0.0-beta0001 is not compatible with netcoreapp2.0"

A: This looks like a bug in the compatibility check during package installation (not sure if because of an asset that is in an unexpected location or issues with package trimming on .NET Core 2.0 since it depends on prerelease versions of .NET Core packages). When you add the package manually to the csproj file, it should restore and build fine:
<ItemGroup>
  <PackageReference Include="SixLabors.ImageSharp" Version="1.0.0-beta0001" />
</ItemGroup>


text:
Q: Global SQLite database in Android Studio So I have an SQLiteDatabase defined in my MainActivity that I populate using some textboxes and a button that confirms the entry. This is the definition:
public class MainActivity extends AppCompatActivity {
    SQLiteDatabase clientsDatabase;
    ...

And later on, in the OnCreate of my MainActivity I have this code in a try and catch that sets up the database:
clientsDatabase = this.openOrCreateDatabase("Clients", MODE_PRIVATE, null);
clientsDatabase.execSQL("CREATE TABLE IF NOT EXISTS clients (id INT(3), fName VARCHAR, lName VARCHAR, age INT(3))");

I have a function that puts data into the database:
clientsDatabase.execSQL("INSERT INTO clients (id, fName, lName, age) VALUES (" + id + ", '" + f + "', '" + l + "', " + a + ")");

And I have a ListView that I fill out using the data in this Database. I want to move this ListView to another activity. How do I make this database sort of a global thing that can be accessed and edited in any activity in my app? Almost every activity in my app needs interaction with the database, so what options do I have?

A: Just add new java class named "DatabaseHandler" and paste below code snippet in your new java file.
  public class DatabaseHandler extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "your database name";

// Contacts table name
private static final String TABLE_CONTACTS = "your table name";

// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_PH_NO + " TEXT" + ")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

    // Create tables again
    onCreate(db);
}

/**
 * All CRUD(Create, Read, Update, Delete) Operations
 */

// Adding new contact
void addContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName()); // Contact Name
    values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone

    // Inserting Row
    db.insert(TABLE_CONTACTS, null, values);
    db.close(); // Closing database connection
}

// Getting single contact
Contact getContact(int id) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
            KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2));
    // return contact
    return contact;
}

// Getting All Contacts
public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Contact contact = new Contact();
            contact.setID(Integer.parseInt(cursor.getString(0)));
            contact.setName(cursor.getString(1));
            contact.setPhoneNumber(cursor.getString(2));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }

    // return contact list
    return contactList;
}

// Updating single contact
public int updateContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName());
    values.put(KEY_PH_NO, contact.getPhoneNumber());

    // updating row
    return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });
}

// Deleting single contact
public void deleteContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });
    db.close();
}

// Getting contacts Count
public int getContactsCount() {
    String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();

    // return count
    return cursor.getCount();
}

}

Now if you want this all methods just intialize "DatabaseHandler" in your activity like below.
DatabaseHandler DBHelper = new DatabaseHandler(getApplicationContext());

and for access any method just write like below.
DBHepler.addContact(your object);


text:
Q: Getiing error message 'Failed Installing JBAS50SVC' whle running service.bat file in Windows 7 I need to run Jboss 7 as service.
Followed these steps :-

*

*Copied my Jboss to C:\Program Files <86>

*Downloaded Jboss-native-2.0.10-windows-x64-ssl and copied the contenst of bin catalog to %JBOSS_HOME%/bin

*Changes done on service.bat as per link instructions
 https://community.jboss.org/message/724488
Changed my dir location to my Jboss bin
and given command service.bat install
C:\Program Files \jboss7>bin>service.bat install
Failed installing JBAS50SVC
Access is Denied.
Service JBoss Application Server 7.1.1 installed.
I'm not able to rectify this problem .

A: It appears to be windows access issue.
Try the following:

*

*Does the windows ID you are using have Administrator privileges? If no, get a Admin ID else if Yes, proceed to step 2.

*Try to do the same but in some other drive (not c: )

UPDATE #1  : OP says he can not see the output of service.bat file
Follow the following steps

*

*Open start menu

*Search for "cmd"

*Right click "cmd" and run as Administrator

*type in following command
cd C:\Program Files \jboss7\bin

*Type service.bat and observe the output

A: On a 2008 Windows Server this occurs because you're not running the command line as an administrator. Those of us who have spent considerable amounts of time on 2003 server, and others before that, keep forgetting that your logged in ADMIN level account does NOT get passed to the command line automatically like with previous versions of Windows.
With any additional errors, past this one, I would keep going back to the service.bat file and looking at the path statements, throughout that file, to ensure that they are all correct to reach what is correct for your installation.
Also, don't forget to create a log folder under standalone (unless you're doing a domain install). Failure to do that will also cause issues as well.
yoda


text:
Q: Parse JSON response store value in variable I'm getting the following JSON response:
"Nitro": {
    "Login": {
        "sessionKey": "NHwxNDQ4MzR8MzY1ODE5ODMwMnwxMzQ0NzE5MTYyfDgxY2M1NjYxZDBiY2NiODI4NmM2Mjc1ODI2MzA1NDY3YmVhNzJjZDR8MA=="
    },
    "res": "ok",
    "method": "user.login",
    "server": "sbnitro01.prod.bunchball.net/nitro4.4.0"
}
}

I don't understand how to parse this with JavaScript and store the value of the sessionKey in a variable. I cannot use jQuery on this project and just cannot seem to get the key with JS.
Thanks!

A: Try:
var sessionKey = obj.Nitro.Login['sessionKey'];

This takes the object that is stored in the obj variable, then takes the Nitro property object and then takes the Login property object and extracts the property sessionKey accordingly.


text:
Q: R: Find the last dot in a string In R, is there a better/simpler way than the following of finding the location of the last dot in a string?
x <- "hello.world.123.456"
g <- gregexpr(".", x, fixed=TRUE)
loc <- g[[1]]
loc[length(loc)]  # returns 16

This finds all the dots in the string and then returns the last one, but it seems rather clumsy. I tried using regular expressions, but didn't get very far.

A: Does this work for you?
x <- "hello.world.123.456"
g <- regexpr("\\.[^\\.]*$", x)
g

*

*\. matches a dot

*[^\.] matches everything but a dot

** specifies that the previous expression (everything but a dot) may occur between 0 and unlimited times

*$ marks the end of the string.

Taking everything together: find a dot that is followed by anything but a dot until the string ends. R requires \ to be escaped, hence \\ in the expression above. See regex101.com to experiment with regex.

A: Someone posted the following answer which I really liked, but I notice that they've deleted it:
regexpr("\\.[^\\.]*$", x)

I like it because it directly produces the desired location, without having to search through the results. The regexp is also fairly clean, which is a bit of an exception where regexps are concerned :)

A: How about a minor syntax improvement?
This will work for your literal example where the input vector is of length 1. Use escapes to get a literal "." search, and reverse the result to get the last index as the "first":
 rev(gregexpr("\\.", x)[[1]])[1]

A more proper vectorized version (in case x is longer than 1):
 sapply(gregexpr("\\.", x), function(x) rev(x)[1])

and another tidier option to use tail instead:
sapply(gregexpr("\\.", x), tail, 1)

A: There is a slick stri_locate_last function in the stringi package, that can accept both literal strings and regular expressions.
To just find a dot, no regex is required, and it is as easy as
stringi::stri_locate_last_fixed(x, ".")[,1]

If you need to use this function with a regex, to find the location of the last regex match in the string, you should replace _fixed with _regex:
stringi::stri_locate_last_regex(x, "\\.")[,1]

Note the . is a special regex metacharacter and should be escaped when used in a regex to match a literal dot char.
See an R demo online:
x <- "hello.world.123.456"
stringi::stri_locate_last_fixed(x, ".")[,1]
stringi::stri_locate_last_regex(x, "\\.")[,1]


text:
Q: Setting up a virtual host on Linux I'm setting up a virtual host on a linux machine.
I've already made necessary DNS changes and they have propagated and are working correctly.
There are many other virtual hosts setup in my /etc/httpd/conf/httpd.conf file that are working correctly (someone else set all these up).  My config for the new virtual host is this (where the real IP has been replaced with ##.###.###.###):
<VirtualHost ##.###.###.###:80>
    ServerName www.website.com
    ServerAlias website.com
    DocumentRoot /var/www/html/website.com
    ErrorLog logs/website.com-error_log
    CustomLog logs/website.com-access_log combined
</VirtualHost>
<Directory /var/www/html/website.com>
    Order deny,allow
    Allow from all
    AllowOverride All
</Directory>

All the files for the site are sitting in /var/www/html/website.com.  When I visit website.com, the main site on this server is displayed rather than website.com.
What are some other configuration settings (anywhere) that could be doing this?  There are other virtual hosts set up in an identical manner (from what I can tell) and they are working correctly.

A: Do you have such lines for you ip?
# Listen for virtual host requests on IP addresses
NameVirtualHost ##.###.#.###:80

or
NameVirtualHost *

http://httpd.apache.org/docs/2.0/vhosts/examples.html

Note
You can, if you wish, replace * with the actual IP address of the system. In that case, the argument to VirtualHost must match the argument to NameVirtualHost


text:
Q: Se repite la consulta tengo un problema con el siguiente codigo, básicamente es que en mi página hay 3 buscadores, el problema es que los 3 me sacan la misma consulta sql, aunque estas sean distintas:

<asp:Panel CssClass="form-group" ID="Panel1" runat="server" Visible="true">
    <asp:Label Text="Tema" runat="server" CssClass="col-md-2 control-label" AssociatedControlID="ddlAutores" />

                        <asp:DropDownList ID="ddlAutores" runat="server" data-live-search="true" CssClass="form-control selectpicker" AutoPostBack="true" DataSourceID="SqlTemas" OnSelectedIndexChanged="Submit_Click" DataValueField="Value">
                            </asp:DropDownList>

            <asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString='<%$ConnectionStrings:DEFAULT %>' SelectCommand="SELECT DISTINCT DOCUMENTO.ID_DOCUMENTO AS Value FROM DOCUMENTO INNER JOIN TEMAS ON TEMAS.ID_TEMA = DOCUMENTO.ID_TEMAP WHERE (TEMAS.ID_TEMA = 2)">
            </asp:SqlDataSource>
     </asp:Panel>

<asp:Panel CssClass="form-group" ID="Panel1" runat="server" Visible="true">
    <asp:Label Text="Tema" runat="server" CssClass="col-md-2 control-label" AssociatedControlID="ddlAutores" />

                        <asp:DropDownList ID="ddlAutores" runat="server" data-live-search="true" CssClass="form-control selectpicker" AutoPostBack="true" DataSourceID="SqlTemas" OnSelectedIndexChanged="Submit_Click" DataValueField="Value">
                            </asp:DropDownList>

            <asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString='<%$ConnectionStrings:DEFAULT %>' SelectCommand="SELECT DISTINCT DOCUMENTO.ID_DOCUMENTO AS Value FROM DOCUMENTO INNER JOIN AUTORES_DOCUMENTO ON DOCUMENTO.ID_DOCUMENTO = AUTORES_DOCUMENTO.ID_DOCUMENTO WHERE AUTORES_DOCUMENTO.ID_AUTOR = 1;">
            </asp:SqlDataSource>
     </asp:Panel>

<asp:Panel CssClass="form-group" ID="Panel2" runat="server" Visible="true">
        <asp:Label Text="Lugar" runat="server" CssClass="col-md-2 control-label" AssociatedControlID="ddlFondos" />

                        <asp:DropDownList ID="DropDownList2" runat="server" data-live-search="true" CssClass="form-control selectpicker" AutoPostBack="true" DataSourceID="SqlTemas" OnSelectedIndexChanged="Submit_Click" DataValueField="Value">
                            </asp:DropDownList>

            <asp:SqlDataSource runat="server" ID="SqlDataSource2" ConnectionString='<%$ ConnectionStrings:DEFAULT %>' SelectCommand="SELECT DISTINCT DOCUMENTO.ID_DOCUMENTO AS Value FROM DOCUMENTO INNER JOIN TEMAS ON TEMAS.ID_TEMA = DOCUMENTO.ID_TEMAP INNER JOIN AUTORES_DOCUMENTO ON DOCUMENTO.ID_DOCUMENTO = AUTORES_DOCUMENTO.ID_DOCUMENTO WHERE ((AUTORES_DOCUMENTO.ID_AUTOR = @idAutor) OR (@idAutor IS NULL)) UNION SELECT 0 AS Value">
            </asp:SqlDataSource>
</asp:Panel>

Gracias de antemano :)


text:
Q: How do I use expect to test for less than Relish suggests the following...
expect(actual).to be <  expected

However if I try...
 x.rand(10)
 expect(x).to be < 11

full spec
Then(/^I find each world produces just up to (\d+) fighters per turn and no higher$/) do |arg1|
    test = Planet.new
    test.production.each_index do |ndx|
       expect(test.production[ndx]).to be < 11
    end
  end

I'll get
undefined method `<' for #<RSpec::Matchers::BuiltIn::BePredicate:0x0000000268a3b0> (NoMethodError)

What is the current proper syntax to use expect in a less than comparison?

A: Syntax looks good. I would first make a very small simple spec, independent of your code to see if your setup works. For example (it should fail btw ;):
describe 'test' do
  it 'works' do
    expect(2).to be < 1
  end
end

A: Looking at the source code for rspec-expectations it should return
RSpec::Matchers::BuiltIn::Be not RSpec::Matchers::BuiltIn::BePredicate
Is it possible you have be_ ? That returns a RSpec::Matchers::BuiltIn::BePredicate in the following dummy test
describe 'test' do
  it 'works' do
    puts "be is a #{be.class}"
    puts "be_ is a #{be_.class}"

    puts "be is defined on #{method(:be)}"
    expect(2).to be_ < 1
  end
end

outputs
be is a RSpec::Matchers::BuiltIn::Be
be_ is a RSpec::Matchers::BuiltIn::BePredicate
be is defined on #<Method:RSpec::ExampleGroups::Test(RSpec::Matchers)#be>

Alternatively maybe the be method has been redefined?


text:
Q: jScrollPane and jQuery 1.8.0 After update to jQuery 1.8.0, jScrollPane gives me this error:

Uncaught Error: Syntax error, unrecognized expression:
  [type=text/javascript],not([type])

in this line:
$("script",elem).filter('[type=text/javascript],not([type])').remove();

Can anyone help?
Thanks

A: *

*not is a pseudo selector and should be preceded by a : used as :not()

*While filtering by attribute name-value use as selector[attr="value"] - [type="text/javascript"].

So it should be -
.filter('[type="text/javascript"],:not([type])')

A: Here is a patch for jScrollPane. Works fine with jquery 1.8.x
https://github.com/jarednorman/jScrollPane/commit/2ef4821afa1dd62db056e3dea737e6f84b17fb13
This is a final minified version:
https://raw.github.com/jarednorman/jScrollPane/2ef4821afa1dd62db056e3dea737e6f84b17fb13/script/jquery.jscrollpane.min.js

A: The latest version of jScrollPane (v2.0.0beta12 - 2012-09-27) added support for jQuery 1.8:
$("script", elem).filter('[type="text/javascript"],:not([type])').remove();


text:
Q: syntaxis on matching urls from an array saved on extension storage I have been going through the Google chrome APIs in order to work on an extension and the processes regarding it.  I stumbled upon the chrome.webRequest https://developer.chrome.com/extensions/webRequest#event-onBeforeRequest I have been tinkering with the syntax but I am lost with it because I'm relatively new to programming and using the chrome APIs
What I was thinking was using chrome.webRequest.onBeforeRequest.addListener(function callback) and then making it use chrome.tabs.remove to remove the tab is it matches the array but I am not sure how to do that
I have this for the removing of the tab using the google chrome match filters
var urlArray= ["*://facebook.com/*", "*://example.com/*", "*://google.com/*" ];
chrome.tabs.onCreated.addListener(function (tab) {
    for (var i = 0, len = urlArray.length; i < len; i++) {
        if (tab.url.indexOf(urlArray[i]) > -1) {
            chrome.tabs.remove(tab.id);
            alert("things");
            break;
        }
    }
});

A: The problem in your code is that, if you check for "*somestring*", the .indexOf() function will actually look for that exact string, meaning that asterisks aren't used as a wildcard, and will only match if the string contains them.
Here's an example:
"hello".indexOf("*hello")     // -1 there's no *
"123hello".indexOf("*hello")  // -1 there's no *
"*hello".indexOf("*hello")    // 0  here it is, in the first position
"123*hello".indexOf("*hello") // 3  and again, in the fourth position

So, in your case, you should use Regular Expressions, like this:
var urlExp= /https?\:\/\/(facebook|google|example)\.com/i;

chrome.tabs.onCreated.addListener(function (tab) {
    if (urlExp.test(tab.url)) {
        chrome.tabs.remove(tab.id);
        alert("things");
    }
});


text:
Q: Magento 2. How to fetch available shipping methods for current customer I'd like to know how can I fetch all shipping careers available for the current customer (quote wasn't created yet).

A: i don't know do you find any way but i am work around this now .
i get all shipping method and pass the param that each shipping method needed for example :
  /**
     * @var $free \Magento\OfflineShipping\Model\Carrier\Freeshipping
     * @var $req \Magento\Quote\Model\Quote\Address\RateRequest
     */
    $free=$this->_objectManager->create("Magento\OfflineShipping\Model\Carrier\Freeshipping");
    $req=$this->_objectManager->create("Magento\Quote\Model\Quote\Address\RateRequest");
    $req->setBaseSubtotalInclTax(10);
    $res= $free->collectRates($req);
  //  var_dump($res->getRatesByCarrier("freeshipping")->asArray());

    $rates = [];
    foreach ($res->getAllRates() as $rate) {
        $rates[$rate->getCarrier()]['title'] = $rate->getCarrierTitle();
        $rates[$rate->getCarrier()]['methods'][$rate->getMethod()] = [
            'title' => $rate->getMethodTitle(),
            'price' => $rate->getPrice(),
            'price_formatted' => 111,
        ];
    }
    var_dump($rates);

and now i can find this shipping method can be available or not.
if you have a better way or find any thing please share it


text:
Q: Vue3-My provide is not updated after changing the data using mounted I tried to provide my data from a parent element like below.
data(){
    return{
    allData:null,
    ingCollection:null,
    selectedDish:[]
    }
  },

  mounted(){
    Promise.all([
      d3.json('data.json'),
      d3.json('ingredientsonly.json')
    ]).then((data)=>{
      this.allData=data[0];
      this.ingCollection=data[1];

    })
  },
  components:{sidePanel,centerPiece},

  methods: {
    // receiveIngredients(selected){
    //   let selections = this.allData.filter(d=>{
    //     d.ingredients.includes(selected)
    //   });

    // }
  },
    provide() {
    return{
    allData:this.allData,
    ingCollection:this.ingCollection,
    selectedDish:this.selectedDish,
    receiveIngredients:this.receiveIngredients
    }
  }

However, after mounted lifecycle hook was run,
data is updated while provide elements were not updated.
Why is it?
Thank you

A: provide() is only called once at initialization, and not when there's a change to the references within.
Instead, you can provide an object (e.g., named root), and then update a property of that object in mounted():
export default {
  provide() {
    return {
      root: {
        allData: null,
        ingCollection: null,
      }
    }
  },
  mounted() {
    Promise.all([
      d3.json('data.json'),
      d3.json('ingredientsonly.json')
    ]).then((data)=>{
      this.root.allData = data[0];
      this.root.ingCollection = data[1];
    })
  }
}


text:
Q: RSpec: how to test Rails logger message expectations? I am trying to test that the Rails logger receives messages in some of my specs.  I am using the Logging gem.
Let's say that I have a class like this:
class BaseWorker

  def execute
    logger.info 'Starting the worker...'
  end

end

And a spec like:
describe BaseWorker do

  it 'should log an info message' do
    base_worker = BaseWorker.new
    logger_mock = double('Logging::Rails').as_null_object
    Logging::Rails.stub_chain(:logger, :info).and_return(logger_mock)

    logger_mock.should_receive(:info).with('Starting the worker...')
    base_worker.execute
    Logging::Rails.unstub(:logger)
  end

end

I get the following failure message:
 Failure/Error: logger_mock.should_receive(:info).with('Starting worker...')
   (Double "Logging::Rails").info("Starting worker...")
       expected: 1 time
       received: 0 times

I've tried out several different approaches to get the spec to pass.  This works for example:
class BaseWorker

  attr_accessor :log

  def initialize
    @log = logger
  end

  def execute
    @log.info 'Starting the worker...'
  end

end

describe BaseWorker do
  it 'should log an info message' do
    base_worker = BaseWorker.new
    logger_mock = double('logger')
    base_worker.log = logger_mock

    logger_mock.should_receive(:info).with('Starting the worker...')
    base_worker.execute
  end
end

But having to setup an accessible instance variable like that seems like the tail is wagging the dog here. (Actually, I'm not even sure why copying logger to @log would make it pass.)
What's a good solution for testing the logging?

A: If you want to keep consistency in your tests, but setting the expectations at last you need to add in your setup:
setup do
 allow(Rails.logger).to receive(:info)
end
...

it 'should log an info message' do
 {code}

  expect(Rails.logger).to have_received(:info).with('Starting the worker...')
end

A: With RSpec 3+ version
Actual code containing single invocation of Rails.logger.error:
Rails.logger.error "Some useful error message"

Spec code:
expect(Rails.logger).to receive(:error).with(/error message/)

If you want the error message to be actually logged while the spec runs then use following code:
expect(Rails.logger).to receive(:error).with(/error message/).and_call_original

Actual code containing multiple invocations of Rails.logger.error:
Rails.logger.error "Technical Error Message"
Rails.logger.error "User-friendly Error Message"

Spec code:
expect(Rails.logger).to receive(:error).ordered
expect(Rails.logger).to receive(:error).with(/User-friendly Error /).ordered.and_call_original

Also if you care about just matching the first message and not any subsequent messages then you can use following
  expect(Rails.logger).to receive(:debug).with("Technical Error Message").ordered.and_call_original
  expect(Rails.logger).to receive(:debug).at_least(:once).with(instance_of(String)).ordered

Note in above variation setting .ordered is important else expectations set start failing.
References:
http://www.relishapp.com/rspec/rspec-mocks/v/3-4/docs/setting-constraints/matching-arguments
http://www.relishapp.com/rspec/rspec-mocks/v/3-4/docs/setting-constraints/message-order

A: Instead of using this line before the message is logged:
expect(Rails.logger).to receive(:info).with("some message")
something that triggers the logger...

You could set the Rails logger as a spy and use have_received instead:
allow(Rails.logger).to receive(:info).at_least(:once)

something that triggers the logger...

expect(Rails.logger).to have_received(:info).with("some message").once

A: While I agree you generally don't want to test loggers, there are times it may be useful.
I have had success with expectations on Rails.logger.
Using RSpec's deprecated should syntax:
Rails.logger.should_receive(:info).with("some message")

Using RSpec's newer expect syntax:
expect(Rails.logger).to receive(:info).with("some message")

Note: In controller and model specs, you have to put this line before the message is logged. If you put it after, you'll get an error message like this:
Failure/Error: expect(Rails.logger).to receive(:info).with("some message")
       (#<ActiveSupport::Logger:0x007f27f72136c8>).info("some message")
           expected: 1 time with arguments: ("some message")
           received: 0 times

A: If your goal is to test logging functionality you may also consider verifying the output to standard streams.
This will spare you the mocking process and test whether messages will actually end up where they supposed to (STDOUT/STDERR).
With RSpec's output matcher (introduced in 3.0) you can do the following:
expect { my_method }.to output("my message").to_stdout
expect { my_method }.to output("my error").to_stderr

In case of libraries such as Logger or Logging you may have to use output.to_<>_from_any_process.

A: Even I had very similar error:
Failure/Error: expect(Rails.logger).to receive(:info).with("some message")
       (#<ActiveSupport::Logger:0x007f27f72136c8>).info("some message")
           expected: 1 time with arguments: ("some message")
           received: 0 times

The below worked for me,
expect { my_method }.
            to output(/error messsage/).to_stdout_from_any_process

Reference: https://relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/output-matcher


text:
Q: Push doesn't modify the list being a function argument I'm new to common lisp, so hope someone would clarify this to me:
say we have a list and want to add an item with push to modify it:
CL-USER> (defparameter xx '(1 2 3))
XX
CL-USER> xx
(1 2 3)
CL-USER> (push 100 xx)
(100 1 2 3)
CL-USER> xx
(100 1 2 3)

as expected. But when i try to do the same with the function, it doesn't modify a list:
CL-USER> (defun push-200 (my-list)
           (push 200 my-list))
PUSH-200
CL-USER> (push-200 xx)
(200 100 1 2 3)
CL-USER> xx
(100 1 2 3)

so i tried to compare argument and my list like this:
CL-USER> (defun push-200 (my-list)
           (format t "~a" (eq my-list xx))
           (push 200 my-list))

WARNING: redefining COMMON-LISP-USER::PUSH-200 in DEFUN
PUSH-200
CL-USER> (push-200 xx)
T
(200 100 1 2 3)
CL-USER> xx
(100 1 2 3)

it says the objects are identical.
So the question is: what was the thing I've overlooked here?

A: (defun push-200 (my-list)
  (push 200 my-list))

This modifies the variable my-list. The variable now points to a new cons.
It is basically: (setq my-list (cons 200 my-list).
(push-200 xx)

Common Lisp evaluates xx to a value and passes the list to push-200. xx is not passed, but the value of it. So, the Lisp system can't modify xx to point to a different cons, since it is not passed.

A: This is (essentially) the same problem highlighted by the following:
(let ((a (list 2 3 4 5)))
  (let ((b a))
    (push 1 a)
    (list (eql a b)
          (eql (cdr a) b))))

This form should return (NIL T) when run.

A: What Rainer Joswig writes (and Vatine demonstrates). Just replace (push <A> <B>) with (setq <B> (cons <A> <B>)) wherever you see it, because push is a macro:

"push item place => new-place-value"

And,

"new-place-value [is] a list (the new value of place)"

Notice CLHS didn't say "(the updated structure referred to by place)".
So, the value of place changes. And that place, in your case, is the local variable my-list. It was eq to xx before the (setq ...), but obviously not,  after it. To actually alter a list structure you can use rplaca and ⁄ or rplacd.
We can think about argument passing in Common Lisp mostly as if what was passed is a pointer to a value; the pointer itself is passed by value, i.e. copied. So xx "points" at some list; and initially my-list "points" at the same memory location. That's why the initial eq test succeeds.


text:
Q: Calling constructor from shared method (C# to VB.Net) I have not enough experience in VB.NET, I have a Windows Forms VB.NET application and I'm trying to do what in C# I'd do in this way:
public class MyForm{
    MyForm(string caption) {
        _caption = caption;
        if(...){
            BaseForm.Show(caption);
      }
    }

    public static void Show(string caption) {
        new MyForm(caption);
    }
}

(BaseForm is another class I have in the application with a static method Show). All works fine in C#, but in Visual Basic .NET I'm not able to call the constructor.
The constructor has become:
Public Sub New(ByVal caption As String)
        _caption = caption
        If ...
            BaseForm.Show(caption)
        End If
End Sub

But what is the VB.NET equivalent for new classname(parameters)? What i've tried:
Public Shared Sub Show(ByVal caption As String)
    MyForm.New(caption)
End Sub

Public Shared Sub Show(ByVal caption As String)
    Me.New(caption)
End Sub

Public Shared Sub Show(ByVal caption As String)
    New MyForm(caption)
End Sub

None of these works. It also appears that online C#-VB.NET converters give me the third option as answer (I wouldn't have tried that) but it's wrong. VS 2017 gives me the following errors respectively:

*

*"Constructor call is valid only as the first statement in an
instance constructor"

*This obviously doesn't work because a shared/static method can't call an instance

*"Syntax error"

EDIT: Sorry for the mistake, I originally posted a code where I was passing three arguments in the VB.NET functions. However, in my real code the functions have more arguments and I'm sure this is not the problem. I thought it would have been clearer if I had only shown you the essential code since the complete code is too long but forgot to delete the additional arguments in some functions

A: In VB.NET, you should use a temporary variable:
Dim tempVar As New MyForm(caption)

A: The essential issue here is that VB does not allow "naked" expressions to be statements. C# (and Java) restricts expressions as statements to the following:

*

*Assignment expressions

*Any use of ++ or --

*Method invocations

*Object creation expressions

Regarding the first two points, VB has sort-of equivalents. VB doesn't have a built-in assignment expression; instead it has an assignment statement. VB doesn't have ++ or -- operators; it only has += and -= assignment statements. In any case, via helper Functions one can make fully emulated equivalents of them in VB.
Of the above points, only the "Method invocations" one is allowed in VB. The "Object creation expressions" is not.
So something like New MyForm() is an expression, despite the pretense of Sub New(). The most straight-forward work-around is to make use of local variables (as others have already suggested):
Dim tmp As New MyForm(Text, caption, timeout)

Another idea is using With:
With New MyForm(Text, caption, timeout) : End With

If you figure this is the sort of thing you'll be doing a lot, maybe you could add a private or protected method to your class that does nothing:
    Private Sub NoOp()
    End Sub

and use it like so:
Call New MyForm(Text, caption, timeout).NoOp()

That works because the Call statement allows for expressions on the way towards getting at a method invocation.
Alternatively, you could make a helper function in a Module like so:
#Disable Warning IDE0060 ' Remove unused parameter
    Friend Sub [Call](Of T)(x As T)
#Enable Warning IDE0060 ' Remove unused parameter
    End Sub

And then do this with it:
[Call](New MyForm(Text, caption, timeout)) ' Note square brackets on [Call]

A: Your MyForm constructor takes only one parameter and your Show method is wrong and should be like this to return the newly created instance.
Public Shared Function Show(ByVal caption As String) As MyForm
    Return New MyForm(caption)
End Function

The real issue here is your design, you should not have any logic implemented inside of your constructor.
Something like this instead
Public Sub Show()
    BaseForm.Show(_caption)
End Sub

Public Shared Sub Show(ByVal caption As String)
    Dim form = New MyForm(caption)
    form.Show()
End Sub

A: For these kinds of question there are many C# to VB converters, including at least 2 Free Open Source once that will do the conversion for you. One is mine at https://github.com/paul1956/CSharpToVB


text:
Q: Sale Order Line And Manufacturing Order BOM Creation Process I need to know that , after the confirmation of sale order how to generate and also process and the function in bill of materials field  in manufacturing order?
Thank You!

A: *

*Install Sale and MRP modules.

*Create few products for example: product and product_component

*Create a BoM for product, where material is a product_component

*Set Make to Order in product, and set it as manufacture

*create sale order, sell one product and go to your MO.


text:
Q: How can I calculate my position, if I have 3 points coordinates and distance? How can I calculate my position, if I have 3 points coordinates and distance from every coordinate to my position. All coordinates by longitude and latitude.This is example

A: What do you mean?  The image you provide answers your own question.
You have three points denoting the centers of circles.  You have the distance from each coordinate, therefore you have the radii of the circles.  So you can fully describe each circle in space.
Your position is the intersection of those three circles.  You need to find the unique point that satisfies all three equations.

A: Suppose the three points are $A, B, C$.  Since you're talking about longitude and latitude then these points are on a sphere of known radius $R$ like the Earth.
Therefore, their coordinates are given by
$ A = ( \cos(\theta_1) \cos(\phi_1) , \cos(\theta_1) \sin(\phi_1), \sin(\theta_1))$
$ B = ( \cos(\theta_2) \cos(\phi_2) , \cos(\theta_2) \sin(\phi_2), \sin(\theta_2))$
$ C = ( \cos(\theta_3) \cos(\phi_3) , \cos(\theta_3) \sin(\phi_3), \sin(\theta_3))$
where $\theta_1, \phi_1$ are the latitude and longitude of $A$, $\theta_2, \phi_2$ are the latitude and longitude of $B$, $\theta_3, \phi_3$ are the latitude and longitude of $C$.
The above the $3D$ $x,y,z$ coordinates.  Now you have the following equations for your unknown position $P (x, y, z)$
$(P - A)^T (P - A) = d_A^2 $
$(P - B)^T (P - B) = d_B^2 $
$(P - C)^T (P - C) = d_C^2 $
Subtracting the second equation from the first, gives us
$ - 2 P (A - B) + A^T A - B^T B = d_A^2 - d_B^2 $
And substracting the third equation from the first, gives us
$ - 2 P(A - C) + A^T A - C^T C = d_A^2 - d_C^2 $
These are two linear equations in the three unknown coordinates of $P$.
Solving them using standard linear algebra methods results in the solutions being of the form
$ P = V_0 + t V_1 $
where $t \in \mathbb{R}$ is yet to be determined.
To determine $t$, plug in the above expression for $P$ into any of the three equations specifying the distances, for example, the first one, gives us
$ (V_0 - A + t V_1)^T (V_0 - A + t V_1) = d_A^2 $
Expanding this equation yields the following quadratic equation in $t$
$ (V_1^T V_1) t^2 + (2 (V_0-A)^T V_1 ) t + (V_0 - A)^T (V_0 - A) - d_A^2 = 0 $
This equation can be solved for two possible values of $t$.  To choose the correct value for $t$ we have to check that the point $P$ (assumed to lie on the surface of the Earth) has a magnitude equal to the radius of Earth.
That is, choose $t$ such that
$ (V_0 + t V_1)^T (V_0 + t V_1) = R^2 $


text:
Q: Jquery not working fine with out an alert box Please ignore if I am asking a repeated or common question.
Jquery is working fine if i have an alert in the code.
Example:
var selectedEvent = jQuery("#DemoEvents").jqGrid('getGridParam','selrow');
var imagePath = jQuery("#DemoEvents").getCell(selectedEvent, 9);
var locationArr = imagePath.split("rel");
var evtId = jQuery("#DemoEvents").getCell(selectedEvent, 0);
**alert(evtId);**
var anchorId = jQuery("#DemoEvents").getCell(selectedEvent, 7);
jQuery('#tr_anchorId .FormElement').val(anchorId);

jQuery("#tr_anchorId .FormElement option[value='"+evtId+"']").remove();

is working fine...  and....
var selectedEvent = jQuery("#DemoEvents").jqGrid('getGridParam','selrow');
var imagePath = jQuery("#DemoEvents").getCell(selectedEvent, 9);
var locationArr = imagePath.split("rel");
var evtId = jQuery("#DemoEvents").getCell(selectedEvent, 0);
**//alert(evtId);**
var anchorId = jQuery("#DemoEvents").getCell(selectedEvent, 7);
jQuery('#tr_anchorId .FormElement').val(anchorId);

jQuery("#tr_anchorId .FormElement option[value='"+evtId+"']").remove();

is not working. any ideas please give.

A: The only reason it should not be working is because there is an AJAX call in your method.
Placing an alert on this snippet gives time for that AJAX call to fetch your data. Otherwise it won't work because the snippet runs out before your AJAX call returns.
If there is an AJAX Call then you should ideally be writing the rest of the code in its call back method and this would solve the issue.
P.S: I was wrong about getCell. Its a jqGrid method. Sorry.


text:
Q: Character limit isn't working on iPad I've used the below script to limit characters with the resize of window, it works as I wanted it on desktop web, but when I open the page on iPad, the characters aren't limiting or changing. What could be the done to fix this? any help would be appreciated.
/*limit characters in featured text column */
$( document ).ready(function() {
    function checkWidth() {
        if ($(window).width() < 1270) {
            $(".i-trim-header").addClass('i-text-trim');
            $(".i-trim-header").each(function(i){
                len=$(this).text().length;
                if(len>25) {
                    $(this).text($(this).text().substr(0,25)+'...');
                }
            });
        } else {
            $('.i-trim-header').removeClass('i-text-trim');
            $(".i-trim-header").each(function(i){
                $(this).text($(this).data('.i-trim-header-o'));
            });
        }
    }
    $(".i-trim-header").each(function(){
        $(this).data({originalTxt: $(this).text()});
      });
    $(window).resize(checkWidth);
});

/* default character limit in text column */
// <![CDATA[
$(function(){
    $(".i-trim-header-o").each(function(i){
        len=$(this).text().length;
        if(len>55) {
            $(this).text($(this).text().substr(0,55)+'...');
        }
    });
});
// ]]></script>

A: Go to settings->Safari->Advanced->JavaScript and make sure it's turned on although most javascript codes don't work on mobile devices.


text:
Q: jquery-1.10.2.js:1472 Uncaught Error: Syntax error, unrecognized expression: label[for='team[]'], label[for='team[]'] *, #team[]-error I'm using multiselect js plugin in select element and jquery validate plugin to validate form elements.
I know this is because of '[]' in select element name attribute, that is causing this error, but I want to enable multiple selections.
When I remove '[]', it is working fine..
Here's my HTML:

    Team *

              <select name="team[]" class="form-control multiselect-ui" multiple>
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              </select>

Here's my jquery validate:
rules:
{
   "team[]": "required"
},
messages:
{
     "team[]": "Please select team",
}

How do I solve this issue??
Any help is very much appreciated. Thanks.

A: Have you tried assigning an id to select tag and retrieving values with multiselect method?
<select name="team[]" class="form-control multiselect-ui" id="team" multiple="multiple">

$('#team').multiSelect()

A: You have to escape the [] because jQuery thinks its an attribute selector.
$("label[for='team[]'], label[for='team[]'] *, #team[]-error")
Should be
$("label[for='team[]'], label[for='team[]'] *, #team\\[\\]-error")
demo

$("label[for='team[]'], label[for='team[]'] *, #team\\[\\]-error")


text:
Q: JAVA HIbernate 4.2.4: Add additional hibernate criteria (AND condition) to 3 joined entities without using HQL I am trying to join 3 entities using hibernate criteria with relation defined as follows:

*

*Each Employee has one Department and a Specialization.

*A Department could have many Employees.

*A Department may contain more than one Specializations.

*One Specialization could belong to many Departments.

I want to get a response given an Employee's ID with all its details. The problem here is that Employee and Specialization  entities do not have a direct foreign key relationship between them. And hence I am not able to join the two entities.
Below some sample data:
Employee:
| emp_id | emp_name | emp_specialization | dept_id |
|:-------|---------:|:------------------:|--------:|
| 1      |     John |         electronics|        1|
| 2      |     Wick |               frame|        2|
| 3      |    Three |               radar|        1|

Department:
| dept_id | dept_name |
|:-------|-----------:|
| 1      | F21 Raptor |
| 2      | F35 Panther|

Specialization:
| spec_id | dept_id | spec_name          |
|:-------|---------:|:------------------:|
| 1      |         1|         electronics|
| 2      |         1|               frame|
| 3      |         2|               radar|

As given, emp_specialization and spec_name define a relationship between the two entities - Employee and Specialization.
Here are the snippets for 3 classes:
@Entity
@Table(name = "Employee")
Class Employee {
private Long emp_id;
private String emp_name;
private String emp_specialization;

@ManyToOne
@JoinColumn(name = "dept_id")
private Department department;
}

@Entity
@Table(name = "Department")
Class Department {
private Long deptId;

@OneToMany(mappedBy="dept_id", fetch=FetchType.EAGER)
private Set<Specialization> specialization;
}

@Entity
@Table(name = "Specialization")
Class Specialization {
private Long spec_id;
private Long dept_id;
private String spec_name;
}

Criteria criteria = session.createCriteria(Employee.class);
criteria.add(Restrictions.eq("emp_id", 1));
List<Employee> empList = criteria.list();

The above criteria results in below SQL:
SELECT
    Employee.*
FROM
    Employee emp
LEFT OUTER JOIN
    Department dpt
        ON emp.dept_id = dpt.dept_id
LEFT OUTER JOIN
    Specialization spec
        ON dpt.dept_id =  spec.dept_id
WHERE emp.emp_id = 1

But this results in multiple Specializations for Employee with ID=1 :
{
    "Employee": [{
            "emp_id": 1,
            "emp_name": "John",
            "emp_spec": "electronics",
            "department": {
                "dept_id": 1,
                "dept_name": "F21 Raptor",
                "specialization": [{
                        "spec_id": 1,
                        "spec_name" "electronics"
                    }, {
                        "spec_id": 2,
                        "spec_name" "frame"
                    }
                ]
            }
        }
    ]
}

What I really want is something like:
SELECT
    Employee.*
FROM
    Employee emp
LEFT OUTER JOIN
    Department dpt
        ON emp.dept_id = dpt.dept_id
LEFT OUTER JOIN
    Specialization spec
        ON dpt.dept_id =  spec.dept_id
WHERE emp.emp_id = 1
AND emp.emp_specialization = spec.spec_name

And would give a response in below JSON format:
{
    "Employee": [{
            "emp_id": 1,
            "emp_name": "John",
            "emp_spec": "electronics",
            "department": {
                "dept_id": 1,
                "dept_name": "F21 Raptor",
                "specialization": {
                    "spec_id": 1,
                    "spec_name" "electronics"
                }
            }
        }
    ]
}

Please advise.

A: You can do this in FluentJPA, return the Employee and serialize it to JSON.


text:
Q: getting 404 modal when I do click event on Laravel livewire I have started using livewire but I can't make it work im using a wire:click to load a form either on create mode or edit mode, but when I did click all I got was some sort of modal with 404 error
this is the livewire component

namespace App\Http\Livewire;

use Livewire\Component;

class Activities extends Component
{
    public $view = 'none';

    public function render()
    {
        return view('livewire.activities');
    }

    public function create_view(){

        $this->view = 'create';

    }

    public function edit(){

        $this->view = 'edit';

    }
}

this is the view

<button wire:click="create_view" class="button-warning">{{ __('Create') }}</button>

@if ($view != 'none')

        @include("livewire.$view")

@endif

Edit: I load the view manually and it loads correctly, for example:

@if ($view != 'none')

        @include("livewire.edit")

@endif

A: if like you said this work then you have to check for the $view value. Always that you close the view remember change the property to the default value.
@if ($view != 'none')

        @include("livewire.edit")

@endif

A: I think you might be having a Livewire configuration issue. Check your installation and specifically your asset_url in your config/livewire.php if you have published your config

php artisan livewire:publish --config

The 404 modal should disappear once your config is correct.

A: If your livewire.php file in config not best config
this error should not disappear
make asset_url 'asset_url' asset_url => 'http://127.0.0.1:8000' (if you have localhost)

A: Change your code like this.
Because in your code the variable $view will consider part of string. So livewire is searching a page like livewire.$view. But in our case we didn't have like that filename. We have only the view file create. So change as per the code given below. It will work
<button wire:click="create_view" class="button-warning">{{ __('Create') }}</button>

@if ($view != 'none')

        @include('livewire.'.$view)

@endif