text:
Q: C# PDF Delete - File 'being used by another process' I've searched far and wide for an answer to this question. I know WHY I'm received the exception, but I can't for the life of find the cause of it in my code.
Basically, my code creates four separate PDF files, joins them into on big PDF file and then deletes the original four files. Everything words fine, except I receive an IOException when trying to delete the files because they are 'being used by another process.'
Here is the code I use to merge the files:
private static Document MergeFiles(string[] fileNames, string finalFileName)
{
    Document doc = new Document(PageSize.A4, 20, 20, 25, 25);
    if (fileNames.Length > 0)
    {
        int a = 0;
        PdfReader reader = new PdfReader(fileNames[a]);
        int n = reader.NumberOfPages;
        FileStream output = new FileStream("C:\\temp\\" + finalFileName, FileMode.Create);
        PdfWriter writer = PdfWriter.GetInstance(doc, output);
        doc.Open();
        PdfContentByte cb = writer.DirectContent;
        PdfImportedPage page;
        int rotation;

        while (a < fileNames.Length)
        {
            int i = 0;
            while (i < n)
            {
                i++;
                doc.SetPageSize(reader.GetPageSizeWithRotation(i));
                doc.NewPage();
                page = writer.GetImportedPage(reader, i);
                rotation = reader.GetPageRotation(i);
                if (rotation == 90 || rotation == 270)
                    cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                else
                    cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
            }
            a++;
            if (a < fileNames.Length)
            {
                reader = new PdfReader(fileNames[a]);
                n = reader.NumberOfPages;
            }
        }
    }
    doc.Close();
    return doc;
}

And here is the code for deleting the files:
private static void DeleteFile(string[] fileNames)
{
    if (fileNames != null)
    {
        for (int x = 0; x < fileNames.Length; x++)
        {
            if(!fileNames[x].Equals(""))
                System.IO.File.Delete(fileNames[x]);
        }
    }
}

Any assistance would be greatly appreciated. I presume somewhere in the loop when I'm merging the documents, something isn't being closed (reader/writer) but I've tried lots of different combos and nothing seems to work. It's REALLY starting to annoy me.
UPDATE
Thanks for your comments, everyone. I've amended my code to this:
private static Document MergeFiles(string[] fileNames, string finalFileName)
{
    Document doc = new Document(PageSize.A4, 20, 20, 25, 25);
    if (fileNames.Length > 0)
    {
        while (a < fileNames.Length)
        {
            using (PdfReader reader = new PdfReader(fileNames[a]))
            using (FileStream output = new FileStream("C:\\temp\\" + finalFileName, FileMode.Create))
            using (PdfWriter writer = PdfWriter.GetInstance(doc, output))
            {
                int n = reader.NumberOfPages;
                doc.Open();
                PdfContentByte cb = writer.DirectContent;
                PdfImportedPage page;
                int rotation;

                int i = 0;
                while (i < n)
                {
                    i++;
                    doc.SetPageSize(reader.GetPageSizeWithRotation(i));
                    doc.NewPage();
                    page = writer.GetImportedPage(reader, i);
                    rotation = reader.GetPageRotation(i);
                    if (rotation == 90 || rotation == 270)
                        cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                    else
                        cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                }
                a++;
                if (a < fileNames.Length)
                {
                    n = reader.NumberOfPages;
                }
            }
        }
    }
    doc.Close();
    return doc;
}

It compiles, but I get an error at runtime which points to the closing brace of the Using loop:
System.ObjectDisposedException was unhandled
  Message=Cannot access a closed file.

A: You're not disposing any of your resources.
PdfReader, PdfWriter, and FileStream all implement IDisposable. These all need to either be Disposed or wrapped in a using block (preferably the latter).
My guess is it's the PdfReader instances that are holding those files open.
P.S. It's not enough to just Close them at the end of the method, as that will leave them open "permanently" (or as long as the process runs) if any exceptions occur before those calls execute. Either put your cleanup in a finally block or just use using.

A: Although you're closing the document (doc.Close();), you're not closing the filestream, writer and reader.
Add this after doc.Close();:
writer.Close();
output.Close();
reader.Close();


text:
Q: Program-Name Detection this is how the lines look like:
  //|                                                        Vegas.c |

and I would like to get the name, here Vegas.c
This works in PS' regex:
  $found = $body -match '.+?\s+(\w.+?\.c[\+]+)[\s\|]+'

But what if the name does not start with a-zA-Z0-9 (=\w) but e.g. ~ or other none-word-chars?
The first char of the name must be different from a blank so I tried:
  $found = $body -match '.+?\s+(\S+.+?\.c[\+]+)[\s\|]+'
  $found = $body -match '.+?\s+([^\ ]+.+?\.c[\+]+)[\s\|]+'
  $found = $body -match '.+?\s+([^\s]+.+?\.c[\+]+)[\s\|]+'

None of them work even some more work. In most of the cases this detects only the whole line!
Any ideas?

A: How about this?
 \/\/\| *([^ ]*)

\/ matches the character /
\/ matches the character /
\| matches the character |
 * matches 0 to many of the character
 round brackets (  ) are the first capture group
[^ ] captures all the characters that are ^(not) a space (so long as all your file names do not contain spaces this should work)

A: I think you made your question more basic then you needed from what I see in your comments but I have this which worked with your test string.
$string = @"
      //|                                                        Vegas.c |
"@

Just look for data inbetween the pipes and whitespace the pipes border. Not sure how it will perform with you real data but should work if spaces are in the program names.
[void]($string -match "\|\s+(.+)\s+\|")
$Matches[1]
Vegas.c

You could also used named matches in PowerShell
[void]($string -match "\|\s+(?<Program>.+)\s+\|")
$Matches.Program
Vegas.c

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to get output when sending commands via ssh.net to aruba switch or virtual controller I am attempting to remote into a virtual controller to run aruba commands into the console such as "show run" etc but no output is coming up for the commands. It appears I am able to successfully connect, and I am not seeing any errors, but nothing happens when running a command.
I have connected via putty to validate the commands, and also validate credentials. I have been able to do similar functionality via python, but am needing to be able to do this via C# for dependency reasons.
                var methods = new List<AuthenticationMethod>();
                methods.Add(new PasswordAuthenticationMethod(UserName, Password));
                var con = new ConnectionInfo(virtualController, 22, UserName, methods.ToArray());

                Console.WriteLine("Attempting Connection with Network...");
                var Client = new SshClient(con);
                Client.Connect();
                Console.WriteLine("Successfully Connected.");

                var cmdRun = Client.RunCommand(showClients);
                var result = cmdRun.Result;
                Console.WriteLine(result);

                cmdRun = Client.RunCommand(showRun);
                result = cmdRun.Result;
                Console.WriteLine(result);

                Client.Disconnect();

The console outputs "Successfully Connected." and continues to execute all code, but never outputs anything on the line:
Console.WriteLine(result);
I would expect for the terminals output that I would see when running this command via putty.

A: I use SSHClient instead of Client. Using my class from this answer, here's some sample code after calling Client.Connect():
SSHStream = SSHClient.CreateExtShellStream("dumb", 120, 80, 0, 0, 65536);
if (SSHStream != null) {
    DoCommand("no page");
    Connected = true;
}

var result = DoCommand("show cdp neighbors | begin Port", TimeSpan.FromSeconds(2), "#");

Here is the helper method:
public static IEnumerable<string> DoCommand(string c, TimeSpan? timeout = null, string prompt = "#") {
    return SSHStream.DoCommand(c, timeout ?? TimeSpan.FromSeconds(2), prompt);
}


text:
Q: mod_rewrite keep square brackets in URL I'm trying to use mod_rewrite to rewrite a URL but keep the square brackets as it's required by the script to process:
RewriteRule ^(order|cart)/([0-9]+)/([0-9]+)/?$ /cart?a=add&pid=$2&addons\[$3\] [L,NE]

Unfortunately, the above URL gets translated as follows:
from: https://example.com/order/1/5  to https://example.com/cart?a=add&pid=1&addons%5B7%5D=
This is what I need as the URL result:
from https://example.com/order/1/5 to https://example.com/cart?a=add&pid=1&addons[5]
I need the square brackets [$3] to stay as square brackets in the URL instead of being changed in mod_rewrite to escaped characters %5B and %5D. No, adding the backslashes does nothing to fix this. I also tried the "B" flag and others.
Any help?
Thanks!

A: The NE flag is the correct one but it's probably confused by the fact you escape the square brackets in your rule. The second argument is not a regular expression and you don't have to escape these.
So, this should work:
RewriteRule ^(order|cart)/([0-9]+)/([0-9]+)/?$ /cart?a=add&pid=$2&addons[$3] [L,NE]


text:
Q: R - Count the Number of 6s in a Variable I am trying to write an algorithm that will allow me to calculate the probability of rolling a six on a variable number of dice.  Here is what I have:
num.dice <- 6

## x is the number of iterations

x <- 1
a <- c()
while(x < 1000) {
  a[(x:x)] <- sum(sample(1:6, num.dice, replace=TRUE)==1)
  x <- x + 1
}
sum(a)/1000

I would prefer to use a monte carlo style simulation, but I believe I cannot get the count of 6s right.
Where am I going wrong?

A: my math is a bit rusty, but is this what you are looking for?
library( gtools )

num_dice <- 1:6

lapply(num_dice, function(x) {
  sum(
    apply(
      permutations( 6, x, 1:6, repeats.allowed = TRUE ),
      1,
      function(y) any( y == 6 )
      )
    ) / 6^x
})

[[1]]
[1] 0.1666667

[[2]]
[1] 0.3055556

[[3]]
[1] 0.4212963

[[4]]
[1] 0.5177469

[[5]]
[1] 0.5981224

[[6]]
[1] 0.665102


text:
Q: Lazy loading don't find the declaration of my component I'm trying to apply lazy loading in my app routing module, but when i exclude the "Dashboard Module" from app.module.ts, my component "DialogConfirmacaoExclusao" is alerted that is not part of any ngModule.
I try:
My app routing module:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const appRoutes: Routes = [
  {path: 'dash', loadChildren: 'src/app/components/dashboard/dashboard.module#DashboardModule'}
];

@NgModule({
  imports:[RouterModule.forChild(appRoutes)],
  exports: [RouterModule]
})
export class AppRoutingModule{}

In my app.module i import my appRoutingModule e exclude the DashboardModule from the list of imports:
import { AppRoutingModule } from './app.routing.module';

My dashboard routing module:
const dashboardRoutes: Routes = [
    {path: 'dash', component: DashboardComponent, canActivate: [AuthGuard],
    children: [
    { path: '', component: BemvindoComponent, pathMatch: 'full' },
    { path: 'home', component: BemvindoComponent, pathMatch: 'full' },
    { path: 'custofixo', component: CustofixoComponent, pathMatch: 'full' },
    { path: 'custoextra', component: CustoextraComponent, pathMatch: 'full'},
    { path: 'custovariavel', component: CustovariavelComponent, pathMatch: 'full'},
    { path: 'listagemcustofixo', component: CustoMensalFixo, pathMatch: 'full'},
    { path: 'operador', component: OperadorComponent, pathMatch: 'full', canActivate: [CadOperadorGuard]},
    { path: 'produtos', component: ProdutoComponent, pathMatch: 'full'},
    { path: 'tipoprodutos', component: TipoprodutoComponent, pathMatch: 'full'},
    { path: 'meuperfil', component: MeuperfilComponent, pathMatch: 'full'},
    { path: 'confestoque', component: ConfEstoqueComponent, pathMatch: 'full'},
    { path: 'confprecificacao', component: ConfPrecificacao, pathMatch: 'full'},
    { path: 'monitoramento', component: MonitoramentoComponent, pathMatch: 'full'},
    { path: 'listagemcustovariavel', component: CustoMensalVariavel, pathMatch: 'full'},
    { path: 'listagemcustoextra', component: CustoExtraMensal, pathMatch: 'full'},
    { path: 'produtoscalculados', component: ProdutosCalculadosComponent, pathMatch: 'full'},
  ]}
];

