text:
Q: How can I set up log4net in dot net core to log all unhandled exceptions? I am using the implementation suggested here for adding log4net to current dot net core project, https://thecodebuzz.com/log4net-file-logging-console-logging-asp-net-core/ (this is using  Microsoft.Extensions.Logging.Log4Net.AspNetCore), how can log4net be set up to log all unhandled exceptions? I haven't figured out a way to do this. Any pointers please?
Later edit:
public class LogFilter : ExceptionFilterAttribute
{
    public readonly ILogger _logger;

    public LogFilter(ILogger logger)
    {
        _logger = logger;
    }

    // public Logger Logger { get; set; }
    public override void OnException(ExceptionContext Context)
    {
        //Log what you need here, the exception is in Context.Exception
        _logger.LogError(Context.Exception, null);

        Context.ExceptionHandled = true;
    }
}

I tried adding a LogFilter class like this, coupled with this change in Startup.cs:
services.AddMvc(o =>
{
    o.Filters.Add(new LogFilter(Logger));
});

in the ConfigureServices method as well as the public ILogger Logger { get; } property, but the error I get is about _logger being null in my LogFilter class.
Later update (side note):
In a controller, I can get _logger to work by adding a property:
private readonly ILogger _logger;
and passing it in the constructor: ILogger<MyController> logger but in the FilterClass following the same approach with ILogger<ControllerBase> logger in the constructor doesn't work.
Error is the same as mentioned above.

A: To log any unhandled exception in .net Core you must create an exception filter, something like this:
public class LogFilter : ExceptionFilterAttribute
{
    public override void OnException(ExceptionContext Context)
    {
        //Log what you need here, the exception is in Context.Exception

        Context.ExceptionHandled = true;
    }
}

And register the filter:
public void ConfigureServices(IServiceCollection Services)
{
    // Add framework services.
    Services.AddMvc(o =>
    {
        o.Filters.Add(new LogFilter());
    });
}


text:
Q: ReactJS - update component (generated from a list) in the same div It's a basic question but I searched for a guide without success...
I want to have a list of dropdowns and inputs and each dropdown will change the input next to it.
var list = [{ name: "foo1"}, {name: "foo2"}];

return (
    {list.map( (name) => {
        return (<div>
                    <dropdown data={someData}
                        onChange={(ev) => {
                                       if(ev.value == 'clearIt')
                                            <CHANGE THE NEAR INPUT VALUE>
                                     }
                             }/>
                     <input value={name.name} />
                </div>)
     })});

I don't want to use DOM nor ref cause I understood that it's better to avoid it.
Any suggestions?
Or maybe the ref is the only option?
Thanks

A: So you can achieve this by doing the following steps:

*

*Create a new component and move the dropdown and input to this new component.

*Add state to your component by following this example:
https://reactjs.org/docs/state-and-lifecycle.html#adding-local-state-to-a-class

*Add an event listener onChange to the dropdown with an event handler which can update the state you created in the first step. (Remember to bind the handler in the constructor.

*Add the new component within the div element of this example you gave and pass the relevant data you need to the new component you created.

This should allow you to update only the input next to the dropdown. Also it allows you to have different data for each dropdown you created.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Open an executable file without an ".exe" extension with CreateProcess I want to create a process whose filename doesn't have the .exe extension. This is the same question as Open an executable file without an ".exe" extension with ShellExecute had, only with CreateProcess. The answer to his question said to set the sei.lpClass = TEXT("exefile");. No such parameter in the STARTUPINFO structure.
Is there an equivalent solution for CreateProcess. Currently, it fails with no extension. Doesn't even give a proper error message. Just crashes the program.
Edit2:
Sorry, here's a complete test program demonstrating my problem:
#include "stdafx.h"
#include <Windows.h>

LPCTSTR FILE_PATH_NAME = _tcsdup( TEXT( "C:\\File1.exe" ) ); // ok, launches new process correctly
//LPCTSTR FILE_PATH_NAME = _tcsdup( TEXT( "C:\\File1" ) ); // debug assertion in mfc
LPCTSTR FILE_PATH_NAME = _tcsdup( TEXT( "C:\\File1." ) ); // ok, launches new process correctly. Needs ending period (.) to work
LPTSTR commandLine = _tcsdup( TEXT( "1234" ) );

int main()
{
  PROCESS_INFORMATION pi;
  STARTUPINFO si;

  ZeroMemory( &pi, sizeof( pi ) );
  ZeroMemory( &si, sizeof( si ) );
  si.cb = sizeof( si );

  CreateProcess
  (
    FILE_PATH_NAME,          // must be fully qualified file path name
    commandLine,            // Command line (cannot be const or literal str)
    NULL,                 // Process handle is not inheritable
    NULL,                 // Thread handle is not inheritable
    FALSE,                // handle inheritance false
    0,                    // default
    NULL,                 // Use parent's environment block
    NULL,                 // Use parent's starting directory
    &si,                  // Pointer to startupinfo structure
    &pi                   // Pointer to process_information structure
  );

  DWORD lastError = GetLastError();
  if( lastError != ERROR_SUCCESS )
  {
    // failed
  }

  CloseHandle( pi.hThread );
  CloseHandle( pi.hProcess );

  return 0;
}

Edit3:
Crash image


text:
Q: ¿Para que se usa el while(1) en un bucle? Navegando por la red y buscando códigos de otras personas he visto poner un 1 o true, pero realmente no sé cual es el propósito de esto.
while(1){

  //CODIGO AQUI!
}

A: El while 1 no se usa para nada en específico salvo para permitir la ejecución sin límite del contenido del ciclo, su equivalente en cualquiera de sus derivados seria:
while (true) {
  // Código aquí.
}

Se va a mantener ejecutando lo que hay en el bucle hasta que pongas alguna condición que lo haga salir con un break o algo parecido.
En C, es común utilizar while (1) para dejar esto claro: "No existe una condición lógica que sea exacta para detener este ciclo"
Por ejemplo:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BUF (1024)

int main(void) {
  int c = 0, ind = 0; char str[MAX_BUF];
  while (1) {
    printf("Escribe algo (No mas de 1024 caracteres): ");
    ind = 0; /* Reseteamos el indice. */
    while (((c = fgetc(stdin)) != '\n') && (ind < MAX_BUF))
      str[ind] = c, ind++;
    if (0 == strcmp(str, "salir")) /* Salimos si es necesario. */
      break;
    if (ind) /* Nos aseguramos que el usuario no presiono enter nomas. */
      printf("Has escrito: '%s'\n", str);
  }
  return 0;
}

Fíjate que en el código anterior, solo va a salir del ciclo si la variable str contiene el valor "salir", de igual forma puedes poner más de una condición para la salida del ciclo, pero mientras ninguna se cumpla, simplemente se seguirá ejecutando.
De hecho, puedes tratar de hacer un while (1) y ver como tu programa nunca finaliza. :^)
Saludos :)

A: El proposito de dicho codigo es crear un bucle infinito.
En el mundo real el uso mas comun es prevenir que otro codigo de bloque se alcanzado, ya sea que si se alcanza algun bloque codigo fuera de dicho bucle algun error ha ocurrido o que entre en dicho bucle si algun error ha ocurrido.
Siendo el segundo tipo de uso el que se le ha dado a un archivo que forma parte del kernel de linux y puede ser apreciado en la linea 678 del archivo pc_keyb.c en su version 2.4.x.
http://www.kneuro.net/cgi-bin/lxr/http/source/drivers/char/pc_keyb.c?a=mips#L678


text:
Q: Swift - Attempting to change UITableView row height dynamically but heightForRowAtIndexPath never gets called I've been trying for over a day now to change the row height dynamically of a UITableView cell depending on the amount of text that is in a label contained within the cell. I've tried numerous suggestions from websites and videos to no avail. The function heightForRowAtIndexPath never gets called for some reason even though cellForRowAtIndexPath gets called every time.
Here is some code I've just been using to see if I could get results to change during runtime. The values you see are just for testing. The main issue I'm facing with this portion is that the entire function does not get called even though the UITableViewDelegate is set up properly.
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    let cell: VCNewsFeedCell = tvPosts.dequeueReusableCellWithIdentifier("NewsFeedCell", forIndexPath: indexPath) as VCNewsFeedCell

    cell.lblDescription.setNeedsLayout()
    cell.lblDescription.layoutIfNeeded()

    var size: CGSize = cell.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)

    return 500
}

I've also tried the newer methods for dynamically increasing the row height for iOS8, but that hasn't worked either. The methods I tried for this include the following lines of code placed in the viewDidLoad function:
    self.tvPosts.rowHeight = UITableViewAutomaticDimension
    self.tvPosts.estimatedRowHeight = 350

Neither of the above methods have done anything to change the height of the row.
As a side note, I have successfully placed constraints on all of the user interface items contained in the table view cell and as a result, all of the user interface items show up in the proper location at runtime and they move properly according to the amount of text in a label which is also contained in the table cell.
In summary, I'm able to get all of the user interface components contained within a custom UITableViewCell to move properly according to the amount of text contained with a label in the cell, but the cell itself remains the same size every time which causes the user interface components to sometimes overrun the bounds of the cell and get placed in the next cell below it.
Any suggestions on what I can try?

A: Lets say you have a UILable in tableviewcell, So just remove all auto layout constraints, and calculate the hight required to set uilalbe in border of uitableviewcell like this,
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font
                    constrainedToSize: CGRectMake(UILable.frame.size.width, CGFLOAT_MAX)
                    lineBreakMode:yourLabel.lineBreakMode];

    return  expectedLabelSize.height; //You can add padding size like in top and bottom.
}

Hope this helps you,
HTH, Happy Coding!!


text:
Q: Google OAuth redirect_uri_mismatch when exchanging one-time-code for refresh token I'm implementing Google OAuth2 server one-time-code flow as described here:
https://developers.google.com/identity/sign-in/web/server-side-flow
The client gets the code from google (after user completes the oauth flow),
and POSTs it to the server.
The server tries to exchange the code for a refresh token (using the Java SDK) using this call:
val authorizationScopes = Seq(GmailScopes.GMAIL_READONLY, GmailScopes.GMAIL_SEND, "email").asJavaCollection

val googleAuthorizationCodeFlow = new GoogleAuthorizationCodeFlow.Builder(
      GoogleNetHttpTransport.newTrustedTransport(),
      JacksonFactory.getDefaultInstance,
      googleAppInfo.googleClientId,
      googleAppInfo.googleClientSecret,
      authorizationScopes)
  .setTokenServerUrl(new GenericUrl(googleAppInfo.tokenServerUrl))
  .setAccessType("offline")
  .build()

