text:
Q: Replace function not working in C#, but working in SQL Server 2008 Replace function working when using command
exec MyStoredProcedure param1, param2,

etc..., but when running it through C# code, it is not replacing the text properly, so I end up with an email that still says @@Comments, instead of the actual comments. I try to check it in SQL Server 2008, but it works fine and the email comes through properly. Is there something that I need to check?
Here is my C# code:
public static void SetRequestStatusChange(int reqID, int newStatus, string assignTo)
{
    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand("spUpdateRequest", con);
    cmd.CommandType = CommandType.StoredProcedure;

    // Status
    cmd.Parameters.Add(new SqlParameter("@RequestNo", SqlDbType.Int, 4));
    cmd.Parameters["@RequestNo"].Value = 276;

    // Queue
    cmd.Parameters.Add(new SqlParameter("@userID", SqlDbType.NVarChar, 12));
    cmd.Parameters["@userID"].Value = "1091912";

    // State
    cmd.Parameters.Add(new SqlParameter("@RequestStatus", SqlDbType.Int, 4));
    cmd.Parameters["@RequestStatus"].Value = 2;

    // Buyer Emp ID
    cmd.Parameters.Add(new SqlParameter("@assignedTo", SqlDbType.NVarChar, 12));
    cmd.Parameters["@assignedTo"].Value = "1091912";

    try
    {
        con.Open();
        cmd.ExecuteNonQuery();
    }
    catch (SqlException err)
    {
        throw new ApplicationException("Data Error." + err.ToString());
    }
    finally
    {
        //close the connection
        con.Close();
    }
}