@NgModule({
    imports: [RouterModule.forRoot(dashboardRoutes)],
    exports: [RouterModule]
})

export class DashboardAppRouting {}

My dashboard module declare and export the component "DialogConfirmacaoExclusao":
import { DialogConfirmacaoExclusao } from '../dialogexclusao/dialog-exclusao.component';
  exports:[
    DialogConfirmacaoExclusao
]

...

  declarations: [DialogConfirmacaoExclusao]

But i receive:

Uncaught Error: Component DialogConfirmacaoExclusao is not part of any
  NgModule or the module has not been imported into your module.

@Edit:
My app.module.ts:
//Importação de módulos angular
import { FormsModule } from '@angular/forms';
import { MyMaterialDesignModule } from '../app.materialdesign.module';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';
import { MDBBootstrapModule } from 'angular-bootstrap-md';
import { NgxMaskModule } from 'ngx-mask';
//Importação de módulos do sistema
import { LoadingModule } from './components/loading/loading.module';
import { DialogEdicaoMovimentacaoModule } from './components/dashboard/dialogedicaomovimentacao/dialog-edicao.module';
import { AppRoutingModule } from './app.routing.module';
import { DashboardModule } from './components/dashboard/dashboard.module';
import { LoginComponent } from './components/login/login.component';
import { CustoextraModule } from './components/dashboard/custoextra/custoextra.module';
import { CustovariavelModule } from './components/dashboard/custovariavel/custovariavel.module';
import { OperadorModule } from './components/dashboard/operador/operador.module';
import { TipoProdutoModule } from './components/dashboard/tipoproduto/tipoproduto.module';
import { ProdutoModule } from './components/dashboard/produto/produto.module';
import { LoginModule } from './components/login/login.module';
import { BemVindoModule } from './components/dashboard/bemvindo/bemvindo.module';
import { CustoFixoModule } from './components/dashboard/custofixo/custofixo.module';
import { MeuPerfilModule } from './components/dashboard/meuperfil/meuperfil.module';
import { DialogsModule } from './components/dashboard/dialogedicaolistagemcustos/dialog-edicao.module';
import { ConfEstoqueModule } from './components/dashboard/confestoque/confestoque.module';
import { ConfPrecificacaoModule } from './components/dashboard/confprecificacao/confprecificacao.module';
import { MonitoramentoModule } from './components/dashboard/monitoramento/monitoramento.module';
import { CustoExtraModule } from './components/dashboard/customensalextra/customensalextra.module';
import { SearchPipeModule } from './pipes/searchpipe/searchpipe.module';
import { ProdutosCalculadosModule } from './components/dashboard/produtoscalculados/produtoscalculados.module';
import { DialogEsqueceuSenhaModule } from './components/login/dialogesqueceusenha/dialog-esqueceu-senha.module';
import { CallBackRecuperacaoSenhaModule } from './components/login/callbackrecuperacaosenha/callbackrecuperacaosenha.module';
import { CustoMensalFixoModule } from './components/dashboard/customensalfixo/customensalfixocomponent';
import { CustoMensalVariavelModule } from './components/dashboard/customensalvariavel/customensalvariavel.module';

@NgModule({
  declarations: [
  ],
  imports: [
    BrowserModule,
    CallBackRecuperacaoSenhaModule,
    CustoMensalFixoModule,
    DialogEdicaoMovimentacaoModule,
    DialogEsqueceuSenhaModule,
    DialogsModule,
    ProdutosCalculadosModule,
    CustoExtraModule,
    SearchPipeModule,
    ConfPrecificacaoModule,
    CustoFixoModule,
    MonitoramentoModule,
    LoadingModule,
    CustoFixoModule,
    TipoProdutoModule,
    ProdutoModule,
    MeuPerfilModule,
    OperadorModule,
    CustovariavelModule,
    CustoextraModule,
    BemVindoModule,
    CustoMensalVariavelModule,
    NgxMaskModule.forRoot(),
    FormsModule,
    BrowserAnimationsModule,
    MyMaterialDesignModule,
    MDBBootstrapModule.forRoot(),
    LoginModule,
    DashboardModule,
    AppRoutingModule,
    ConfEstoqueModule
  ],
  schemas: [ NO_ERRORS_SCHEMA ],
  providers: [],
  bootstrap: [LoginComponent],
})

export class AppModule { }

@Edit:
i imported, declared and exported the DialogConfirmacaoExclusao in app.module but now i receive: "dashboard component is not part of any ngmodule..." but don't make sense but if i declare in app module i lose the perform from my lazy loading, right?

A: You should check the usage of .forRoot vs. .forChild in the routing modules. As the app module lazily loads the dashboard modules, it should be the other way around (at least that is how I successfully modularized my projects' routing):
imports: [RouterModule.forChild(dashboardRoutes)],

and
imports:[RouterModule.forRoot(appRoutes)],

Link to Angular Docs

A: You have to change/swap RouterModule forChild and forRoot functions in AppRoutingModule respectively DashbooardRoutingModule.
In AppRoutingModule the router should be imported with forRoot. You can have only one forRoot in your application and it must be used for your main routing definition:
@NgModule({
   imports:[RouterModule.forRoot(appRoutes)],
   exports: [RouterModule]
})
export class AppRoutingModule{}

DashboardRoutingModule must use RouterModule with forChild function. Every lazy loaded module which contains sub-routing, must be initialized with forChild:
@NgModule({
    imports: [RouterModule.forChild(dashboardRoutes)],
    exports: [RouterModule]
})
export class DashboardAppRouting {}

IMPORTANT:
Be sure not to include DashboardModule in the AppModule.
Also don't forget to import DashboardRouterModule into DashboardModule, respectively AppRoutingModule into AppModule

A: There could be three posible solutions:
a) Using relative path loadChildren: './...
b) Using absolute path starting with loadChildren: 'src/app/...
c) tsconfig.app.json --> BaseUrl: "./"
Actually, the problem comes from typescript config.
Before NG 6, the scaffold generated by CLI set the BaseUrl in tsconfig.app.json which is located inside /src. Currently, it is set by tsconfig.json located outside /src, but continues pointing to ./. Because of this, loadChildren path to module should be relative or include src folder.


text:
Q: Neo4J deep duplicated nodes For the data (below), my query looks like that:
MATCH p = (ob:Obiect)<--(w:Word { value:'game' })-[*]-(x) RETURN {id: id(x), value: x.value}

CREATE (w0:Obiect { value : 'Obiect' })
CREATE (w1:Word { value:'game' })
CREATE (w2:Word { value:'unreal' })
CREATE (w3:Word { value:'a' })
CREATE (w4:Word { value:'b'})
CREATE (w5:Word { value:'c' })
CREATE (w6:Word { value:'d'})
CREATE (w1)-[:IS]->(w0)
CREATE (w2)-[:IS]->(w1)
CREATE (w3)-[:HAS]->(w2)
CREATE (w4)-[:HAS]->(w3)
CREATE (w5)-[:HAS]->(w4)
CREATE (w6)-[:HAS]->(w5)
CREATE (w6)-[:HAS]->(w3)

If the relation (value:d)-->(value:a) doesn't exist then it's okay and my results looks like this:
id 4070    value unreal
id 4071    value a
id 4072    value b
id 4073    value c
id 4074    value d

but if the relation exists then i have duplicates nodes (below). The question is how to avoid this problem?
id 4063    value unreal
id 4064    value a
id 4065    value b
id 4066    value c
id 4067    value d
id 4064    value a
id 4067    value d
id 4066    value c
id 4065    value b
id 4064    value a

A: You can use the MERGE clause : http://docs.neo4j.org/chunked/stable/query-merge.html
MERGE (w3:Word { value:'a' })
MERGE (w4:Word { value:'b'})
MERGE(w3)-[:HAS]->(w4)

MERGE acts as "MATCH or CREATE" .
Be aware that MERGE will attempt to match the entire pattern, which can be confusing the first times, so I recommend you this helpful article from Graphaware : http://graphaware.com/neo4j/2014/07/31/cypher-merge-explained.html


text:
Q: mysql: very simple SELECT id ORDER BY LIMIT will not use INDEX as expected (?!) I have a simple table with about 3 million records. I made the neccessary indexes, i also force the index PRIMARY but still doesnt work. It searches for nearly all 3 million rows instead of using the index to execute this one (record_id is INT auto-increment):
EXPLAIN SELECT record_id
FROM myrecords
FORCE INDEX (
PRIMARY )
ORDER BY record_id ASC
LIMIT 2955900 , 300

id  select_type     table     type  possible_keys   key     key_len     ref     rows    Extra
1   SIMPLE          myrecords index NULL            PRIMARY 4           NULL    2956200 Using index

The index is
Keyname Type    Unique  Packed  Column      Cardinality Collation   Null
PRIMARY BTREE   Yes     No      record_id   2956742     A           No

I would like to know why this FORCED index is not being used the right way.
Without forcing index 'primary' both ASC and DESC tried, result is the same. Table has been repaired-optimized-analyzed. No luck.
query needs over a minute to execute!
WHAT I EXPECTED: query should proccess only 300 rows since that column is indexed. not nearly all 3 million of them as you can see in the first code-formatted block (scroll a little to the right)

A: Index lookups are by value, not by position.  An index can search for a value 2955900, but you're not asking for that.  You're asking for the query to start at an offset of the 2955900th row in the table.
The optimizer can't assume that all primary key values are consecutive.  So it's pretty likely that the 2955900th row has a value much higher than that.
Even if the primary key values are consecutive, you might have a WHERE condition that only matches, for example, 45% of the rows.  In which case the id value on the 2955900th row would be way past the id value 2955900.
In other words, an index lookup of the id value 2955900 will not deliver the 2955900th row.
So MySQL can't use the index for a limit's offset.  It must scan the rows to count them until it reaches offset+limit rows.
MySQL does have optimizations related to LIMIT, but it's more about stopping a table-scan once it has reached the number of rows to return.  The optimizer may still report in an EXPLAIN plan that it expects it might have to scan the whole table.
A frequent misunderstand about FORCE INDEX is that it forces the use of an index.  :-)
In fact, if the query can't use an index (or if the available indexes don't have any benefit for this query), FORCE INDEX has no effect.

Re your comment:
Pagination is a frequent bane of data-driven web applications.  Despite how common this feature is, it's not easy to optimize.  Here are a few tips:

*

*Why are you querying with offset 2955900?  Do you really expect users to sift through that many pages?  Most users give up after a few pages (exactly how many depends on the type of application and the data).

*Reduce the number of queries.  Your pagination function could fetch the first 5-10 pages, even if only it shows the first page to the user.  Cache the other pages, with the assumption that the user will advance through a few pages.  Only if they advance past the cached set of pages does your app have to do another query.  You could even cache all 10 pages in Javascript on the client's browser so clicking "Next" is instantaneous for them (at least for those first few pages).

*Don't put a "Last" button on any user interface, because people will click it out of curiosity.  Notice Google has a "Next" button but not a "Last" button.  So the UI itself discourages people from running inefficient queries with high offsets.

*If the user is advancing one page at a time, use the highest id value returned in the previous page in the WHERE clause of the next page's query.  I.e. the following does use the index, even with no FORCE INDEX hint:
SELECT * FROM thistable WHERE id > 544 LIMIT 20