val googleTokenResponse: GoogleTokenResponse = googleAuthorizationCodeFlow
  .newTokenRequest(code)
  .setRedirectUri(redirectUri)
  .execute()

I get:

com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request {  "error" : "redirect_uri_mismatch",  "error_description" : "Bad Request"}

The redirectUri is exactly the same as in the Google cloud console > Credentials > Client Id (Web Application) > Authorized redirect URIs.
Also, it already worked when we used the OAuth redirect flow, but when we switched to the POST flow, it stopped working with this message.
I tried sending an empty redirectUri (as I saw in some answers about the matter), but than I get:

com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request {  "error" : "Missing required parameter: redirect_uri",  "error_description" : "Bad Request"}

I even tried sending the actual 'referer' url.
What am I doing wrong here?

A: It's not documented but when you work with Google client SDK you don't redirect.
The SDK opens a new windows and communicate with it using post message.
If you set the redirect uri as "postmessage" it should work for you.

A: In case you are getting that error when using popup mode, the solution was having the same redirect_uri both in the front- and back- end.
I.e. Front-
const client = google.accounts.oauth2.initCodeClient({
  redirect_uri: 'postmessage',
  some_other_params,
})

client.requestCode()

Back-
export const oauth2Client = new google.auth.OAuth2(
  clientId,
  clientSecret,
  "postmessage"
)

let { tokens } = await oauth2Client.getToken(code)


text:
Q: Faster way to retrieve large value in column I am using MVC, EF & Repository, and database in Azure. I have a table, that has only 5 columns. ID, name, message, Exceptions & otherdetails. Exceptions & otherdetails, both are a varchar(max) datatype. Now, Exceptions column max string length is a 2300 word & otherdetails column max string length is 1500 word.
  can anyone tell me, the faster way to find whole data? because now I am searching one-day data, so it took almost 20sec or more to execute. I executed the same query in SQL. but it took the same time. Also, I tried to use table view but the same time to execute.
here is my code -
public IEnumerable<ErrorLogModel> GetErrorLogData(DateTime? startDate, DateTime? endDate)
    {
        return _unitOfWork.ErrorLogRepository.Get(e.Date >= startDate && e.Date <= endDate).Select(e => new ErrorLogModel
        {
            ID= e.ID,
            name = e.name,
            message= e.message,
            Exceptions = e.Exceptions,
            otherdetails = e.otherdetails
        });

    }

A: Indexing can increase performance of your query, now it scans all the table so query works really slow.
EF 6.1 supports indexing, try to use it like this: https://learn.microsoft.com/ru-ru/ef/ef6/modeling/code-first/data-annotations#index
[Index]
public DateTime ExceptionDate { get; set; }

If you prefer FluentAPI and use EF 6.2 you can use this answer: How to create index in Entity Framework 6.2 with code first

A: The issue isn't so much the field size as it is the total data size based on the number of records returned. For an entire day, how many records can come back? 10's, 1000's? You're attempting to pull ~4k per record, so depending on the # of records this will have a big impact on the amount of time needed to retrieve that data. At a minimum if you do need all of that data you should implement server-side paging to load pages of 10-50 records at a time.
Also, what does ErrorLogRepository.Get return, IQueryable<ErrorLog> or IEnumerable<ErrorLog>?  If you're returning IQueryable and the repository is just returning the result of your .Where() criteria without calling .ToList() or the like then all should be good, but if you're returning IEnumerable then you would be doubling up the memory use on your app server. The repository would effectively do a "SELECT *" to load the entities into memory, then your follow-up .Select would create a new set of view models. (2x the amount of memory needed.)


text:
Q: always-use-default-target="false" and default-target-url do not work with spring-social always-use-default-target and always-use-default-target="false" works fine if the user logins with username and password
Both attributes seems to be ignored when using spring-social
When the user logins using Facebook or Twitter:

*

*If the user went to the login page because he/she clicked the "login" button, he/she is redirected to "/" after a successful login. I expected he/she to be redirected to default-target-url

*If the user was redirected to the login page because he/she tried to access a protected url, he/she is also redirected to "/" after a successful login. I expected he/she to be redirected to original protected url he/she requested.

I am using

*

*spring 3.1.3.RELEASE

*spring security 3.1.3.RELEASE

*spring social 1.0.2.RELEASE

This is my spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                    http://www.springframework.org/schema/security
                    http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <http use-expressions="true" access-denied-page="/ingresar/?acceso_denegado=true">
        <intercept-url pattern="/" access="permitAll" />
        <intercept-url pattern="/signin/**" access="permitAll" />
        <intercept-url pattern="/url1/**" access="permitAll" />
        <intercept-url pattern="/url2/**" access="hasAnyRole('ROLE_XXX')"/>
        ...
        <intercept-url pattern="/**" access="denyAll" />
        <form-login login-page="/url3/" default-target-url="/url4" always-use-default-target="false"
                    authentication-failure-url="/url5" login-processing-url="/url6"/>
        <logout logout-url="/logout"/>
    </http>

    <beans:bean id="myUserService" class="my.kalos.service.MyUserServiceImpl"/>

    <beans:bean id="encoder" class="org.springframework.security.crypto.password.StandardPasswordEncoder"/>

    <authentication-manager alias="authenticationManager">
        <authentication-provider user-service-ref='myUserService'>
            <password-encoder ref="encoder"/>
        </authentication-provider>
    </authentication-manager>
</beans:beans>

This is my spring-social config class
@Configuration
public class MyAppSocialConfig {

    @Inject
    MyAppConnectionSignUp myAppConnectionSignUp;

    @Inject
    private DataSource dataSource;

    @Bean
    public ConnectionFactoryLocator connectionFactoryLocator() {
        ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();
        registry.addConnectionFactory(new FacebookConnectionFactory(myAppConf.getFbAppId(), myAppConf.getFbAppSecret()));
        registry.addConnectionFactory(new TwitterConnectionFactory(myAppConf.getTtConsumerKey(), myAppConf.getTtConsumerSecret()));
        return registry;
    }

    @Bean
    public UsersConnectionRepository usersConnectionRepository() {
        JdbcUsersConnectionRepository repository = new JdbcUsersConnectionRepository(dataSource,
                connectionFactoryLocator(), Encryptors.noOpText());
        repository.setConnectionSignUp(myAppConnectionSignUp);
        return repository;
    }

    @Bean
    @Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
    public ConnectionRepository connectionRepository() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        MyUser user = (MyUser) authentication.getPrincipal();
      return usersConnectionRepository().createConnectionRepository(String.valueOf(user.getId()));
    }

    @Bean
    @Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
    public Facebook facebook() {
        return connectionRepository().getPrimaryConnection(Facebook.class).getApi();
    }

    @Bean
    @Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
    public Twitter twitter() {
        return connectionRepository().getPrimaryConnection(Twitter.class).getApi();
    }

    @Bean
    public ProviderSignInController providerSignInController() {
        ProviderSignInController controller = new MyAppProviderSignInController(...);
        controller.setSignInUrl("/someUrl/");
        return controller;
    }
}

A: I finally get it to work but I use XML configuration. The idea is to override the default URL ("/") using postLoginUrl property.
<http auto-config="true" use-expressions="true">
    <!-- Enable csrf protection -->
    <csrf />
    <form-login login-page="/sign" default-target-url="/dashboard" authentication-failure-url="/sign" username-parameter="username" password-parameter="password" />
    <!-- Dashboard is protected -->
    <intercept-url pattern="/dashboard**/**" access="hasRole('ROLE_USER')" />
    <!-- Adds social authentication filter to the Spring Security filter chain. -->
    <custom-filter ref="socialAuthenticationFilter" before="PRE_AUTH_FILTER" />
</http>

<!-- Configures the social authentication filter which integrates Spring Social with Spring Security -->
<beans:bean id="socialAuthenticationFilter" class="org.springframework.social.security.SocialAuthenticationFilter">
    <beans:constructor-arg index="0" ref="authenticationManager" />
    <beans:constructor-arg index="1" ref="userIdSource" />
    <beans:constructor-arg index="2" ref="usersConnectionRepository" />
    <beans:constructor-arg index="3" ref="connectionFactoryLocator" />
    <!-- Sets the url of the registration - use in case the sign in has failed -->
    <beans:property name="signupUrl" value="/user/register/" />
    <!-- Sets the url of the dashboard - use in case the sign in has succeed -->
    <beans:property name="postLoginUrl" value="/dashboard/" />
</beans:bean>


text:
Q: which lambda has more chances to be inlined The way I see it, if the lambda has to store state, it will likely not be inlined. If it doesn't store state, then it's like a simple free function, and there's more chances that it's gonna be inlined.
Does the standard say anything about it?
class Window {public:int value = 5;};

class SomeClass:
{
public:
    Window *w;

    void DoSomething()
    {
         auto error = [&](int n)
         {
             std::cout << (w->value  * 5);
             return w->value * n;
         };

         auto error  = [](Window *w, int n)
         {
             std::cout << (w->value  * 5);
             return w->value * n;
         };

         error(w, 7);
         error(7);
         // ...

         error(w, 10);
         error(10);

    }
}

A: As someone that has spent much of my spare time the past couple of years writing a compiler to go on top of LLVM, I'm pretty sure any decent compiler will inline both of these - if not, I'd raise a bug with whoever makes the compiler that doesn't.
The stuff in [...] will just be an extra argument (a "closure argument"), which typically turns into a pointer to a structure [which can be "unpicked" into regular arguments when/if the function is inlined].
The main reason that a simple small function is NOT inlined is that it's called through a function pointer, including the vtable. A non-static [at a global level] function may also be produced in the non-inline version, since the compiler can't determine that the function is not called elsewhere.
Of course, LARGE functions may not get inlined because the compiler thinks it is a waste of space to do so, but gcc for example will inline very large functions when they are known to becalled from only one place.
I would also argue that there is no difference in how the compiler inlines lambda to other functions - aside possibly from the fact that they obviously can't be called from anywhere else [unless the lambda is passed out of the function where it is declared as a std::function or similar - but it can't be inlined either way].
If you REALLY care, then check the compiler output.


text:
Q: read a .db file in C#  string Path = @"c:\Database\Mydatabase.db";

     string myConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Path + ";Extended Properties=Paradox 5.x;";

    // Define the database query
    string mySelectQuery = "SELECT id,name FROM people WHERE id < 3;";

    // Create a database connection object using the connection string
    OleDbConnection myConnection = new OleDbConnection(myConnectionString);

    // Create a database command on the connection using query
    OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection);

    // Open the connection
    myCommand.Connection.Open();

    // Create a database reader
    OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