Here is the part of the stored procedure that actually performs the replace. The actual stored procedure is very long, and calls many other stored procedures (I didn't write it), and it would be extremely cumbersome to read.
select @html = replace(replace(replace(@html, '@@COMMENTS', case when @activityID <> 20 then  'The following comments were noted when the Request' else '' end +

   case @ActivityID when  2 then ' was submitted: ' +  case when requestorComments > '' then requestorComments  else 'None' end
   when 0 then ''
   when  4 then ' was edited: ' + isnull(L.Comments,  'None')
   when  15 then ' was edited: ' + isnull(LL.Comments,  'None')
   when  20 then ''
   when  21 then  ' material was returned: ' + case when dbo.fnLastComment(lamSpecRecallComments) > '' then replace(dbo.fnLastComment(lamSpecRecallComments),':',':  ') else 'None' end
   when  -21 then  ' material was returned: ' + case when dbo.fnLastComment(lamSpecRecallComments) > '' then replace(dbo.fnLastComment(lamSpecRecallComments),':',':  ') else 'None' end
   when  8 then ' was approved: ' + case when ccMgrCOmments > '' then ccMgrCOmments  else 'None' end
   when  9 then ' was approved: ' + case when lamAprCOmments > '' then lamAprCOmments  else 'None' end
   when 13 then ' was stored: ' + case when dbo.fnLastComment(lamSpecCOmments) > '' then dbo.fnLastComment(lamSpecCOmments)  else 'None' end
   when -8 then ' was closed: ' + case when ccMgrCOmments > '' then ccMgrCOmments  else 'None' end
   when -9 then ' was closed: ' + case when lamAprCOmments > '' then lamAprCOmments  else 'None' end
   else '' end),

   '@@PLEASE',
   case when @activityID =  8 or @activityID = 9 or @activityID = 20 or @activityID = 2  then 'Please click the link below to view the Request and ensure it is worked expeditiously.'
   else '' end),'@@RECALL',@list)

   from (select * from strgRequests where requestNumber = @requestID) r
   left join (select * from  ActivityLog  where TransactionID = @transactionID) L on 1 = 1
   left join (select * from  ActivityLineItemLog where TransactionID = @transactionID) LL on 1 = 1

@@Comments, @@RECALL, and @@Please come from a table. This allows for the emails to be customized.

A: "@@" is normally used for global/default variables.
"@" is normally used for parameters.
I'd have to see more code to be sure.  My instincts tell me that switching your @@ for @ is the next direction you should take in sorting this out.
Also, if a field has the value of "@@Comments" you probably have a code somewhere that looks like:
set @cmd=`insert into Table (field,field,field) values ('somethinguseful','@@Comments','more stuff')
exec(@cmd)
This has two problems.

*

*You didn't translate @@Comments

*You are injection prone.

use something like:
execute sp_executesql N'insert into Table (field,field,field) values (@var1,@var2,@var3)'
,N'@var1 varchar(256)'
, @var1=@Comments
...


text:
Q: How to highlight a searched text inside a document which is indexed in Apache Solr I am using Apache Solr 8.6 to index the documents using POST Tool in Linux as mentioned in the Apache Solr Reference Guide.
POST Tool Command
bin/post -c testcore /testdocs/

The documents are getting indexed successfully. Now when I searched the string eg: hello in Solr Admin UI, It is returning the matching documents.
Now I want to highlight this string "hello" which is present inside the document as content. But I am unable to achieve the same.
I have tried putting highlighting enabled and entering text_* in the hl.fl=text_*. Yet I am unable to achieve the result. However if this searched string is present in any of the indexed fields it is correctly highlighting in the results.
In managed-schema.xml i have added content and text Fields as shown below.
<field name="content" type="text_general" indexed="false" stored="true" multiValued="false"/>

<field name="text" type="text_general" indexed="true" stored="false" multiValued="true"/>

I have tried below queries:
http://localhost:8983/solr/testcore/select?q=_text_%3a*hello*&hl=true&hl.fl=content&hl.usephrasehighlighter=true

http://localhost:8983/solr/testcore/select?q=_text_%3a*hello*&hl=true&hl.fl=text_*&hl.usephrasehighlighter=true

Will be grateful if you could guide me further.
Edit: As per recommendation
I have changed the fields of content and text as shown below, but it is not working either. That means when I am searching the text string it is not highlighting the searched string inside the document as content.
<field name="content" type="text_general" indexed="true" stored="true" multiValued="false"/>

<field name="text" type="text_general" indexed="true" stored="true" multiValued="true"/>

A: Finally the issue resolved by modifying _text _ field in manage-schema.xml file. I have changed the value of stored="false" to stored="true" as shown in below syntax.
<field name="_text_" type="text_general" indexed="true" stored="true" multiValued="false"/>

Then I have restarted the solr and refindexed the document.
Now i have fired the query to highlight the text as shown below. In this query i have used hl=on & hl.fl=_text _ to highlight the comment.
Query to highlight the searched string
http://localhost:8983/solr/testcore/select?q=_text_%3a*hello*&hl=on&hl.fl=_text_

redpajama_set_name: RedPajamaStackExchange


text:
Q: Send (g)ARP request to broadcast address using c++ on windows I want to send a broadcast ARP request with the destination address (255.255.255.255) on Windows 10 using c++. I am aware of the SendARP function, however, it does not work for broadcasting.
There is also other methods using winpcap and pcap headers, however, I need to do it without external libraries other than winsock. I tried to use
SOCKET sock = socket(AF_INET,SOCK_RAW,htons(0x0806));

But the socket is never valid on Windows. Is there a way to implement such broadcast ARP without the wnpcap library?
================
Methods tried:
SendARP works for sending ARP messages with specific destination IP address but not to a broadcast one
https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-sendarp
The code in here didn't work for windows. I extracted and modified it, but either the socket is invalid or sendto function does not send the ARP request.
http://usuaris.tinet.cat/sag/send_arp.htm


text:
Q: Can unit/time dummies be included with PCSE or XTGLS? I am currently working with a balanced time-series cross-section dataset (or a T dominant panel), consisting in 8 units (countries) and 32 observations (quarters) per unit. Thus, the dataset has 8 x 32 = 256 observations. The dependent variable is continuous and there are 5 regressors. I am estimating my model using Fixed Effects (in Stata, "xtreg, fe"), Random Effects (in Stata, "xtreg, re"), Beck and Katz Panel Corrected Standard Errors ("xtpcse") and GLS ("xtgls"). Since my data is not what Greene would called "well-behaved data" -it shows panel heteroskedasticity, serial correlation and contemporaneous correlation-, I am proecting the models against these issues. Thus, my first question is about how to control for time and unit unobserved heterogeneity with PCSE and GLS models. Or, in different words:
(a) Does it make sense to include time and unit dummies with PCSE and GLS models? Any reference supporting your statement will be appreciated. I have found some other people asking this out there, but no proper answer so far.
(b) Does it make sense to include a time trend and time dummies simultaneously in FE/RE/PCSE/GLS? I have found different answers to this question: ones arguing that it makes sense and some others arguing that it does not. Again, explanations with a minimal reference or link are welcome.
Thank you all!

A: (a) PCSE just changes the estimated standard errors and can be used with time/unit dummies and/or time trends; in fact the inclusion of dummies and trends is not really related to the issue of how to get appropriate standard errors. So yes, it makes sense. PCSE were introduced by Beck and Katz 1995 and in fact the use of unit dummies and PCSE together is something like a standard in political science at least.
GLS is a different way to estimate both the coefficients and the standard errors, and is also not really related to the model specification (dummies and trends). So you would also include dummies or trends based on substantive considerations, and then you might apply GLS if OLS leads to heteroskedasticity or serial correlation. However, and this is extensively discussed in Beck and Katz 1995, the (F)GLS procedure especially for your kind of data has really bad finite-sample behavior.
(b) Jeff Wooldrdige says: "No, it doesn't make sense to include a full set of time dummies along with any function of time. Putting in time dummies allows for any kind of trend, of which a linear trend is a special case." (You get a linear time trend if all the time dummies happen to haven the same estimate). The inclusion of time dummies is of course "conservative", in a sense, but could be more or less warranted depending on the question you try answer - essentially, do you think that units pick up the treatment because of unobserved stuff that changes over time, that this also influences the dependent variable, and that it somehow is common across units?


text:
Q: Can you specify columns for a calculation in a dataframe using values from another list/set? I have a dataframe with this format, generated by pivoting an excel file:
Gene             Ref      y       z
Sample
1             29.2877  29.0625  20.9868
2             29.9897  32.8044  25.8783
3             31.6335  34.7172  24.6268

I want to perform a calculation with columns ref and y, then with ref and z, to generate 2 new columns.  I know how to do these individually but I want something where I can specify how many columns need to be evaluated (y, z... etc), based on a number_of_columns = len(list) object generated earlier.  Ideally, I'd also like the new columns to have names taken from another set  that is also generated earlier.  I always have the ref column as the first column, so I was trying something like this:
while number_of_columns != 0:
    for column in df[(number_of_columns + 2)].iteritems():
        df[set_of_names_of_new_columns] = df.(names_of_columns_to_use) + df[ref_column]
        number_of_columns -= 1

Obviously this doesn't work but I have put it in to show what I was thinking.  This also isn't the calculation but just simplified here.
Any help very much appreciated!

A: If your df isn't too wide, a simple for-loop approach will work just fine as each column operation is vectorized.  Just identify your reference row and columns of interest programatically (by name rather than index value):
ref = df["Ref"]
cols = [col for col in df.columns if col != "Ref"]

for col in cols:
    new_col = "output_{}".format(col)
    df[new_col] = df[col]*ref

result:
Gene          Ref        y        z     output_y    output_z
Sample
1         29.2877  29.0625  20.9868   851.173781  614.655102
2         29.9897  32.8044  25.8783   983.794115  776.082454
3         31.6335  34.7172  24.6268  1098.226546  779.031878


text:
Q: Nginx, Passenger setup with RVM: Permissions problems & 403 error I'm trying to deploy a rails application to a Ubuntu server running passenger and nginx. The server was operational for about a year on ruby 1.8, but I recently upgraded to 1.9.3 (this time using RVM) and as a result had to reinstall everything. I am currently running into two problems:
403 forbidden error
I was able to start the nginx server, but when I try to access the rails application, I receive a 403 Forbidden error that reads:
*2177 directory index of "/srv/myapp/public/" is forbidden

I did some looking around in the nxinx help docs and made sure that the /srv/myapp/ directory has the proper permissions. It is owned by a deploy user that owns the worker process of nginx, and is set chmod 755.
Nginx and Passenger installation problems
When I restart the nginx server, I also receive another error in indicating a problem with my phusion passenger installation:
Unable to start the Phusion Passenger watchdog because its executable (/usr/local/rvm/gems/ruby-1.9.3-p194/gems/passenger-3.0.13/agents/ PassengerWatchdog) does not exist. This probably means that your Phusion Passenger installation is broken or incomplete, or that your 'passenger_root' directive is set to the wrong value. Please reinstall Phusion Passenger or fix your 'passenger_root' directive, whichever is applicable.

I reinstall the passenger gem from my non-root (but sudo enabled) user, and reinstall nginx using rvmsudo passenger-install-nginx-module, but then I get this error repeatedly:
Your RVM wrapper scripts are too old. Please update them first by running 'rvm get head && rvm reload && rvm repair all'.

I performed the RVM reload (both with rvmsudo and without) and the error still appears. I tried performing the nginx install without rvmsudo, but ran into permissions problems because I couldn't edit the /opt/nginx/ directory (where I have nginx installed). Now I don't even get that far, because the installer fails to pass the required software check.
Background information
This is what my nginx process currently looks like:
  PID  PPID USER     %CPU    VSZ WCHAN  COMMAND
10174     1 root      0.0  18480 ?      nginx: master process /opt/nginx/sbin/nginx
29418 10174 deploy    0.3  18496 ?      nginx: worker process
29474 12266 1001      0.0   4008 -      egrep (nginx|PID)

My installation process
I've been documenting my installation process in a step-by-step guide for further reference. Please take a look to see how I have my new installation set up.

A: Try to reinstall all your environment following this guide and put your Rails application on /var/rails/your_app_dir with this permisions:
sudo chown deployment_user:www-data -R /var/rails/your_app_dir

Use this nginx.conf example to put all pieces together:
user  www-data;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    passenger_root /usr/local/rvm/gems/ruby-2.0.0-p195/gems/passenger-4.0.5;
    passenger_ruby /usr/local/rvm/wrappers/ruby-2.0.0-p195/ruby;

    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    log_format gzip '$remote_addr - $remote_user [$time_local]  '
                '"$request" $status $bytes_sent '
                '"$http_referer" "$http_user_agent" "$gzip_ratio"';

    access_log  logs/access.log  gzip  buffer=512k;

    server_names_hash_bucket_size  64;
    sendfile        on;
    #tcp_nopush     on;
    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    ##
    # Virtual Host Configs
    ##
    #include /opt/nginx/conf/*.conf;
    include /opt/nginx/conf/sites-enabled/*;
}


text:
Q: How to return redirect response from aiohttp.web server How do I return a response with HTTP redirect in an aiohttp server handler?

A: Documentation: http://aiohttp.readthedocs.io/en/stable/web_quickstart.html#redirects
async def handler(request):
    raise web.HTTPFound('/redirect')

The exception classes and their corresponding HTTP status codes: http://aiohttp.readthedocs.io/en/stable/web_quickstart.html#exceptions
  * 300 - HTTPMultipleChoices
  * 301 - HTTPMovedPermanently
  * 302 - HTTPFound
  * 303 - HTTPSeeOther
  * 304 - HTTPNotModified
  * 305 - HTTPUseProxy
  * 307 - HTTPTemporaryRedirect
  * 308 - HTTPPermanentRedirect


text:
Q: Trying to find the recursive function for a sequence of numbers. (Python)

n
F(n)

0
1

1
4

2
10

3
19

4
37

5
70

...
...

10
2062

Trying to determine the recursive function for he above sequence of numbers. Its also given that an even and an odd n are computed differently. Any help would be appreciated.
Edit: this is what I have so far:
def F(N):
    if N <= 0:
        return 1
    elif N % 2 == 0:
        return F(N-1) + (N-1) * 6
    else:
        return F(N-1) + (N) * 3

A: It could be this formula:
2n+1 + ⌊3n/2⌋ − 1
Here is JavaScript snippet that outputs the first 11 results:

function F(n) {
    return 2**(n+1) + ((3*n)>>1) - 1;
}

for (let n = 0; n <= 10; n++) {
    console.log(n, F(n));
}

Python:
def F(n):
    return 2**(n+1) + ((3*n)//2) - 1

for n in range(11):
    print(n, F(n))

Recurrence relationship
F0 = 1
Fn = 2Fn−1 − 3⌊(n+1)/2⌋ + 5

function F(n) {
    if (n == 0) return 1;
    return 2*F(n-1) - 3*((n+1)>>1) + 5;
}

for (let n = 0; n <= 10; n++) {
    console.log(n, F(n));
}

Python:
def F(n):
    if n == 0:
        return 1
    return 2*F(n-1) - 3*((n+1)//2) + 5

for n in range(11):
    print(n, F(n))


text:
Q: Do you have to clean your test data before feeding into an NLP model? This is a natural language processing related question.
Suppose I have a labelled train and unlabelled test set. After I have cleaned my train data(stopword, stem, punctuations etc), I use this cleaned data to build my model.
When fitting it on my test data, will I also have to clean the test data text using the same manner as I did with my train set? or should I not touch the test data completly.
Thanks!

A: Yes, you should do the same exact preprocessing on your training and testing dataset.

A: Yes, data cleaning is a mandatory step in machine learning or NLP problem.
So you have to always first clean our data and then only have to feed it to the model.
Reg. Test and train data cleaning --> you can clean both data there is no harm of doing this.


text:
Q: how to use php multidimensional array in jquery my php code
$classObject = new class_functions();
$city = $_REQUEST['city'];
$locations[] = $classObject->populate_locations($city);
echo "var result=".json_encode($locations);

my jquery
$("select[name='city']").change(function(){
    var city = $("select[name='city']").serialize();
    $.ajax(
    {
       type: "POST",
       url: "jquerycalls.php",
       data: city,
       beforeSend: function() {
       //alert("asdf");
       },
       success: function(data1) {
       // multidimensional array over here
       }

    });
});

The result i get from an alert in the success: part of jquery
var result=[[["Aabpara Market"],["AGHOSH"],["Akbar Town"],["Alipur Farash"],["Atomic Energy Employee Society"],["AWT"],["B-17"],["Bahria Town"],["Bani Gala"],["Bharakhu"],["Blue Area"],["British Homes Colony"],["Burma Town"],["CBR Town"],["Chak Shahzad"],["Chaklala Scheme 3"],["Civic Centre"],["D-12"],["D-13"],["D-16"],["D-17"],["D-18"],["Darussalam Co-Op Society"],["Defence Phase-2"],["Defence Phase-I"],["DHA Valley"],["Diplomatic Enclave"],["E-6"],["E-7"],["E-11"],["E-12"],["E-14"],["E-16"],["E-17"],["E-18"],["Engineers Cooperative Housing Society"],["F-10"],["F-11"],["F-13"],["F-15"],["F-16"],["F-17"],["F-5"],["F-6"],["F-7"],["F-8"],["Fateh Jang"],["G-5"],["G-6"],["G-7"],["G-8"],["G-9"],["G-10"],["G-11"],["G-13"],["G-14"],["G-15"],["G-16"],["G-17"],["Ghauri Town"],["Gulzar Housing Scheme"],["H-13"],["H-15"],["H-8"],["H-9"],["Humak"],["I-8"],["I-9"],["I-10"],["I-11"],["I-12"],["I-14"],["I-15"],["I-16"],["I-17"],["Islamabad Airport"],["Islamabad Cooperative Housing Society"],["J and K Zone-V"],["Jinnah Garden"],["Jinnah Super Market"],["Jinnah Town"],["Judicial Town"],["Kahuta"],["Korang Town"],["Margalla Town"],["Melody Market"],["Motorway City"],["Muree Expressway"],["National Police Foundation"],["Naval Anchorage"],["New Shakrial"],["O-9"],["Orchard Scheme"],["P.W.D Housing Scheme"],["PAF Tarnol"],["Pakistan Housing Society"],["Pakistan Town"],["PECHS"],["Rawal Town"],["River Garden"],["Roshan Pakistan Scheme"],["Sangjani"],["Sawan Garden"],["Shehzad Town"],["Sihala"],["Sohan Valley"],["Super Market"],["Tarlai"],["Top City 1"],["University Town"],["Wapda Town"],["Zero Point"],["Zone 5"]]]

How can i use the multidimensional array that is returned from the php code?

A: Easiest method is to use json_encode to turn it into a string that can be evaluated as a JavaScript object.
ie:

$locations[] = $classObject->populate_locations($city);
echo "var result = " . json_encode($locations) . ";" // valid JavaScript.

A: Change the PHP to:
echo json_encode($locations);

And then in the JQuery you can do:
success: function(data1) {
    var result = eval(data1);
    result[0][0];
}

You can access the other elements in the array the same way.


text:
Q: Steps involved to create a web service Can anyone please help me on below?
I have a WSDL and some XSD files used in it. I have to create the webservice and client to test them on local Tomcat machine.
What I have done so far:

*

*Using cxf in maven I have created the Java source files from WSDL.

*I have created a new implementation class for the interface (interface generated from WSDL file).

*Then created the WAR file of the above project and deployed on Tomcat. I can test them and they are running fine.
My question is if this is the right way of doing this ??
Also, how can I auto-create client Java sources to test this webservice?
Thanks

A: NetBeans has a wizard to create the client code for a given WSDL.

A: Create 3 maven projects:
1) Web service client project. Use CXF's wsdl2java codegen maven plugin to generate the client code. It works best to have the client turned into a nice, neat little jar you can include in other projects.
2) Web service server interface project. Same procedure, just have maven generate the server code.
3) A third project which includes the jar from #2, your code that implements the details and builds the war with all dependencies and the CXF configuration.
This is more or less how I did this very thing recently. CXF had an issue with its codegen plugin which forced me to generate the impl during the server code generation. That's no big deal. That meant there was a stub impl in jar #2. The way I got around that was I just created another bean that implemented the main service interface and had NetBeans generate all of the stubs for me again (and implemented each one).
It's especially helpful if you use NetBeans and its maven plugin during this.
EDIT: I saw that you are using Eclipse, not NetBeans. To each his own, but NetBeans is a lot easier to do this sort of thing with. In fact, NetBeans and maven play a lot nicer together than anything I've seen with eclipse and maven. NetBeans now can treat maven projects literally like its own native projects.


text:
Q: Ajax Handler 'onPagePosts' not found (October Newbie) EDIT:
I know there is no code. Largely because I do not know where this code is!
I'm curious as to /where/ I should start looking (based on the stacktraces that I have) within the backend.
I'm looking to solve my own problem, as it is, but am unsure where to begin.
Anyone who knows where AJAX code is stored for October? Or a simple diagram of what is being called where? It's a great system, I am just a slow learner of machine languages.
EDIT2:
 Code present in the layouts that throws an error
public function onPagePosts()
{
    $this->blogPosts->setProperty('pageNumber', post('page'));
    $this->pageCycle();
}

I have an AJAX script load more posts (sale items, articles, etc) as the user scrolls down the main page.
However, I did not build this (part of template) and am uncertain what exactly is wrong with the code. I have tried adding components to the proper pages, but am unsure where AJAX is calling from.
The code should be present on /home, and has been added to the default and home .htm and .conf.
The first few lines of the stacktrace (0-5) look like this:
Symfony\Component\Debug\Exception\FatalThrowableError: Call to undefined function is_countable() in /home/andmorew/public_html/modules/system/controllers/requestlogs/_referer_field.htm:1
Stack trace:
#0 /home/andmorew/public_html/modules/system/traits/ViewMaker.php(247): include()
#1 /home/andmorew/public_html/modules/system/traits/ViewMaker.php(97): Backend\Classes\Controller->makeFileContents('/home/andmorew/...', Array)
#2 /home/andmorew/public_html/modules/backend/widgets/form/partials/_field_partial.htm(7): Backend\Classes\Controller->makePartial('_referer_field....', Array)
#3 /home/andmorew/public_html/modules/system/traits/ViewMaker.php(247): include('/home/andmorew/...')
#4 /home/andmorew/public_html/modules/system/traits/ViewMaker.php(97): Backend\Classes\WidgetBase->makeFileContents('/home/andmorew/...', Array)
#5 /home/andmorew/public_html/modules/backend/widgets/Form.php(277): Backend\Classes\WidgetBase->makePartial('_field_partial....', Array)

The page should load the next "page" of results (viewed card-style by the user) but instead throws this error and does nothing.


text:
Q: finding the actual executable and path associated to a windows service using c# I am working on an installation program for one of my company's product. The product can be installed multiple times and each installation represents a separate windows service. When users upgrade or reinstall the program, I would like to look up the services running, find the services that belong to the product, and then find the executable file and its path for that service. Then use that information to find which one of the services the user wishes to upgrade/replace/install/etc. In my code example below, I see the service name, description, etc, but don't see the actual filename or path. Could someone please tell me what I'm missing? Thank you in advance!
The code I have is as follows:
        ServiceController[] scServices;
        scServices = ServiceController.GetServices();

        foreach (ServiceController scTemp in scServices)
        {
            if (scTemp.ServiceName == "ExampleServiceName")
            {
                Console.WriteLine();
                Console.WriteLine("  Service :        {0}", scTemp.ServiceName);
                Console.WriteLine("    Display name:    {0}", scTemp.DisplayName);

                ManagementObject wmiService;
                wmiService = new ManagementObject("Win32_Service.Name='" + scTemp.ServiceName + "'");
                wmiService.Get();
                Console.WriteLine("    Start name:      {0}", wmiService["StartName"]);
                Console.WriteLine("    Description:     {0}", wmiService["Description"]);
            }
        }

A: the interface has changed since @sidprasher answered, try:
var collection = searcher.Get().Cast<ManagementBaseObject>()
        .Where(mbo => mbo.GetPropertyValue("StartMode")!=null)
        .Select(mbo => Tuple.Create((string)mbo.GetPropertyValue("Name"), (string)mbo.GetPropertyValue("PathName")));

A: I might be wrong but the ServiceController class doesn't provide that information directly.
So as suggested by Gene - you will have to use the registry or WMI.
For an example of how to use the registry, refer to http://www.codeproject.com/Articles/26533/A-ServiceController-Class-that-Contains-the-Path-t
If you decide to use WMI (which I would prefer),
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Service");
ManagementObjectCollection collection = searcher.Get();

foreach (ManagementObject obj in collection)
{
    string name = obj["Name"] as string;
    string pathName = obj["PathName"] as string;
    ...
}

You can decide to wrap the properties you need in a class.


text:
Q: Solution of Helmholtz equation in three dimensional Let $k$ be a complex number such that
$$im \;k>0$$
the function
$$u(x,y):=\frac{1}{4\pi} \frac{e^{ik|x-y|}}{|x-y|}, x,y\in \mathbb{R^3}, x\neq y$$
is a solution of the Helmholtz equation
what i tried is :
the equation $\nabla^2 u(\vec x)+k^2u(\vec x)=0$
reduced to $\nabla^2 u+k^2 u=\frac1{r^2}\frac{\partial }{\partial r}\left(r^2\frac{\partial u}{\partial r}\right)+k^2u=0$ by using spherical symmetry
which can be $\frac{\partial^2}{\partial r^2}(r u)+k^2 (ru)=0 $
then $ru=C_1 \cos(kr)+C_2 \sin (kr)$ from here how to processed
thank you so much


text:
Q: I need to create a flat file from database table with fixed field length The export needs to be fixed length file that means each field will have predefined location and length like below:
Field A: 20 char

Field B: 15 char

Field C: 10 char

For following values:

Field A                 Field B                  Field C
Test 1                  Test 2                   Test 3
This is value 1         This is value 2          This is va

Flat file contents should be:

Test 1              Test 2         Test 3
This is value 1     This is value 2This is va

like Test 1 field have all 20 character including space up to the field Test 2 and same as Test 2 field have 15 character up to field Test 3 and Test 3 field also have 15 character up to end including spaces.
please tell me solution for this either i want to generate it from sql server database table or by c# coding  any way.

A: This code shows how to do it:
// 1 reading data from database
var data = new List<Tuple<string, string, string>>();

for (var i = 0; i < 10; i++)
{
    data.Add(new Tuple<string, string, string>(i.ToString(), (i + 1).ToString(), (i * 3000).ToString()));
}

// 2 writing data to file
foreach (var record in data)
{
    var str = string.Format("{0,-20}{1,-15}{2,-10}", record.Item1, record.Item2, record.Item3);

    Console.WriteLine(str); // <- or file.WriteLine(...)
}

Since I have no idea what are your model (or domain) objects, I have used a simple Tuple<string, string, string> instead.


text:
Q: TFS - How do I clone a project so I can rollback the original? I have a project in TFS that has been live for a year. In June we made our final release (we labelled the sources) before we began a massive 3 month overhaul during which the live site would not change.
Unfortunately we are now required to make a change to the live site and the codebase has changed significantly. What I want to do ideally is check-out by label the final release (June) into another folder and check that in to TFS to create another project. This way my team can work on both projects.
How can I best achieve this?

A: You should create a branch. This doesn't need to be in a new project. In fact it would be better if it wasn't, however depending on your folder structure keeping it in the same project might not be an option.
Right click on the root of the folder you want to branch. This should be the folder highest in your folder structure that contains all of the code you want to modify.
On the right click menu select "Branching and Merging" and then "Branch"
Choose a sensible location for the new branch.
In the dropdown select "Label" then choose the appropriate selection.

Hit branch. This will create a new branch from the label and you will be able use the new branch to modify your live code base


text:
Q: Is make no longer included with MinGW and/or MSYS? I installed MinGW and MSYS on my Windows 7 computer. I added C:\Program Files (x86)\MinGW\bin to my path. Commands such as gcc and g++ work, but make does not. I looked in the directory, and there is no executable called make, even though I installed all components. There is a file called mingw32-make. There are also other files prefixed with mingw32-, such as c++, g++, gcc, gcc-4.6.1, and gfortran. However, there is a make in C:\Program Files (x86)\MinGW\msys\1.0\bin.
If I open the MinGW Shell and type in make, make executes. However, it does not execute from the Windows terminal.
Is this intentional, or could I be missing other executables as well? Should I just add C:\Program Files (x86)\MinGW\msys\1.0\bin to my path?

A: Yup, add the msys bin directory to your path (after MinGW's bin dir). That's exactly what the MinGW shell does and why it works there.

A: Try gmake. Sometimes the GNU version of Make installs itself as gmake in order to distinguish from non-GNU Make.

A: C:\Program files\xxx has spaces in it! Since shell scripts are involved, spaces are significant and have to be escaped. Hence this path will not work with mingw. The documentation recommends to install MingW in C:\MingW.

A: MSYS Answer

*

*Open up your MSYS command terminal (is installed with latest MSYS).

*Type in "make".  It will say it doesn't exist.

*Accordingly with: https://packages.msys2.org/package/make, type in pacman -S make.  Type Y for yes.

*Make is now installed!

*Type "make", and it ask you to specify input files.

*Probably only call it from the MSYS command terminal.

*Pin MSYS command terminal to taskbar by right-clicking its taskbar icon while it's running.


text:
Q: Can anybody confirm a successful flash of open gapps on genymotion emulator While not succeeding in flashing gapps on genymotion emulator I would like to check if there is any known case that someone actually managed to install gapps on genymotion emulator.
Configuration:
Windows 10, 64 AMD proc
Genymotion 2.8.1
Oracle VM VirtualBox 5.1.14
Devices I tried varied: 5.1. 6.0, 7.0 custom phones, Nexus 6P all included in genymotion.
I used gapps found at http://opengapps.org/.
I used the following archives: x86 platform,
 android 5.1, 6.0, 7.0,
 variants pico, nano, micro, mini, full, stock
 archives from 2nd february, 4th february, and some from 5th february
I have tried all possible combinations from above. Not even a single one works.
So, I need confirmation that it is even possible to flash this gapps archives.
Anyone?

A: I can confirm success using both 6.0.0 and 7.0.0 Custom Tablet devices AND the equivalent nano version of opengapps.
Here is my setup:

*

*Genymotion 2.8.0

*Open Gapps 20170613 x86 (not x86_64) NANO variant

*Custom Tablet devices (6.0.0 or 7.0.0) with varying resolutions

*MacOS Sierra

*VirtualBox 5.1.16

I "flashed" it the normal way by dragging and dropping the opengapps zip file onto the running Genymotion window.
Of note is that 6.0.0 does seem to be more reliable/repeatable in my testing. I can't comment on whether or not it works with Phone devices as I've not tried it.


text:
Q: When running "serve -s build" to serve my React build folder locally, no content renders In my browser console, I get these errors:
Uncaught SyntaxError: Unexpected token '<'     2.e1e7f2e0.chunk.js:1
Uncaught SyntaxError: Unexpected token '<'     main.c36879cd.chunk.js:1
Manifest: Line: 1, column: 1, Syntax error.    :5000/React-Portfolio/manifest.json:1*
My app was built with create-react-app.  It runs fine locally when I'm not running from the build folder.  It has no back end.
Thoughts?

A: I needed to remove "homepage" from my package.json.


text:
Q: Passing 2 dimensional array into a function using pointer C Here is an example of my code (magic square):
    int magicsqr(int *magic,int size);
    int main()
    {
        int size,*ptr;
        char stop;
        repeat:
        printf("Please Enter an Odd number for the magic square(3 or greater):\n");
        scanf("%d",&size);
        fflush(stdin);
        ptr=(int*)calloc(size*size,sizeof(int));
        while((size%2==0)||(size<=1))
        {
            printf("U entered a wrong number.\n");
            repeat1:
            printf("Do you wish to continue?(Y or N)\n");
            scanf("%c",&stop);
            fflush(stdin);
            if(stop=='Y'||stop=='y')
                goto repeat;
            else if(stop=='N'||stop=='n')
                printf("Thanks for trying our beta program.\n");
            else
            {
                printf("U entered a wrong character.\n");
                goto repeat1;
            }
        }
        magicsqr(ptr,size);
        return 0;
    }
    int magicsqr(int *magic,int size)
    {
        int i,j,num;
        i=1;
        j=(size+1)/2;
        for(num=1;num<=size*size;num++)
        {
            *(magic+i*size+j)=num;
            if(num%size==0){
                i++;
                continue;
                }
            if(i==1)
               i=size;
            else
               i--;
            if(j==size)
               j=1;
            else
               j++;
        }
        for(i=1;i<=size;i++)
        {
            printf("\n");
            for(j=1;j<=size;j++)
                printf("%d\t",*(magic+i*size+j));
        }
}

so i got few questions that confused me ..
1- As far as i know Arr[i][j]==*(Arr[i]+j)
so why only this works : *(magic+i*size+j).
2- I read a lot in passing 2 dimensional array into a function using pointers but somehow i am still confused, how to represent a 2D array or more in this code.
3- I am still a beginner in programming, so i wish if you could explain a little.

*

*Thanks a lot guys, finally i got it worked using pointer to pointer and array of pointers.

A:
1- Ass far as i know Arr[i][j]==*(Arr[i]+j) so why only this works :
  (magic+isize+j).

Don't cast result of calloc when yo are doing
ptr = calloc(size*size,sizeof(int));

It's allocating 1D array (or ptr is 1D array pointer ) so (magic+isize+j) this is working. it's just conversion of 2D index to 1D to access array.

2- I read a lot in passing 2 dimensional array into a function using
  pointers but somehow i am still confused, how to represent a 2D array
  or more in this code.

For passing 2 dimensional array into a function have look on correct way of passing 2D array.

A: This is not a 2D array at all, but a one dimensional array which is used to imitate a 2D array.
So, the memory allocation is
ptr=calloc(size*size,sizeof(int));

This is an allocation for a 1D array of (size * size) elements
Data is accessed for this array like this
*(magic+i*size+j)=num;

Each element position is calculated by from the base index by adding the no of rows * i + j.
These are called flat arrays.

A: Finally got it, thanks for helping.
int main()
{
char stop;
int i,j,size,num;
repeat:
printf("Please Enter an Odd number for the magic square(3 or greater):\n");
scanf("%d",&size);
fflush(stdin);
int **magic=(int**)malloc(size*sizeof(int*));   //size = row
if((size%2==0)||(size<=1))
{
    printf("U entered a wrong number.\n");
    repeat1:
    printf("Do you wish to continue?(Y or N)\n");
    scanf("%c",&stop);
    fflush(stdin);
    if(stop=='Y'||stop=='y')
        goto repeat;
    else if(stop=='N'||stop=='n')
        printf("Thanks for trying our beta program.\n");
    else
    {
        printf("U entered a wrong character.\n");
        goto repeat1;
    }
}

for(i=0;i<size;i++)
    magic[i]=(int*)calloc(size,sizeof(int));
for(i=0;i<size;i++)
{
    printf("\n");
    for(j=0;j<size;j++)
        printf("%d\t",*(magic[i]+j));
}
i=0;
j=(size)/2;;
for(num=1;num<=size*size;num++)
{
    magic[i][j]=num;
    if(num%size==0){
        i++;
        continue;
        }
    if(i==0)
       i=size-1;
    else
        i--;
    if(j==size-1)
        j=0;
    else
        j++;
}
for(i=0;i<size;i++)
{
    printf("\n");
    for(j=0;j<size;j++)
        printf("%d\t",*(magic[i]+j));
}
return 0;
}


text:
Q: Is there a way to set a default parameter equal to another parameter value? For example, I have a basic method that will return a list of permutations.
import itertools
def perms(elements, set_length=elements):
    data=[]
    for x in range(elements):
        data.append(x+1)
    return list(itertools.permutations(data, set_length))

Now I understand, that in its current state this code won't run because the second elements isn't defined, but is there and elegant way to accomplish what I'm trying to do here? If that's still not clear, I want to make the default setLength value equal to the first argument passed in. Thanks.

A: Because of the way Python handles bindings and default parameters...
The standard way is:
def perms(elements, setLength=None):
    if setLength is None:
        setLength = elements

And another option is:
def perms(elements, **kwargs):
    setLength = kwargs.pop('setLength', elements)

Although this requires you to explicitly use perms(elements, setLength='something else') if you don't want a default...

A: You should do something like :
def perms(elements,setLength=None):
    if setLength is None:
        setLength = elements

A: No, function keyword parameter defaults are determined when the function is defined, not when the function is executed.
Set the default to None and detect that:
def perms(elements, setLength=None):
    if setLength is None:
        setLength = elements

If you need to be able to specify None as a argument, use a different sentinel value:
_sentinel = object()

def perms(elements, setLength=_sentinel):
    if setLength is _sentinel:
        setLength = elements

Now callers can set setLength to None and it won't be seen as the default.

A: Answer 1:
The solution from above looks like this:
def cast_to_string_concat(a, b, c=None):
  c = a if c is None else c

  return str(a) + str(b) + str(c)

While this approach will solve a myriad of potential problems, (and maybe yours)! I wanted to write a function where a possible input for variable "c" is indeed the singleton None, so I had to do more digging.
To explain that further, calling the function with the following variables:
A='A'
B='B'
my_var = None

Yields:
cast_to_string_concat(A, B, my_var):
>>>'ABA'

Whereas the user might expect that since they called the function with three variables, then it should print the three variables, like this:
cast_to_string_concat(A, B, my_var):
>>> 'ABNone' # simulated and expected outcome

So, this implementation ignores the third variable, even when it was declared, so this means the function no longer has the ability to determine whether or not variable "c" was defined.
So, for my use case, a default value of None would not quite do the trick.
For the answers that suggest this solution, read these:

*

*Is there a way to set a default parameter equal to another parameter value?

*Python shortcut for variable default value to be another variable value if it is None

*Function argument's default value equal to another argument

*What is the pythonic way to avoid default parameters that are empty lists?

But, if that doesn't work for you, then maybe keep reading!

A comment in the first link above mentions using a _sentinel defined by object().
So this solution removes the use of a None, and replaces it with the object() through using the implied private sentinel.

Answer 2:
_sentinel = object()
def cast_to_string_concat(a, b, c=_sentinel):
  c = a if c == _sentinel else c

  return str(a) + str(b) + str(c)

A='A'
B='B'
C='C'

cast_to_string_append(A,B,C)
>>> 'ABC'

cast_to_string_concat(A,B)
>>> 'ABA'

So this is pretty awesome! It correctly handles the above edge case! See for yourself:

A='A'
B='B'
C = None

cast_to_string_concat(A, B, C)
>>> 'ABNone'

So, we're done, right? Is there any plausible way that this might not work? Hmm... probably not! But I did say this was a three-part answer, so onward! ;)

For the sake of completeness, let's imagine our program operates in a space where every possible scenario is indeed possible. (This may not be a warranted assumption, but I imagine that one could derive the value of _sentinel with enough information about the computer's architecture and the implementation of the choice of the object. So, if you are willing, let us assume that is indeed possible, and let's imagine we decide to test that hypothesis referencing _sentinel as defined above.

_sentinel = object()
def cast_to_string_concat(a, b, c=_sentinel):
  c = a if c == _sentinel else c

  return str(a) + str(b) + str(c)

A='A'
B='B'
S = _sentinel

cast_to_string_append(A,B,S)
>>> 'ABA'

Wait a minute! I entered three arguments, so I should see the string concatenation of the three of them together!

*queue entering the land of unforeseen consequences*
I mean, not actually. A response of: "That's negligible edge case territory!!" or its ilk is perfectly warranted.
And that sentiment is right! For this case (and probably most cases) this is really not worth worrying about!
But if it is worth worrying about, or if you just want the mathematical satisfaction of eliminating all edge cases you're aware of ... onward!

Exercise left to reader:

Deviating from this technique, you can directly assert c=object(), however, in honesty, I haven't gotten that way to work for me. My investigation shows c == object() is False, and str(c) == str(object()) is also False, and that's why I'm using the implementation from Martin Pieters.

Okay, after that long exercise, we're back!
Recall the goal is to write a function that could potentially have n inputs, and only when one variable is not provided - then you will copy another variable in position i.
Instead of defining the variable by default, what if we change the approach to allow an arbitrary number of variables?
So if you're looking for a solution that does not compromise on potential inputs, where a valid input could be either None, object(), or _sentinel ... then (and only then), at this point, I'm thinking my solution will be helpful. The inspiration for the technique came from the second part of Jon Clements' answer.

Answer 3:
My solution to this problem is to change the naming of this function, and  wrap this function with a a function of the previous naming convention, but instead of using variables, we use *args. You then define the original function within the local scope (with the new name), and only allow the few possibilities you desire.
In steps:

*

*Rename function to something similar

*Remove the default setup for your optional parameter

*Begin to create a new function just above and tab the original function in.

 def cast_to_string_concat(*args):

*Determine the the arity of your function - (I found that word in my search... that is the number of the parameters passed into a given function)

*Utilize a case statement inside that determines if you entered a valid number of variables, and adjust accordingly!

def cast_to_string_append(*args):

    def string_append(a, b, c):
        # this is the original function, it is only called within the wrapper
        return str(a) + str(b) + str(c)

    if len(args) == 2:
        # if two arguments, then set the third to be the first
        return string_append(*args, args[0])

    elif len(args) == 3:
        # if three arguments, then call the function as written
        return string_append(*args)

    else:
        raise Exception(f'Function: cast_to_string_append() accepts two or three arguments, and you entered {len(args)}.')

# instantiation

A='A'
B='B'
C='C'
D='D'

_sentinel = object()
S = _sentinel

N = None

""" Answer 3 Testing """

# two variables

cast_to_string_append(A,B)

>>> 'ABA'

# three variables

cast_to_string_append(A,B,C)

>>> 'ABC'

# three variables, one is _sentinel

cast_to_string_append(A,B,S)

>>>'AB<object object at 0x10c56f560>'

# three variables, one is None

cast_to_string_append(A,B,N)

>>>'ABNone'

# one variable

cast_to_string_append(A)

>>>Traceback (most recent call last):
>>>  File "<input>", line 1, in <module>
>>>  File "<input>", line 13, in cast_to_string_append
>>>Exception: Function: cast_to_string_append() accepts two or three arguments, and you entered 1.

# four variables

cast_to_string_append(A,B,C,D)

>>>Traceback (most recent call last):
>>>  File "<input>", line 1, in <module>
>>>  File "<input>", line 13, in cast_to_string_append
>>>Exception: Function: cast_to_string_append() accepts two or three arguments, and you entered 4.

# ten variables

cast_to_string_append(0,1,2,3,4,5,6,7,8,9)

>>>Traceback (most recent call last):
>>>  File "<input>", line 1, in <module>
>>>  File "<input>", line 13, in cast_to_string_append
>>>Exception: Function: cast_to_string_append() accepts two or three arguments, and you entered 10.

# no variables

cast_to_string_append()

>>>Traceback (most recent call last):
>>>  File "<input>", line 1, in <module>
>>>  File "<input>", line 13, in cast_to_string_append
>>>Exception: Function: cast_to_string_append() accepts two or three arguments, and you entered 0.

""" End Answer 3 Testing """

So, in summary:

*

*Answer 1 - the simplest answer, and works for most cases.

def cast_to_string_concat(a, b, c=None):
  c = a if c is None else c

  return str(a) + str(b) + str(c)

*

*Answer 2 - use if None does not actually signify an empty parameter by switching to object() , through _sentinel .

_sentinel = object()
def cast_to_string_concat(a, b, c=_sentinel):
  c = a if c == _sentinel else c

  return str(a) + str(b) + str(c)

*

*Answer 3 seeks out a general solution utilizing a wrapper function with arbitrary arity using *args, and handles the acceptable cases inside:

def cast_to_string_append(*args):

    def string_append(a, b, c):
        # this is the original function, it is only called within the wrapper
        return str(a) + str(b) + str(c)

    if len(args) == 2:
        # if two arguments, then set the third to be the first
        return string_append(*args, args[0])

    elif len(args) == 3:
        # if three arguments, then call the function as written
        return string_append(*args)

    else:
        raise Exception(f'Function: cast_to_string_append() accepts two or three arguments, and you entered {len(args)}.')

Use what works for you! But for me, I'll be using Option 3 ;)


text:
Q: Error "undefined is not an object (evaluating 'RNGestureHandlerModule.State')" when using react-native-firebase with react-navigation I met the error below when I using react-native-firebase with react-navigation(and also react-native-gesture-handler)

undefined is not an object (evaluating 'RNGestureHandlerModule.State')
I followed the guide of https://rnfirebase.io/docs/v5.x.x/installation/ios
below is call stack of error screen.
<unknown>
GestureHandler.js: 54:37
<unknown>
Swipeable.js: 11
<unknown>
index.js:1
<unknown>
StackViewLayout.js:19
<unknown>
StackView.js:4
<unknown>
createStackNavigator.js:3

here is my package.json
"dependencies": {
  "axios": "^0.18.0",
  "react": "16.6.3",
  "react-native": "0.57.8",
  "react-native-dialog": "^5.5.0",
  "react-native-firebase": "^5.2.0",
  "react-native-gesture-handler": "^1.0.12",
  "react-native-safari-view": "^2.1.0",
  "react-native-vector-icons": "^6.1.0",
  "react-navigation": "^3.0.9",
  "react-redux": "^6.0.0",
  "redux": "^4.0.1",
  "redux-logger": "^3.0.6",
  "redux-promise-middleware": "^5.1.1",
  "redux-thunk": "^2.3.0" }

here is my source code using react-navigation
const AppStack = createBottomTabNavigator({
  Main: {
    screen: Main
  },
  Setting: {
    screen: Setting
  }
})
const AuthStack = createStackNavigator({
  Login: {
    screen: Login
  },
  Join: {
    screen: Join
  },
  JoinDetails: {
    screen : JoinDetails
  }
})
const AppContainer = createAppContainer(createSwitchNavigator(
{
  AuthLoading: AuthLoadingScreen,
  App: AppStack,
  Auth: AuthStack
},
{
  initialRouteName: 'AuthLoading',
}))

and I did below command at project root

react-native link react-native-gesture-handler

if I comment createStackNavigator in javascript source code, error was disappeared.
could you anyone help me? I've struggled with this issue during a few days.

A: try to run this commands :

*

*npm install

*npm install --save react-navigation

*npm install --save react-native-gesture-handler

*react-native link


text:
Q: PowerShell New-Item will create the directory where the script is and not in the path specified I am writing a PowerShell script and I need to create a directory in C:\Users
My script is located on the desktop.
My line of script to create the directory is this:
New-Item -ItemType "directory" -Force -Path "C:Users\username\scripts\documents"

It instead creates the directory:
C:\Users\username\Desktop\Users\username\scripts\documents

How can I make the new directory directly in C:\Users?

A: You are missing a backslash \ after the path root (the drive letter):
New-Item -ItemType "directory" -Force -Path "C:\Users\username\scripts\documents"

See also: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.ispathrooted?view=net-5.0

A rooted path is file path that is fixed to a specific drive or UNC
path; it contrasts with a path that is relative to the current drive
or working directory. For example, on Windows systems, a rooted path
begins with a backslash (for example, \Documents) or a drive letter
and colon (for example, C:Documents).
Note that rooted paths can be either absolute (that is, fully
qualified) or relative. An absolute rooted path is a fully qualified
path from the root of a drive to a specific directory. A relative
rooted path specifies a drive, but its fully qualified path is
resolved against the current directory. The following example
illustrates the difference.

$relative1 = "C:Documents"
$relative2 = "\Documents"
$absolute = "C:\Documents"

foreach ($p in $relative1,$relative2,$absolute) {
    "'$p' is Rooted: {0}" -f [System.IO.Path]::IsPathRooted($p)
    "Full path of '$p' is: {0}" -f [System.IO.Path]::GetFullPath($p)
}

(I did not include the [System.IO.Path]::IsPathFullyQualified() call in the linked example, because it is not included in Windows PowerShell 5.1)


text:
Q: Back transform dummy columns into one variable Example:
my_diamonds <- diamonds %>% fastDummies::dummy_cols(select_columns = "color", remove_selected_columns = T)
my_diamonds %>% glimpse

Looks like this:
Observations: 53,940
Variables: 16
$ carat   <dbl> 0.23, 0.21, 0.23, 0.29, 0.31, 0.24, 0.24, 0.26, 0.22, 0.23, 0.30, 0.23, 0.22, 0.31, 0.20, 0.32, 0.30, 0.30, 0.30, 0.30, 0.30, 0.23, 0.2…
$ cut     <ord> Ideal, Premium, Good, Premium, Good, Very Good, Very Good, Very Good, Fair, Very Good, Good, Ideal, Premium, Ideal, Premium, Premium, I…
$ clarity <ord> SI2, SI1, VS1, VS2, SI2, VVS2, VVS1, SI1, VS2, VS1, SI1, VS1, SI1, SI2, SI2, I1, SI2, SI1, SI1, SI1, SI2, VS2, VS1, SI1, SI1, VVS2, VS1…
$ depth   <dbl> 61.5, 59.8, 56.9, 62.4, 63.3, 62.8, 62.3, 61.9, 65.1, 59.4, 64.0, 62.8, 60.4, 62.2, 60.2, 60.9, 62.0, 63.4, 63.8, 62.7, 63.3, 63.8, 61.…
$ table   <dbl> 55, 61, 65, 58, 58, 57, 57, 55, 61, 61, 55, 56, 61, 54, 62, 58, 54, 54, 56, 59, 56, 55, 57, 62, 62, 58, 57, 57, 61, 57, 57, 57, 59, 58,…
$ price   <int> 326, 326, 327, 334, 335, 336, 336, 337, 337, 338, 339, 340, 342, 344, 345, 345, 348, 351, 351, 351, 351, 352, 353, 353, 353, 354, 355, …
$ x       <dbl> 3.95, 3.89, 4.05, 4.20, 4.34, 3.94, 3.95, 4.07, 3.87, 4.00, 4.25, 3.93, 3.88, 4.35, 3.79, 4.38, 4.31, 4.23, 4.23, 4.21, 4.26, 3.85, 3.9…
$ y       <dbl> 3.98, 3.84, 4.07, 4.23, 4.35, 3.96, 3.98, 4.11, 3.78, 4.05, 4.28, 3.90, 3.84, 4.37, 3.75, 4.42, 4.34, 4.29, 4.26, 4.27, 4.30, 3.92, 3.9…
$ z       <dbl> 2.43, 2.31, 2.31, 2.63, 2.75, 2.48, 2.47, 2.53, 2.49, 2.39, 2.73, 2.46, 2.33, 2.71, 2.27, 2.68, 2.68, 2.70, 2.71, 2.66, 2.71, 2.48, 2.4…
$ color_D <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, …
$ color_E <int> 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, …
$ color_F <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, …
$ color_G <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, …
$ color_H <int> 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, …
$ color_I <int> 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, …
$ color_J <int> 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, …

Is there an out of the box, non custom function way to get my_diamonds back into it's original form with a single column for 'color'?

A: You can use pivot_longer :
library(dplyr)

tidyr::pivot_longer(my_diamonds, cols = starts_with('color'),
                    names_to = 'color',
                    names_pattern = '.*_(.*)') %>%
       filter(value == 1) %>%
       select(-value)

# A tibble: 53,940 x 10
#   carat cut       clarity depth table price     x     y     z color
#   <dbl> <ord>     <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl> <chr>
# 1 0.23  Ideal     SI2      61.5    55   326  3.95  3.98  2.43 E
# 2 0.21  Premium   SI1      59.8    61   326  3.89  3.84  2.31 E
# 3 0.23  Good      VS1      56.9    65   327  4.05  4.07  2.31 E
# 4 0.290 Premium   VS2      62.4    58   334  4.2   4.23  2.63 I
# 5 0.31  Good      SI2      63.3    58   335  4.34  4.35  2.75 J
# 6 0.24  Very Good VVS2     62.8    57   336  3.94  3.96  2.48 J
# 7 0.24  Very Good VVS1     62.3    57   336  3.95  3.98  2.47 I
# 8 0.26  Very Good SI1      61.9    55   337  4.07  4.11  2.53 H
# 9 0.22  Fair      VS2      65.1    61   337  3.87  3.78  2.49 E
#10 0.23  Very Good VS1      59.4    61   338  4     4.05  2.39 H
# … with 53,930 more rows

A: A base R option:
cols <- sub("color_", "", grep("^color_", names(my_diamonds), value=TRUE)); cols
[1] "D" "E" "F" "G" "H" "I" "J"

my_diamonds$color <- cols[
     apply(my_diamonds[,grep("^color_", names(my_diamonds))], 1, which.max]

all(my_diamonds$color==diamonds$color)
#[1] TRUE

Or using the much quicker max.col (thanks @chinsoon12):
my_diamonds$color <- cols[max.col(my_diamonds[,grep("^color_", names(my_diamonds))])]

all(my_diamonds$color == diamonds$color)
#[1] TRUE

A: Another option using max.col:
col <- "color"
my_diamonds$color <- my_diamonds %>%
    select(starts_with(col)) %>%
    {gsub(paste0(col,"_"), "", names(.))[max.col(.)]}


text:
Q: AngularJS templateUrl not loading templates in Internet Explorer 7 As per the title, when I use templateUrl inside of my $routeProvider, the template and controller do not load.
In my config, I have:
.when('/thing/:thingId', {
    templateUrl: 'views/things.html',
    controller: 'ThingController'
})

If I change that to
.when('/thing/:thingId', {
    template: '
Hello you!
',
    controller: 'ThingController'
})

It works. I'm using AngularJS 1.2.2.
Ideas I've tried:

*

*I've tried adding the template to a script tag which still doesn't work. I get no errors and, since it's on IE, no debug messages. I've got an alert that fires the moment my controller is instantiated. This doesn't happen in IE 7 (and probably 8).

*Added html5shiv, json3 shim, angular-ui's ie shiv, and I've created all the common document elements.

*I've got the following at the top of my site:

Each idea I've tried works in Chrome and IE10 emulating IE7 (the entire thing works in IE10 emulating IE7, just not real IE7).
I'll try to put up an example to demonstrate the problem but wanted to pose the question first.
EDIT In hindsight I've realized a plunkr example is silly because plunkr doesn't run in IE7 and this code works in things that DO run plunkr. Anyway, I created it so that code can be viewed.
http://plnkr.co/edit/Yswo2QzcwfpzT2PXJV8m

A: For Angular versions 1.2+, you will need to inject $sce and wrap your resourceUrl with $sce.trustAsResourceUrl('...') for IE7 and below, giving you the following in your directive:
...
templateUrl: $sce.trustAsResourceUrl('/Resource/That/YouTrust.html')
...

reference
you may also need to monkey patch document.querySelector by doing something like the following (if you are using jQuery):
if (!document.querySelector)
{
    document.querySelector = function (selector)
    {
        return $(selector).get(0);
    };
}

otherwise angular will blow up here (from Angular source):
var active = !!(document.querySelector('[ng-csp]') ||
              document.querySelector('[data-ng-csp]'));

also ensure you are following the Angular IE Compatibility Reference, specifically adding id="ng-app" and not using element directives.
Do all of this and IE7 might work ;)
Edit: fixing the reference URL

A: It appears that AngularJS from 1.2 onward, does not support IE7. Fixed this issue by switching to AngularJS 1.1.5.


text:
Q: How do I connect my wireless device to my Windows 7 wireless connection? https://blogs.ncl.ac.uk/isg/?p=437
I can do all this and see my network ssid being broadcast.
But I cannot figure out what to put for IP addresses.  I have not changed anything in the sharedaccess key in the registry.  Everything should be default.
I tried 192.168.137.055 just to see if that ip would work, as the 192.168.137.1 is the default access point gateway (from my research anyway).
It's a Nintendo DSi LX, if that matters.  Here is what I put into the device after my SSID is found:
192.168.137.55
255.255.255.0
192.168.137.1
I used no key in my creation of the network on my Windows 7 PC (pro version), so I didn't put anything for security in the device.
The hotspot is running.  My "server" can browse the Internet.  I just can't get the "tethered" device to connect.
What do I do?
Thanks.
I would just use the wireless router in my house, but the DSi XL only does WEP, which I do not use (WPA-2).

A:
I would just use the wireless router in my house, but the DSi XL only does WEP, which I do not use (WPA-2).

It's been a while since I've connected a DS to a network, but if the process hasn't changed it should be simple enough to do. There should be an option in the Advanced Setup under Connection Settings to select Connection 4, 5, or 6. Those connections should allow you to connect to WPA networks, though I remember there being issues if you used special characters in your WPA passkey.
As for the method you're trying to do, I'd recommend that if you have Windows Firewall enabled, try disabling it momentarily or creating a rule to allow inbound connections. This can be done through the file path "Control Panel\All Control Panel Items\Windows Firewall". Heading into the advanced settings from that page will allow you to create inbound rules.

A: You have to use an IP address inside the range ICS supports, not inside the range your LAN supports. The tethered device is not on your LAN. I believe it uses 192.168.0.0/24 by default. Ideally, the device would just use DHCP to get its own IP address automatically.


text:
Q: When a user deletes his/her post from Stack Overflow, is it completely removed? When a user deletes his/her post from SO, is it completely removed?
I think the post should remain in SO.  Users generally remove their downvoted questions and answers to save their reputations, but a deleted post might be a genuine answer with a good solution, or a good question; thus, it should not be deleted from SO entirely.
The post should remain on SO without any info about the user who asked it.  In this way, that post remains available for discussion.

A: No, the question is just marked as "deleted". 10k users can still view it and vote to undelete it.
Also, normal users cannot directly delete questions with voted-up answers.


text:
Q: How do I make an html form appear in a box on top of another html page So I am currently using google picker, and once the user selects the proper file I want a much smaller html box to appear on top of the picker.
 // A simple callback implementation.
function pickerCallback(data) {
  if (data.action == google.picker.Action.PICKED) {
    var fileId = data.docs[0].id;
    window.document.location.href = 'metadata.html';
 }
}

Obviously the last line is wrong I was just testing. The issue's that the picker is disappearing once the action is performed and I don't know how to format the html to make it appear as a smaller window, i think its a container but I dont know. It makes sense as to why I just don't know a way around it. I want to mention that the other html is in a separate file and looks like this.
<!DOCTYPE html>

    <base target="_top">

<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
  <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/themes/cupertino/jquery-ui.css">

Department ID: <select id = "drop" style="margin-bottom: 0.25cm;">
  <option value="#001">#001---Law</option>
  <option value="#002">#002---Sales</option>
  <option value="#003">#003---Tech</option>
</select>
<input
  type="button"
  style="position:relative; left:60px;"
  id="set_dep"
   value="Set Department"
   onclick="     google.script.run.description(document.getElementById('drop').value)"
  />

Date:<input type="text" id = "date" style="margin-left: 60px; margin-bottom: 0.25cm;"/>
 <input
  type="button"
  id="set_date"
  value="Set Date"
  onclick="   google.script.run.submitDates(document.getElementById('date').value)"
  />

Additional Tag: <input type="text" id="metadata" style="overflow: hidden;  padding-right: .5em; margin-bottom: 0.25cm;" onkeydown="if(event.keyCode == 13) document.getElementById('set_tag').click();"/>
<input
    type="button"
    id="set_tag"
    value="Set Tag"
     onclick="google.script.run.submitDates(document.getElementById('metadata').value    ); clearFields();"
    />

  <input
    type="button"
    value="Close"
    onclick="google.script.host.close()"
   />
  <input
  type="button"
  value="Clear"
  onclick="google.script.run.clear()"
  />

Basically i just want this to appear as a little pop-up that can receive users information. Ignore the methods as those are fine and were used for a previous project. I'm sure it's super obvious but im not used to working with Javascript.
Thanks everyone.

A: Opening a Bootstrap modal with JQuery can be done with the following
$('#myModal').modal('toggle');
$('#myModal').modal('show');
$('#myModal').modal('hide');

Example
function pickerCallback(data) {
  if (data.action == google.picker.Action.PICKED) {
    var fileId = data.docs[0].id;
    $('#myModal').modal('show')
 }
}

Source


text:
Q: Symfony2 FosUser : CSRF token issue I use the authentification system provided by FOSUser bundle
Everything was doing fine but recently when clicking on :
     <form action="{{ path('fos_user_registration_register') }}" method="post">
                           <button class="btn btn-small btn-success" type="submit">S'inscrire</button>
     </form>

that generated the error: The CSRF token is invalid. Please try to resubmit the form.
none of the view nor controller of FOSUserBundle have being modified...!?
How come this happened and how can this be fixed?

A: Make sure your twig templates have
{{form_rest(form)}}

or your php files have
<?php echo $view['form']->rest($form) ?>

if you specify the individual fields


text:
Q: quickly find a subfolder So i have a piece of code that scans through the subfolders contained in a source folder. I know the first part of each subfolder name (or at least, this is a known variable i scroll through), the remaining part is an "issue number" that determines which design is most recent. Inside these subfolders are the files that i then copy into some other directory, for further use.
The trouble is i am using a For loop to scan through EVERY subfolder, until it finds the relevant start section of the folder name, and then recording the second half to compare.
This takes considerable time (there are something in the region of 21,000 subfolders and the list grows every day) and i was hoping to find a quicker way of achieving the same end.
Is there such a thing or do i just grit my teeth and bear it!?
If it helps, the format of the folders is always the same, eg DP0123456_00_01_003, currently i'm searching for the DP0123456 part and recording the rest as a comparator. Below is what i am using so far...
Sub Build_Issue_list()
    Dim objFSO As FileSystemObject, objFolder As Folder, objSub As Folder
    Dim MajArr(99) As String, MinArr(99) As String, DoArr(999) As String
    Dim FullArr(99) As String
    Dim IssCnt As Integer

    Dim StrSourceFolder As String

    Dim TopIssue As String
    Dim TmpStr As String
    Dim DpNo As String

    Dim dpCount As Integer, DpScroll As Integer

    Dim StartRow As Integer, StartCol As Integer

    Dim FoundIt As Boolean
    Dim I As Integer
    IssErr = False

    'default to start looking for list is "a5"
    StartRow = 5
    StartCol = 1
    dpCount = GetTableRows(StartRow, StartCol)
    'MsgBox DpCount

    For DpScroll = StartRow To dpCount
        DpNo = Cells(DpScroll, StartCol)

        'THIs BLOCK TAKES A DPNO AND FINDS THE HIGHEST ISSUE OF IT FOUND.
        '''''''''''''''''''''''''''''''''''''''''''''''''
        Set objFSO = New FileSystemObject 'creates a new File System Object reference
        Set objFolder = objFSO.getfolder(StrSourceFolder) 'get the folder
        IssCnt = 0
        For Each objSub In objFolder.Subfolders 'for every sub-folder in the folder...
            'see if the DPno matches
            If objSub.Name Like DpNo & "*" Then
                'note that one instance is found
                FoundIt = True
                'record the rest as 3 seperate parts
                TmpStr = Replace(objSub.Name, DpNo & "_", "")
                MajArr(IssCnt) = Left(TmpStr, 2)
                MinArr(IssCnt) = Mid(TmpStr, 4, 2)
                DoArr(IssCnt) = Right(TmpStr, 3)
                'combine these for later
                FullArr(IssCnt) = MajArr(IssCnt) & MinArr(IssCnt) & DoArr(IssCnt)

                'MsgBox DPno & vbCrLf & TmpStr & vbCrLf & MajArr(IssCnt) & vbCrLf & MinArr(IssCnt) & vbCrLf & DoArr(IssCnt) & vbCrLf & FullArr(IssCnt)
                IssCnt = IssCnt + 1
            ElseIf FoundIt = True Then
                'assuming folders are scanned in order? if a non-matching one is subsequently found then stop looking
                FoundIt = False
                Exit For
            End If
        Next
        'temporarily stick screenupdating on to give user some feedback on progress!
        Application.ScreenUpdating = True
        'IOMaxValOfIntArray is a function that gets the index of the highest integer in array.
        'This coincides with the index used across other isses, so when "topissue" is concatenated it will match the highest issue found.
        IssCnt = IOMaxValOfIntArray(FullArr)
        TopIssue = "_" & MajArr(IssCnt) & "_" & MinArr(IssCnt) & "_" & DoArr(IssCnt)
        'if one was never found then the array will be empty.
        If TopIssue = "___" Then
            TopIssue = "Not found"
            Cells(DpScroll, StartCol + 4) = "Not Found"
            'this prints the DPno to an error message displayed at the end.
            IssErr = True
            IssErrMsg = IssErrMsg & vbCrLf & DpNo
        End If
        '''Print the full issue number, and time found.
        Cells(DpScroll, StartCol + 4) = Format(Timer() / 86400, "HH:MM:SS")
        'MsgBox TopIssue
        Cells(DpScroll, StartCol + 2) = TopIssue
        ' save in case of a rage quit. in this way those that have been retrieved are not reset.
        ActiveWorkbook.Save
        Application.ScreenUpdating = False
        ''''''''''''''''''''''''''''''''''''
        'reset array
        For I = 0 To IssCnt
            MajArr(I) = ""
            MinArr(I) = ""
            DoArr(I) = ""
            FullArr(I) = ""
        Next
    Next

    If IssErr Then MsgBox IssErrMsg

End Sub

A: I'll try to put more detail later... But you can use the Dir command to return file system objects that match a pattern...
So first you would run Dir("DP0123456*") to get your first match. Then just Dir() to get subsequent ones until it returns with a blank (meaning no more matches)

A: Consider Shell32 usage. Place this code at the beginning of your Sub:
' add reference to Microsoft Shell Controls and Automation (Shell32)
Const SHCONTF_FOLDERS = &H20
Const SHCONTF_INCLUDEHIDDEN = &H80
Dim Shell As Shell32.Shell
Dim FolderItems As Shell32.FolderItems
Dim FolderItem As Shell32.FolderItem
Set Shell = New Shell32.Shell

And here is a part of code to populate the arrays:
    '''''''''''''''''''''''''''''''''''''''''''''''''
    Set FolderItems = Shell.NameSpace(StrSourceFolder).Items
    FolderItems.Filter SHCONTF_FOLDERS + SHCONTF_INCLUDEHIDDEN, DpNo & "_*"
    IssCnt = 0
    For Each FolderItem In FolderItems
        TmpStr = Replace(FolderItem.Name, DpNo & "_", "")
        MajArr(IssCnt) = Left(TmpStr, 2)
        MinArr(IssCnt) = Mid(TmpStr, 4, 2)
        DoArr(IssCnt) = Right(TmpStr, 3)
        'combine these for later
        FullArr(IssCnt) = MajArr(IssCnt) & MinArr(IssCnt) & DoArr(IssCnt)
        'MsgBox DPno & vbCrLf & TmpStr & vbCrLf & MajArr(IssCnt) & vbCrLf & MinArr(IssCnt) & vbCrLf & DoArr(IssCnt) & vbCrLf & FullArr(IssCnt)
        IssCnt = IssCnt + 1
    Next


text:
Q: HTML APIs - Are they a part of the HTML5 standard? When reading about HTML5 on W3Schools I have come across a section called HTML APIs.
These are for example how to use geolocation and drag/drop on a webpage. See example here W3Schools.com - geolocation
Now the code is JavaScript and placed inside a HTML script tag.
So my questions is, is these APIs a part of the HTML5 standard?
I thought HTML was only HTML and not Javascript so why is this placed under HTML5?

A: There is no HTML5 standard, in the strict sense of "standard" (a normative document issued by a recognized international or national authority, such as ISO, IEC, CEN, or DIN), and probably never will.
There is HTML5 Recommendation by the W3C. Although such Recommendations are often called "standards", the W3C is an industry consortium, not a standardization authority.
There is also the WHATWG group (community), which has an online document they call HTML Living Standard. It may change without prior or posterior notice, and generally does so almost every day. So in addition to not being issued by a standardization authority, it also lacks a basic requirement of standards: a standard has fixed content, and it can only be changed by issuing a new standard (a new version of the standard, identified in a unique way so that each version can be cited).
Intepreting the question as relating to the W3C HTML5 Recommendation, the answer is that some HTML APIs are part of it, some are not, and some are defined in separate documents cited normatively or non-normatively in it. Much of the basic HTML APIs are an integral part of the Recommendation, such as the specification of the interface used to access the properties of an HTML element (a DOM node representing an HTML element) in client-side scripting, i.e. in client-side JavaScript in practice.
Geolocation is not part of W3C HTML5 Recommendation or even cited in it. It has been described separately in the W3C Geolocation API Specification.
Drag and drop API was part of W3C HTML5 drafts but was dropped from the specification. It is present in the draft for HTML 5.1.

A: I think this is more of a factor of W3Schools sucking at what it does. While the HTML5 standard (recently completed! yay) sets only HTML elements I suspect w3schools added this on here because it is newer. You are correct in assuming this is not an HTML thing but really a javascript thing.
Might I direct you to Mozilla Developer Network which is more accurate and awesome. Javascript evolves on its own separate of HTML.
EDIT:
So it appears what has happened here is you have stumbled upon one of the weird gray areas of the standards organization. While HTML5 is a specification directly aimed at HTML there are also certain feature that are nice to have for the webapp age we live in. One of these is geolocation. A geolocation API was laid out by the W3 as a means for encouraging support of it among browser vendors. These vendors naturally chose ECMAScript (javascript) to support the api instead of an HTML tag or whatever.
So no this is not necessarily part of the HTML standard but it is something that falls under the W3's sphere of influence because their overall concern is the standards that help to make developing on the web better.


text:
Q: ImageView Frame Change Condition I am building a sample project where I am creating an UIImageView and UIButton programmatically and changing its frame inside a loop. My condition is when I tap my button imagePicker will come and after picking an image from the library and then it will how in the imageView and the button will shift just beside the image view. In this way if I keep on choosing image button will shift every time. I have to keep 3 items in a row, but I have to do this without using collectionView or tableview. For the first row my code is working fine but when I choose image for the third time it is not working as expected. The screenshots will make it more clear.
This is what I want.

For the first row it is working fine like this

But when I am tapping the button for the third time and select an image then I am getting like this

The code for shifting imageView and button is
 int x = 8;
 int y = 8;
 int margin = 9;

 for (int i=1;i<=self.arrImages.count;i++){
 if (i%2 == 0 && i%3!=0) {

     [myImage setFrame:CGRectMake(x+margin+95.0, y, 95.0, 95.0)];
     [_addPhotoButton setFrame:CGRectMake((x+margin+95.0)*2, y, 95.0,95.0)];
     x = 8;
     y = y + margin + 95.0;

 }
 else if (i%3 == 0 && i%2 !=0) {
     [myImage setFrame:CGRectMake(x+margin+95.0+95.0+margin, y, 95.0,95.0)];
     [_addPhotoButton setFrame:CGRectMake(x, y+95.0+margin, 95.0, 95.0)];
     x = 8;
     y = y + margin + 95.0;

  }
  else {

      [myImage setFrame:CGRectMake(x, y, 95.0, 95.0)];
      [_addPhotoButton setFrame:CGRectMake(x+margin+95.0, y, 95.0, 95.0)];

        }

    }

}

I am sure that inside for loop, the condition that I have given is wrong. Can anyone please rectify my problem. Any help is highly appreciated.

A: int margin = 9;
CGFloat size = 95.0;

UIImage *chosenImage = [info objectForKey:UIImagePickerControllerOriginalImage];
[self.arrImages addObject:chosenImage];

UIImageView *myImage = [[UIImageView alloc] initWithImage:chosenImage];

myImage.frame = _addPhotoButton.frame;
[self.scrollView addSubview:myImage];

CGFloat x,y;
if(self.arrImages.count %3 == 0) {
    x = 8;
    y = _addPhotoButton.frame.origin.y + _addPhotoButton.frame.size.height + margin;

}
else {
    x = myImage.frame.origin.x + size + margin;
    y = _addPhotoButton.frame.origin.y;
}
_addPhotoButton.frame = CGRectMake(x, y, _addPhotoButton.frame.size.width, _addPhotoButton.frame.size.height);

[self.scrollView setContentSize:CGSizeMake(self.view.frame.size.width, _addPhotoButton.frame.size.height + _addPhotoButton.frame.origin.y + 8)];

[self.scrollView layoutIfNeeded];
[picker dismissViewControllerAnimated:YES completion:NULL];


text:
Q: SwiftUI: implement fae-in/out animation when inserting/removing items to list I wonder if it's possible to customize List animation when inserting/removing/etc. items? The default animation is based on the diff result. What I'd like to have, however, is fade-in/out, just like the default transition animation between two lists.
Background: in my app I have multiple lists and user can select any one to show. Usually this should be implemented by using switch statement or if/else statement or id() modifier and SwiftUI's default transition animation should just work fine. However, due to this bug, I have to implement them by using a single list and swap in/out list content based on the current logical list user selects. Since they are different lists logically, I don't want the default diff based animation, instead I'd like to have fade-in/out animation.
I have tried to emulate the fade-in/out animation as below. While the code works, the UI effect is not satisfying. The root cause is that, to implement fade-in/out animation, I need to get the snapshot of the old list (that is, the fade-out animation should be implemented before the list was changed), which is impossible in hack like this.
MyList(listContent: selectedList)
    .opacity(listOpacity)
    // This emulates fade-out.
    .onChange(of: selectedList) { newValue in
         withAnimation {
             listOpacity = 0
         }
     }
     // This emulates fade-in.
     .onChange(of: listOpacity) { newValue in
         if newValue == 0 {
             withAnimation {
                 listOpacity = 1
             }
         }
     }

As far as I can tell, there isn't an API to customize list animation. But just in case, does anyone have suggestions on how to implement it? Thanks.


text:
Q: Where is my error (R Programming) The below code works when i=0 and having problem when i=2. Below is the error:

"Error in while (Net_Present_value$NPV[year] <= 0) { :
    missing value where TRUE/FALSE needed" in second iteration

    vaaa=10000
    concession<-data.frame("case1"=integer(vaaa),"case2"=integer(vaaa),"case3"=integer(vaaa))

    #discount
    discount<-c(10,11,12)
    discount_sd<-c(2,2.5,2)
    #volume
    volume_growth<-c(15,16,17)
    volume_growth_sd<-c(2.5,2,3)
    #Cost
    C_cost<-c(-3000000,-3500000,-4000000) # Construction cost in dollar
    volume<-c(600000,700000,800000) #quantity of licence to be converted to smart driving licence
    #cost per unit
    cost_to_produce<-c(8,7,8) #including all cost such as material, operation and maintenance
    cost_to_driver<c(11,12,13)

    Net_Present_value<-data.frame(year=integer(25),value=double(25),NPV=double(25))
    cash_flow<-data.frame(year=integer(25),value=double(25))

    for(i in 1:3){
      bstrap_discount <- rnorm(vaaa,discount[i],discount_sd[i])
      #Volume
      bstrap_volume <- rnorm(vaaa,volume_growth[i],volume_growth_sd[i])

      for( iteration in 1:vaaa){
        year<-1
        #Net_Present_value=0
        #cash_flow=0

        Net_Present_value$NPV[year]<-C_cost[i]
        cash_flow$value[year]<-C_cost[i]
        new_volume<-volume[i]
        print(iteration)

        while(Net_Present_value$NPV[year]<=0){
          #print(Net_Present_value$NPV[year])
          year<-year+1

          if(year==2){ #everybody should change old to new driving license
            Revenue<-volume[i]*(cost_to_driver[i]-cost_to_produce[i])
            NPV<-Revenue/(1+bstrap_discount[iteration]/100)^(year)
          }

          else if(year>2){
            temp_vol<-new_volume
            new_volume<-temp_vol*bstrap_volume[iteration]/100+temp_vol
            Revenue<-(new_volume-temp_vol)*(cost_to_driver[i]-cost_to_produce[i])
            NPV<-Revenue/(1+bstrap_discount[iteration]/100)^(year)
          }

          Net_Present_value$year[year]<-year
          Net_Present_value$NPV[year]=Net_Present_value$NPV[year-1]+NPV

          cash_flow$year[year]<-year

          cash_flow$value[year]<-Revenue

        }

        concession$count[iteration]<-iteration
        if(i==1)
          concession$case1[iteration]<-year
        else if (i==2)
          concession$case2[iteration]<-year
        else if (i==3)
          concession$case3[iteration]<-year
        }
}


text:
Q: Java already implementing a class apologies if this is an easy question, I have a java class that implements Serializable
  public class product extends UnicastRemoteObject implements Serializable

I wish however to use threading within the same class, can anyone point me in the right direction please it would be much appreciated.
** apologies please notice the change above

A: You have two choices , either :

public class product implements Serializable,Runnable { }

or

public class product extends Thread implements Serializable  {}


text:
Q: AngularJS directive for mobile navigation I'm trying to built an AngularJS directive for toggling my mobile nav but it doesn't work. What am I doing wrong?
The directive
app.directive('mobileDirective', function(){
  return {
    restrict: 'A',
    link: function (scope, element, attrs){
      element.bind('onclick', function(){
        var status = element[0].className = "is-o";
        if(status){
          element[0].className = ".mobile-nav-toggle mobile-nav";
        }else{
          element[0].className = ".mobile-nav-toggle mobile-nav is-o";
        }
      });
    }
  }
});

The index.html

            {{item.name}}

          {{item.name}}

With jQuery it looks like this and works fine
function mobileNav(){
  $('.mobile-nav-toggle').on('click', function(){
    var status = $(this).hasClass('is-o');
    if(status){
      $('.mobile-nav-toggle, .mobile-nav').removeClass('is-o');
    }else{
      $('.mobile-nav-toggle, .mobile-nav').addClass('is-o');
    }
  });
}

A: For the record (I know this is ancient) I'm pretty sure the problem might have been this line;
var status = element[0].className = "is-o";
You're setting status and element[0].classname to "is-o", instead it should read;
var status = element[0].className === "is-o";
Meaning status equall whatever the result of element[0].className === "is-o" is.. I'm not convinced that's a solution as such but for such an old post I'm not even sure why I'm pointing this mistake out.


text:
Q: Microsoft CodePush App Center migration: future deployments I'm using Microsoft's CodePush service for my Cordova app.  As noted here this service will be migrated over the next 10-12 months to App Center.
It sounds like there will be a new CodePush SDK (aka cordova plugin) in February 2018.  If we do not use the new SDK when it comes out, but we start using the new App Center CLI to deploy releases, will the old CodePush SDK (cordova plugin) still work to pick up the newly deployed packages that were deployed from the App Center CLI?

A: We highly recommend switching over to the new App Center CodePush SDK when it's completed. But, we understand there are circumstances that can prevent that from happening immediately.
We are committed to keeping the old SDK available until late 2018, which means you are free to use the old SDK with the App Center CLI until then.
Also, Cordova support in the App Center portal was recently released in preview. You can now view CodePush in the App Center portal as well as the App Center CLI.


text:
Q: Rails - can't access custom join data I've got a really complicated query (which finds bus connections between two towns) and I haven't got any idea how to access data from joins (I'd like to know at which stop does the connection start and at which does it end). Is it possible to access this data using ActiveRecord?
Course.joins("INNER JOIN stop_times as start_stop ON start_stop.course_id=courses.id")
.joins("INNER JOIN stop_times as end_stop ON end_stop.course_id = courses.id")
.joins('INNER JOIN stops as start_stopi ON start_stop.stop_id = start_stopi.id')
.joins('INNER JOIN stops as end_stopi ON end_stop.stop_id = end_stopi.id')
.where('start_stop.hour>= ? OR (start_stop.hour>= ? AND start_stop.minute>= ?)',hour,(hour+1)%24,minute)
.where('start_stopi.town_id = ? and end_stopi.town_id = ?',start_town,end_town)
.where('start_stop."order"<end_stop."order"').order('start_stop.minute ASC').order('start_stop.hour ASC')

EDIT:
I've managed to rewrite it to use active record joins, although it broken my names, it works.
Course.joins(end_stop_times: :stop).joins(start_stop_times: :stop)
.where('start_stop_times_courses.hour>= ? OR (start_stop_times_courses.hour>= ? AND start_stop_times_courses.minute>= ?)',hour,(hour+1)%24,minute)
.where('stops_stop_times.town_id = ? and stops.town_id = ?',start_town,end_town)
.where('start_stop_times_courses."order"<stop_times."order"')
.order('start_stop_times_courses.minute ASC').order('start_stop_times_courses.hour ASC')

Using this new query models are:
class Course < ActiveRecord::Base
  belongs_to :carrier
  has_many :end_stop_times, class_name: 'StopTime'
  has_many :start_stop_times, class_name: 'StopTime'

class Stop < ActiveRecord::Base
  belongs_to :town

class StopTime < ActiveRecord::Base
  belongs_to :stop
  belongs_to :course

A: You need to add sth like:
your_query.select('courses.*, start_stopi.id as start_stop_id, end_stopi.id as end_stop_id)

and then you can access it by calling start_stop_id and end_stop_id on course object.
However you should probably use association for this kind of operations. Could you show us you models?

A: Check your log for the output of this query, you should find that it starts with select courses.* - therefore it will not bring through data from the included tables.
You can add some select other_table.some_column statements to your query, but this isn't the rails way.
I would suggest you separate your scope into the relevant models - put scopes in the stop_times model (and others) so that you can call the scopes on the object you actually want to get data from.

A: When you're constructing custom SQL of that complexity I think you've taken the Rails-way of doing things too far. You're using practically no activerecord association information to construct it, and you've built a programming construct that is horribly ugly and difficult to read.
I'd advise that you rewrite it as well formatted SQL
results  = ActiveRecord::Base.connection.execute(
"select c.*
 from   courses    c
 join   stop_times ss on ss.course_id = c.id
 join   stop_times es on es.course_id = c.id
 ... etc ...
 where  (start_stop.hour  >= #{ActiveRecord::Base.sanitize(hour)} or
        ... etc ...")

Now it could be that you can improve your models and associations to the point where this level of complexity is not required (eg. the associations between courses, stop_times (start) and stop_times (end) could probably be encapsulated in activerecord pretty well, but at the moment you seem to be falling between the pure SQL and the pure activerecord approaches in a very uncomfortable way.


text:
Q: Angular 7+: Rendering directives in dynamic user content (HTML) fetched from REST API in runtime I have an app which fetches user-content like blog content, which is saved as HTML on the server.
I need to render it and it might have custom directives like
REST API RESPONSE SAMPLE:
content: "

This is rendered perfectly by passing HTML to sanitizer.bypassSecurityTrustHtml
and
SpiderMan dies on Page 142: Rendered as HTML. Directive not processed (naturally)

"

I need to render the spoiler directive on this dynamically returned user-content.
I have come to know from SO and extensive searching that one way to do it is by enabling JIT (no AOT) during the build process (buildOptimizer: false, and import 'core-js/es7/reflect' in polyfills.ts, create module/component dynamically using JIT) in a long complicated way (which might break on angular version upgrades)
Is there any other way to render my use-case dynamically that I'm unaware of ?

A: Possible ways to implement this

*

*Enabling JIT compiler and creating dynamic modules

*Angular Elements

*Modifying the rendered HTML using native JS or some other library

A: You can use:

Which will render your content variable inside that element
However, thats not the purpose of a REST api.


text:
Q: How to validate my custom object received in the controller? So I am starting a new project and I am trying to figurate out what would be the best approach to validate my customs objects.
I have this class:
public class UserRegistrationDto
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public string InvitationCode { get; set; }
    public Enums.UserRole UserRole { get; set; }
}

And I receive it in the body of the controller:
    [HttpPost]
    public async Task RegisterUserAsync(UserRegistrationDto user)

So when passed to the service layer, I would like to perform the following validations:
        if (Name.Length > 35)
            return false;

        if (UserRole == Roles.Administrator && string.IsNullOrEmpty(InvitationCode))
        {
            return false;
        }

What would be the best approach/design to do this kind of validations?

A: I would suggest the following read MVC model validation

*

*[StringLength] for the one validation

*Custom attribute for the joint option

You can find them in the data annotations


text:
Q: Changing \leftmargin in \enumerate based on width of largest label Here is an MWE:
\documentclass{article}
\usepackage{enumitem}
\usepackage{lipsum}

\begin{document}

\begin{enumerate}[leftmargin=1.5cm, font=\bfseries, labelsep=1em]
    \item[1-1.*] Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Ut
    purus elit, vestibulum ut, placerat ac, adipiscing vitae, felis. Curabitur
    dictum gravida mauris.
    \item[1-2.] Nam arcu libero, nonummy eget, consectetuer id, vulputate a,
    magna. Donec vehicula augue eu neque. Pellen- tesque habitant morbi tristique
    senectus et netus et malesuada fames ac turpis egestas. Mauris ut leo. Cras
    viverra metus rhoncus sem.
    \begin{enumerate}[leftmargin=1.5cm, label=(\alph*)]
        \item Nulla et lectus vestibulum urna fringilla ultrices. Phasellus eu
    tellus sit amet tortor gravida placerat.
        \item Integer sapien est, iaculis in, pretium quis, viverra ac, nunc.
    Praesent eget sem vel leo ultrices bibendum. Aenean faucibus.
    \end{enumerate}
    \item[1-12.*] Morbi dolor nulla, malesuada eu, pulvinar at, mollis ac,
    nulla. Curabitur auc- tor semper nulla. Donec varius orci eget risus.
\end{enumerate}

\end{document}

I'm wondering if there is a way to make it so that everything is aligned like it is, but the largest number (in this case, 1-12.*) is flush left with the margin and everything else is aligned based on that. I also want to be able to indent the sublist (a), (b), etc. starting from the beginning of the text (not the numbers) in the main list.

A: Here is a solution, which uses the widest= key, from enumitem:
\documentclass{article}
\usepackage[showframe]{geometry}
\usepackage{enumitem}
\usepackage{lipsum}

\begin{document}

\begin{enumerate}[widest=\bfseries1-12.*, labelindent =-0.333em, font=\bfseries, labelsep = 1em, leftmargin = *]
  \item[1-1.*] Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Ut
        purus elit, vestibulum ut, placerat ac, adipiscing vitae, felis. Curabitur
        dictum gravida mauris.
  \item[1-2.\hphantom{*}] Nam arcu libero, nonummy eget, consectetuer id, vulputate a,
        magna. Donec vehicula augue eu neque. Pellen- tesque habitant morbi tristique
        senectus et netus et malesuada fames ac turpis egestas. Mauris ut leo. Cras
        viverra metus rhoncus sem.
        \begin{enumerate}[wide = 0pt, align = left, label=(\alph*), leftmargin=*]%leftmargin=2em
          \item Nulla et lectus vestibulum urna fringilla ultrices. Phasellus eu
                tellus sit amet tortor gravida placerat.
          \item Integer sapien est, iaculis in, pretium quis, viverra ac, nunc.
                Praesent eget sem vel leo ultrices bibendum. Aenean faucibus.
        \end{enumerate}
  \item[1-12.*] Morbi dolor nulla, malesuada eu, pulvinar at, mollis ac,
        nulla. Curabitur auc- tor semper nulla. Donec varius orci eget risus.
\end{enumerate}

\end{document}

A: Since it seems you want to type in arbitrary labels for your first level, you may be better of using description lists (use calc package and enter the longest label into the description list options).
\documentclass{article}
\usepackage{enumitem}
\usepackage{lipsum}
\usepackage{calc}

\begin{document}
\begin{description}[leftmargin=!,labelwidth=\widthof{\bfseries 1-12.*}]
    \item[1-1.*] Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Ut
    purus elit, vestibulum ut, placerat ac, adipiscing vitae, felis. Curabitur
    dictum gravida mauris.
    \item[1-2.] Nam arcu libero, nonummy eget, consectetuer id, vulputate a,
    magna. Donec vehicula augue eu neque. Pellen- tesque habitant morbi tristique
    senectus et netus et malesuada fames ac turpis egestas. Mauris ut leo. Cras
    viverra metus rhoncus sem.
    \begin{enumerate}[label=(\alph*)]
        \item Nulla et lectus vestibulum urna fringilla ultrices. Phasellus eu
    tellus sit amet tortor gravida placerat.
        \item Integer sapien est, iaculis in, pretium quis, viverra ac, nunc.
    Praesent eget sem vel leo ultrices bibendum. Aenean faucibus.
    \end{enumerate}
    \item[1-12.*] Morbi dolor nulla, malesuada eu, pulvinar at, mollis ac,
    nulla. Curabitur auc- tor semper nulla. Donec varius orci eget risus.
\end{description}

\end{document}


text:
Q: How do i modify only 1 dimension in Unity using c#? I'm doing a simple game to get started with unity, there's a cube who goes straight and dodge other cubes (obstacles) which are spawned randomly. To make the obstacle always spawn in front of the player I set up a code that makes the 7 spawn position (the blocks get generated in them randomly) follow the player's coordinates but adding 100 to the Z so they get generated not upside the player. Now, my problem is that when generated the obstacle also changes their X position, making them fall from the platform when I go to the right or to the left with the player. How can I make they follow only the Z position of the player and not the X?
Here is the code that makes the spawners change position:
public class MoveSpawn : MonoBehaviour
{

    public Transform player;
    public Vector3 offset;

    // Update is called once per frame
    void Update()
    {
        transform.position = player.position + offset;

    }
}

A: I would simply multiply the player's position by (0,0,1) (in other words, Vector3.forward) before adding it to the offset:
public class MoveSpawn : MonoBehaviour
{

    public Transform player;
    public Vector3 offset;

    // Update is called once per frame
    void Update()
    {
        transform.position = player.position * Vector3.forward + offset;

    }
}

A: Oh, that's pretty easy.
So if you only want to look at the Z(or any other) coordinates of the Cube or any object in Unity you can simply use:
transform.position.z
That's the same thing you would do with vectors. Something like that:
Vector3 offset = ...;
Debug.Log(offset.x) //returns x coordinate of offset