text:
Q: Making stdin writable in a safe and portable way I was trying to run two programs.
Case 1
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
        int n;
        int k = 10;
        int ret_val = 0;
        ret_val = write (0, &k, sizeof(int));
        if (-1 == ret_val)
        {
                printf ("Failed to write");
                exit (EXIT_FAILURE);
        }
        scanf ("%d", &n);
        printf ("Integer read is %d \n", n);
        return 0;
}

Then I tried the next one.
Case 2
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
        int n;
        int k = 10;
        int ret_val = 0;

        /* Open file from which content shall be inserted to stdin_buffer */
        int source_fd = open ("file_in.txt", O_CREAT | O_RDWR, S_IRWXU);
        if (-1 == source_fd)
        {
                printf ("Failed to open file for reading");
                exit (EXIT_FAILURE);
        }
        int stdin_fd;

        /* Close STDIN_FILENO */
        close(0);
        /* dup the source */
        stdin_fd = dup (source_fd);
        if (-1 == stdin_fd)
        {
                printf ("Failed to dup");
                exit (EXIT_FAILURE);
        }

        /* write to stdin_buffer (content will be taken from file_in.txt) */
        ret_val = write (stdin_fd, &k, sizeof(int));
        if (-1 == ret_val)
        {
                printf ("Failed to write to stdin_buffer");
                exit (EXIT_FAILURE);
        }

        scanf ("%d", &n);
        printf ("Integer read is %d \n", n);

        close(source_fd);
        return 0;
}

Now in the first case, I was not able to write to stdin. In the second case, I was able to take the input from a file, "file_in.txt", and send the content to the standard input buffer.
I couldn't get a good explanation for why my first case didn't work out. Can someone explain?
stdin should be like any other file right? If it is write protected, fine. But then when I redirected the input (in the second case), there was no "permission denied" problem. This code seems to be non-portable. Is there a portable and safe way to redirect stdin from a file?

After going through the comments, I have come up with a better working code. I would like some feedback on this code
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

#define LEN 100

int main()
{
        int n;
        char buffer[LEN];
        memset (buffer, '\0', LEN);
        int ret_val = 0;

        /* Open file from which content shall be inserted to stdin_buffer */
        int source_fd = open ("file_in.txt", O_CREAT | O_RDONLY, S_IRWXU);
        if (-1 == source_fd)
        {
                perror ("Failed to open file for reading");
                exit (EXIT_FAILURE);
        }
        /* Temp stdin_buffer */
        int temp_fd = open ("temp_in.txt", O_CREAT | O_RDWR, S_IRWXU);
        if (-1 == temp_fd)
        {
                perror ("Failed to open temp stdin");
                exit (EXIT_FAILURE);
        }

        int stdin_fd;
        /* Close STDIN_FILENO */
        close(0);
        /* dup the source */
        stdin_fd = dup (temp_fd);
        if (-1 == stdin_fd)
        {
                perror ("Failed to dup");
                exit (EXIT_FAILURE);
        }

        ret_val = read (source_fd, buffer, LEN);
        if (-1 == ret_val)
        {
                perror ("Failed to read from source");
                exit (EXIT_FAILURE);
        }
        else
        {
                printf ("%s read from Source file\n", buffer);
        }

        /* write to stdin_buffer (content taken from file_in.txt) */
        ret_val = write (stdin_fd, buffer, LEN);
        if (-1 == ret_val)
        {
                perror ("Failed to write to stdin_buffer");
                exit (EXIT_FAILURE);
        }

        ret_val = lseek (stdin_fd, 0, SEEK_SET);
        if (-1 == ret_val)
        {
                perror ("Failed lseek");
                exit (EXIT_FAILURE);
        }

        ret_val = scanf ("%d", &n);
        if (-1 == ret_val)
        {
                perror ("Failed to read stdin_buffer");
                exit (EXIT_FAILURE);
        }
        printf ("Integer read is %d \n", n);

        close(source_fd);
        return 0;
}

A: Before the updates
In the first program, 3 null bytes and a newline were (probably) written to the screen (not necessarily in that order); the program then tries to read from the keyboard (assuming that there's no I/O redirection on the command line).  Writing to standard input does not load the input buffer.  You very often can write to standard input (and read from standard output and standard error) because the classic technique opens a file descriptor with O_RDWR and then connects that to the standard I/O channels.  However, there is no guarantee that you can do so.  (The first program needs <unistd.h>, incidentally.)
The second program has so much undefined behaviour it is difficult to analyze.  The open() call needs three arguments because it includes O_CREAT; the third argument is the mode for the file (e.g. 0644).  You don't check that the open() succeeds.  You don't check that the write succeeds; it won't, because the file descriptor is opened O_RDONLY (or, rather, the source_fd is opened O_RDONLY, and the dup() will copy that mode to file descriptor 0), which means the write() will fail.  The input operation is not checked (you don't ensure that scanf() succeeds).  (The second program doesn't really need <sys/types.h> or <sys/stat.h>.)
Basically, you don't know anything about what is going on because you've not checked any of the critical function calls.
After update 1
Note that error messages should be written to standard error and should be terminated with newlines.
I get the first program working as stated (Mac OS X 10.10 Yosemite, GCC 4.8.1), though it is hard to prove that the null bytes got written to standard input (but a newline was written there).  I could then type 10 (or 20, or 100, or …) plus Return and that integer would then be printed.
The second program fails on the scanf() because the file pointer is at the end of the file when you try to read.  You can see with this variant of your program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

int main(void)
{
    /* Open file from which content shall be inserted to stdin_buffer */
    int source_fd = open ("file_in.txt", O_CREAT | O_RDWR, S_IRWXU);
    if (-1 == source_fd)
    {
        printf ("Failed to open file for reading\n");
        exit (EXIT_FAILURE);
    }

    close(0);
    int stdin_fd = dup (source_fd);
    if (-1 == stdin_fd)
    {
        printf("Failed to dup\n");
        exit(EXIT_FAILURE);
    }

    int k = 10;
    int ret_val = write(stdin_fd, &k, sizeof(int));
    if (-1 == ret_val)
    {
        printf("Failed to write to stdin_buffer\n");
        exit(EXIT_FAILURE);
    }

    int rc;
    int n;
    if ((rc = scanf("%d", &n)) != 1)
        printf("Failed to read from standard input: rc = %d\n", rc);
    else
        printf("Integer read is %d (0x%08x)\n", n, n);

    close(source_fd);
    return 0;
}

It produces:
Failed to read from standard input: rc = -1

If you rewind the file before reading, you will get 0 returned; the binary data written to the file is not a valid string representation of an integer.
After update 2
I've written a small function err_exit() because it allows the code to be smaller on the page.  I've modified your code in a couple of places to report on the return value from a previous function.  The absence of input is not an error.  When you get 0 bytes read, that isn't an error; it is EOF.  When there is data to be read but it isn't the text format for an integer value, no conversions take place, but that isn't an error.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

#define LEN 100

static void err_exit(const char *msg)
{
    perror(msg);
    exit(EXIT_FAILURE);
}

int main(void)
{
        int n = 99;
        char buffer[LEN];
        memset(buffer, '\0', LEN);
        int ret_val = 0;

        /* Open file from which content shall be inserted to stdin_buffer */
        int source_fd = open("file_in.txt", O_CREAT | O_RDONLY, S_IRWXU);
        if (-1 == source_fd)
                err_exit("Failed to open file for reading");
        /* Temp stdin_buffer */
        int temp_fd = open("temp_in.txt", O_CREAT | O_RDWR, S_IRWXU);
        if (-1 == temp_fd)
                err_exit("Failed to open temp stdin");

        /* Close STDIN_FILENO */
        close(0);
        /* dup the source */
        int stdin_fd = dup(temp_fd);
        if (-1 == stdin_fd)
                err_exit("Failed to dup");

        ret_val = read(source_fd, buffer, LEN);
        if (-1 == ret_val)
                err_exit("Failed to read from source");
        else
                printf("(%d bytes) <<%s>> read from Source file\n", ret_val, buffer);

        /* write to stdin_buffer (content taken from file_in.txt) */
        ret_val = write(stdin_fd, buffer, LEN);
        if (-1 == ret_val)
                err_exit("Failed to write to stdin_buffer");

        ret_val = lseek(stdin_fd, 0, SEEK_SET);
        if (-1 == ret_val)
                err_exit("Failed lseek");

        ret_val = scanf("%d", &n);
        if (-1 == ret_val)
                err_exit("Failed to read stdin_buffer");
        printf("Integer read is %d (ret_val = %d)\n", n, ret_val);

        close(source_fd);
        return 0;
}

Output:
(0 bytes) <<>> read from Source file
Integer read is 99 (ret_val = 0)

When scanf() fails to read a value, it (usually) doesn't write anything into the corresponding variable.  That's why the 99 survives.  If you want data that can be read by scanf() as an integer, you need:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

#define LEN 100

static void err_exit(const char *msg)
{
    perror(msg);
    exit(EXIT_FAILURE);
}

int main(void)
{
        int n = 99;
        char buffer[LEN] = "";
        int ret_val = 0;

        /* Open file from which content shall be inserted to stdin */
        int source_fd = open("file_in.txt", O_CREAT | O_RDONLY, S_IRWXU);
        if (-1 == source_fd)
                err_exit("Failed to open file for reading");
        /* Temp stdin */
        int temp_fd = open("temp_in.txt", O_CREAT | O_RDWR, S_IRWXU);
        if (-1 == temp_fd)
                err_exit("Failed to open temp stdin");

        /* Close STDIN_FILENO */
        close(0);
        /* dup the source */
        int stdin_fd = dup(temp_fd);
        if (-1 == stdin_fd)
                err_exit("Failed to dup");

        ret_val = read(source_fd, buffer, LEN);
        if (-1 == ret_val)
                err_exit("Failed to read from source");
        else
                printf("(%d bytes) <<%s>> read from Source file\n", ret_val, buffer);

        /* write to stdin (content taken from file_in.txt) */
        ret_val = write(stdin_fd, "10\n", sizeof("10\n")-1);
        if (-1 == ret_val)
                err_exit("Failed to write to stdin");

        ret_val = lseek(stdin_fd, 0, SEEK_SET);
        if (-1 == ret_val)
                err_exit("Failed lseek");

        ret_val = scanf("%d", &n);
        if (-1 == ret_val)
                err_exit("Failed to read stdin");
        printf("Integer read is %d (ret_val = %d)\n", n, ret_val);

        close(source_fd);
        return 0;
}

Output:
(0 bytes) <<>> read from Source file
Integer read is 10 (ret_val = 1)

A: Let's see what your three programs are doing...
Program 1
The first program writes to the filedescriptor 0. By default, this is stdout, hence the macro STDOUT_FILENO has that value. Since stdout is a unidirectional stream that runs into the process, writing fails.
Program 2
In this program, you open a file, which probably gets FD (filedescriptor) 3 (after 0-2 for the standard streams). Then, you close stdout with FD 0. Then, you dup() FD 3 and since the first open spot is at index 0, that's the new FD to the file. Since scanf() just uses the (unchanged) macro STDIN_FILENO, it will pick up the content of that file there.
Program 3
In program 3, you do pretty much the same as in program 2, only that you open the file twice. The explanation of what is going on pretty much follows the two above.
Question now is what you mean when you say "a better working code". The point is that "better" is impossible to say unless you specify what you actually want. Guessing from your topic and your comment, you want to remote-control a second process, just like using the pipe symbol in bash.
In order to do that, you will have to resort to OS-specific means, just search for "input output redirection" and you should be able to find some info. Since you already mentioned execl(), portability beyond POSIX (e.g. to win32) seems not be an issue though, and for that you should find lots of example code out there, much better that what I can write up here.
In any case, it boils down to roughly these steps:

*

*pipe() to create a pair of FDs

*fork() to create a new process

*child: dup2() to reassign the input FD from pipe() to stdin

*child: execl() the new process

*parent: write to output FD to generate input for the child process

In addition, you should close unused streams or configure them with fcntl(FD_CLOEXEC) to have them closed automatically for you. The important point is that the two FDs remain connected to the same (!) channel, although you have both end in both processes. Closing one end in each leaves a unidirectional channel between the two processes.


text:
Q: Returning a table from a function with parameters in SQL As far as I know, we can return a table as a result of a db function:
CREATE FUNCTION MyFunction(@Value varchar(100))
RETURNS table
AS RETURN (select * from MyTable where ColumnName = '@Value')

in this example we can make the column name as a parameter for the function. My question is, can we write the column name and table name as a parameter for the function? hence we can write a more generic function something like:
CREATE FUNCTION MyGenericSearchFunction(@TableName varchar(100), @ColumnName varchar(100), @Value varchar(100))
RETURNS table
AS RETURN (select * from @TableName where @ColumnName = '@Value')

A: No, you can't.
This would then be a dynamic query.
For dynamic queries in SQL Server, one has to use exec() or sp_executesql() functions, which are not allowed in functions.


text:
Q: Highcharts MySQL Data Filtering I used the following code to generate a chart using highchat JS for stock management event.
HTML
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <a href="<?= site_url('welcome') ?>"> <input type="button" class="btn btn-warning" value="Back to Home">
                    Item Request Summary

Model
function get_request_data()
{
    $this->db->select('sur.update_stock_id, sus.branch_id, sus.request_no, sus.billed_date, store_branch.branch_name,
    si.item_id, si.item_name AS item,   tf.avqty,   sur.r_qty as r_qty, sur.ap_qty as ap_qty,
    tf1.issued_qty');
    $this->db->from('store_update_request sur');
    $this->db->join('store_update_stock sus', 'sus.update_stock_id=sur.update_stock_id', 'left');
    $this->db->join('store_branch', 'sus.branch_id=store_branch.branch_id', 'left');
    $this->db->join('store_item si', 'sur.item=si.item_id', 'left');

    $this->db->join('(select update_stock_id, item, is_qty AS issued_qty
        from store_update_issue
        where store_update_issue.status=1
        ) AS tf1',
        'si.item_id=tf1.item AND sur.update_stock_id = tf1.update_stock_id','left' );

    $this->db->join('(select item, sum(qty)  AS avqty
        from store_update_stock_details
        where store_update_stock_details.status=1
        group by item) AS tf', 'si.item_id=tf.item', 'left');
    $this->db->where(array('sus.status' => 1));

    $query = $this->db->get();
    if ($query->num_rows() > 0) {
        return $query->result();
    }
    return false;
}

Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Chart extends CI_Controller {

 public function __construct()
 {
 parent::__construct();
 $this->load->model('data');
 }

 public function index()
 {
 $this->load->view('charts/chart');
 }

 public function data()
 {

 $data = $this->data->get_request_data();

 $category = array();
 $category['name'] = 'Item';

 $series1 = array();
 $series1['name'] = 'Request Qty';

 $series2 = array();
 $series2['name'] = 'Approved Qty';

 $series3 = array();
 $series3['name'] = 'Issued Qty';

 foreach ($data as $row)
 {
 $category['data'][] = $row->item;
 $series1['data'][] = $row->r_qty;
 $series2['data'][] = $row->ap_qty;
 $series3['data'][] = $row->issued_qty;
 }

 $result = array();
 array_push($result,$category);
 array_push($result,$series1);
 array_push($result,$series2);
 array_push($result,$series3);

 print json_encode($result, JSON_NUMERIC_CHECK);
 }

 }

The code is working properly and generate the follwing out put.

Then, I needs to apply filters for the chart. One is branch wise and other is billed date range wise. In my model these fields are as in "branch_name" & "billed_date".
What can do for in the code to get this disired output. Can anyone help on this ?


text:
Q: Providing a common viewForHeaderInSection for multiple UITableViewControllers I have several UITableViewControllers which creates the same exact section header. Currently, I have copy pasted the viewForHeaderInSection code in each of the view controllers. But this is a bad practice. I can create a base class which can provide that implementation but I am looking for a better way. The problem with base class is that it will only work with UITableViewController unless I have the base class from UIViewController. If I use UIViewController as base class then most of the view controllers will be getting that functionality even though they dont require it.
How can I solve this problem? I tried Protocol Extensions but you cannot override methods in protocol extensions.

A: A good way to handle this is to create a custom UIView subclass for your header. Then, in each of your TableViewControllers, you can do this:
class TVC: UITableViewController {
    //...
    override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return MyCustomHeaderView(title: "sometitle", ... )
    }
    //...
}