The Error is at myCommand.Connection.Open(); and it says:
'c:\Database\Mydatabase.db' is not a valid path.  Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.
I am trying to read a .db file in C#. However, I am getting an error, I am sure that file is located there, the error does not make sense for me. Could you please help me ? Or How can I read a .db(paradox) database file in C# ?
EDIT:
string Path = @"c:\Database\";
The Error for this case is "The Microsoft Jet database engine could not find the object 'people'.  Make sure the object exists and that you spell its name and the path name correctly."
If I change it like that, How can C# find which database file is gonna be used ? Since, I did not specify file name which is "Mydatabase.db" at anywhere

A: if the application cannot see the file than chances are it's a security issue. while "you" can access the file. the application cannot.
is this a web application? if so, then this is the problem. asp.net/IIS cannot see outside of its virtual directory. In which case you either need to elevate/modify privileges of the asp.net user account to access the file, or move the database file within the virtual directory. This is a good candidate for the App_Data directory.

A: Confirmed it is an SQLite database, I just downloaded it on my phone and viewed it with an SQLite viewer.

You will need to download an ADO.NET provider for SQLite:
"Official" version (from SQLite, not MS)
http://system.data.sqlite.org/index.html/doc/trunk/www/index.wiki
Older version
http://sqlite.phxsoftware.com/

A: Try one of these connection strings instead.

A: According to this site, you should only specify the folder name, not the db file.

Please note that you should only specify the folder where the database
  resides. Not the database name itself.

The linked MSDN article says that Jet 4.0 Service Pack 5 should be used if you want to update the data, otherwise it may be read-only. In any case I would recommend installing the service pack.


text:
Q: Div-ы внутри div-ов не отображаются. Как это исправить? Есть код отображения div-ов в зависимости от выбранных значений select-ов. Но он не отображает вложенный код. Т.е. Если в блоке есть просто текст, то он отобразится, но если внутри есть ещё блок, то он не отобразится. Подскажите, пожалуйста, как это исправить? Код ниже:

$(function() {
  $("#people, #days").on("change", function() {
    $(".all-price div, .all-blocks div").hide();
    $("#pr" + $("#people").val() + '-' + $("#days").val()).show();
    $("#bl" + $("#people").val() + '-' + $("#days").val()).show();
  });
});
.podbor {
  display: block;
}

.drop {
  cursor: pointer;
  overflow: hidden;
  display: inline-block;
  position: relative;
  border-radius: 3px;
  padding: 10px;
  outline: 0;
  letter-spacing: .2px;
  border: 1px solid #ecebeb;
}

.all-price {
  font-size: 18px;
  font-weight: bold;
  display: inline-block;
  padding: 10px 20px;
}

.all-price>div {
  display: none
}

.all-blocks {
  width: 300px;
  height: 300px;
  background-color: #f9f9f9;
}

.all-blocks>div {
  display: none
}

#pr2-5, #bl2-5{
  display:block;
}
.1c3d{width:100px;height:50px;background-color:red;}

  Для
  <select class="drop" id="people">
    <option value="1">1-го</option>
    <option value="2" selected>2-х</option>
    <option value="s">семьи</option>
  </select>
  на
  <select class="drop" id="days">
    <option value="3">3 дня</option>
    <option value="5" selected>5 дней</option>
  </select>

Цена для 1-го на 3 дня ХХХХХХ

Цена для для 1-го на 5 дней ХХХХХХ

Цена для 2-х на 3 дня ХХХХХХ

Цена для 2-х на 5 дней ХХХХХХ

Цена для семьи на 3 дня ХХХХХХ

Цена для семьи на 5 дней ХХХХХХ

Содержимое блока для 1-го на 3 дня

Содержимое блока для 1-го на 5 дней

Содержимое блока для 2-х на 3 дня
Вот такая Хурма!

Содержимое блока для 2-х на 5 дней

Содержимое блока для семьи на 3 дня

Содержимое блока для семьи на 5 дней

A: Скрывайте только блоки первого уровня.
$(".all-price > div, .all-blocks > div").hide();

$(function() {
  $("#people, #days").on("change", function() {
    $(".all-price > div, .all-blocks > div").hide();
    $("#pr" + $("#people").val() + '-' + $("#days").val()).show();
    $("#bl" + $("#people").val() + '-' + $("#days").val()).show();
  });
});
.podbor {
  display: block;
}

.drop {
  cursor: pointer;
  overflow: hidden;
  display: inline-block;
  position: relative;
  border-radius: 3px;
  padding: 10px;
  outline: 0;
  letter-spacing: .2px;
  border: 1px solid #ecebeb;
}

.all-price {
  font-size: 18px;
  font-weight: bold;
  display: inline-block;
  padding: 10px 20px;
}

.all-price>div {
  display: none
}

.all-blocks {
  width: 300px;
  height: 300px;
  background-color: #f9f9f9;
}

.all-blocks>div {
  display: none
}

#pr2-5, #bl2-5{
  display:block;
}
.1c3d{width:100px;height:50px;background-color:red;}

  Для
  <select class="drop" id="people">
    <option value="1">1-го</option>
    <option value="2" selected>2-х</option>
    <option value="s">семьи</option>
  </select>
  на
  <select class="drop" id="days">
    <option value="3">3 дня</option>
    <option value="5" selected>5 дней</option>
  </select>

Цена для 1-го на 3 дня ХХХХХХ

Цена для для 1-го на 5 дней ХХХХХХ

Цена для 2-х на 3 дня ХХХХХХ

Цена для 2-х на 5 дней ХХХХХХ

Цена для семьи на 3 дня ХХХХХХ

Цена для семьи на 5 дней ХХХХХХ

Содержимое блока для 1-го на 3 дня

Содержимое блока для 1-го на 5 дней

Содержимое блока для 2-х на 3 дня
Вот такая Хурма!

Содержимое блока для 2-х на 5 дней

Содержимое блока для семьи на 3 дня

Содержимое блока для семьи на 5 дней


text:
Q: file:// links open in non-default browser on Windows. Why? I set a new default browser and http:// urls open in it by default as they should. But I have some file:// urls and they open in the browser which previously was my default browser.
Why do file:// urls behave differently and not open in my default browser?

A: Open Control Panel > Default Programs > Set your default programs
Select your browser and click Set this program as default
This properly sets your browser as the default browser.


text:
Q: Extension of a finite group I am working on extension of finite groups. Let $G$ be a finite group with trivial center such that it has a normal subgroup $N$ with odd order and $G/N=L_{2}(p)$ ($p$ is prime). I am looking for an example of group $G$. Please let me know if you know an example of this type of group. Thanks.

A: You must have some extra condition, such as $N \le G'$, otherwise the direct product of a centreless group of odd order by $\operatorname{PSL}(2, p)$ will do.
If it's a particular example you're looking for, consider $H = \operatorname{PSL}(2,2) \cong S_{3} = \langle s, t \rangle$, where $s$ has order $3$ and $t$ has order $2$.
Consider the action on $G$ on a vector space $N = \Bbb{Z}_{7}^{2}$, where
$$
s \mapsto \begin{bmatrix}2&0\\0&4 \end{bmatrix},
\qquad
t \mapsto \begin{bmatrix}0&1\\1&0 \end{bmatrix}.
$$
(Note that $2$ is a primitive $3$-rd root of unity in $\Bbb{Z}_{7}$.)
Then $G = N \rtimes H$ will do. In fact $H$ clearly acts irreducibly on $N$, so the centre of $G$ is trivial. Here $N \le G'$.

A: How about $\text{PSL}(2,5)\cong A_5$? Consider the group $\mathbb{Z}_3^5\rtimes A_5$.


text:
Q: GridView Hyperlink with ID from database I have and oBjectDataSource which Gets my Information for my Grid View.
It shows all Information perfectly with this, automaticly generated:
<asp:BoundField DataField="Name" ItemStyle-Width="250px" HeaderText="Name" SortExpression="Name">
            <ItemStyle Width="250px"></ItemStyle>
        </asp:BoundField>

But I want to have an Hyperlink with the Field "Name" as Text and the field "UserID" as paramater in the navigateURL:
 <asp:TemplateField>
            <ItemTemplate>
                <asp:HyperLink ID="HyperLink2" NavigateUrl="~/Test.asp?id='<%# Eval("userID") %>'" runat="server"><%# Eval("Name") %></asp:HyperLink>
            </ItemTemplate>
        </asp:TemplateField>

I got an error here...
whats wrong?

A: Try this:
<asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl='<%# "~/Test.asp?id="+Eval("userID") %>' Text='<%# Eval("Name") %>'></asp:HyperLink>

A: You can also achieve it this way - easier and simpler:
<asp:HyperlinkField DataTextField="Name"
        DataNavigateUrlFormatString="~/Test.asp?id={0}"
        DataNavigateUrlFields="userID"
        />

A: Try this. It seems like the problem was in using double quotes in Eval("userID") that conflicted with opening double quotes in NavigateUrl
<asp:HyperLink ID="HyperLink2" NavigateUrl='~/Test.asp?id=<%# Eval("userID") %>' runat="server"><%# Eval("Name") %></asp:HyperLink>

A: Add this field within your gridview
In this example Id = ContentId
<asp:HyperLinkField DataNavigateUrlFields="ContentId" DataNavigateUrlFormatString="EditContent.aspx?ContentId={0}" Text="Edit" HeaderText="Edit" />


text:
Q: Perl Scripts fails to connect to Netconf server when using Net::Netconf::Manager I am using a perl script to log onto a remote router running JUNOS and get few information through the NETCONF port.
I am using the following library in order to do this
Net::Netconf::Manager
Net::Netconf::Device
Net::Netconf::Access

The script runs on the routers present on the same network but is failing to log into the routers that are on different networks, where as i am able to log onto the routers manually through Netconf over ssh.
The arguments I am parsing looks fine. Could any one help me resolve why this is happening.
If I need to do any checks in configuration (configuration looks fine to me) prior to running the script.


text:
Q: Manga about a modern day girl who is transported in time to marry a king, but is rejected due to her boyish looks There was this manga I forgot the title of and am trying to find. It's about a modern day girl who is transported in time; apparently she is considered holy and is to marry the womanising king. But due to her boyish looks she is rejected and is sent off by the king to marry one of his veteran knights, who is an old man.

A: This is The Best Is Saved for Last, aka Nokori Mono niha Fuku ga Aru.

Nako's been summoned as a sacred figure, but she doesn't have the special powers her summoners expected to make this "other world" a better place.
She's sent away to live in a detached palace with Lynn, her lady-in-waiting, until one day, she's ordered to marry an earl who's said to be the country's hero. The thing is, he's over the age of 60.

The description matches most of the question; modern age girl is summoned and ends up being married off to an older man. The king that ordered her summoning rejects her offhand for being too boyish. She was summoned as a "sacred virgin".