text:
Q: Trigger snakemake rule-execution upon reference db update I want to trigger a snakemake rule (essentially a BLAST call) whenever my reference DB (a moderatly-sized fasta file) is updated.

*

*When I pull the latest version of the DB, would snakemake execute the "BLAST" rule, e.g. due to a newer time stamp of the reference file?

What about if I want to see if there is a relevant change in the DB in the first place? So I would first put the reference DB under git version control and make a git diff and execute only if the git diff is non-zero.

*

*How would Snakemake trigger a rule based on a git diff?

A: Snakemake relies on the time stamp for triggering. You can ignore the timestamp by marking a file as ancient (see docs). Then, you can figure out whether you want to update or not and trigger the rule manually via the -R flag. Alternatively you can use a remote provider to download the DB. I guess if the modification date changes on the server, there will also always be a change in the DB.

A: If you need a custom "freshness" check which is not essentially just comparing timestamps, you will need to implement your own input file modifier abstraction. temp(), and ancient() are two examples of modifiers. @johannes-köster also hints at remote files. Those are also good examples which rely on the timestamps provided as part of response headers (e.g. reported by the http server).
Another possibility is to do it in two steps. You would mark your database reference as ancient() to let snakemake ignore the timestamps, and specify an additional input file whose timestamp you control with a script. In a first step, you run a custom script to query the database state, and if the database state has changed, you simply touch your special file to update its timestamp. The second step would be to run the snakefile as normal.
Example: is_newer
https://bitbucket.org/snakemake/snakemake/src/9a4bb3fc84a8302a080bd7c0c37749b45f8e538a/snakemake/io.py#lines-294
In the case where the file is a remote object, it will use the implementation of the remote provider. (you might have to implement your own custom).


text:
Q: JBoss 7.2: Active Sessions Count How can I get the number of active session counts at the Jboss AS 7.2 (all sessions, not at single war)? I looked deeply for a MXBean that could give me that information but I didn't find one. There are a lot of information about that, but just for older versions. This seens to be an easy thing to do, but it's been very difficult to find an answer.
JMX is not a must if I can get this programatically by another way. I just cant modify the older projects to add listeners to check for that.

A: Well, after some digging I found an way using JBoss CLI (just google a little about it and the special syntax called Detyped Management Model). With that in mind just call this command at the CLI:
/deployment=<YOUR-EAR-NAME>.ear/subdeployment=<YOUR-WAR-NAME>.war/subsystem=\"web\"/:read-attribute(name=active-sessions)
With that you can know the connected users for that specific war. This can be tunned with different ways to look for all wars, so just play with it. There's an API to do that programatically too.


text:
Q: How can a compiler cross-compile to a different OS and architecture? I'm very intrigued by the fact that Go (since v1.5) has in-built cross compilation options.
But how is it possible to compile for a different OS and architecture?
I mean that would require knowing (and probably behaving like) the target machine language and platform.

A:
I mean that would require knowing (and probably behaving like) the target machine language and platform.

Yes, the Go compiler has to know how the target operating system works, but it doesn't need to behave like the target OS, as the Go compiler will not run the compiled executable binary, it just needs to produce it.
All the Go tools need to know is the binary formats of the different Operating Systems, and OS and architectural details (such as the instruction set, word size, endianness, alignment, available registers etc.; more info on this). And this knowledge is built into the Go tools.


text:
Q: How to store Movies on a separate volume from the iTunes media folder? I have a rather enormous Music collection. The music itself is approaching the 1TB mark. I am storing that on an external drive already. My iTunes library files are in their default location (/Users/me/Music/iTunes). My iTunes media folder is on an external drive /Volumes/iTunes/iTunes Music
This has been working as expected.
Now I would like to store just the contents of the Movies folder in the iTunes media folder on a separate drive. Apparently, iTunes doesn't like aliases or symlinks.
I saw somewhere that one could mount a volume in a different directory than the default /Volumes. I would like to permanently mount my new Movies volume in the directory /Volumes/iTunes/iTunes Music/Movies. I know there is a command to do this, but how does one configure Mac OS 10.6.4 to always automatically mount that volume in this directory?
I hope someone can enlighten me... If I find a solution, I can finally import all my movies into iTunes and be able to search them and stuff - it would be a dream.
Thanks,
M

A: For everyone's reference:
I ended up settling on a 3 TB RAID because Mac OS X doesn't like any other solution. When using the above procedure and mounting the drive in a non default location, any item I would try to play (I was dealing with movies) would immediately disappear from iTunes. Poof! Gone. The item would still exist on the drive, just gone from the iTunes library.
So I thought - that sucks and went with a RAID.
I think Apple is going to have to deal with this at some point because it is rather impractical that one can't store their Music, Movies, TV Shows - anything that resides in a separate folder in iTunes on its own volume. My iTunes library is approaching 2TB at the moment and the only reason it hasn't passed the 3TB mark yet is because the realization that I will need an even bigger RAID (hateful!) to handle all of my content halted my quest to finally import and organize my 500+ DVD collection.
Oh, well... I guess I will continue to painfully browse the huge DVD storage folders where you can't search and even keeping things in alphabetical order is a chore. I had wanted to import all the movies and then properly tag them so I could search based on the score composer, director, actor etc. That would be sweet.
Anyway - just wanted to make sure anyone arriving at this page knows the solutions described are of no use in this particular case. Must be something about the way the iTunes database engine handles links. Apparently it is unable to follow them...
M

A: This is possible with an automount share from a server. It should also be possible in the terminal with the diskutil. You will need to determine what your actual device identifier for the Movie drive is first. You can show all of this information by entering
diskutil list

in the terminal. You will see information like this:
/dev/disk0
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      GUID_partition_scheme                        *250.1 GB   disk0
   1:                        EFI                         209.7 MB   disk0s1
   2:                  Apple_HFS Macintosh HD            249.7 GB   disk0s2

The Disk Identifier for my Macintosh HD, for example, is disk0s2. You would use that information to mount the device in the place you want it.
diskutil mount -mountPoint /Users/username/Music/iTunes/iTunes\ Music/Movies disk2s2

If something goes haywire, you might have to unmount the disk with:
diskutil unmount disk2s2

I haven't actually tried this, but it's probably close. If it works, you might have to use a login hook script to make it mount every time you log in.

A: iTunes used to follow symlinks inside its media folder fine, but recent versions (10.4 upwards, iI think) seem to have lost that ability (I had my Movies on an external drive symlinked into the folder and never experienced any trouble; with the 10.4 update, I noticed iTunes could still see the files, but would ignore the link for organizational purposes, i.e. newly added media files would not be filed into "Movies"). However, there is another, slightly less convenient way to achieve what you want:
iTunes will happily manage files stored anywhere there by just storing the path to them in its library. That is exactly what it does when you uncheck the "Copy media into the iTunes folder" option in settings. If you would like iTunes to manage all your library but your movies, TuneSpan (freeware) will leverage this ability to just link a subset of your files stored somewhere else into the library.


text:
Q: How can I install latest VLC player in CentOS 6.4? I have installed CentOS 6.4 in my laptop, I want to know the method of installing VLC in CentOS 6.4, Is it necessary to download the vlc package and compile or can I use yum install vlc to install the same ?

A: You can install the following yum repositories (EPEL, famillecollet, & RPMFusion) so that you can install VLC:
$ sudo yum localinstall --nogpgcheck http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-7.noarch.rpm
$ sudo yum localinstall --nogpgcheck http://rpms.famillecollet.com/enterprise/remi-release-6.rpm

$ sudo yum localinstall --nogpgcheck http://download1.rpmfusion.org/free/el/updates/6/i386/rpmfusion-free-release-6-1.noarch.rpm
$ sudo yum localinstall --nogpgcheck http://download1.rpmfusion.org/nonfree/el/updates/6/i386/rpmfusion-nonfree-release-6-1.noarch.rpm

Now test to see if you see the VLC package:
$ yum --enablerepo=remi-test info vlc
Loaded plugins: fastestmirror, refresh-packagekit
Loading mirror speeds from cached hostfile
Available Packages
Name        : vlc
Arch        : i686
Version     : 2.0.3
Release     : 1.el6
Size        : 1.9 M
Repo        : rpmfusion-free-updates
Summary     : The cross-platform open-source multimedia framework, player and server
URL         : http://www.videolan.org
License     : GPLv2+
Description : VLC media player is a highly portable multimedia player and multimedia framework
            : capable of reading most audio and video formats as well as DVDs, Audio CDs VCDs,
            : and various streaming protocols.
            : It can also be used as a media converter or a server to stream in uni-cast or
            : multi-cast in IPv4 or IPv6 on networks.

Update the system before installing vlc
$ sudo yum update -y

To install it:
$ sudo yum --enablerepo=remi-test install vlc

To test it:
$ vlc


text:
Q: Uninstall Python 3.4.3 from Windows 10 (not replace) I installed Python 3.4.3 a while ago for a Python workshop, but I never use it and want to uninstall it.  Whenever I try to uninstall it I get a message that says "There is a problem with this Windows Installer package. A program required for this install to complete could not be run. Contact your support personnel or package vendor."
I did see a couple similar questions on here with the same message, but all of them had to do with wanting to install a DIFFERENT version of Python and all the answers just told them to run them simultaneously.  I just want this uninstalled with no other version to replace it. Please help?


text:
Q: Need for CPU-GPU sync if write and read happens on different memory pages of MTLBuffer? I am using an MTLBuffer in Metal that I created by allocating several memory pages (using vm_allocate) with
device.makeBuffer(bytesNoCopy:length:options:deallocator:).
I write the buffer with CPU and the GPU only reads it. I know that generally I need to synchronise between CPU and GPU.
However, I have more knowledge about where in the MTLBuffer write (by CPU) and read (by GPU) happens and in my case writing is into different memory pages than the read (in a given time interval).
My question: Do I need to sync between CPU and GPU even if the relevant data that is written and read are on different memory pages (but in the same MTLBuffer)? Intuitively, I would think not, but then MTLBuffer is a bit opaque and I don't really know what kind of processing/requirement the GPU actually does/has with the MTLBuffer.
Additional info: This is a question for iOS and MTLStorageMode is shared.
Thank you very much for help!

A: Assuming the buffer was created with MTLStorageModeManaged,  you can  use the function didModifyRange to sync CPU to GPU  for only a portion (a page for example) of the buffer.


text:
Q: Symfony redirect if already loggedin from login page I'm using FOSUser Bundle to login. Now if user is already loggedin, how can I redirect user to homepage ('/'), if user visit to /login url.
I have copied SecurityController to src\AppBundle\Controller location and changed renderlogin method but it doesn't work.
renderLogin() method
protected function renderLogin(array $data)
{
    if (false === $this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_ANONYMOUSLY')) {
        return new RedirectResponse('/', 403);
    }
    return $this->render('@FOSUser/Security/login.html.twig', $data);
}

I have added this line as well in the security controller,
use Symfony\Component\HttpFoundation\RedirectResponse;

Any help is much appreciated.

A: Well you need to make some changes in the SecurityController
 /**
 * Renders the login template with the given parameters. Overwrite this function in
 * an extended controller to provide additional data for the login template.
 *
 * @param array $data
 *
 * @return Response
 */
protected function renderLogin(array $data)
{
   /**
    * If the user has already logged in (marked as is authenticated fully by symfony's security)
    * then redirect this user back (in my case, to the dashboard, which is the main entry for
    * my logged in users)
    */
   if ($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
       return $this->redirectToRoute('homepage');
   }
    return $this->render('@FOSUser/Security/login.html.twig', $data);
}
}

And to redirect authenticated users who try to visit the registration page, you need to change the ``
class RegistrationController extends BaseController
{
/**
 * @param Request $request
 *
 * @return Response
 */
public function registerAction(Request $request)
{
    /**
    * If the user has already logged in (marked as is authenticated fully by symfony's security)
    * then redirect this user back (in my case, to the dashboard, which is the main entry for
    * my logged in users)
    */
    if ($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
       return $this->redirectToRoute('homepage');
    }
    /** @var $formFactory FactoryInterface */
    $formFactory = $this->get('fos_user.registration.form.factory');
    /** @var $userManager UserManagerInterface */
    $userManager = $this->get('fos_user.user_manager');
    /** @var $dispatcher EventDispatcherInterface */
    $dispatcher = $this->get('event_dispatcher');
    $user = $userManager->createUser();
    $user->setEnabled(true);
    $event = new GetResponseUserEvent($user, $request);
    $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);
    if (null !== $event->getResponse()) {
        return $event->getResponse();
    }
    $form = $formFactory->createForm();
    $form->setData($user);
    $form->handleRequest($request);
    if ($form->isSubmitted()) {
        if ($form->isValid()) {
            $event = new FormEvent($form, $request);
            $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
            $userManager->updateUser($user);
            if (null === $response = $event->getResponse()) {
                $url = $this->generateUrl('fos_user_registration_confirmed');
                $response = new RedirectResponse($url);
            }
            $dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
            return $response;
        }
        $event = new FormEvent($form, $request);
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_FAILURE, $event);
        if (null !== $response = $event->getResponse()) {
            return $response;
        }
    }
    return $this->render('@FOSUser/Registration/register.html.twig', array(
        'form' => $form->createView(),
    ));
}
}

It's weird that this has not been fixed in the FOSUserBundle, anyway I had two Github Gists that handles this issue:
Registration : https://gist.github.com/teeyo/147f2d5d21d1beadce133a51b02d9570
Login : https://gist.github.com/teeyo/121e21b35d71a9ab4a8f321043b6f6cd

A: In the FOS securityController (for login) : add this to login action
if($session->get("_security_main"))
{
$route = $this->container->get('router')->generate('site_faim_homepage');
return new RedirectResponse($route);

    }

A: I just ask if user instance already exists and if yes, then I redirect to desired route (sorry if I somehow duplicated already added post, this is my fresh experience):
        if($this->getUser()){
        return $this->redirectToRoute('homepage');
    }


text:
Q: Using html5blank wordpress theme SCSS not working I'm new to wordpress ad web development in general and I am using html5blank theme to custom make my first website as a project.
I want to use scss which was working fine but for some reason it is now not working. I have tried clearing the cache on my browser and cleared the cache on wordpress admin.
Here is my footer.php

<?php echo date('Y'); ?> Copyright <?php bloginfo('name'); ?>

Designed by Bubbles

        <?php wp_footer(); ?>

This is my style.scss
footer {
    background-color: #99DDFF;
    padding: 1rem;
    display: flex;
    justify-content: space-between;
    .copyright {
        color: red;
        p {
            color: red;

        }
    }
    .designer {
        p {
            a {

            }
        }
    }

}

The footer scss is all working fine but anything nested inside of footer is not working despite it processing correctly in prepros. So the red is not working basically.


text:
Q: ionic 2.3.0 cant install plugin via npm i try to install the plugin "cordova-plugin-network-information" (as administrator) via

npm install --save @ionic-native/network

the process stops at:

/ postinstall: info lifecycle @ionic-native/network@4.2.1~postinstall: @ionic-native/network@4.2.1

and i get the following error:
npm ERR! path C:\path\node_modules\fsevents\node_modules\ansi-regex\package.json
npm ERR! code EPERM
npm ERR! errno -4048
npm ERR! syscall unlink
npm ERR! Error: EPERM: operation not permitted, unlink 'C:\path\node_modules\fsevents\node_modules\ansi-regex\package.json'
npm ERR!     at Error (native)
npm ERR!  { Error: EPERM: operation not permitted, unlink 'C:\path\node_modules\fsevents\node_modules\ansi-regex\package.json'
npm ERR!     at Error (native)
npm ERR!   stack: 'Error: EPERM: operation not permitted, unlink \'C:\\path\\node_modules\\fsevents\\node_modules\\ansi-regex\\package.json\'\n
at Error (native)',
npm ERR!   errno: -4048,
npm ERR!   code: 'EPERM',
npm ERR!   syscall: 'unlink',
npm ERR!   path: 'C:\\path\\node_modules\\fsevents\\node_modules\\ansi-
regex\\package.json' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\username\AppData\Roaming\npm-cache\_logs\2017-09-05T09_43_58_528Z-debug.log

Info:
cli packages: (C:\Users\username.npm-packages\node_modules)
@ionic/cli-utils  : 1.9.2
ionic (Ionic CLI) : 3.9.2

global packages:
Cordova CLI : 7.0.1

local packages:
@ionic/app-scripts : 1.1.4
Cordova Platforms  : android 6.2.1
Ionic Framework    : ionic-angular 2.3.0

System:
Node : v6.9.4
npm  : 5.4.0
OS   : Windows 10

Please help.

A: CrossPost, sorry ;-) but get a solution:
https://forum.ionicframework.com/t/cant-install-plugin/104286/2


text:
Q: Compare one row date with another and decide remark - Pandas I am trying to fill in remarks based on whether the StartTime of a row lies in between the StartTime and EndTime of previous rows or not.
For eg. StartTime of 126 lies in between StartTime and EndTime of 125, thus the remarks states the same. Any idea, how can i achieve this using pandas?

Number
StartTime
EndTime
Remarks

123
2022-03-17 0:01:13
2022-03-17 0:17:29

124
2022-03-17 8:26:09
2022-03-17 9:10:54

125
2022-03-17 16:56:08
2022-03-17 17:18:49

126
2022-03-17 17:00:12
2022-03-17 20:24:33
interval of 125

127
2022-03-18 3:41:13
2022-03-18 3:58:16

128
2022-03-18 3:50:12
2022-03-18 22:56:46
interval of 127

129
2022-03-18 3:55:12
2022-03-19 6:55:22
interval of 127