text:
Q: HTML form PHP post to email I'd like to make a form that posts data to my email.
I found the following code and it works fine except I didn't get any email from the form.
Here is the Php File
<?php

    // Contact subject
    $name ="$name";

    // Details
    $address="$address";
    $id="$id";
    $passport="$passport";
    $issue="$issue";
    $mula="$mula";
    $tamat="$tamat";
    $tel="$tel";
    $select_dd="$select_dd";
    $date="$date";
    $textarea="$textarea";
    $file="$file";

    // Mail of sender
     $email="$email";

    // From
    $header="from: $name <$mail>";

    // Enter your email address

    $to ='rodhiahazzahra@gmail.com';
    $send_contact=mail($to,$subject,$message,$header);

    // Check, if message sent to your email
    // display message "We've recived your information"
    if($send_contact){
    echo "We've recived your contact information";
    }
    else {
    echo "ERROR";
    }?>

A: If i am not mistaken, you need to set the SMTP server before you call mail().
ini_set('SMTP','mySMTP.serv');

Cheers
Edit:
Caution
(Windows only) When PHP is talking to a SMTP server directly, if a full stop is found
on the start of a line, it is removed. To counter-act this, replace these occurrences
with a double dot.

<?php
$text = str_replace("\n.", "\n..", $text);
?>

If you just started learning, one of the basic rules is always RTM before you start using a function. here is the link for PHP Mail function http://us3.php.net/manual/en/function.mail.php

A: Where did you try this code? Local or on a Server? Is there sendmail (or similar) installed and properly configured on your server?
Quote from PHP - Mail Function

It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.

You should check your configuration on the server and check the mail logs and you spam-folder.


text:
Q: complex numbers in binomial function form Is it possible to rewrite $f(z) = z^{n}(z^*)^{m}$ with the use of the binomial function.
The binomial function is defined as $(x+y)^{n} = \sum\limits_{k=0}^n \binom{n}{k} x^{n-k}y^{k} = \sum\limits_{k=0}^n \binom{n}{k} x^{k}y^{n-k}$
For the equation $f(z) = z^{n}(z^*)^{m}= (x+iy)^{n}(x-iy)^{m}$
[lets call $(x+iy)^{n}$ term 1 and $(x-iy)^{m}$ term 2]
we get:
$ 1: \sum\limits_{k=0}^n \binom{n}{k} x^{k}iy^{n-k}$
$ 2: \sum\limits_{k=0}^m \binom{m}{k} x^{k}(-i)y^{m-k}$
the reason why i want to rewrite f(z) is to show that f(z) is not anylical in any point, but am not sure how to draw this conclusion from here.
any help on how i should approach this? And is the binomial function applied correctly?
thanx
added Cauchy-Riemann approach as advised by David:
$f(z) = z^{n}(z^*)^{m}$
write in polar form:
$f(z) = (e^{i\theta})^{n}(e^{-i\theta})^{m} = e^{i\theta n} e^{-i \theta m}$
$f(z) = (cos(\theta n) +i sin(\theta n))(cos(\theta m) -i sin(\theta m)) = cos(\theta n)cos(\theta m) + icos(\theta n)sin(\theta m)+ i cos(\theta m)sin(\theta n) - sin(\theta n)sin(\theta m) $
f(z) = u(n,m) + iv(n,m)
$u = cos(\theta n)cos(\theta m) - sin(\theta n)sin(\theta m) $
$v = icos(\theta n)sin(\theta m)+ i cos(\theta m)sin(\theta n) $
$u_{n} = -\theta sin(\theta n)cos(\theta m) - \theta con(\theta n)sin(\theta m)$
$u_{m} = -\theta cos(\theta n)sin(\theta m)- \theta sin(\theta n)sin(\theta m)$
$v_{n} = - i\theta sin(\theta n)sin(\theta m)+ i \theta cos(\theta m)cos(\theta n)$
$v_{m} = i\theta cos(\theta n)cos(\theta m) - i \theta sin(\theta m)sin(\theta n)$
does not satisfy Cauchy-Riemann eq; not analytical.


text:
Q: How to break sentences to get clear understanding?
Sparva, unlike Treland's other provinces, requires automobile insurers to pay for any medical treatment sought by someone who has been involved in an accident; in the other provinces, insurers pay for nonemergency treatment only if they pre-approve the treatment. Clearly, Sparva's less restrictive policy must be the explanation for the fact that altogether insurers there pay for far more treatments after accidents than insurers in other provinces, even though Sparva does not have the largest population.

My understanding of this passage:
First sentence: Insurers in Sparva are paying for medical treatment, but not paying in other provinces.
Second sentence: Insurers in Sparva pay for far more treatments.
Here I have difficulty in understanding, because in first sentence person is demanding for paying, but in second sentence saying insurers are paying far more for treatment.
It is really confusing...........

A: The writer in the paragraph is trying to explain how and why automobile insurers in Sparva have to pay for far more treatments after accidents compared to any other province in Treland.
I think, what the paragraph is trying to convey is that:
In Sparva, automobile insurers pay for any medical treatment that is sought by someone who has been involved in an accident. Even if the treatment sought by that person is a nonemergency treatment, insurers in Sparva still have to pay for it.
This is not the case in Treland's other provinces, where insurers pay for nonemergency services only if they preapprove them. That's why insurers in Sparva pay for more treatments than Treland's any other province.


text:
Q: Using disconnect function on socket.io and node.js I am trying to have it so when a user disconnects from my chat room, it pops up with " has left chat room".
Here is my server code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendfile('chat/index.html');
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });

  socket.on('disconnect', function(nickname){
   io.emit('disconnect', nickname);
  });

});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

And here is my client code:
var socket = io();
  var nickname;
  var leaving;

  $('messageForm').submit(function(){
    socket.emit('chat message', (nickname + ": " + $('#m').val()));
    $('#m').val('');
    return false;
  });

  $('#nicknameForm').submit(function(){

   nickname = $('#nickname').val();

   if(nickname ==''){
  alert("Please enter a value");
  }else{
   $( "#dialog" ).dialog( "close" );
   leaving = nickname + " has left";
    }
    return false;
  });

  socket.on('chat message', function(msg){
    $('#messages').append($('<li>').text(msg));
  });

   socket.on('disconnect', function(nickname){
    socket.emit('disconnect message', nickname);
  });

At the moment, nothing appears at all, and I'm not too sure why.

A: You need to emit a unique event to the clients when another client disconnects.
Change the following:
socket.on('disconnect', function() {
  io.emit('disconnect', nickname);
});

To something like this:
socket.on('disconnect', function() {
  socket.broadcast.emit('user disconnect', nickname);
});

And add this to your client code:
socket.on('user disconnect', function(nickname){
  $('#messages').append($('<li>').text(nickname+' has left the channel.'));
});


text:
Q: Opening realm files using the realm browser I'm trying to examine my Android app's realm db contents. I've pulled my realm file from the emulator, and am now trying to open it using the Realm browser (Realm browser 2.0.1, Mac OS X El Capitan). I attempt to open the file, and the browser doesn't show anything; it's completely blank, with no Models. Tailing the file indicates that it isn't empty - what am I doing wrong here? It should be as simple as using adb to pull the file, then opening the .realm file in the editor.

A: If you only want to browse the Realm contents, use the super handy library called Stetho-Realm
Add the dependencies,
  repositories {
        maven {
            url 'https://github.com/uPhyca/stetho-realm/raw/master/maven-repo'
        }
    }

dependencies {
    compile 'com.facebook.stetho:stetho:1.4.1'
    compile 'com.uphyca:stetho_realm:2.0.0'
}

Configure it in your Application file,
public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        Realm.init(this);

        Stetho.initialize(
                Stetho.newInitializerBuilder(this)
                        .enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
                        .enableWebKitInspector(RealmInspectorModulesProvider.builder(this).build())
                        .build());
    }
}

Now go to Google Chrome and type in address bar,
chrome://inspect/#devices
Click on the connected device and start browsing the contents,

A: Instead of pulling your realm file to your mac all the time, now there is also option to view your realm files directly on you android device. You can use third party Android Realm Browser I created, to make android development with realm little bit easier. Android app will show you all realm files on your device, and you can view all your realm files real time while testing your app.


text:
Q: Elastic image slideshow don't resize image when I use the elastic image slider I have the same issue as you see at Elastic Image Slideshow Not Resizing Properly
When I resize the window on the downloaded example it works fine, but when I try to integrate the plugin using twitter bootstrap, it resize the image's width only.
when I use bootstrap and resize the window the javascript console return this message:
Uncaught TypeError: Cannot call method 'apply' of undefined

And mark the line 32 in file jquery.eislideshow.js:
line 32: jQuery.event.handle.apply( context, args );

If I resize the window in the example (without making changes), this message doesn't appear.
The first thing I did was add $.noConflict(); and now the image resizing works fine, but the thumbnail control:

*

*disaprears using firefox and

*using chrome the size is too small.

In both cases I cannot change the slide and console error return this message:
Uncaught TypeError: Property '$' of object [object Object] is not a function

Someone have a clue to solve this issue? or $.noConflict() is not a good solution?

A: replace jQuery.event.handle.apply( context, args ); with $(this).trigger(event.type, args);


text:
Q: App Engine Python module Basic and Manual scaling not working My Google App Engine application needs to run a lengthy calculation.  Automatic scaling on my module returns DeadlineExceededError, so I tried switching to manual and basic scaling.
For basic scaling, I added this to my yaml file.
instance_class: B2
basic_scaling:
  max_instances: 5
  idle_timeout: 10m

But when I send a URL request to the module, my logs get flooded with 56:
/_ah/start 404
No handlers matched this URL.

Then eventually returns:
HTTPError: HTTP Error 503: Service Unavailable

For manual scaling, I added this to my yaml file:
instance_class: B2
manual_scaling:
    instances: 1

But when I send a URL request to the module, after a while I get:
HTTPError: HTTP Error 503: Service Unavailable

But nothing in the logs.
What am I missing?  Do I need to put a handler for /_ah/start?  I thought a 404 was acceptable to start the module.

A: Figured it out.  I had to add a handler to my module.
I added:
- url: /_ah/start
  script: colors.handler.app

to my handlers: and it worked.

A: Interesting. I just ran into this issue as well.
When an instance responds to the /_ah/start request with an HTTP status code of 200–299 or 404, it is considered to have successfully started and can handle additional requests. Otherwise, App Engine terminates the instance. Manual scaling instances are restarted immediately, while basic scaling instances are restarted only when needed for serving traffic.


text:
Q: Can I use node-inspector with meteor? Can I use node-inspector with meteor?
I tried "--debug" option, and succeed to connect debug port.
But, cannot to access my codes.

exec "$DEV_BUNDLE/bin/node" "--debug" "$METEOR" "$@"