text:
Q: C# split byte array from file Hello I'm doing an encryption algorithm which reads bytes from file (any type) and outputs them into a file. The problem is my encryption program takes only blocks of 16 bytes so if the file is bigger it has to be split into blocks of 16, or if there's a way to read 16 bytes from the file each time it's fine.
The algorithm is working fine with hard coded input of 16 bytes. The ciphered result has to be saved in a list or array because it has to be deciphered the same way later. I can't post all my program but here's what I do in main so far and cannot get results
static void Main(String[] args)
{
    byte[] bytes = File.ReadAllBytes("path to file");
    var stream = new StreamReader(new MemoryStream(bytes));
    byte[] cipherText = new byte[16];
    byte[] decipheredText = new byte[16];

    Console.WriteLine("\nThe message is: ");
    Console.WriteLine(stream.ReadToEnd());

    AES a = new AES(keyInput);
    var list1 = new List<byte[]>();
    for (int i = 0; i < bytes.Length; i+=16)
    {
        a.Cipher(bytes, cipherText);
        list1.Add(cipherText);
    }

    Console.WriteLine("\nThe resulting ciphertext is: ");
    foreach (byte[] b in list1)
    {
        ToBytes(b);
    }
}

I know that my loops always add the first 16 bytes from the byte array but I tried many ways and nothing work. It won't let me index the bytes array or copy an item to a temp variable like temp = bytes[i]. The ToBytes method is irrelevant, it just prints the elements as bytes.

A: No need to read the whole mess into memory if you can only process it a bit at a time...
var filename = @"c:\temp\foo.bin";
using(var fileStream = new FileStream(filename, FileMode.Open))
{
    var buffer = new byte[16];
    var bytesRead = 0;
    while((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        // do whatever you need to with the next 16-byte block
        Console.WriteLine("Read {0} bytes: {1}",
                bytesRead,
                string.Join(",", buffer));
    }
}

A: I would like to recommend you to change the interface for your Cipher() method: instead of passing the entire array, it would be better to pass the source and destination arrays and offset - block by block encryption.
Pseudo-code is below.
void Cipher(byte[] source, int srcOffset, byte[] dest, int destOffset)
{
    // Cipher these bytes from (source + offset) to (source + offset + 16),
    // write the cipher to (dest + offset) to (dest + offset + 16)
    // Also I'd recommend to check that the source and dest Length is less equal to (offset + 16)!
}

Usage:

*

*For small files (one memory allocation for destination buffer, block by block encryption):
// You can allocate the entire destination buffer before encryption!
byte[] sourceBuffer = File.ReadAllBytes("path to file");
byte[] destBuffer = new byte[sourceBuffer.Length];

// Encrypt each block.
for (int offset = 0; i < sourceBuffer.Length; offset += 16)
{
    Cipher(sourceBuffer, offset, destBuffer, offset);
}

So, the main advantage of this approach - it elimitates additional memory allocations: the destination array is allocated at once. There is also no copy-memory operations.

*For files of any size (streams, block by block encryption):
    byte[] inputBlock = new byte[16];
    byte[] outputBlock = new byte[16];
    using (var inputStream = File.OpenRead("input path"))
    using (var outputStream = File.Create("output path"))
    {
        int bytesRead;
        while ((bytesRead = inputStream.Read(inputBlock, 0, inputBlock.Length)) > 0)
        {
            if (bytesRead < 16)
            {
                // Throw or use padding technique.
                throw new InvalidOperationException("Read block size is not equal to 16 bytes");

                // Fill the remaining bytes of input block with some bytes.
                // This operation for last block is called "padding".
                // See http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Padding
            }

            Cipher(inputBlock, 0, outputBlock, 0);
            outputStream.Write(outputBlock, 0, outputBlock.Length);
        }
    }

A: You can use Array.Copy
byte[] temp = new byte[16];
Array.Copy(bytes, i, temp, 0, 16);


text:
Q: Drag and Drop of Data in InfoPath I'm trying to avoid rolling my own form using .NET and WPF or WinForms and i'm wondering if it is possible to use InfoPath.
The goal is to either be able to drag items from one list (possibly using a multiselect) in to another list of lists. Or, alternatively I would like to drag items in a tree view (or repeating table - the apparently nearest thing in InfoPath).
Drag and drop is definitely preferable to having buttons that push things between lists.  I have played with WPF and it's a lot of work!  Is there a way in InfoPath?
N.B. To be clear I am not asking about using drag and drop during the design of the InfoPath form but using it for data manipulation in the published form.


text:
Q: Having trouble getting certain refsections to print I'm putting together a CV and have a section for technical reports, but am having trouble getting this section, and certain other sections, to be included in the output document.
\begin{refsection} % This is a custom heading for those references marked as "Technical Report"
\nocite{*}
\printbibliography[sorting=chronological, type=techreport, title={technical reports}, keyword={Technical Report}, heading=subbibliography]
\end{refsection}

I definitely have a techreport listed in my .bib file:
@article{Natarajan2011,
author = {Natarajan, Nagarajan and Singh-Blom, Ulf Martin and Tewari, Ambuj and Woods, John O and Dhillon, Inderjit S and Marcotte, Edward M},
file = {:Users/jwoods/Downloads/Papers/Natarajan2011.pdf:pdf},
journal = {UTCS Technical Report},
title = {{Predicting gene\textendash disease associations using multiple species data.}},
volume = {TR-11-37},
year = {2011},
type = {techreport},
keyword = {Technical Report}

I've tried using the keyword and type parameters independently, but it's not working for me. Oddly, the technical report shows up in the article section instead, even though I've been careful to exclude technical reports:
\begin{refsection} % Articles that aren't in preparation
\nocite{*}
\printbibliography[sorting=chronological, type=article, title={articles}, notkeyword={In Preparation}, notkeyword={Technical Report}, heading=subbibliography]
\end{refsection}

It also seems to ignore my \DeclareBibliographyDriver commands in some cases, e.g., for my dissertation:
\RequirePackage[style=verbose, maxnames=99, sorting=ydnt]{biblatex}

\DeclareFieldFormat[patent]{title}{#1\par}
\DeclareFieldFormat[article]{title}{#1\par}
\DeclareFieldFormat[book]{title}{#1\par}
\DeclareFieldFormat[inproceedings]{title}{#1\par}
\DeclareFieldFormat[phdthesis]{title}{#1\par}

%
% ... other declarations, which do work ...
%

\DeclareBibliographyDriver{phdthesis}{%
  \printfield{title}%
  \newblock%
  \printnames{author}%
  \par%
  \newblock%
  {%
    \footnotesize\addfontfeature{Color=lightgray}%
    \printfield{title}%
    \setunit{\addcomma\space}%
    \printfield{year}%
    %\setunit{\addcomma\space}%
    %\printlist{location}%
    \newunit%
  }
  \par\vspace{0.3\baselineskip}
}

Instead, it prints in standard format of author, title, when I clearly indicated title on one line and author on the next.
It seems like I must be misunderstanding the \printbibliography commands somehow. Can anyone help me to correct this misapprehension?

A: Three mistakes!.

*

*The \printbibliography option (key) type  is not to filter the entries by field type, is to print the bibitem by entry names. it means, @book, @article, etc... (without @). The example bibentry is a @article if it is changed to @techreport it works if the type option (\printbibliography) is report.

For filter by field (different to keywords) you can use check option and \defbibcheck. For example, to filter by type equals to techreport.
\defbibcheck{techreport}{%
\iffieldundef{type}
 {\skipentry}
 {\iffieldequalstr{type}{techreport}
    {}
    {\skipentry}}}

and
\printbibliography[check=techreport]

*The bibtex field is keywords not keyword. The example bibtex entry is using keyword.

*By default biblatexnot use the entry phdthesis. It uses the thesis entry for phdthesis and mastersthesis. And it is possible use the type field to choices if the entry is masterthesis or phdthesis. When is defined a entry with @pdfthesis, biblatex 'convert' it to thesis entry and define the type field to phdthesis.
In the example in the question it is necessary to redefine the thesis driver and declare the title format of thesis entry.
\DeclareFieldFormat[thesis]{title}{#1\par}

\DeclareBibliographyDriver{thesis}{%
  \printfield{title}%
  \newblock%
  \printnames{author}%
  \par%
  \newblock%
  {%
    \printfield{title}%
    \setunit{\addcomma\space}%
    \printfield{year}%
    \newunit%
  }
  \par\vspace{0.3\baselineskip}}

MWE:
\documentclass{article}
\RequirePackage[style=authoryear, maxnames=99]{biblatex}
\begin{filecontents}{MWE.bib}
    @techreport{Natarajan2011,
    author = {Natarajan, Nagarajan and Singh-Blom, Ulf Martin and Tewari, Ambuj and Woods, John O and Dhillon, Inderjit S and Marcotte, Edward M},
    file = {:Users/jwoods/Downloads/Papers/Natarajan2011.pdf:pdf},
    journal = {UTCS Technical Report},
    title = {{Predicting gene\textendash disease associations using multiple species data.}},
    volume = {TR-11-37},
    year = {2011},
    type = {techreport},
    keywords = {Technical Report}}

    @phdthesis{thesis000,
    author = {Author Name},
    title = {Title of the thesis},
    type= {phdthesis},
    year = {2011}}
\end{filecontents}

\addbibresource{MWE.bib}

\defbibcheck{techreport}{%
\iffieldundef{type}
 {\skipentry}
 {\iffieldequalstr{type}{techreport}
    {}
    {\skipentry}}}

\DeclareFieldFormat[thesis]{title}{#1\par}

\DeclareBibliographyDriver{thesis}{%
  \printfield{title}%
  \newblock%
  \printnames{author}%
  \par%
  \newblock%
  {%
    \printfield{title}%
    \setunit{\addcomma\space}%
    \printfield{year}%
    \newunit%
  }
  \par\vspace{0.3\baselineskip}}

\begin{document}

\begin{refsection}
\nocite{*}
\printbibliography[type=report,title=Printing the {\it reports} entries]
\printbibliography[check=techreport,title=Filtering by {\it type} field equals to techreport]
\printbibliography[keyword=Technical Report,title=Filtering by keyword]
\printbibliography[title=Editing the {\it thesis} driver, type=thesis]
\end{refsection}

\end{document}


text:
Q: Exploring/Iterating UI Event's In a C# Application we can add an Event Handler like this.button3.Click += new System.EventHandler(this.button3_Click); also we can Remove this.button3.Click -= new System.EventHandler(this.button3_Click); so it means we can add as much as we want event's in an UI Control ,so my question is how can i Explore or Iterate and Remove a Specific Event from an UI .
Eg . If we can in someway populate all Events of an Control on a ListBox (if it's possible) and remove the Selected One .
PS : Im kinda a Junior Programmer ,so i think Code Reflection handles this portion.
Bests

A: You can easily display a list of all possible events for your component with a code like
EventInfo[] allEvents = Button1.GetType().GetEvents(System.Reflection.BindingFlags.Instance
    | System.Reflection.BindingFlags.Public);
foreach (EventInfo curEvent in allEvents)
{
    EventsListBox.Items.Add(curEvent.Name);
}

However, it seems impossible to know which methods are assigned to the delegates, that will be called in case of an event, outside of the component. You can refer to How do I find out if a particular delegate has already been assigned to an event?, Determine list of event handlers bound to event and Iterating through event handlers


text:
Q: Geometry problem dealing with trapezoid and a quadrilateral
Vertex $A$ of a quadrilateral $ABCD$ lies on the $y$-axis and the rest of the points are $B(-5, -11), C(4, 0)$ and $D(7, 12)$. Define the vertex $A$ such that the quadrilateral $ABCD$ is a trapezoid.

I found this one to be very tricky. I tried to define $A(0, y)$, but I'm not getting anywhere. Any help would be appreciated.

A: For a trapezium, the two bases are parallel. Meaning AB is parallel to DC. The gradient of DC is $\frac{12-0}{7-4}=4$. The gradient of AB is $\frac{y+11}{5}$
Setting these two expression equal to each other and solving for $y$, should give you the answer (I'll let you do that bit!)

A: The problem is not tricky. It is just not well-posed. There are two cases: Either $\overline{AB}$ is parallel to $\overline{CD}$ (in which case $y=4$) or $\overline{AD}$ is parallel to $\overline{BC}$ (in which case $y=31/9$).


text:
Q: How to test if a column exists and is not null in a DataFrame I have a python RDD:
rddstats = rddstats.filter(lambda x : len(x) == NB_LINE or len(x) == NB2_LINE)

I created a dataframe based on this RDD:
logsDF = sqlContext.createDataFrame(rddstats,schema=["column1","column2","column3","column4","column5","column6","column7"])

I would like to do a test on the two columns 6 and 7:
if column 6 exists in the dataframe and not null I should return dataframe containing this value of the column 6, else I should return a dataframe that contains the value of the column 7.
This following my small code:
logsDF = sqlContext.createDataFrame(rddstats,schema=["column1","column2","column3","column4","column5","column6","column7"])
if (logsDF['column6'] in rddstats and logsDF['column6'].isNotNull):
    logsDF.select("column1","column2","column3","column4","column5","column6")
else:
    logsz84statsDF.select("column1","column2","column3","column4","column5","column7")

Is the syntax correct and have I the right to write in Python like this ?

A: if set(['A','C']).issubset(df.columns):
   df['sum'] = df['A'] + df['C']

set([]) can alternatively be constructed with curly braces:
if {'A', 'C'}.issubset(df.columns):

See this question for a discussion of the curly-braces syntax.
Or, you can use a list comprehension, as in:
if all([item in df.columns for item in ['A','C']]):

A: if (logsDF['column6'] in rddstats and logsDF['column6'].isNotNull)

I'm pretty sure you are going to be throwing a KeyError if column6 does not exist.
You could do something like:
if 'column6' in logsDF.columns:
    if logsDF['column6'].notnull().any():
        logsDF.select("column1","column2","column3","column4","column5","column6")
    else:
        logsz84statsDF.select("column1","column2","column3","column4","column5","column7")
else:
    logsz84statsDF.select("column1","column2","column3","column4","column5","column7")

Check to see if column6 exists in logsDF columns first.
If so, see if any() value is not null.
Column7 is used if column6 does not exist, or if column6 exists but all values are null.

Editing my own comment:
Since python will not evaluate the second condition if the first is False, you can actually do:
if 'column6' in logsDF.columns and logsDF['column6'].notnull().any():
    logsDF.select("column1","column2","column3","column4","column5","column6")
else:
    logsz84statsDF.select("column1","column2","column3","column4","column5","column7")

as long as the 'column6' in logsDF.columns comes first, the logsDF['column6'] will never evaluate and throw the KeyError if column6 doesn't exist.

A: I think this may be faster
 if 'column_name' not in df.columns:
    do_something
 if len([x in x for df['column_name'].unique() if x.isna()]) > 0:
    do_something_else


text:
Q: Using Lodash to get value by It's key while some keys don't exist How to use Lodash while I am mapping through an array to get and assign the relevant values?
This is what my unfiltered array looks like, I want to extract the ID and name[x].text into an array. But as you can see some objects do not have french text in them, In that case I want to take the English text instead.
const response = {
    "data": {
      "Animals": [
        {
          "id": "1",
          "name": [
            {
              "language": "en-US",
              "text": "Horse"
            }
          ]
        },
        {
          "id": "2",
          "name": [
            {
              "language": "en-US",
              "text": "Pig"
            }
          ]
        },
       {
          "id": "3",
          "name": [
            {
              "language": "en-US",
              "text": "Cat"
            },
            {
              "language": "fr-CA",
              "text": "Un Chat"
            }
          ]
        },
        {
          "id": "4",
          "name": [
            {
              "language": "en-US",
              "text": "Dog"
            },
            {
              "language": "fr-CA",
              "text": "Un Chien"
            }
          ]
        }
      ]
    }
  }

console.log(response.data.Animals.map(animal => animal.name[0].text)); // If I do this I get all the English text, but If I map the same with index of the French, I get undefined error and It crashed my application.

This is more suitable as It returns the French and English text but there are two improvements I want to make,

*

*Get the value from it's key ("en-US" and "fr-CA") so that I know for sure I have the correct value.

*I am mapping to populate a table, So I do not need a new array with values because I don't want to lose the index if the parent array, If text it not available it should go find the English text.

*This is an extra question but it will help me learn to use Lodash better, Incase I want to set the value(either in En or Fr), how would I do that?
 arr.map((obj) => {
 const id = obj.id;
 const englishtext = _.get(obj, 'name[0].text', 'N/A');
 const frenchtext = _.get(obj, 'name[1].text', englishtext);
 return { id, englishtext, frenchtext };

}
UPDATE:
I apologize my question was unclear, to be honest I am a bit confused as well. So here is the expected output I am looking for. So when I map the given variable response, I want an another array that looks like this,
EXPECTED OUTPUT:
[
{
id: 1,
engname: Horse,
frenchname: Horse (because french is not available),
},
.
.
.
{
id:3,
engname:Cat,
frenchname: Un Chat, (because the French array is there this time)
}
.
.
.
and so on..
]

A: I would post a non-Lodash version of solution because I don't find Lodash necessary in this case. But I know you asked for Lodash solution, so ignore this if you must use Lodash.
If I understand your question correctly, the rule set you want to employ for extracting the values is the following:

*

*If there is a French text, use that regardless of the existence of the English text. Also, the French text always comes after the English text in the array (French text always has the index of -1).

*If there is no French text, use the English text (English text is guaranteed to be there for all items).
In that case, I think you could use either Array.prototype.pop() or Array.prototype.at() to achieve what you want.
Array.prototype.pop() solution
response.data.Animals.map(animal => animal.name.pop().text)

Pros:

*

*Widely available among all the modern browsers.

Cons:

*

*This mutates the original data and changes the length of the original array.

Array.prototype.at() solution
response.data.Animals.map(animal => animal.name.at(-1).text)

Pros:

*

*This operation is immutable, so original data is intact.

Cons:

*

*Some browsers might not support this.

If you are open to non-Lodash solutions, I suppose you could use one of these.
Update
Thank you @WildThing for updating the question. I think you can use this to achieve the mapping you want:
response.data.Animals.map(animal => {
  engName = animal.name.find(name => name.language === "en-US");
  frenchNameIfExists = animal.name.find(name => name.language === "fr-CA");

  return {
    id: animal.id,
    engname: engName.text,
    frenchname: (frenchNameIfExists || engName).text,
  }
})

A: May be there is no need lodash:
const toMyArray = (arr, frenchnameCode = "fr-CA", engnameCode = "en-US") => {
  return arr.map(({ id, name }) => {
    const engname = name
      .find(({ language }) => language === engnameCode)
      .text;
    const frenchname =  name
      .find(({ language }) => language === frenchnameCode)
      ?.text;

    return { id, engname, frenchname: frenchname ?? engname }
  });
};

console.log(toMyArray(response.data.Animals));

// [
//   {id: '1', engname: 'Horse', frenchname: 'Horse'},
//   {id: '2', engname: 'Pig', frenchname: 'Pig'},
//   {id: '3', engname: 'Cat', frenchname: 'Un Chat'},
//   {id: '4', engname: 'Dog', frenchname: 'Un Chien'},
// ]


text:
Q: table rows not aligned The alignment of my table is all out of whack. Can you help?
Additionally, the commas and periods are not what I expect them to be.
MWE:
\documentclass[twocolumn]{article}

\usepackage[T1]{fontenc}
\usepackage{newtxtext}
\usepackage{amsmath,geometry,siunitx,booktabs, tabularx}
\newcolumntype{C}{>{\centering\arraybackslash}X}
\newcolumntype{C}{>{\centering\arraybackslash}X}
\newcolumntype{L}{>{\raggedright\arraybackslash}X}
\newcommand\mC[1]{\multicolumn{1}{C@{}}{#1}}
\sisetup{group-separator={,}, group-minimum-digits=4}
\usepackage[skip=1ex]{caption}
\captionsetup[table]{font=small, labelfont=bf, singlelinecheck=no}
\usepackage{makecell}
\renewcommand\theadfont{\normalsize}
\renewcommand\theadgape{}
\setcellgapes{2pt}
\usepackage{textcomp}
\usepackage{graphicx}
\raggedbottom
\usepackage{rotating}
\usepackage[referable]{threeparttablex}
\usepackage{upquote}
\usepackage{balance}
\usepackage{wasysym}
\usepackage{footmisc}
\usepackage{float}
\floatstyle{boxed}
\restylefloat{figure}

\title{\LARGE \bf ECON 425 Term Paper}

\author{}

\begin{document}

\begin{table}
\setlength\tabcolsep{3pt}
\small
\caption{Comparing goodness of fit tests
for different specifications of pay-performance equation.} \label{tab:table}

\medskip
\begin{tabularx}{\columnwidth}{@{}
   l S[table-format=4.2] S[table-format=5.2]
   *{2}{S[table-format=6.2]} @{}}
\toprule
& \mC{eq. 1} & \mC{eq. 2} & \mC{eq. 3} \\
\midrule
R-sqaure    & {.255} & {.072} & {.231} \\
\addlinespace
Adj. R-square   & 0.254   & .070   & .2299    \\
F-statistic & 140.94$^{*}$   & 37.26$^{*}$     & 357.81    \\
Sample Size    & 11,536    &  11,529   & 11,950     \\
\bottomrule
\end{tabularx}
\smallskip
$^{*}$ Significant at the 1\% level.
\end{table}

\end{document}

Thanks a bunch!
UPDATE FOR ZARKO:
When I copy and pasted your preamble in, I got an error. In a mad dash I quickly hit command-z to undo and tried copy and pasting your preamble in a separate section, then worked backwards, deleting the things that were duplicated. This seemed to have worked, but it would be cool if you could look at it and clean it up again if necessary. I'm not sure what the error was by the way.
My new preamble:
\documentclass[twocolumn]{article}

\usepackage[T1]{fontenc}
\usepackage{newtxtext}
\usepackage{amsmath,geometry,siunitx,booktabs, tabularx}
\newcolumntype{C}{>{\centering\arraybackslash}X}
\newcolumntype{C}{>{\centering\arraybackslash}X}
\newcolumntype{L}{>{\raggedright\arraybackslash}X}
\newcommand\mC[1]{\multicolumn{1}{C@{}}{#1}}
\sisetup{group-separator={,}, group-minimum-digits=4}
\usepackage[skip=1ex]{caption}
\captionsetup[table]{font=small, labelfont=bf, singlelinecheck=no}
\usepackage{makecell}
\renewcommand\theadfont{\normalsize}
\renewcommand\theadgape{}
\setcellgapes{2pt}
\usepackage{textcomp}
\usepackage{graphicx}
\raggedbottom
\usepackage{rotating}
\usepackage[referable]{threeparttablex}
\usepackage{upquote}
\usepackage{balance}
\usepackage{wasysym}
\usepackage{footmisc}
\usepackage{float}
\floatstyle{boxed}
\restylefloat{figure}

%ZARKO:
\usepackage{geometry}
\usepackage[T1]{fontenc}
\usepackage{newtxtext}
\usepackage{textcomp}
\usepackage{booktabs, makecell, tabularx}
\renewcommand\theadfont{\normalsize}
\renewcommand\theadgape{}
\setcellgapes{2pt}
\usepackage{siunitx}
\sisetup{group-integer-digits,% in case of rounding decimals to three digits can be omitted
         group-separator={,},
         group-minimum-digits=4
         }
\usepackage[skip=1ex]{caption}
\captionsetup[table]{font=small, labelfont=bf, singlelinecheck=no}
%END ZARKO

\title{\LARGE \bf ECON 425 Term Paper}

\author{}

\begin{document}

Thanks again!

A: let me convert my comments to an answer :-)

*

*you require that groups are separated with comma ...

*if you like to have grouped only integer part of numbers, than in \sisetup use group-integer-digits

*in this case it is sensible to round decimal part of numbers, for example to three digits

of topic:

*

*in mwe below drop out all not relevant packages

*remained packages i grouped according to their functions (coding, fonts, tables, units, caption)

mwe:
\documentclass[twocolumn]{article}
\usepackage{geometry}
\usepackage[T1]{fontenc}
\usepackage{newtxtext}
\usepackage{textcomp}
\usepackage{booktabs, makecell, tabularx}
\renewcommand\theadfont{\normalsize}
\renewcommand\theadgape{}
\setcellgapes{2pt}
\newcolumntype{C}{>{\centering\arraybackslash}X}
\newcolumntype{C}{>{\centering\arraybackslash}X}
\newcolumntype{L}{>{\raggedright\arraybackslash}X}
\newcommand\mC[1]{\multicolumn{1}{C@{}}{#1}}
\usepackage{siunitx}
\sisetup{group-integer-digits,% in case of rounding decimals to three digits can be omitted
         group-separator={,},
         group-minimum-digits=4
         }
\usepackage[skip=1ex]{caption}
\captionsetup[table]{font=small, labelfont=bf, singlelinecheck=no}

\begin{document}
    \begin{table}
\setlength\tabcolsep{3pt}
\small
\caption{Comparing goodness of fit tests
for different specifications of pay-performance equation.} \label{tab:table}

\medskip
\begin{tabularx}{\columnwidth}{@{}
        l
   *{3}{S[table-format=3.3,
          table-space-text-post=*,
          round-mode=places,
          round-precision=3]} @{}}
\toprule
                & \mC{eq. 1}    & \mC{eq. 2}    & \mC{eq. 3} \\
\midrule
R-sqaure        & .255          &  .072         & .231      \\
\addlinespace[2pt]
Adj. R-square   & 0.254         & .070          & .2299     \\
F-statistic     & 140.94$^{*}$  & 37.26$^{*}$   & 357.81    \\
Sample Size     & {11,536}      & {11,529}      & {11,950}  \\
\bottomrule
\end{tabularx}
\smallskip
$^{*}$ Significant at the 1\% level.
    \end{table}
\end{document}

addendum:
my mwe also work with your complete preamble. in my test i reorganize it to
\documentclass[twocolumn]{article}
\usepackage{geometry}
\usepackage[T1]{fontenc}
\usepackage{newtxtext}
\usepackage{textcomp}
\usepackage{wasysym}
%
\usepackage{amsmath}
%
\usepackage{rotating}
\usepackage{booktabs, makecell, tabularx}
\usepackage[referable]{threeparttablex}
\renewcommand\theadfont{\normalsize}
\renewcommand\theadgape{}
\setcellgapes{2pt}
\newcolumntype{C}{>{\centering\arraybackslash}X}
\newcolumntype{C}{>{\centering\arraybackslash}X}
\newcolumntype{L}{>{\raggedright\arraybackslash}X}
\newcommand\mC[1]{\multicolumn{1}{C@{}}{#1}}
%
\usepackage{siunitx}
\sisetup{group-separator={,},
         group-minimum-digits=4
         }
%
\usepackage[skip=1ex]{caption}
\captionsetup[table]{font=small,
                     labelfont=bf,
                     singlelinecheck=no}
\usepackage{float}
\floatstyle{boxed}
\restylefloat{figure}
\usepackage{graphicx}
%
\usepackage{upquote}
\usepackage{balance}
\usepackage{footmisc}

seem if it is complete and if it works with your documents.


text:
Q: An inverse hyperbolic cosine approximation Given $-1<a<b<0<c<d<1$, $\gamma=\frac{a+b}{a-b}$, how do we approximate $\left\lceil \frac{\cosh^{-1}\gamma}{\log\gamma}\right\rceil$ as
$$
\left\lceil \sqrt{\frac{a}{b}}\left(1+\frac{1}{3}\frac{b}{a}+O(b^2/a^2)\right)\right\rceil?
$$
In general how to approximate $\left\lceil \frac{\cosh^{-1}\delta}{\log\gamma}\right\rceil$ where $\delta=\frac{c+d}{c-d}$?

A: Presumably you're taking $b/a \to 0$ here.  If $t = b/a$, then $\gamma = (1+t)/(1-t) = 1 + 2 t + 2 t^2 + O(t^3)$.  Now if $\gamma = 1 + u$, so $u = 2 t + 2 t^2 + O(t^3)$,
$$\eqalign{\cosh^{-1}(\gamma) &= \log\left(\gamma + \sqrt{\gamma^2-1}\right) = \log\left(1+u + \sqrt{2u + u^2}\right)\cr
&= \log\left(1 + \sqrt{2} u^{1/2} + u + \dfrac{\sqrt{2}}{4} u^{3/2} + O(u^{5/2})\right)\cr
&= \sqrt{2} u^{1/2} - \dfrac{\sqrt{2}}{12} u^{3/2} + O(u^{5/2}) \cr
\log(\gamma) &= \log(1+u) = u - \dfrac{u^2}{2} + O(u^3)\cr
\dfrac{\cosh^{-1}(\gamma)}{\log(\gamma)} & = \sqrt{2} u^{-1/2} + \dfrac{5 \sqrt{2}}{12} u^{1/2} + O(u^{3/2})\cr
&= t^{-1/2} + \dfrac{1}{3} t^{1/2} + O(t^{3/2})\cr
}$$
as desired.


text:
Q: Website debugging fails because of port mismatch I am debugging a MVC4 application using VS2012. I press F5 in VS IDE. Then 'ASP.net development Server' gets launched and the tool-tip(shown in the bottom-right corner)
says http://localhost:9553

Then FireFox gets launched with URL
http://localhost:43297/default.aspx

Browser fails to connect to web-server. This is obvious because 'ASP.net development Server' is listening on 9553 but the browser is connecting to 43297.
If any one knows reason for this port mismatch, please let me know.
(There is an another way to know the port being used by 'ASP.net development Server'. First, keep  'ASP.net development Server' running. Then use ProcExp.exe to look at the command-line parameters used for launching WebDev.WebServer40.exe. That cmd-line parameter will have port number. In this case port is 9553)

A: Can you tell us what is under the Web tab in the Project Properties? (right click your project in solution explorer and select Properties) - am interested in whether either or both of those URLs are mentioned anywhere in those settings. Specifically what is in Start URL and Project URL fields.
You should clear out any setting in Start URL and leave anything in Project URL


text:
Q: Creating an MSI or Script to deploy an EXE through AD First:
I know there are other questions that ask similar/the same thing, I have looked at them tried all of them but no solution has helped.
The problem:
We use Epson Iprojection (downloaded from here: https://www.epson.co.nz/products/projectors/software/) However I can not find a way to get an MSI out of it (I am starting to think there is no MSI bundled in the .exe), and I can not seem to install it through CMD on computer start using AD. Any help will be greatly appreciated.

A:
Vague Answer: Let me try to formulate an answer out of those messy comments above. I only briefly tested this software, it might not deploy as badly as expressed. Remember that this is a generic answer for whoever would find this in the future, and not for OP per-se (there is no real answer in here).

Due Diligence: I always try to consult package tip databases if I have problems with a package. Somebody, somewhere will have seen the same problem (eventually).
Silent Installation: Silent installation of legacy setups is usually possible (not always), but never really reliable. For Installshield it involves recording answer files (setup.iss) that record dialog answers. However, unknown dialogs can show up suddenly on some systems (low disk space, reboot prompts, unexpected lock  or application in-use warnings, unexpected service running warnings,etc...) and hence halt the install unexpectedly as the response file has no recorded value for the dialog in question. This particular Epson setup also has an unfortunate reboot requirement on uninstall that is hard to deal with for large scale deployment (spontaneous reboot likely - without warning).
Repackaging: Personally I would try to capture the install using a repackaging tool. Most of these are expensive, but can output MSI, MSIX or other deployment package types. Repackaging fails when the package contains complex, custom logic that - for example - create dynamic content (ciphers, unique GUIDs, etc...) and in a number of very specific technical cases.
Contact Vendor: If you capture an MSI that doesn't work, why not try to send it back to the vendor with some comments on how hard this software is to deploy and maybe mention the major benefits of MSI? I would tell them you have to ditch the whole software from your network if they can't deliver a deployment solution that works. Time is of the essence. "Some solutions are only free if your time is worthless" (quote from Joel Spolsky himself - slightly out of context, but the same issue: we need solutions that work in a timely fashion).

Note: I once had to compile a special setup to deal with a client's
  deployment problem that was our fault. Deployment problems need fixing at a standardization level. Standards!

A: Buried within the single-exe download is iProjection_inst.exe, some sort of wrapper that prompts for language selection, and doesn't seem to have a standard "non-interactive" mode.
Inside this is instData\Setup.exe, a vintage "full screen" InstallShield installer with external ini / cab files.
Running this with Setup.exe /? doesn't give any command line arguments, as it would for a modern InstallShield setup.exe.
Although it supports recording an answer file via Setup.exe /r, when I try to replay the answer file with Setup.exe /s it seems to still prompt for EULA, and then fails to install.
So this is really a design flaw in the innermost installer to do with the dialog sequence.
Assuming Epson won't fix it and repackaging is too hard, a hacky alternative is to use Powershell to automate the UI of instData\Setup.exe once the "Welcome" screen is showing, but I don't think this will work running as an AD script.
$wshell = New-Object -ComObject wscript.shell
$aName = "Epson iProjection Setup"
function Next() {
  if ($wshell.AppActivate($aName)) {
    $wshell.SendKeys(' ');
    start-sleep 1;
  }
}
function AcceptEula() {
  if ($wshell.AppActivate($aName)) {
   $wshell.SendKeys("{TAB}");
   $wshell.SendKeys("{TAB}");
   $wshell.SendKeys(' ');
   start-sleep 1;
  }
}
Next; AcceptEula; AcceptEula; start-sleep 20; Next;

A: I know this is an old thread but it looks like it may be easy now.  The latest 2.41 from here
http://www.downloads.epson.com.au/DownloadFile.asp?filename=iProV2411Win%5FWEB%2Eexe&path=Drivers
seems to have an MSI in it. Just jump into the %temp% folder and organize by date so you can see the latest files.  Run the installer and a new folder named with a GUID should show up, in my case {27CDEEE8-B6F2-45a7-A48E-696862573D9B}.
Under this folder there is a series of InstData folders like InstDataX64 where you can find an MSI.


text:
Q: how to navigate pages in asp.net I have to navigate to another page in asp.net suppose I have two pages i.e. Default.aspx and Default2.aspx how do I navigate between them ?

A: there are many ways, here are a few to get you started
go there

<asp:HyperLink runat="server" ID="lnk" Text="go there" NavigateURL="default2.aspx" />

<asp:LinkButton runat="server" ID="btn" Text="go there" OnClick="server_method_that_redirects" />

A: You could use anchors in your aspx page:
Click to navigate to Default2.aspx

or make a redirect in your code behind:
Response.Redirect("~/Default2.aspx");

A: On your server side codebehind you may also consider using Server.Transfer(..) instead of Response.Redirect(..).
Response.Redirect sends an instruction to the browser to change the page while Server.Transfer does it directly on the server side. Browse the web for further information about the differences.