A: You might have countered the same problem like I have:
On Linux machine, Meteor script will spawn two processes:

*

*Process1: node "meteor files"

*Process2: node "your meteor files"

When you run exec "$DEV_BUNDLE/bin/node" "--debug" "$METEOR" "$@", it spawn process1 in debug mode but process2 still run in normal mode. This is why you can not see your files.
I just run the regular meteor script and send kill -s USR1 to process2 then you can see your file in node-inspector


text:
Q: Cache warming with RABL for JSON templates Okay, this post is a bit wordy before I got to the actual question, so the abridged version basically pertains to cache warming using RABL templates. When calling Rabl.render vs API calls, the caches generated do not have the same cache-keys. When using Rabl.render directly should I expect cache-keys to match, when the same template is called via an API?
K, now the wind-up..
I have a Rails API server on Heroku. I've done a lot of optimization with RABL using russian doll caching to improve the reuse of the underlying objects in collections.  Though, I am still left with collection caches, that when generated by the user on first request, is a burden on the experience ( e.g. 1+ second api calls).
When debugging a sample API call, I get the following cache actions on a given object.
...api/v1/activities/26600 :
Cache read: rabl/activities/26600-20140423170223588554000//hash/d30440d18014c72014a05319af0626f7
Cache generate: rabl/activities/26600-20140423170223588554000//hash/d30440d18014c72014a05319af0626f7
Cache write: rabl/activities/26600-20140423170223588554000//hash/d30440d18014c72014a05319af0626f7

so for the same object when calling ...api/v1/activities ( after above call ) I get the desired cache hit:
Cache read: rabl/activities/26600-20140423170223588554000//hash/d30440d18014c72014a05319af0626f7
Cache fetch_hit: rabl/activities/26600-20140423170223588554000//hash/d30440d18014c72014a05319af0626f7

This works great. The next step is to avoid having the first/any API call spend time generating the cache.
So I have been pursuing cache warming techniques to generate these collections prior to the user accessing them.  One suggestion is using wget as a way to hit the API directly ( see https://stackoverflow.com/a/543988/451488 ).  But this adds a load on the Heroku web dynos, so I want to background cache warming via sidekiq workers.
RABL provides a way to render a template from code directly ( https://github.com/nesquena/rabl#rendering-templates-directly ) which definitely seems like the right approach for this use case. Therefore my intent is to call the RABL engine through some event prior to an API call (for example  - a User login event).
So for the above API example, I'd call the following in rails console and expect a cache hit.
irb(main):002:0> @activity = Activity.find(26600)
irb(main):003:0> Rabl.render(@activity, 'api/v2/activities/show_no_root', :view_path => 'app/views', :format => :json)
Cache read: rabl/activities/26600-20140423170223588554000//hash
Cache generate: rabl/activities/26600-20140423170223588554000//hash
Cache write: rabl/activities/26600-20140423170223588554000//hash

Unexpectedly, I did not get a cache hit, but it is obvious that the cache-keys are not the same since the trailing hash signature is missing. I'm not sure why the cache-keys would be different in this case. I am left with no way to warm caches for RABL templates.
UPDATE
Turns out the hash in the trailing cache key is the template hash.
 Cache digest for api/v1/activities/_show.rabl: d30440d18014c72014a05319af0626f7

Though this tells me the source of that hash, its still not clear why calling Rabl::Renderer directly would not use this as well.

A: I wasn't able to use Rabl::Render due to the missing template digest hash in the cache-key. However by creating a sidekiq worker as below, I am able to warm the cache by calling the api as a background process, which works nicely.
 class CacheWarmApi
   include Sidekiq::Worker
   sidekiq_options :queue => :warmers

   def perform( url_helper, args, params={},method='get')
     if method == 'get'
       session = ActionDispatch::Integration::Session.new(Rails.application)
       session.get(session.send(url_helper, *args), params)
     end
   end
 end

For example :
 CacheWarmApi.perform_async( :api_v2_expensiveapi_url, args_array , params_hash)

I think this is a bit too heavy of a solution, and still think there is a solution out there with Rabl::Render.

A: I've managed to accomplish this by calling Rabl.render(ref) directly, storing the result in cache directly (Redis in my case) and using that from the request handler in the controller:
Worker:
#... do some long work to calculate object_to_render_with
#.
#.
#.

#render the result using Rabl
render_result= Rabl.render(object_to_render_with, rabl_view_relative_path,
                 view_path: File.join(Rails.root, 'app/views'),
                 format: :json) #already the default, being explicit
Redis.current.set(cache_key, render_result, ex: (DEFAULT_CACHE_EXPIRY))

Controller:
def request
    #check if we have a recent result
    res = Redis.current.get cache_key
    if res.nil?
      # No result in cache, start the worker
     Worker.perform_async
    end

    # use that cached result or an empty result
    render json: res || {status: 'in_progress'}
end

Bonus: also added a layer of tracking progress in the same manner (using other key and other request, updating the Redis manually along the progress of work).
HTH


text:
Q: C: Division of two Arrays I have two Arrays of type int. Each is about 17901 elements long. One represents the altitude, while the other the airspeed. I would like to divide the two arrays (this division will result in the mach number). How would I do this?
This is the code I'm using at the moment:
for (i = 0; i < ((size / 2) + 1); i++) {    // size/2 here is 17901
    machNumber[i] = (ASarray[i] / soundspeed[i]);
}

A: replace ((size/2)+1 by the computed size sizeof(ASarray)/sizeof(*ASarray)
This way, there will be no doubt about the loop. Of course, the size of ASarray must be statically defined (the memory must not have been allocated with malloc).
for(i = 0; i < sizeof(ASarray) / sizeof(*ASarray); i++) {
  machNumber[i] = (ASarray[i] / soundspeed[i]);
}

A: Halfing the size does not compute the number of elements correctly: you should instead divide the size of the array by the size of its element (both in bytes). Furthermore, if machNumber is a floating point type and neither ASarray nor soundspeed are, you need a cast to compute the proper Mach value:
for (size_t i = 0; i < sizeof(ASarray) / sizeof(ASarray[i]); i++) {
    machNumber[i] = (double)ASarray[i] / soundspeed[i];
}


text:
Q: snprintf confusion  I am confused with snprintf function.
First of all I have not found the function snprintf in a turbo C version compiler under stdio.h
Secondly in a GNU compiler snprintf is returning -1 when buffer size is smaller than formatted string ,though it should return the number of characters would have been printed if buffer size was sufficiently large. I have following source :
#include<stdio.h>
int main()
{
  char str[100];
  int numchar = snprintf(str,2,"ello jdj");
  printf("%d\n",numchar);
  return 0;
}

This code should output 8 according to as I know about snprintf so far. but it is returning -1 in my GNU compiler. What are the facts behind?

A: It sounds like you are using an old version of glibc. From the man page for snprintf:

The  glibc  implementation of the functions snprintf() and vsnprintf() conforms to the C99 standard, that is, behaves as described above, since glibc version 2.1.  Until glibc 2.0.6 they would return -1 when the output was truncated.


text:
Q: interpolation and projection on geo-spatial data everyone
recently I am trying to solve the location error generated by GPS, so I came up with an idea of projecting the GPS points to the nearest road, as shown bellow [1]. But I know that indeed earth is not a flat plane and general projection method is not adaptive to this problem. What should I do to deal with the projection problem that exists on sphere to get a better precision?
![1]: http://imgur.com/nL7tB7m
Similarly, when it comes to interpolation between two points, same problem emerged. I did once assume two points were closed so I could ignore the flatness
effect, but failed if their distance was long enough. Regular interpolation method won't give me a better-precision result.
![2]: http://imgur.com/rOSu8gk


text:
Q: How to use PDFThumbnailView in iOS app I am trying use PDFThumbnailView in PDFKit to display thumbnails of a pdf document but I cannot get it to work.  There are no errors showing in the console.  I just get a blank viewController. Below is my code.  Please can someone advise on where i am going wrong?
I have dragged an UIView object and assigned it the following class 'PDFThumbnailView'.

 import UIKit
 import PDFKit

 class pdfThumbNailViewController: UIViewController {

@IBOutlet weak var myThumbNailView: PDFThumbnailView!

override func viewDidLoad() {
    super.viewDidLoad()

    // create PDFView Object
    // Then assign this object as the variable of thumbnailview object
    let myPDFViewObject = PDFView.init()
    if let path = Bundle.main.path(forResource: "paper", ofType: "pdf"){
        let url = URL.init(fileURLWithPath: path)
        if let pdfDocument = PDFDocument.init(url: url){
            myPDFViewObject.document = pdfDocument

        }
    }
    // Setting thumbnail size
    let size = CGSize.init(width: 50, height: 50)
    myThumbNailView.thumbnailSize = size
    myThumbNailView.layoutMode = .vertical
    myThumbNailView.pdfView = myPDFViewObject

}
}

A: You get a blank ViewController because you aren't using your myThumbnailView at all..
In viewDidLoad, you created a thumbnail view and assigned data to it, but you never actually use your IBOutlet myThumbNailView.. therefore it is blank and the local one gets deallocated when viewDidLoad finished.
TLDR: thumbNailObject != myThumbNailView.. You're using the wrong object reference.

A: Yes - in your current code you have a memory problem, that's why you dont see anything in the end:
You have defined your let myPDFViewObject: PDFView inside of your viewDidLoad() which then lives only in that methods block; as soon as the end of the method is reached your PDFView gets deallocated, and in turn the PDFThumbnailView has no associated PDFView anymore.
You can resolve your problem by just moving let myPDFViewObject: PDFView above and outside of your viewDidLoad(), which ensures the PDFView is going to live longer
Happy coding!
let myPDFViewObject = PDFView()
override func viewDidLoad() {
    super.viewDidLoad()

    // Then assign this object as the variable of thumbnailview object
    if let path = Bundle...


text:
Q: Inspect function of eclipse tricks me like a dummy, why does it seem to be that tricky while debugging? Eclipse is awesome for writing java programs but today I find that it's awesome to trick new coders like me. @_@
I write a snippet as following,
public static void main(String[] args) {
    for(int i=0;i<3;i++){
        System.out.println("i = " + i);
    }
}

then I add a breakpoint at the line of "System.out.print....", click "Debug" button, eclipse goes to the "Debug" perspective and the line of breakpoint is highlighted, then I move the cursor over variable "i", its value is "0" as expected.
And then, I select the "i++" and click "Inspect"(or press "Ctrl+Shift+I") once, I move the cursor over variable "i", its value changed to "1". I repeat "Inspect" again, the value of i changed to "2"......(its value will add by 1 every time I clicked the "Inspect")!!
Why does this happend!? I ONLY want to watch the value of "i" for debug propuse, DO NOT want to really change its value until I step into next statement. I think that "Inspect", as well as "Display" are only for viewing the variable/expression, they should not impact the value, but in this case, it doesn't work as I expect to.
Could anyone tell me what went wrong?
My eclipse version info:
Version: Indigo Service Release 2
Build id: 20120216-1857

A: If you inspect an expression, eclipse has to execute that expression so you can get the value. Therefore, if you inspect i++, eclipse adds one to i.
Think about it this way: If instead of i++, you inspected myFunction(i), would you expect eclipse to execute the function "myFunction" to get the value? It's the same with i++.

A: If you are concerned about displaying/showing values while debugging and do you want to be sure not affecting the value, you should select the variable or expression and use the "Watch" option.
This will track the variable/expression value without executing, just updating the new value each time this is run. I think is the most secure way.

A: As Pablo mentioned, it has to evaluate the code in order to tell you what value it returns. You could instead put a watch on "i+1" and that would give you the value you want without the side effect you don't want.
Basically, you need to be aware of any side effects of anything you launch, whether from the "main" code or from the debugging tools. As Erhannis mentioned, this is very useful at times for modifying values while debugging your code. (For example, you can verify that a tweak/fix is indeed helpful before actually tweaking your code.)
You were expecting "an isolate area" but this would be extremely hard to do, especially in an object-oriented context where many objects are linked to many other objects. Running the whole thing in parallel might sometimes work, but you'd lose the tweaking ability above. And in any context, you'd run into tons of problems with fighting over resources; e.g. both copies trying to read/write a particular file such as a log file. Also, the two execution paths could diverge, leading to incorrect/misleading watch values.
So, preventing such side effects is not really a feasible option here and would rarely be useful anyway. Just expect that the watches can both reflect and affect the code execution.


text:
Q: caret in mvprintw but only in loop I have the following program
#include <ncurses.h>

int main() {
    initscr();
    const char c = static_cast<char>(65);
    mvprintw(0, 0, "%s", &c);
    getch();
    endwin();
    return 0;
}

it prints simple "A" and waits.

If I modifying "x" argument of mvprintw
        mvprintw(0, 1, "%s", &c);

it will print "A" with empty space prepend on beginning.

If I will add for loop starting from 0 it also works as expected
int main() {
    initscr();
    for (int i = 0; i < 1; i++) {
        const char c = static_cast<char>(65);
        mvprintw(0, i, "%s", &c);
    }
    getch();
    endwin();
    return 0;
}

will show the same result as in first example.
But if this loop starts from 1 there is stragne ^A at the end.
This code:
int main() {
    initscr();
    for (int i = 1; i < 2; i++) {
        const char c = static_cast<char>(65);
        mvprintw(0, i, "%s", &c);
    }
    getch();
    endwin();
    return 0;
}

produces

and I even do not know how to debug it?

A: If mvprintw is anything like printf then you are supposed to provide a nul terminated string when you use %s. Try this instead
const char c[] = { static_cast<char>(65), '\0' };
mvprintw(0, i, "%s", c);

Note in this version c not &c.


text:
Q: err_too_many_redirects when trying to redirect non www to www Inside virtuahost apache conf file /etc/apache2/sites-available/000-default.conf.
I tried to put these code inside apache conf file.
ServerName example.com
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule ^/(.*)$ http://www.example.com/$1 [L,R=301]

Also I tried.
< If "%{HTTP_HOST} != 'YOUR-DOMAIN.com'">
Redirect "/" "http://www.YOUR-DOMAIN.com/"
</If>

Also did this.
<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost *:80>
    ServerName www.example.com
    # real server configuration
</VirtualHost>

A: To resolve your problem you have to understand the concept of 'NameVirtualHosting' and Ubuntu's special way of deploying the apache web service.
NameVirtualHost
Your (local) apache webserver can serve different web sites on the same adress as long as they are 'named' differently. The webserver tries to match the Host name (e.g. example.com) with a corresponding Servername or ServerAlias directive in you apache configuration. For each 'website' you need a separate <VirtualHost> container in your configuration; in your case you need one for example.com and another for www.example.com.
Apache Webserver and Ubuntu
The Ubuntu apache2 server package does alter the default binyries, configuration files and directories:

*

*The Apache Webserver binary is /usr/sbin/apache2

*The server root directory is /etc/apache2

*The main configuration is /etc/apache2/apache2.conf

*Additional server configurations go to /etc/apache2/conf.d

*Module Configurations are in /etc/apache2/mods-available/

*VirtualHost sites are configured in /etc/apache2/sites-available/
So far, so easy; now comes the tricky bit (for me that is): with Ubuntu you get four commands to enable/disable modules and (!) VirtualHosts configuration:

*

*a2ensite / a2dissite

*a2enmod / a2dismod

with these commands you enable the actual websites, that you have configured in /etc/apache2/sites-available/. There is at least one default virtualhost configuration default.conf which, when enabled by a2ensite default is linked as sites-enabled/000.default.conf.
And it all works, because the main config apache2.conf contains this Include directive:
Include sites-enabled/
Let's get practical:
Remove all symbolic links in sites-enabled/ and if you happen to have stored actual config files in sites-enabled/ move those to sites-available (be careful not overwrite existing files in sites-available/ rather rename the old ones).
Now, you create two new virtualhost files in sites-available/:
vi /etc/apache2/sites-available/0_www.example.com
<VirtualHost *:80>
    ServerName www.example.com

    DocumentRoot /var/www
    DirectoryIndex index-www.html
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /var/www/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error-www-example-com.log
    LogLevel warn
    CustomLog ${APACHE_LOG_DIR}/access-www-example-com.log combined
</VirtualHost>

vi sites-available/1_example.com
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName example.com

    ErrorLog ${APACHE_LOG_DIR}/error-example-com.log
    LogLevel warn
    CustomLog ${APACHE_LOG_DIR}/access-example-com.log combined

    RewriteEngine On
    RewriteRule ^/(.*) http://www.example.com/$1 [R=302]
</VirtualHost>

and enable them and the script creates a symbolic link from sites-available/ to sites-enabled/:
sudo a2ensite 0_www.example.com
sudo a2enmod rewrite
sudo a2ensite 1_example.com
(restart the apache2 service - service apache2 restart or systemctl restart apache2)
ls -l sites-enabled/
total 0
lrwxrwxrwx 1 root root 30 Jan  8 17:59 example.com -> ../sites-available/example.com
lrwxrwxrwx 1 root root 34 Jan  8 17:52 www.example.com -> ../sites-available/www.example.com

We need simple index pages
# cat /var/www/index-non.html

example.com

This is the NON-www index page

# cat /var/www/index-www.html

www.example.com

This is the www.example.com index page.

Please keep in mind, that the first <VirtualHost >directive encountererd by the apache webserver will be the default Webcontainer, so the order of the VirtualHost directives is important; in our case, if I call the webserver with no specific hostname or a hostname, that is not configured, I am being served the www-index because it is the first virthost directive.
# No Hostname given
curl http://127.0.0.1/

www.example.com

This is the www.example.com index page.

# index-www
curl -H "Host: www.example.com" http://127.0.0.1/

www.example.com

This is the www.example.com index page.

# non-www index
curl -H "Host: example.com" http://127.0.0.1/
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<title>302 Found</title>

Found

The document has moved here.

<address>Apache/2.2.22 (Ubuntu) Server at example.com Port 80</address>

(Please note the use of the Host Header variable -H)
To keep in mind is that for NameVirtualHosting to work, both webserver and webclient have to be correctly configured.
I hope my instructions can help you to solve your problem.


text:
Q: Extern variables aren't initialized In a project I am doing I use some global variables using "extern" so that all files can access them.
The following is my case:
main.cpp:
#include <iostream>
#include "test.h"

std::string val2 = val;

int main()
{
    std::cout << val2 << std::endl;
}

test.h:
#pragma once
#include <string>

extern std::string val;

test.cpp:
#include "test.h"

std::string val = "Hello World";

And what I am expecting to get as output is "Hello World" however it will just print a new line.
If instead of std::string I use a built-in type (like int) it will work as expected.
From my understanding, what happens is val has not been initialized when we are trying to assign it to val2, so we end up copying nothing, then after that (probably) val gets initialized with the value Hello World but since we are printing val2 we get only the new line.
So my question is, How can I force val to initialize first.
If that's not possible, how can I make global variables (that can be used between multiple files)
NOTE: Those are not my real files but I checked and the problem appears here as well, I think this counts as a Minimal Code Example (or whatever it is called)


text:
Q: index value of the tuples write a function named sums that takes 3 arguments: 2 lists of integers nums1 and nums2, and an integer target; then return a tuple containing indices i and j of the two numbers in nums1 and nums2, respectively, where the numbers at that indices add up to target (i.e, nums1[i] + num2[j] = target). If there is no solution, return "Not found". The function sums must contain exactly only one loop (either a for-loop or a while-loop), otherwise you will get no point. A nested-loop is considered as more than one loop.
def sums(nums1, nums2, target):
nums1 = [11, 2, 15, 7, 8]
nums2 = [2, 3, 4, 5]
target_number = 9
for i in range(len(nums1)):
    for j in range(len(nums2)):
        total = nums1[i] + nums2[j]
        if total == target:
            a = (nums1[i], nums2[j])
            print(a)

This is the code that i have written and i am struggling to get the index values can anyone please  help!

A: You can solve it in O(n) with a dictionary and a single for loop;
nums1 = [11, 2, 15, 7, 8]
nums2 = [2, 3, 4, 5]
target_number = 9

def sums(nums1, nums2, target):
    d = dict(zip(nums2, range(len(nums2))))
    for i,n in enumerate(nums1):
        remainder = target-n
        if remainder in d:
            return (i, d[remainder])
    return 'Not found'

sums(nums1, nums2, target_number)

Output: (3, 0)
Be aware that while there is a single for loop, the code is looping to construct the dictionary, it's just not visible directly.

A: Here's an alternative solution using basic index incrementing. It's not as efficient as using a dictionary and finding the difference, as this naively iterates over b as many times as there are items in a. In the worst case, with two equal-length lists, this solution is O(n^2).
Although it may actually be faster in smaller cases, if there happens to be a bottlneck around the creation of any of the intermediate data structures that @mozway uses. I'm only speculating on this, I don't actually know.
def target_sum_idxs(a, b, target):
    i = j = 0
    while i < len(a):
        if a[i] + b[j] == target:
            return i, j
        j += 1
        if j == len(b):
            i += 1
            j = 0
    return "Not found"

Demo:
>>> target_sum_idxs(nums1, nums2, target=9)
(3, 0)

>>> target_sum_idxs(nums2, nums1, target=9)
(0, 3)

>>> target_sum_idxs(nums1, nums2, target=999)
'Not found'

A: just one little thing.
Check that the variable in the if statement is really your parameter, not the "target_number" variable.
Also, in the if statement, you need to stop execution, maybe you can use a break or return the tuple.
I would use something like this:
def sums(nums1, nums2, target):
    for i in range(len(nums1)):
        for j in range(len(nums2)):
            total = nums1[i] + nums2[j]
            if total == target:
                a = (i, j)
                return a

    return "Not found"


text:
Q: Caching of numba functions leads to error Whenever I use caching on a function, ..
@jit(cache=True)
def test(x):
    return x

.. I get a RuntimeError similar to ..

RuntimeError: cannot cache function 'test.test': no locator available for file '/tmp/ipykernel_3392909/373547737.py'

.. and yes, /tmp should be writable (rwxrwxrwt).
Whats happening here?

A: One file is cached by another.
When @jit compiles a function, it creates a '.py' file with the same name that contains the bytecode of that function.
At every call to test, Numba tries to use this file and it fails because there is no locator for this file in the cache.
This issue has been reported already.

A: It seems to have been caused by a mix-up of conda and pip. I thought conda would prevent that, but no.
After having wiped pip and conda completely, it now works by using conda alone.
Additionally, there seems to be a bug involved.
Advice to the outside world: Don't use conda if you don't have a special reason to.


text:
Q: How to Compress/Zip a directory(with files) without creating directories from my file system ? I have problems with ZipArchive that compresses a directory of files. Most of the samples from the internet is easy to understand and it work EXCEPT that when I look at the zip result of my zipping process. My zip file creates folders based from my filesytem directory.

For example:

C > workspace > myproject > temp > ziptest > (files....)
When it should suppose to contain only a folder that starts with "ziptest" as the parent folder of my zipfile. Can anyone help me with this. How do I get rid of unecessary folders that have been created in my zip file.
My code looks like this:
$zip = new ZipArchive();
$zip->open($zipFile, ZIPARCHIVE::CREATE);
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($tempFile));
foreach ($iterator as $key => $value) {
  $zip->addFile(realpath($key), $key);
}
$zip->close();


text:
Q: Difference between a variable and a declared object This might be more of a general question, but I hope this is the right place to ask.  I'm not new to writing code, but somewhat new to VB.net.  My background is not in computer science, so what I do know I know from the few classes I've taken, my own personal interest, and professional needs.
What I'm wondering is what the technical difference is between a variable like a string:
Dim myString As String

and a variable like a collection which must be instantiated:
Dim myCollection As Collection
myCollection = New Collection

I realize the latter is an object, but what I'm not sure I understand is why both the former and the latter aren't implemented in the same manner when neither require references outside of Visual Basic?

A: The answer is different for VBA and VB.NET.
Actually, in VB.NET, you do need to instantiate a String.  For instance, the following code throws and exception in VB.NET:
Dim s As String
Dim same As Boolean = s.Equals("")  ' Throws NullReferenceException

The reason it throws an exception is because you are trying to call the Equals method on using a variable which is not currently referencing (pointing to) any object.  In other words, the s variable is currently null (Nothing in VB).  To fix it, you'd need to instantiate an object, like this:
Dim s As String = ""
Dim same As Boolean = s.Equals("")  ' Works (same = True)

However, your question is still valid because you don't need to instantiate some types of variables such as Integer:
Dim i As Integer
Dim same As Boolean = i.Equals(0)  ' Works (same = True)

The different between the two is that String is a Reference Type (a Class) whereas Integer is a Value Type (a Structure).  You can read more about the difference on the MSDN here.
In VBA, the difference is similar, a bit more murky.  VBA has a set of core primitive data types which do not require instantiation (like value types in .NET), and everything else is considered an Object, which does require instantiation (like reference types in .NET).  Also, VBA allows you create Structure types which are treated like primitive types in that you do not instantiate them.
To further complicate things, in VBA, String is a primitave data type, but in VB.NET it is a reference type.


text:
Q: Fetch data having a specific id defined in the view instance I need to fetch data having a specific id
and which id is defined in the view instance.
Here the example, see the comments in MyModel definition:
// my view instance
var myView = new MyView({
    model: {id: 12321}
});

MyView = Backbone.View.extends({
        initialize: function()
        {
            myModel.fetch();
        }
});

MyModel = Backbone.Model.extends({
        url: function url ()
        {
          // how to get the id passed to view instance?
          return "http:..../id/" + this.id;
        }
});

A: Model should not has any knowledge of the existence of the View, so the View should be the one that sais to the Model which id to fetch:
MyView = Backbone.View.extends({
        initialize: function()
        {
            myModel.id = this.model.id;
            myModel.fetch();
        }
});

(I've used your example code as template for my example, but I have to say I feel several weird things on it, I suppose is just a matter of taste)
Update: My very personal taste opinions
Is very difficult to do this but as you requested I'll share with you my very personal code review of your example code. Take this as it is: a very humble opinion.
this.model confused
I would not use attribute names that can create confussion:
var myView = new MyView({
    model: {id: 12321}
});

Into this instance this.model is making reference to a raw Hash but in a Backbone context this is against the intuitive feeling that this is gonna be a Backbone.Model.
I rather change it for something like this:
var MyView = Backbone.View.extend({
  initialize: function( opts ){
     this.model_id = opts.model_id;
  }
})
var myView = new MyView({ model_id: 12321 });

I think this naming is more intuitive.
close variables scopes
This code can only works if myModel is in an scope bigger that it should be:
MyView = Backbone.View.extends({
        initialize: function()
        {
            myModel.fetch();
        }
});

I rather prefer using more encapsulated scopes, even if myModel has been declared in the out-side context of your View the View should use a variable of its private context. For example
var MyView = Backbone.View.extends({
  initialize: function( opts ) {
    this.model = opts.model;
    this.model.fetch();
  }
});

var myView = new MyView({ model: myModel });

Check the detail that I have also added var in front of MyView because if not MyView will be a window global variable.
use the Backbone urlRoot
In your example, this ...
MyModel = Backbone.Model.extends({
    url: function url ()
    {
      // how to get the id passed to view instance?
      return "http:..../id/" + this.id;
    }
});

... can be summarized as this:
MyModel = Backbone.Model.extends({
    urlRoot: "http:..../id"
});


text:
Q: C++ weird 'undefined reference' error @ link-time when one specific function's definition is in another file I have a small C++ project whose structure looks like this

*

*build

*

*obj

*makefile

*include

*

*utils.h

*src

*

*utils.cpp

*main.cpp

The header files contains custom types and multiple functions' declarations like so
#pragma once
#include "utils.h"

...

#include <boost/math/constants/constants.hpp>
#include <gsl/gsl_poly.h>

typedef boost::multiprecision::float128 float128;
typedef boost::multiprecision::mpf_float_1000 float1k;

template<typename type>
int compute_n(const type& lambda_max, const type& lambda_min);

template<typename type>
float1k compute_estimate(const type& input_lambda, const int& num_nodes, const std::string& envelope);

...

Their definitions are implemented in utils.cpp. In main.cpp the functions are called like so
#include "utils.h"

int main(int argc, char** argv)
{

    float128 lambda_max = 1.0, lambda_min = 2.0;

    ...

    int n_nodes = compute_n(lambda_max, lambda_min);

    ...

My makefile is simple
CXX = g++

INCDIR = ../include
SRCDIR = ../src
OBJDIR = obj

OBJ = $(OBJDIR)/main.o $(OBJDIR)/utils.o

CXXOPTIONS = -g #-Wall
CXXFLAGS = $(CXXOPTIONS) -I $(INCDIR)

LDLIBS = -lm -lgsl -lgslcblas -lgmp -lquadmath
LDFLAGS = $(LDLIBS)

default: $(OBJ)
    $(CXX) $^ -o HiSink $(LDFLAGS)

$(OBJDIR)/main.o: $(SRCDIR)/main.cpp $(SRCDIR)/utils.cpp $(INCDIR)/utils.h
    $(CXX) -c $< -o $@ $(CXXFLAGS)

$(OBJDIR)/utils.o: $(SRCDIR)/utils.cpp $(INCDIR)/utils.h
    $(CXX) -c $< -o $@ $(CXXFLAGS)

clean:
    rm -f $(OBJDIR)/*.o HiSink

Both source files are compiled and object files are created. At link time however I get an undefined reference for one specific function, that is compute_n which I left in the scripts above on purpose. The error is
/usr/bin/ld: obj/main.o: in function `main':
/home/path-to-main/main.cpp:30: undefined reference to `int compute_n<double>(double const&, double const&)'
collect2: error: ld returned 1 exit status

Even weirder is that if I "move" the definition of compute_n in main.cpp the issue disappears, the linker doesn't complain and the executable is created and runs correctly.
I want to stress on the fact that I have multiple (6) functions declarations in utils.h and all their definitions are in utils.cpp yet the only one that does this little trick is compute_n.
Can anyone shed some light here (I am a begineer in C++) ?


text:
Q: R - Haven - SPSS (.sav): Iterate over all columns and replace name and label of columns for a project I needed to merge an Excel and an SPSS file with R.
Not sure if this was my best idea. I got the merge done, however in the process
I had to use the attribute(col)$label as the name in order to work.
My final merged data.frame has thus way to long column names including special characters (e.g. :).
Here are the first few examples how the colnames of the current merged df look like
colnames(combined_retro)
  [1] "Zeitpunkt zu dem das Interview begonnen hat (Europe/Berlin)"
  [2] "Studiencode: [01]"
  [3] "Format"
  [4] "Geschlecht"
  [5] "Alter (direkt): Ich bin   ... Jahre"
  [6] "Staatsangehörigkeit"

So I created another data.frame Naming_Back in which I have two columns: Name Label
Naming_Back
   Name     Label
 1 CASE     Interview-Nummer (fortlaufend)
 2 SERIAL   Seriennummer (sofern verwendet)
 3 REF      Referenz (sofern im Link angegeben)
 4 QUESTNNR Fragebogen, der im Interview verwendet wurde
 5 MODE     Interview-Modus

So now I would like to iterate over the Columns of my merged data.frame combined_retro
and check if the current name of the column (e.g. "Zeitpunkt zu dem das Interview begonnen hat (Europe/Berlin)" is available in the Label column of the second (Naming_Back) data.frame.
If it is I would like to exchange the current column name with the one provided by the Name column.
My Current approach is the following loop:
for(i in 1:ncol(retro)) {       # for-loop over columns
  new_name_buffer <- Naming_Back %>%
    filter(Label == colnames(retro[ , i]))
  if(!(is_empty(new_name_buffer$Name))){
    colnames(retro[ , i]) <- new_name_buffer$Name
    print(colnames(retro[ , i]))
    print(new_name_buffer$Name)
  }
}

Examples for the print commands from the loop
[1] "Geschlecht"
[1] "SD02"
[1] "Staatsangehörigkeit"
[1] "SD04"
[1] "Staatsangehörigkeit: Anders"
[1] "SD04_04"

So obviously the problem is this line colnames(retro[ , i]) <- new_name_buffer$Name as it does not change the column name. Has anyone a quick idea how to fix it?
EDIT: Found a solution, by creating a character vector and stepwise filling it with either the abbreviated name when available or the old name if not
new_col_names <- c()
for(i in 1:ncol(retro)) {       # for-loop over columns
  new_name_buffer <- Naming_Back %>%
    filter(Label == colnames(retro[ , i]))
  if(!(is_empty(new_name_buffer$Name))){
    colnames(retro[ , i]) <- new_name_buffer$Name
    new_col_names <- c(new_col_names, new_name_buffer$Name)
  }
  else{
    new_col_names <- c(new_col_names, colnames(retro[ , i]))
  }
}
colnames(retro) <- new_col_names

EDIT 2: Just found an alternative solution to overwrite a column name while iterating over the columns with a for loop, you can just do names(dataframe)[index] and then just assign a  new value with <- "newColName"
  for(i in 1:ncol(retro)) {       # for-loop over columns
  new_name_buffer <- Naming_Back %>%
    filter(Label == colnames(retro[ , i]))
  if(!(is_empty(new_name_buffer$Name))){
    names(retro)[i] <- new_name_buffer$Name
    print(colnames(retro[ , i]))
    print(new_name_buffer$Name)
  }
}

A: The problem (as correctly identified in the comments to the OP by @IRTFM) with the original code was, that the assignment of the new column name: colnames(retro[ , i]) <- new_name_buffer$Name was not working properly, as colnames does not work on an atomic vector.
I found work-around to overwrite a column, name while iterating over the columns of a data.frame with a for loop. One can just do call names(dataframe)[index] and then just assign a new column name with <- "newColName"in my example the important line would thus look like this:
Assigning a new column name
names(retro)[i] <- new_name_buffer$Name

The Complete solution with the for loop
for(i in 1:ncol(retro)) {       # for-loop over columns
      # Check if a row with the label is available in the Naming_Back dataframe
      new_name_buffer <- Naming_Back %>%
         filter(Label == colnames(retro[ , I]))

  # When a Name matching the label is found, replace the old name
  if(!(is_empty(new_name_buffer$Name))){
    names(retro)[i] <- new_name_buffer$Name
  }
}


text:
Q: jQuery: Search for div containing specific mark up I'm stuck with a editor that outputs

 when the textfield is empty and now I want to target the divs with that none content.
I've been trying .filter, text lengths, :contains, .html and what not but can't seem to find a way to look for a
 that contains that mark up.
Other
 may contain that and some text which would be just normal and fine, so I will need to target the code below specifically.

Any idea how to approach this?

A: Try this...
var $div = $("div").filter(function() {
    return this.innerHTML.replace(/\s+/g, '').toLowerCase() == "

";
});

The resulting object ($div) will be a jQuery collection of the divs you're interested in.

A: Try this jquery code :
$('div').each(function() {
    if ($.trim($(this).text) == '') {
        $(this).remove()
        // or maybe : $(this).empty()
    }
})


text:
Q: Phone can't send SMS message from APP, in emulator work great I have to make a mega-simple app that, when a button is pressed, reads the number entered in the text field and sends an SMS to that number. The last time I had contact with Java was a couple of years ago but I managed to stick something out there with the help of the Internet. The code for the SMS sending itself looks like this:
package com.example.nextchat;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

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

        int PERMISSION_ALL = 1;
        String[] PERMISSIONS = {
                Manifest.permission.READ_SMS,
                Manifest.permission.RECEIVE_SMS,
                Manifest.permission.SEND_SMS,
        };

        if (!hasPermissions(this, PERMISSIONS)) {
            ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
        }

        Button button = findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                SmsManager sm = SmsManager.getDefault();
                sm.sendTextMessage("48123456789", null, "Bla bla bla", null, null);
            }
        });
    }

    public static boolean hasPermissions(Context context, String... permissions) {
        if (context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

}

I added the necessary permissions to the file AndroidManifest.XML:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.nextchat">

    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Nextchat"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I checked in the emulator and everything works, the message shows as sent in the device. The problem occurred when I generated the APK file and wanted to test the code on a real phone. The app launches normally and asks for permissions to send and read SMS. However, the problem is that the SMS admittedly shows up in the default SMS app and even matches the contact based on the number but the message does not send. With every such message I get the message "Not sent. Touch to try again. Of course, when I touch, the message sends correctly. I have tried on two phones, one with Android 12, the other Android 10, and in both cases the same error occurs. Do any of you know what this could be about? I accept any advice because I have no idea what is going on.


text:
Q: Multithreading Query Code Throwing Null Exception Whats wrong with the below code? I have very little experience with threading, my limited understanding based on an msdn tutorial I may have misinterpreted is that the t1 and t2 declarations, the address of bits, I would be able to run the methods multithreaded (is that the best way to do it?)
And this isn't working. Previous the code worked fine for the methods that are there. The error flagged is

system null exception, value can't be zero...

Oh also, it's reading a .txt so don't worry about that being thread unsafe stuff I don't think.
Private Sub Rreader(path As String)
  Dim reader1 As New RReaderClass
  Dim t1 As New System.Threading.Thread(AddressOf reader1.stage1)
  Dim t2 As New System.Threading.Thread(AddressOf reader1.stage2)
  Try
    t1.Start()
    t2.Start()
  Catch ex As Exception
    MessageBox.Show(ex.toString)
  End Try
End Sub

Private Sub stage1()
  Try
    a()
    b()
    c()
  Catch ex As Exception
    MessageBox.Show(ex.toString)
  End Try
End Sub

Private Sub stage2()
  ….


text:
Q: Updating 3 Rows (fixed) Using 1 UPDATE Statement So far I have this code updating only 1 row but is there a way to specify the three rows? (3 different ID's)
Public Shared Sub UpdatePrice(ByVal NewPrice As Decimal, ByVal id As Integer)

    Dim dtoffenseinfo As New DataTable

    If Not DBConnection.State = ConnectionState.Open Then
        'open connection
        DBConnection.Open()
    Else

    End If

    cmd.Connection = DBConnection

    cmd.CommandText = "UPDATE tblStockPrice " & _
                   " SET Price=" & NewPrice & " WHERE id=" & id & ""

    cmd.ExecuteNonQuery()

    DBConnection.Close()
End Sub

I assume I need 2 more parameters for the other two rows and that would be fine.

A: You can use one UPDATE statement with an appropriate WHERE clause to affect multiple records but, if you want to affect each record differently, calling ExecuteNonQuery once is not a very good option.  Just create one command with appropriate parameters and then you can set the Value of each parameter multiple times to affect multiple records, e.g.

Using connection As New SqlConnection("connection string here"),
      command As New SqlCommand("UPDATE MyTable SET Price = @Price WHERE Id = @Id", connection)
    Dim priceParameter = command.Parameters.Add("@Price", SqlDbType.Money)
    Dim idParameter = command.Parameters.Add("@Id", SqlDbType.Int)

    Dim prices = {12.45, 132.67, 9.8}
    Dim ids = {1, 19, 56}

    connection.Open()

    For i = 0 To 2
        priceParameter.Value = prices(i)
        idParameter.Value = ids(i)

        command.ExecuteNonQuery()
    Next
End Using


text:
Q: Find a text string in a file and output only the rest of the text that follows it? I am finding a lot of posts on this forum that have to do with finding various values in a text file and outputting text surrounding it.  However, I don't seem to find any "stream oriented".
I want to find a particular string in a file, and output only the text that follows it until the end of the file is reached.  In other words, I want something that acts like a filter that ignores the text in a file until a specific string value is reached, and then from that point on outputs text to stdout until the end of the file.  I want to use stdout so I can pipe output to a file if I so chose.
Is there a Linux text utility that will help me do this and if so, how?  Or if I need to write a bash shell script to accomplish that, what are the general steps and command line utilities I would use to do this?
For example, given a sample file below:
one
two
three
four
five

Suppose I wanted to output all the text after the "three" so the result would be:
four
five

NOTE: I did find this seemingly related post but as you can see it's a bit of a mess:
how to find a text and copy the text after?

A: With GNU sed:
sed 0,/three/d

Note that Linux is a kernel, it doesn't have utilities. GNU sed is the sed implementation commonly found on GNU/Linux systems like Debian GNU/Linux. GNU sed predates Linux and has been compiled to run on most Unix-like systems including most of those running Linux as their kernel. It is itself a Free, Libre and OpenSource re-implementation (with a few extensions including that 0 address) of the UNIX sed utility from the late 70s.

A: Use awk:
awk 's;/^three$/{s=1}' file

or
awk 's;$0=="three"{s=1}' file

*

*s; will print the line if variable s is true, which is the case first time after the pattern/word has been found ...

*/^three$/{s=1} will set variable s to true (1) if pattern/word is found.

A: With POSIX sed you can do as:
sed -ne '/three/!d;:a;n;p;ba' inp.file

Using Perl:
perl -lne 'print if 1 <(/three/...eof)' inp.file


text:
Q: Apache rewrite for sub-domain I have 2 applications running on JBoss with an Apache server in-front.
The applications are currently being proxied by Apache:
ProxyPass /App1 http://mydomain.com:8080/App1
ProxyPassReverse /App1 http://mydomain.com:8080/App1
ProxyPass /App2 http://mydomain.com:8080/App1
ProxyPassReverse /App1 http://mydomain.com:8080/App1

I have 2 sub-domains:
 app1.mydomain.com
 app2.mydomain.com

So I can now access my apps with:
 http://app1.mydomain.com/App1
 http://app2.mydomain.com/App2

How can I configure Apache so that I can serve these apps from:
 http://app1.mydomain.com
 http://app1.mydomain.com

Is it possible to do this with a mod_rewrite rule?
Thanks!

A: The way to do this 'correctly' is to set up a couple of vhosts in your apache config like so:
NameVirtualHost *:80 #only if this is not present earlier in httpd.conf

<VirtualHost *:80>
    ServerName: app1.mydomain.com
    ProxyPass http://mydomain.com:8080/App1
    ProxyPassReverse http://mydomain.com:8080/App1
</VirtualHost>

<VirtualHost *:80>
    ServerName: app2.mydomain.com
    ProxyPass http://mydomain.com:8080/App2
    ProxyPassReverse http://mydomain.com:8080/App2
</VirtualHost>