text:
Q: optional where clause condition in mysql I am working on a project where I load a list of students depending on the date selected and the teacher chosen from a dropdown.The list contains those students data whose class teacher is the teacher selected. Now i am using the following query:
select s.studentcode,s.studentname,a.attdate,if(a.period='01' or
a.period='AM',a.status,'') as attAM,if(a.period='PM',a.status,'') as attPM
from tblstudent s left join tblattendance a on s.studentcode=a.studentcode
where s.classcode='10002' and a.attdate='2014-04-11'

Now the problem with the above is query is that if i chose some date like 2014-04-15 then as attendance is not marked for this date then no record is found,but i want that the student list is always displayed and if attendance is marked for that date it should be displayed accordingly else those fields will be blank

The above screenshot is displaying the list which I want.Now the field AM should be blank if attendance for that date is not marked and if it is marked it should contain the corresponding attendance

A: Move your AND a.attdate = '2014-04-11' to join's ON() clause so if date is not present it still returns the records for s.classcode = '10002' and a.attdate column will be null in the result set,where filter is applied to whole resultset where as using additional condition in join will filter the records from right table i.e tblattendance not on whole resultset
SELECT
  s.studentcode,
  s.studentname,
  a.attdate,
  IF(
    a.period = '01'
    OR a.period = 'AM',
    a.status,
    ''
  ) AS attAM,
  IF(a.period = 'PM', a.status, '') AS attPM
FROM
  tblstudent s
  LEFT JOIN tblattendance a
    ON (s.studentcode = a.studentcode AND a.attdate = '2014-04-11')
WHERE s.classcode = '10002'


text:
Q: onclick= return window.confirm not working in a concatenate php string this is my permière question about this forum, I hope to find one from my problem
    I can not display the message of "retrun.windows.confirm share (" blah blah blah ")"
      for information when I remove the message popup confirmation appears.
Here is the code I use
$msg=$msg .'

            '.$row["Lib_Fr"].'
            '.$row["Lib_En"].'
            '.$row["Lib_Es"].'

';

A: a class="mouse" onclick="SimpleModal.open("Contenu_Maj.php?ID=".$row["_ID"]."&Table=".$_SESSION["NomTable2"]."", 350, 500);"
you suppose to use apostrophe to concatenate php values here
PS: sorry im on mobile and i dont have wysiwyg editor available

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dependency Injection of Repository Interface for a Domain Specification Object not sure if I'm just too tired and missing something so apologies in advance.
I have a php domain which I need to restructure because ended having an anemic model using services. This is because I'm not using Doctrine but Eloquent by Laravel as my mapper (reasons are due to linking to other different DB server types)
My reviewed structure needs to be something similar to do this: ( I'm only including a couple of things for this example)
Template Entity has TemplateName as VO.
The TemplateName must satisfy 2 specs. Has to be more than 3 chars long and has to be unique.
I am using a TemplateRepositoryInterface to check the uniqueness and the interface has an Eloquent implementation bounded in a service provider.
Therefore the Template Entity has a method:
public function create()
    {
        if ($this->meetsTemplateNameSpecification())
        {
            //fire events etc... saving to repo is done one step above from a service that call this class and gets $this to send tot he interface

            return $this;
        }

        throw new InvalidArgumentException("Template name is not valid.");
    }

Then my meetsTemplateNameSpecification method:
private function meetsTemplateNameSpecification($originalTemplateName = null)
    {
        $templateNameSpecification = new TemplateNameSpecification($this->name, $originalTemplateName);

        if($templateNameSpecification->isMet())
        {
            return true;
        }

        return false;
    }

Before this restructure, a service was initiating all these and passing the RepositoryInterface to them so that was easy. However, this way I don't know how and /or where to pass or inject the interface because if I have it injected from the container to the Specification class then I cannot initiate from the Entity and I cannot inject the Spec class to the entity either because i want to be able to use it's constructor.
I find it very hard to do in PHP and Active Record with keeping a separation of concerns and not having a dependency on persistence in the domain.
Does anyone have a better structure? Let me know if you need more code please.
So far the only solution that comes to mind is to have static methods in my specification objects so that they do not need to be initiated and I can inject the Repo dependency from the container. Is this the way to go or there's better ways that work with PHP. I hate having to inject from the container to the Domain too but don't think there's any better way unless you're using a different architecture.

A: I think you're overcomplicating things.
Specification pattern is cool if used in a very general method signature that takes specifications as parameters, or if you have a whole family of specifications. With just one or two particular conditions to test, it might be overkill.
Also, trying to inject a Repository into a domain object (as I guess you are) may be causing you more trouble than good. String length is most probably not a domain rule and uniqueness may not be either. You might be better off checking those constraints at the Application Service (or Controller) level, directly calling the Repository there for uniqueness, which will spare you all the injection trouble.


text:
Q: Windows Anaconda Keras Install error Collecting keras
  Using cached Keras-2.0.0.tar.gz
Collecting tensorflow (from keras)
  Could not find a version that satisfies the requirement tensorflow (from keras) (from versions: )
No matching distribution found for tensorflow (from keras)

A: Your question definitely needs more info, but probably you need to install the right version of tensorflow first.
Keras 2 goes well with tensorflow 1, which goes well with python 3.5. If your anaconda runs python 2 or 3.6, first create a python 3.5 conda environment, and install tensorflow and keras there:

conda create -n myenv python=3.5 anaconda
activate myenv
(myenv) pip install tensorflow
(myenv) conda install keras


text:
Q: Knowing the order in which the javascript files are loaded in the page I am using requirejs to load all the javascript files in my application. Now i want to know the order in which the files are loaded in the page. So is there a way to get to know that in chrome dev tools?
Thanks in advance

A: If you want to use the chrome dev tools, you can open the network tab.


text:
Q: on passing 2 datetime values using json.stringify to controller with ajax call first one is passed in datetime format but second one becomes null I am trying to pass multiple parameters including 2 datetime type parameters using json.stringify() method through ajax call to mvc controller jsonresult type action method.
All paramters values are passed successfully. From 2 datetime type parameters 1st value is passed successfully but 2nd parameter value becomes null!
below is my code.
javascript code:
    var MobileNumber = $('#MobileNumber').val() == "" ? 0 : $("#MobileNumber").val();
    var FromDate = $('#FromDate').val() == "" ? 0 : $("#FromDate").val();
    var FromTime = $('#FromTime').val() == "" ? 0 : $("#FromTime").val();
    var ToDate = $('#ToDate').val() == "" ? 0 : $("#ToDate").val();
    var ToTime = $('#ToTime').val() == "" ? 0 : $("#ToTime").val();

$.ajax({
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        type: "POST",
        url: '@Url.Content("~/Merchant/GetRejectedMerchantTransactions")',
        data: JSON.stringify({ mobileNumber: MobileNumber, fromDate: FromDate, fromTime: FromTime, toDate: ToDate, toTime: ToTime }),
        success: function (data) {
        $('#statusBox').removeClass('alert-danger').addClass('alert-success').show(500, function () {
                                        $('#statusMessage').html(data.Message);
                                    });
                                }
        }
    });

and controller code is as below:
[HttpPost]
[Authorize]
public JsonResult GetRejectedMerchantTransactions(string mobileNumber, DateTime? fromDate, string fromTime, DateTime? toDate, string toTime)
{
     List<MerchantTransactions> lstMerchantTransactions = new List<MerchantTransactions>();
        try
        {
            string  shortFromDate = "";
            string  shortToDate = "";
            string fromFinalDate = "";
            string toFinalDate = "";

            if (fromDate.HasValue && fromTime.Length > 1)
            {
                shortFromDate = fromDate.Value.ToShortDateString();
                fromFinalDate = shortFromDate + " " + fromTime;
            }

            if (toDate.HasValue && toTime.Length > 1)
            {
                shortToDate = toDate.Value.ToShortDateString();
                toFinalDate = shortToDate + " " + toTime;
            }

            List<TransactionStatus> lstTransactionStatus = GetTransactions();
            TransService.TransServiceClient transServiceClient = new TransService.TransServiceClient();
            TransService.GetTransactionsRequest getTransactionsRequest = new TransactionService.GetTransactionsRequest
            {
                MobileNumber = Convert.ToDecimal(mobileNumber),
                FromDate = string.IsNullOrEmpty(fromFinalDate) ? fromDate : Convert.ToDateTime(fromFinalDate),
                ToDate = string.IsNullOrEmpty(toFinalDate) ? toDate : Convert.ToDateTime(toFinalDate)
            };
}

i have also tried by changing the parameters name but it gives same result.

A: I have resolved this issue by applying new Date() javascript function for all datetime type values in my .cshtml file.
like
var FromDate = $('#FromDate').val() == "" ? 0 : new Date($("#FromDate").val());
var FromTime = $('#FromTime').val() == "" ? 0 : new Date($("#FromTime").val());


text:
Q: What is the D3D12 equivalent of Direct3DCreate9(D3D_SDK_VERSION)? So I am currently coding a D3D12 engine and was wondering what the D3D12 equivalent of this D3D9 function is ?
direct3D = Direct3DCreate9(D3D_SDK_VERSION);

A: The closest equivalent is D3D12CreateDevice. It's used for example like this:
hr = D3D12CreateDevice( adapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS( &device ) );

A: There is no distinct equivalent, the closest could be CreateDXGIFactory to me, as it is the access point to adapters and outputs.
But if you are asking that kind of question, d3d12 is not for you. Unless you are already a d3d11 more than expert everyday user working on a triple A kind graphic engine, d3d12 is not what you are looking for. It is better to stick to d3d11.


text:
Q: join issue MYSQL/PHP i have a bit of a problem, ive never used JOIN before, and this is the first time, and i got into some problems:
<?php
//$count to keep the counter go from 0 to new value
    $count=0;

//I need to select the level for the users building first, meanwhile i also
//need to get the money_gain from the table buildings, which is a table that
//is common for each member, which means it doesnt have a userid as the other table!
//And then for each of the buildings there will be a $counting

    $qu1 = mysql_query("SELECT building_user.level,buildings.money_gain FROM building_user,buildings WHERE building_user.userid=$user");

    while($row = mysql_fetch_assoc($qu1))
    {
     $count=$count+$row['level'];
     echo $row['level'];
        }
?>

So basically ive heard that u should tie them together with a common column but, in this case thir isnt any.. im just lost right now?
EDIT Oh right, I need the right level to be taken out with the correct money_gain too, in building_user its 'buildingid'and in buildings, its just 'id'! have no idea how to make a common statement though!

A: i think you problem is, that MySQL doesn't know how to JOIN the two Tables. Therefor you have to tell MySQL how to do that.
Example
SELECT * FROM TABLE1 INNER JOIN Table1.col1 ON TABLE2.col2;

where col1 and col2 are the columns to join (a unique identifier)

A: <?php

$count=0;

$qu1 = mysql_query("SELECT bu.level, bs.money_gain FROM building_user bu, buildings bs WHERE bu.userid=$user");

while($row = mysql_fetch_assoc($qu1))
{
 $count=$count+$row['level'];
 echo $row['level'];
}

?>

A: From your edit,
SELECT building_user.level,buildings.money_gain FROM building_user,buildings WHERE building_user.userid=$user AND building_user.buildingid = building.id;

You essentially get the records for the user joining them at the building id
Performance-wise, joins are a better choice but for lightweight queries such as this, the query above should work fine.
You can also give each column a neater name
SELECT building_user.level as level,buildings.money_gain as money gain FROM building_user,buildings WHERE building_user.userid=$user AND building_user.buildingid = building.id;

and access them as
$level = $row['level'];
$gain  = $row['gain'];

A: Try this
$qu1 = mysql_query("SELECT building_user.level,buildings.money_gain
                    FROM building_user
                    JOIN buildings  ON building_user.building_id = buildings.id
                    WHERE building_user.userid=$user");

building_user.building_id is the foreght key of table building_user and
buildings.id  is the primary key of table buildings


text:
Q: Professional Printer for Mass-Producing A4 Brochures? The company I work for is looking at printing tens of thousands of high-quality A4 brochures, and we want to explore the possibilities of buying some printer(s) and producing them in-house, which may work out better for us in the long-run (several re-prints down the line).
Should we consider buying a high-quality printer, or should we hire a professional printing service?
Many thanks.

A: Such quantities are really something you should put into the hands of a specialist printing service, who will have the equipment and knowledge to ensure the product you receive is of a satisfactory quality.
That said, if you do want to do it in house, I'd personally recommend speaking to a printer vendor like HP directly and asking what solutions they can provide for your task, and make sure to mention stapling! The outlay wont be cheap but if it means saving in the long run then go for it!

A: For brochures, while you can get very good results with a standard high-quality printer for what you are looking to spend, you likely will not get the same results as a professional printer, and you may not be totally pleased with the results (read, you wasted a lot of money). For brochures, most smaller print shops don't even do them themselves, and send them out to places that have equipment costing 100's of thousands of dollars. They don't use standard printers to get the best results.
Farm it out.
http://www.brochuremonster.com/printing/printing.php (go to the section on commercial printers).


text:
Q: Getting a specific value from a table created in Code Behind I am trying to retrieve a specific value from a table created at runtime in the code behind.
using jquery.
sb.Append("
");
                sb.Append(prodCode);
                sb.Append("	");

                sb.Append("");
                sb.Append("<input type='checkbox' name='chkBestSeller' value='Best Seller' style='font-size:x-small;'");
                sb.Append("<input type='hidden' name='prodCodeBestSeller' value='" + prodCode + "'");
                sb.Append("	");
Products.InnerHtml = sb.ToString();

this is my jquery function.
$(document).on("click", "input[name='chkBestSeller']", function () {
var code = $(this).parent().find("input[name='prodCodeBestSeller']").val();
alert(code);

});

My feeling is that it should work but it brings back a value of 'undefined' instead.
How can i achieve retrieving the code value at the specific row

A: try this
$("input[name='chkBestSeller']").click( function () {
var code = $(this).closest('tr').find("input[name='prodCodeBestSeller']").val();
alert(code);
});

A: $(document).on("click", "input[name='chkBestSeller']" ...

this refers to the element clicked on, i.e. input[name='chkBestSeller'].
In your case you can get the value of the hidden field with
$(this).next().val()


text:
Q: how to read different files in differents runnable threads Java I need to read all .txt files in a folder with 4 Threads running at the same time. What can I do so each thread reads a different file. Ex: Thread 1 reads file 1, Thread 2 reads file 2... and so on until there's no more files to read.
Thread h;

public Hilo(){
    h= new Thread(this,"Hilo 1");
    h.start();
}

public void run(){
    int contador;
    File folder = new File("C:/Users/Jose/Desktop/java");
    File[] listOfFiles = folder.listFiles();
    for (File file : listOfFiles) {
        if (file.isFile()) {
            contador=0;
            int i=0;
            //System.out.println(file.getName());
            Scanner scan = null;
            try {
                scan = new Scanner (file);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            while (scan.hasNext()){
                String linea=scan.next();
                String[] lineas = linea.split("(?=[,.])|\\s+");
                if (Palindrome.is(lineas[i])){
                    contador++;
                }
            }
            scan.close();

        }

    }
}

A: package z;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {

    public static void main(String[] args) {

    ExecutorService exec = Executors.newFixedThreadPool(4);

    File folder = new File("C:/Users/Jose/Desktop/java");

    File[] files = folder.listFiles();

    for(File file : files){

        exec.execute(new Worker(file));
    }

    }
}

class Worker implements Runnable {

    private File file;

    public Worker(File file) {
    this.file = file;
    }

    @Override
    public void run() {
    int contador;
    if (file.isFile()) {
        contador = 0;
        int i = 0;
        Scanner scan = null;
        try {
        scan = new Scanner(file);
        } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
        while (scan.hasNext()) {
        String linea = scan.next();
        String[] lineas = linea.split("(?=[,.])|\\s+");
        if (Palindrome.is(lineas[i])) {
            contador++;
        }
        }
        scan.close();

    }

    }

}

A: This is the code, without the palindromo method, its not necesary.
public class main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Hilo numero1 = new Hilo();
        Hilo numero2 = new Hilo();
        Hilo numero3 = new Hilo();
        Hilo numero4 = new Hilo();
    }
}

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Hilo implements Runnable {

    Thread h;

    public Hilo() {
        h = new Thread(this, "Hilo 1");
        h.start();
    }

    public void run() {
        int c = 0;
        int contador;
        File folder = new File("C:/Users/Jose/Desktop/java");
        File[] listOfFiles = folder.listFiles();
        for (File file : listOfFiles) {
            if (file.isFile()) {
                contador = 0;
                int i = 0;
                //System.out.println(file.getName());
                Scanner scan = null;
                try {
                    scan = new Scanner(file);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                while (scan.hasNext()) {
                    String linea = scan.next();
                    String[] lineas = linea.split("(?=[,.])|\\s+");
                    if (Palindromo.es(lineas[i])) {
                        contador++;
                    }
                    c++;
                }
                scan.close();
                System.out.println("La cantidad de Palindromos en el archivo " + file + " es de: " + contador);
            }

        }
    }
}

A: Try it:
1. Create a class ReadFiles:
public class ReadFiles {

    public interface IEvents {
        void onFile(File file);
    }
    int maxConcurrentThread = 5;
    ThreadPoolExecutor pool = null;

    volatile int countFiles = 0;
    String folder = "";
    IEvents event = null;

    public ReadFiles(String folder, int maxConcurrentThread) {
        this.folder = folder;
        this.maxConcurrentThread = maxConcurrentThread;
    }

    public void setEvent(IEvents event) {
        this.event = event;
    }

    public void read() {

        ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(this.maxConcurrentThread);

        File ffolder = new File(folder);
        File[] listOfFiles = ffolder.listFiles();
        for (final File file : listOfFiles) {
            if (file.isFile()) {
                pool.execute(new Runnable() {

                    @Override
                    public void run() {
                        countFiles++;
                        event.onFile(file);
                    }

                });
            }
        }

        pool.shutdown();
    }

}

How to use:
int maxConcurrentThread = 5;
        ReadFiles read = new ReadFiles("C:/Users/Jose/Desktop/java", maxConcurrentThread);
        read.setEvent(new ReadFiles.IEvents() {

            @Override
            public void onFile(File file) {
                Scanner scan = null;
                try {
                    scan = new Scanner(file);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                while (scan.hasNext()) {
                    String linea = scan.next();
                    String[] lineas = linea.split("(?=[,.])|\\s+");
                    if (Palindrome.is(lineas[i])) {
                        contador++;
                    }
                }
                scan.close();
            }
        });
        read.read();


text:
Q: Who proposed the bulk-edge correspondence principle? Who proposed the bulk-edge correspondence principle?
The principle is often quoted in counting the number of zero energy states localized on the interface between two insulators with distinct band topology. However, I could not retrieve who was the first to say that.

A: I believe it was Xiao-Gang Wen in 1989, see also this 1994 paper by him and his collaborators

http://dao.mit.edu/~wen/pub/ednab.pdf

He's at MIT. I was once hosting a seminar by him, he is one of the most creative and playful folks in this segment of condensed matter physics. The paper above contains some other relevant references, including a paper by Wen and Tony Zee.

A: Maybe it is R. Jackiw and C. Rebbi (Phys. Rev. D 13, 3398)
When explaining the quantum Hall effect, Hasan and Kane (Rev. Mod.Phys. 2010, 82: 3045–3067) said "This interplay between topology and gapless modes is ubiquitous in physics and has appeared in many contexts. It was originally found by Jackiw and Rebbi (1976) in their analysis of a 1D field theory" in pages 3048-3049.

A: @Hai-Yao Deng. I hope that by now you might have found the answer to your question. I have recently started reading about the topological phases of matter. I find that in his paper, Y. Hatugai PRB 48, 1993 study in detail about this correspondence for the integer quantum Hall effect. He also summaries a sort of development of the argument from TKNN calculation of Hall conductance to the numerical computation of edge states in the same system by Rammal, Toulouse, Jaekel, and Halperin.


text:
Q: How to programmatically execute undo and redo in CKEDITOR, and reset their stacks? Is there a way to programmatically execute undo and redo in CKEDITOR?
And the other question is: is there a way to reset the undo stack and also the redo stack?

A: Undo:
editor.execCommand( 'undo' );

Redo:
editor.execCommand( 'redo' );

Reset:
editor.resetUndo();


text:
Q: Merge Route::group domain Laravel 5 My project need new mirrors domain each weeks only for the API.
To do that, in the route file I add a Route::group for each domains.
Route::group(['domain' => 'domain2.com'], function(){
    Route::group(['namespace' => 'Api', 'prefix' => 'r'], function() {
        Route::get('/{hash}', 'ApiController@index');
    });
    Route::get('/', function(){
        return view('errors.noshort');
    });
});

Route::group(['domain' => 'domain1.com'], function(){
    Route::group(['namespace' => 'Api', 'prefix' => 'r'], function() {
        Route::get('/{hash}', 'ApiController@index');
    });
    Route::get('/', function(){
        return view('errors.noshort');
    });
});

*

*How can I merge this two Route::group and the next ?

*Can I get all the domains from my database to dynamically do the route ?

A: 1 link your domains like this:
$apiRoutes = function() {
    Route::group(['namespace' => 'Api', 'prefix' => 'r'], function() {
        Route::get('/{hash}', 'ApiController@index');
    });
    Route::get('/', function(){
        return view('errors.noshort');
    });
};

Route::group(['domain' => 'domain2.com'], $apiRoutes);
Route::group(['domain' => 'domain1.com'], $apiRoutes);

2 Difficult to understand what you mean by import your domains

A: Directly you can not assign array to domain. It expects only single string parameters.
You can do like this. to assign Route::group store in your DB  fetch it in your route file
Try this hope it helps.
like,
$domains = \App\Domain::all();

foreach ($domains as $domain) {
    Route::group(['domain' => $domain->domainName], function(){
        Route::group(['namespace' => 'Api', 'prefix' => 'r'], function() {
        Route::get('/{hash}', 'ApiController@index');
        });
        Route::get('/', function(){
        return view('errors.noshort');
        });
    });
}


text:
Q: Using Bamboo to build Subversion/Maven project that defines parent POM(s) I have a complex project structure that goes something like this:
- root (no pom)
     - parent(parent pom.xml)
     + project A (pom.xml)
     + project B (pom.xml)
     - project C (pom.xml)
         - subproject 1 (pom.xml)
         - subproject 2 (pom.xml)
     + project N (pom.xml)

I need to build subproject 2 using Bamboo server. I use Bamboo to checkout subproject 2 code but when I run mvn install on that it fails with "Non-resolvable parent POM" message.
The build runs fine when all the code is in the single location. I don't want to checkout code on root level since there are tons of projects that I don't want to check out (in my example that would be projects A, B, N and subproject 1)
I attempted to check out code 3 times for parent, project C/pom and subproject 2 but the code is placed onto separate directories with no relation to each other so there's not much help there
P.S.
I'm using no modules, though I did try it with modules and it made no difference. I'm not posting the actual POMs since these are very trivial, basically child pom has parent element and that's all relation there is.
All upstream projects are deployed to both local and remote repos

A: mvn will look for dependencies in three places, in a relative path on the local file system, cached in the m2 repo on your local machine, or in an external repo.  If you install all the dependencies on a repo that bamboo can access, your build will probably work.
To test this, on your local machine, can you do a mvn install from the root directory (placing all the dependencies in the m2 repo on your machine), and then checkout subproject2 in a separate directory and then mvn install subproject2?
If that works, then the dependencies of subproject 2 need to be in a maven repo that bamboo can access.  Deploy them using something like artifactory before doing mvn install with bamboo.

A: We have a very similar project structure, and I just verified that I'm able to create a Jenkins job that only checks out the equivalent of subproject1 and builds it with mvn -U clean install.  I have no access to a Bamboo instance, but both Jenkins and Bamboo just invoke Maven under the hood, so there should be no difference here.
The other option that works, as you mentioned, is to checkout the entire repository, (or directory containing root and all modules) and run mvn -U clean install -pl subproject1 -am on the parent POM.
To help you with this, we really need more information.  You mentioned in one of your comments that "all [upstream] dependencies are already deployed to repo".  Do you mean your local repository (i.e. .m2/repository)?  You should double check that this directory contains all of the parent POMs. Are you resolving all artifacts from a proxy (i.e. Artifactory/Nexus)?  If so, also check that the POMs are available there.
Your current structure diagram doesn't show the location of the POMs.  I assume you've got it setup correctly, but I have seen cases where people put child modules in strange locations, which can cause problems.  The relative locations of the POMs matter (unless you do some customization). Could you run tree on the root and sanitize the output so that we know exactly where your POMs are in relation to one another? For example:
parentProject
|-- projectA
|   |-- pom.xml
|
|-- projectB
|   |-- pom.xml
|   |
|   |-- subProject1
|   |   |-- pom.xml
|   |
|   |-- subProject2
|       |-- pom.xml
|
|-- pom.xml

Lastly, could you navigate to the child project/module you're attempting to build and post the output of mvn help:effective-pom?

A: Each of the maven modules should be self contained, using relative links that talk about ../parent breaks this design.
Try and explicitly define the parents by GAV properties, and then ensure these poms are installed in your local maven repo and you will be able to build sub projects.
We run a 15 module build down 3 levels and this is all possible.
The only issue you have is when you bump versions, you will have to kick off an install of the root pom file to boostrap the resolution process.


text:
Q: fragmenting data from text file into list of facts to prolog file I want to separate the data file into list of facts like functor(arg1, arg2, ..., argN) which the name of functor is the uppercase line and the arguments are the lowercase lines  that follow them,
subsequently, new clauses are saved in a prolog file created at the execution
file.txt
FUNCTOR1
arg1
arg2
FUNCTOR2
arg1
arg2
arg3
FUNCTOR3
arg1
arg2
arg3
arg4

result :
?- split_data_to_facts('file.txt',List,'file.pl').
List = ['functor1(arg1,arg2)','functor2(arg1,arg2,arg3)','functor3(arg1,arg2,arg3,arg4)'].

file.pl
"." will be appended as the last
functor1(arg1,arg2).
functor2(arg1,arg2,arg3).
functor3(arg1,arg2,arg3,arg4).

after building and compiling the new prolog file file.pl:
?- functor2(X,Y,Z).
X=arg1,
Y=arg2,
Z=arg3;
yes

A: Let's assume a builtin read_line_to_codes/2 is available: then you could apply a lookahead of one line:
process_file(Path) :-
  open(Path, read, In),
  read_line_to_codes(In, Line1),
  read_line_to_codes(In, Line2), % assume not empty
  process_lines(Line2, [Line1], In, Facts),
  maplist(writeln, Facts).  % just for test

process_lines(end_of_file, LastFactDef, In, [LastFact]) :-
  lines_fact(LastFactDef, LastFact),
  close(In).
process_lines([U|Us], LastFactDef, In, [LastFact|Facts]) :-
  upper_lower(U, _),
  lines_fact(LastFactDef, LastFact),
  read_line_to_codes(In, Line),
  process_lines(Line, [[U|Us]], In, Facts).
process_lines(Last, Lines, In, Facts) :-
  read_line_to_codes(In, Line),
  process_lines(Line, [Last|Lines], In, Facts).

lines_fact(Lines, Fact) :-
  reverse(Lines, [FunctorUpper|ArgCodes]),
  maplist(make_lower, FunctorUpper, FunctorCodes),
  maplist(atom_codes, [Functor|Args], [FunctorCodes|ArgCodes]),
  Fact =.. [Functor|Args].

% if uppercase get lowercase
upper_lower(U, L) :-
  between(0'A, 0'Z, U), L is 0'a + U - 0'A.

make_lower(C, L) :- upper_lower(C, L) ; L = C.

running a test in SWI-Prolog (where we have by default available read_line_to_codes/2 and between/3):
?- process_file('/home/carlo/test/file.txt').
functor1(arg1 ,arg2)
functor2(arg1,arg2,arg3)
functor3(arg1,arg2,arg3,arg4)
true


text:
Q: My Website Crashes In IE9 My website is crashing sporadically in IE9 on a certain page.  The page has a lot of Javascript, including Twitter Bootstrap, JQuery, Google Analytics, Olark, Facebook, ZeroClipboard, and a lot of custom script, which is mostly compiled from CoffeeScript. I also use a good bit of CSS3, even some animation stuff, but I have removed all of that from this page (I think).
This is a hard crash of the IE executable.  F12 script debugger does not catch this or give any hint what it might be.  Windows event viewer logs the crash, but there is no useful detail.
The page is fine on all other major browsers on Windows, Mac and iOS.  I'm at a loss of even how to troubleshoot this.  I've just been hacking at various stuff.
The crash is somewhat at random. However, you should be able to reproduce like this:

*

*Go here: http://slotted.co/sheets/edit/94cvk6as

*Click "Delete This Sheet" then "Cancel" repeatedly

After a few times, it should crash.
NOTE: If the above link is broken, go the home page and create a new sheet.
Any ideas of how to approach this are much appreciated.
UPDATE: If you cannot reproduce with the steps above, F5 a couple of times in between clicks of the link.

A: *

*Get into a position where you can preciptiate the crash reliably by automating the button clicks using Selinium, or something similar.

*Binary chop the non essential js, retying the tests (A B then back to A) to confirm you've found it.

A: I'm pretty sure the problem was ZeroClipboard. Let me elaborate. Zero Clipboard comes with two flash files ZeroClipboard.swf and ZeroClipboard10.swf.  I had been using the former.
I switched to ZeroClipboard10.swf, and the problem goes away.
It did not seem to go away at first.  Event after completely removing ZeroClipboard, I was still able to reproduce a crash.  My theory is that IE was retaining some harmful state in cache.
I can't say for sure.  What I can say is that I can no longer reproduce the crash after switching to ZeroClipboard10.swf  I believe that change was the thing that made the difference.


text:
Q: Datepart into previous year based on week I am learning SQL at the moment and needed a query that would return the previous 12 weeks (excluding the current week) and the below worked just fine - that was until we moved in to 2019!
My table has 4 columns, BuildWeek, BuildYear, Info1, Info2, all are int.
select *
from Dashboard
where BuildWeek in (datepart(week, getdate()) - 1,
                    datepart(week, getdate()) - 2,
                    datepart(week, getdate()) - 3,
                    datepart(week, getdate()) - 4,
                    datepart(week, getdate()) - 5,
                    datepart(week, getdate()) - 6,
                    datepart(week, getdate()) - 7,
                    datepart(week, getdate()) - 8,
                    datepart(week, getdate()) - 9,
                    datepart(week, getdate()) - 10,
                    datepart(week, getdate()) - 11,
                    datepart(week, getdate()) - 12,
                    datepart(week, getdate()) - 13)
  and BuildYear = datepart(year, getdate())
order by
    BuildWeek desc

I know this is not the cleanest query so I'm quite open to being educated, I have tried a few things (using dateadd to no avail) but cannot seem to get it to function how I wish. I'm guessing the above stems from the query perhaps looking into a minus (current date -1 would be 0, -2 would be -1 so no results would be found?) but I'm not sure how to make it look backwards to return those extra weeks.

A: Assuming you have one row per week:
select top (12) d.*
from Dashboard d
order by d.year desc, d.BuildWeek desc;

To avoid future weeks:
select top (12) d.*
from Dashboard d
where year < year(getdate()) or
      (year = year(getdate()) and buildweek <= datepart(week, getdate())
order by d.year desc, d.BuildWeek desc;

Or, if you want to use a where and years have 52 weeks:
select d.*
from dashboard d
where (y.year * 52 + buildweek) >= year(getdate()) * 52 + datepart(week, getdate());

This method becomes a bit trickier if years can have 53 weeks.

A: Another solution would be to generate a date from BuildWeek and BuildYear  (say, the first day of the week), that can be used in the WHERE clause.
The advantage with this approach is that is guaranteed to return the records of the last 12 weeks, even if there is not exactly 12 of them (for example if you have gaps in the weeks series), or if future records exist.
SELECT d.*
FROM Dashboard d
WHERE
    DATEADD( wk, DATEDIFF( wk, 7, CAST( d.BuildYear AS NVARCHAR(100) ) ) + (d.BuildWeek-1) , 7 )
        BETWEEN DATEADD( week, -12, GETDATE() ) AND GETDATE()
ORDER BY
    d.BuildYear DESC,
    d.BuildWeek DESC

Tested in this db fiddle.


text:
Q: CORS issues with domain address, but working fine with direct ip address and localhost I am having a django service hosted on a server which has apis with endpoint http://something.com/api_link
I have a Webapp in react which tries to hit the api http://something.com/api_link. The react webapp is hosted with domain http://somethingother.com and i have enabled CORS at django level to allow all origin to access the api.
But i am seeing a weird behavior :-
Behavior 1
whenever i try to hit the api from localhost or direct ip address(from which the domain http://somethingother.com is linked)there is no issue and the api succeeds.
Behavior 2
But whenever i tries to hit the api from domain name http://somethingother.com i get this issue in the OPTIONS call of the browser.
Access to fetch at 'http://something.com/api_link' from origin 'http://somethingother.com' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
And the difference i noticed in both the cases where that in Request Header of behavior 1 the Access-Control-Request-Headers: content-type
and
in behavior 2's Request Header the Access-Control-Request-Headers: access-control-allow-origin,content-type
And in the Response Headers of both behavior I get
Access-Control-Allow-Headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with
I understand that in response header the Access-Control-Allow-Headers doesn't contains access-control-allow-origin but i am not able to understand that how come localhost and even direct ip address are not running into the issue as the domain request is running into.
Why is access-control-allow-origin is getting added when request is from domain and not when the request is from ip Address or localhost.
Here is how i am calling the api from client
fetch(" http://something.com/api_link", {
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    mobile: number
  })
});


text:
Q: Symfony 4 - Problem sending email after change my DNS Click here

to see my diagram app.
Hey, my client change her DNS (like that : xxx-dns.com to dns.com) and this is ok, except one problem.. In react native app, I have contact form for send message to pro "partner", and this pro partner are in the process of switching their emails from xxx-dns.com to dns.com.
BUT the contact form provide by SwitchMailer doesn't work with the new DNS, I have check all configuration files, same for the server, the controller is (I think) ok.
Please help me, it's been a week
I have var_dump() all information in my controller, check api endpoint, navigate into my server and check configuration files.
This is my contact controller :

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Twig\Environment as Twig;

class ContactController extends AbstractController
{
    /**
     * @var string
     */
    private $mailFrom;

    /**
     * @var string
     */
    private $backUrl;

    private $tokenStorage;

    public function __construct(string $mailFrom, string $backUrl, TokenStorageInterface $tokenStorage)
    {
        $this->mailFrom     = $mailFrom;
        $this->backUrl      = $backUrl;
        $this->tokenStorage = $tokenStorage;
    }

    /**
     * @Route("/contact", name="app_send_contact")
     */
    public function sendAction(\Swift_Mailer $mailer, Twig $twig, Request $request)
    {
        // Retrieve user
        $currentUser = $this->tokenStorage->getToken()->getUser();
        if (!$currentUser) {
            return $this->json(array('success' => false, 'message' => 'Utilisateur introuvable.'));
        }

        // Prepare parameters
        $contactObject  = $request->request->get('object');
        $contactMessage = $request->request->get('message');

        // Retrieve establishment
        $establishment = $currentUser->getEstablishments()->first();
        if (!$establishment) {
            return $this->json(array('success' => false, 'message' => 'Etablissement introuvable.'));
        }

        // Prepare mail
        $mailTitle = $currentUser->getFirstname() . ' ' . $currentUser->getLastname() . ' vous a envoyé un message : ' . $contactObject;

        // Send mail to establishment
        $message = (new \Swift_Message($mailTitle))
            ->setFrom($this->mailFrom)
            ->setTo($establishment->getEmail())
            ->setReplyTo($currentUser->getEmail(), $currentUser->getFirstname() . ' ' . $currentUser->getLastname())
            ->setBody(
                $twig->render(
                    'emails/contact.html.twig',
                    array(
                        'user'            => $currentUser,
                        'establishment'   => $establishment,
                        'contact_object'  => $contactObject,
                        'contact_message' => $contactMessage,
                        'back_url'        => $this->backUrl,
                    )
                ),
                'text/html'
            );
        $mailer->send($message);

        // Prepare mail
        $mailTitle = 'Confirmation de demande de contact';

        // Send mail to parent
        $message = (new \Swift_Message($mailTitle))
            ->setFrom($this->mailFrom)
            ->setTo($currentUser->getEmail())
            ->setBody(
                $twig->render(
                    'emails/contact_confirmation.html.twig',
                    array(
                        'user'            => $currentUser,
                        'establishment'   => $establishment,
                        'contact_object'  => $contactObject,
                        'contact_message' => $contactMessage,
                        'back_url'        => $this->backUrl,
                    )
                ),
                'text/html'
            );
        $mailer->send($message);

        return $this->json(array('success' => true));
    }
}```


text:
Q: Check windows update file integrity I have to update frequently offline windows systems.
So i download the update file (KB) on windows website and run the file on the systems.
I would like to know if there is a recommended way to check the integrity of a windows update file (kb).
My purpose is to be sure that the file is correct and has not been modified in a way or another before applying it.
So i need something like an official MD5 signature as reference value to compare with the signature of the downloaded file, but i can't find anything like that.

A: If you downloaded the update files through Microsoft Update Catalog:

You will see SHA1 of the MSU package present in its file name:

The string highlighted in blue is its SHA-1 (Secure Hash Algorithm-1) value, which is always 40 characters long, this value will be changed if the file content is modified.
You can use this method to check if the file is authentic, you can use PowerShell to do this;
First, to open PowerShell:
Win+R>>type PowerShell>>Ctrl+Shift+Enter
Then you need the full path of your file and filename, in this example, the file is downloaded to the default downloads folder, which is C:\Users\USERNAME\Downloads folder, in PowerShell you can use this variable: $home to represent C:\Users\Username (your user profile) folder.
You can use Get-Filehash cmdlet to get the hash of the file and check it against the hash in its filename by using -eq operator, if the result is true then the file is good. If it returns false then the file is corrupted.
I will give you this example to describe the method better:
(get-filehash -path "$home\downloads\windows10.0-kb4592438-x86_95758bd6e2c3a4a98a19efaa4056213531f84f5c.msu" -algorithm SHA1).hash -eq "windows10.0-kb4592438-x86_95758bd6e2c3a4a98a19efaa4056213531f84f5c.msu".split("_")[1].substring(0,40)

It returns true, means my file isn't corrupted.
When you use it, just replace the file name and file path with the real name and path of the file you want to check. And then you are good to go.

A: Суомынона's answer is correct, I just want to add that you can wrap the code in a function:
function Check-Update {
Param(
  [Parameter(Mandatory=$True, Valuefrompipeline=$True)] [Validatenotnullorempty()] [String]$Path
)
$IsGood=$false

if ($(Test-Path $Path) -and $Path.EndsWith(".msu")) {
    $SHA1 = [System.IO.Path]::GetFileNameWithoutExtension($Path).Split("_")[1]
    $Hash = (Get-FileHash -Path $path -Algorithm SHA1).Hash
    $IsGood=$($SHA1 -eq $Hash)
    Switch ($IsGood)
    {
        $true {Write-Host "Your update file: $path is NOT corrupted"}
        $false {Write-Host "Your update file: $path IS corrupted"}
    }
} else {
    Write-Error -Message "Update file: $path doesn't exist as a valid update file"
    }
}

Paste the function into a working PowerShell session, and then you can check integrity of an update file by calling the function, e.g.:
Check-Update "$home\downloads\windows10.0-kb4592438-x86_95758bd6e2c3a4a98a19efaa4056213531f84f5c.msu"

If everything is alright it will return:
Your update file: C:\Users\Estranger\downloads\windows10.0-kb4592438-x86_95758bd6e2c3a4a98a19efaa4056213531f84f5c.msu is NOT corrupted

I hope my answer helps you; Regards.

A: All Windows Update files (.exe, .msi, .msu, .cab) are signed using Authenticode – the data hash together with a digital signature are embedded into the file so Windows can verify it on its own.

*

*Through PowerShell:
Get-AuthenticodeSignature foo.cab | Format-List

*Through Cmd (only if you have the Windows 10 SDK installed):
signtool verify /v /pa foo.msi

*Through GUI:

*

*Right-click the file, select "Properties" → "Digital Signatures".

*Select a signature from the list and click "Details".

In all three cases, make sure the signature is valid and comes from "Microsoft Code Signing PCA" (chaining to Microsoft Root Certificate Authority).
Note that MD5 or SHA1 hashes on their own aren't signatures. A signature is created by combination of a hash and a secret key (such as Authenticode signing certificate).


text:
Q: IEEE 802.11 standard on channels Could someone please help me find (page#) where in the IEEE 802.11 standard it directly says that Access Points are responsible for choosing the channel/frequency to be used and not clients. I know it's in there somewhere but I can't find where it says that in plain text and was hoping maybe someone on here is more familiar with the standard may know.

A:
Channel usage information is provided by the AP to the non-AP STA to recommend channels for
  noninfrastructure networks or an off-channel TDLS direct link. The non-AP STAs can use the channel usage
  information as part of channel selection processing for a noninfrastructure network or an off-channel TDLS
  direct link.

At page 58.

The AP Channel Report element contains a list of channels where a STA is likely to find an AP.

At page 580.

The Channel Switch Announcement element is used by an AP in a BSS, a STA in an IBSS, or a mesh STA
  in an MBSS to advertise when it is changing to a new channel and the channel number of the new channel.

At page 490.
Source: IEEE-802.11


text:
Q: Testing Issues on Particular Android Devices for Mobile Website I am trying to recreate an issue which is only caused on HTC One XL phone running Android 4.2.2. It is a styling issue which can be fixed with CSS. The problem is that the Chrome Developers Tool does not have a profile for HTC One XL phone running Android 4.2.2.
I do not have a real device! How can I test for an issue that only exists on particular phone running a particular Android version?

A: FInd someone with the device to test a beta or debug info gathering build.  There's three reasons one particular device has issues.
1)Hardware problem.  No emulator will solve this as they won't perfectly emulate hardware.
2)Software bug on this device's framework.  Since each OEM ships their own set of patches, there's no way to know what is actually running, except for having the device.
3)Something weird in the system of an individual user.  Some odd combo of software, hardware, and data. You need that actual phone to fix this, but it generally only effects a handful of users.
But none of these are solvable without access to the device, or a real Eureka moment.  More logging helps, but you'd still need to get those logs which requires a device.


text:
Q: How to change grub2 keylayout on Samsung laptop Trying to change grub2 key layout on a Samsung laptop and failing badly.
Created /etc/grub.d/50_keyboard file containing
 #!/bin/sh
 exec tail -n +3 $0
 # Clavier fr
 insmod keylayouts
 keymap /boot/grub/layouts/fr.gkb

Edited /etc/default/grub file to add
GRUB_TERMINAL_INPUT="at_keyboard"

Used command ckbcomp fr |sudo grub-mklayout -o /boot/grub/layouts/fr.gkb to create the keylayout file
Used command sudo update-grub to ensure my changes were written to /boot.

A: Your /etc/grub.d/50_keyboard is incorrect.
#!/bin/sh
exec tail -n +3 $0
# Clavier fr
insmod keylayouts
keymap /boot/grub/layouts/fr.gkb

The "exec" line is incorrect for your file, but rather than change it or renaming it to 39_keyboard and fixing the exec line...

*

*delete /etc/grub.d/50_keyboard

*edit /etc/grub.d/40_custom
Add this to the end of this file:
insmod keylayouts
keymap /boot/grub/layouts/fr.gkb

so that the final file looks like:
#!/bin/sh
exec tail -n +3 $0
# This file provides an easy way to add custom menu entries.  Simply type the
# menu entries you want to add after this comment.  Be careful not to change
# the 'exec tail' line above.
insmod keylayouts
keymap /boot/grub/layouts/fr.gkb


text:
Q: How can I add chart data labels with percentage? I want to add chart data labels with percentage by default with Excel VBA. Here is my code for creating the chart:
Private Sub CommandButton2_Click()
ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range("'Sheet1'!$A$6:$D$6")
ActiveChart.ChartType = xlDoughnut
End Sub

It only creates Doughnut chart with no information labels.
Also, when I want to create another chart type with this same information how can I change the coordinates of the chart so it will not appear look like it overwrites the same one?

A: Here is one way to have Data Label in %:
            Private Sub CommandButton2_Click()
Dim Cell As Range
    Set Cell = ActiveCell
            Set Myrange = Sheets("Sheet1").Range("$A$6:$D$6")

            ActiveSheet.Shapes.AddChart.Select
            ActiveChart.SetSourceData Source:=Myrange
            ActiveChart.ChartType = xlDoughnut

            With PlotArea
                ActiveChart.ApplyLayout (6)
            End With

            With ActiveChart
                .Legend.Delete
                '.ChartTitle.Delete
                '.ChartTitle.Text = "Here goes your tittle"
            End With

        With ActiveChart.SeriesCollection(1)
            .Points(1).Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
            .Points(2).Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
            .Points(3).Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
            .Points(4).Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
        End With

    With ActiveChart.Parent
             .Height = 200 ' resize
             .Width = 300  ' resize
             .Top = Cell.Top    ' reposition
             .Left = Cell.Left  ' reposition
         End With

            End Sub

Second Type of Graph:
Private Sub CommandButton2_Click()
    Set MyRange = Sheets("Sheet1").Range("$A$6:$D$6")

    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.SetSourceData Source:=MyRange
    ActiveChart.ChartType = xlColumnClustered

    With PlotArea
        ActiveChart.ApplyLayout (2)
    End With

    With ActiveChart
        .Legend.Delete
        '.ChartTitle.Delete
        '.ChartTitle.Text = "Here goes your tittle"
    End With

With ActiveChart.SeriesCollection(1)
    .Points(1).Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
    .Points(2).Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
    .Points(3).Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
    .Points(4).Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
End With

With ActiveChart.Parent
     .Height = 200 ' resize
     .Width = 300  ' resize
     .Top = 300    ' reposition
     .Left = 300   ' reposition
 End With

End Sub

And here you can find the color code:
http://dmcritchie.mvps.org/excel/colors.htm


text:
Q: linking problem: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86' Im trying to run sample app from wxFreeChart library. After compilation on linking there is an error:
wxcode_msw28d_freechart.lib(wxfreechart_lib_xydataset.obj) : fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

I tried to switch linker option\advanced\target machine to MachineX64 but it doesnt work.
Im using visual studio 2008, any suggestion ?
thanks for help

A: Go to project properties-> configuration properties -> Librarian
Set Target Machine to MachineX64 (/MACHINE:X64)

A: In my case it appears it was because I had "copied settings" from a 32-bit to a new configuration (64 bit) and it hadn't updated the libraries.  Odd.
1>MSVCRTD.lib(ti_inst.obj) : fatal error LNK1112: module machine type 'X86' conflicts with target machine type 'x64'
this meant "your properties -> VC++ Directories -> Library Directories" is pointing to a directory that has 32 bit libs built in it. Fix somehow!
In my case http://social.msdn.microsoft.com/Forums/ar/vcgeneral/thread/c747cd6f-32be-4159-b9d3-d2e33d2bab55
ref: http://betterlogic.com/roger/2012/02/visual-studio-2010-express-64-bit-woe

A: The error is explicit, you are trying to link libraries that were compiled with different CPU targets.  An executable image can only contain pure x86 (32-bit) or pure x64 (64-bit) code.  Mixing is not possible.
You change the target CPU by creating a new configuration for the project, only changing the linker setting isn't enough.  Build + Configuration Manager, Active solution platform combo on upper right, choose New and select x64.  That creates a new configuration with several modified project settings, most importantly the compiler that will be used.
Beware that prior to VS2010, the 64-bit compilers are not installed by default.  If you don't see x64 in the platform combo then you'll need to re-run setup.exe and turn on the option to install the 64-bit compilers.  Then also re-run any service pack installer you may have applied.
A possible approach with less pain points is to use the 32-bit version of the library.

A: Since the problem is due to the difference in compilation and target machine specifications (x86 & x64) Follow the steps below:

*

*Open the C++ project that you want to configure.

*Choose the Configuration Manager button to open the Configuration Manager dialog box.

*In the Active Solution Platform drop-down list, select the option to open the New Solution Platform dialog box.

*In the Type or select the new platform drop-down list, select a 64-bit platform.

This solved my problem.

A: I bumped into this too and found a solution.
First on how I got into this problem.  I have a project which builds in x86.  Then I used the Configuration Manager to add x64, and I hit this problem.
By looking at BuildLog.htm carefully, I saw both of these listed as linker options:
/MACHINE:X64
/machine:X86

I could not find anywhere in the Property Pages dialog where I could change this, so I opened up the .vcproj file and looked for the appropriate line and changed it to:
AdditionalOptions=" /STACK:10000000 /machine:x64 /debug"

and problem solved.

A: Try changing every occurence of .\Release into .\x64\Release in the x64 properties. At least this worked for me...

A: I know this is a bit old, but I thought I would provide another tip.
In my situation, I inherited this application that I had to maintain.
The VS2008 project came with the same string in C/C++->OutputFIles->"ObjectFIleName" and "Program Database File Name" (for both platforms Win32 and x64).
So when I built Win32 platform, it built fine, but when I tried to build x64, I got the error:
\Debug64\Objects\common.obj : fatal error LNK1112: module machine type 'X86' conflicts with target machine type 'x64'
Obviously, both patforms were storing common.obj at the same location, so when I tried to build x64, the linker took the existing object file, which was x86.
To fix I just replaced the existing string with the macro "$(IntDir)\" for x64 (no quotes), and made sure that the macro resolved to the correct path, as in the rest of the projects.
That solved my problem.

A: An update to i00g's and Thomas' answers, this time for VS2012 (some names have changed). After copying x86 settings over into an x64 target with the configuration manager, you'll have the problem for the same reason as was the case earlier (lib targets aren't correct in the x64 config). Open your .vcxproj (text editor) and replace MachineX86 with MachineX64 where appropriate. (I still haven't found where this is on the property sheets....) This only seems to be necessary with static libs.

A: before going for the step "compile -DIPLIB=NONE filename.cxx"
take the path of VIsual Studio installation upto the vcvarsall batch file and change the configuration as shown below.
*C:\apps\MVS9\VC\vcvarsall.bat x86_amd64*
now next step should be
compile -64bit -DIPLIB=none filename.cxx
this solved the problem for me

A: Thanks for the answers guys.  My problem was that I changed a x64 solution in Visual Studio to 32 bit in the Configuration Manager only.  I ended up just creating a new solution as 32 bit and then copying my C++ code and this error was gone.  I think l00g33k and RogerAttrill's suggestions may have been the solution, but mine worked, too.

A: Recently,I also encountered this problem. That's because I used qt(x64) in vs win32. If you want to use qt application x64, you could choose vs x64--as the above. If you want to use win32 and perhaps you haven't,you need to download qt(32bit),then correctly set your enviroment, such as the lib directory, etc.(note: maybe you are is old set in x64(other version), if you convert your win32 or x64 into another, Additional Dependencies includes the old directory!)

A: This problem has nothing to do with the linker, so modifying it's setting won't affect the outcome. You're getting this because I assume you're trying to target x86 but for one reason or another wxcode_msw28d_freechart.lib is being built as an x64 file.
Try looking at wxcode_msw28d_freechart.lib and whatever source code it derives from. Your problem is happening there. See if there are some special build steps that are using the wrong set of tools (x64 instead of x86).

A: building on these answers - i also had to modify an X86 reference under Librarian -> Command Line -> Additional Options (for the x64 Platform)


text:
Q: Code running under ant doesn't find a properties file unless I fork the JVM I'm just getting started with Ant, and I'm having problems getting a "run" target to work. Part of my code loads a properties file, and it always fails to find this file unless I make my run target use a new JVM. Below is a very simplified example, the "run" target fails, the "run_fork" target works. My understanding is that Ant has it's own class loader that replaces the default one, so I imagine this is mucking with the search path somehow. Is there any way I can change my code to make this work without having to fork a new JVM?
build.xml:
<project name="PropsExample" default="compile" basedir=".">

<property name="src" location="src"/>
<property name="bin" location="bin"/>

<target name="init">
    <tstamp/>
    <mkdir dir="${bin}"/>
</target>

<target name="compile" depends="init">
    <javac includeAntRuntime="false" srcdir="${src}" destdir="${bin}"/>
    <copy todir="${bin}">
        <fileset dir="${src}" includes="**/*.properties"/>
    </copy>
</target>

<target name="clean">
    <delete dir="${bin}"/>
    <delete dir="${dist}"/>
</target>

<target name="run" depends="compile">
    <java classname="com.example.Test">
        <classpath>
            <pathelement location="${bin}"/>
        </classpath>
    </java>
</target>

<target name="run_fork" depends="compile">
    <java fork="true" classname="com.example.Test">
        <classpath>
            <pathelement location="${bin}"/>
        </classpath>
    </java>
</target>

example code:
package com.example;

import java.util.Properties;
import java.io.InputStream;

public class PropertiesLoader {

    public static String getProperty() throws Exception {

        InputStream in = ClassLoader.getSystemResourceAsStream("com/example/test.properties");
        if ( in == null ) {
            throw new Exception("Cannot find test.properties");
        }
        Properties p = new Properties();
        p.load(in);
        in.close();
        return p.getProperty("test");
    }
}

and:
package com.example;

public class Test {

    public static void main(String[] args) throws Exception {

        try {
            System.out.println(PropertiesLoader.getProperty());
        } catch ( Exception e ) {
            e.printStackTrace(System.out);
        }
    }
}

A: ANT, having already launched by the time it reads the XML file containing your run's specified classpath, cannot actually reset the classpath of the running JVM.  Instead it attempts to append to it as it goes with chains of classloaders; however, your call to the class loader is likely grabbing the root classloader.  You might want to do something like this:
this.getClass().getClassLoader().getResourceAsStream("com/example/test.properties");

which would force the class to use the same classloader as it was loaded with.  This should (hopefully) jump into the ClassLoader chain at the right spot, as if it loaded the current class and the properties file is appropriately "moved" along with the current class, then the properties file should be accessible through the same class loader.
Note that there are a lot of good reasons to fork the JVM anyway.  The most important in my mind is to rid the entire JVM of ANT related classes.  You don't want to accidentally bind your run time to classes which are only available during the software build process, and if you want to bind your classes to ANT, it should be managed as a 3rd party library (so you can control the versions it binds to, the degree of binding, the ability to reproduce the build identically across multiple versions / releases of ANT, etc.)


text:
Q: How can I insert a custom field and the fields value via mysql Alright here is the problem... we have posts that are missing a custom field. We just recently received the values for that field.
Is there a way via phpmyadmin to insert in to the table post_meta a custom field named "translation" and then the value for each post already published?
I am trying to avoid having to go back to each post and adding this custom field one by one.
Thanks!

A: Yes, it's doable ... but tricky.  You'll have to run an INSERT script on the wp_postmeta table.  Remember, the table has three columns: post_id, meta_key, and meta_value.
So if you know the ID of the post and the meta value you want to set, you'd run the following query:
INSERT INTO `wp_postmeta` (post_id, meta_key, meta_value) VALUES (*ID*, 'translation', *VALUE*;

Where *ID* is the id of the post you're attaching the value for and *VALUE* is the meta value of the "translation" field.
Like I said, doable ... but you'll need a separate INSERT query for each post.  You could dump all of these into a single text file and run the entire set in one pass if you want, otherwise it might take as much time as it would to just add the key through the WordPress UI in the first place.

A: You can easily add the column with phpMyAdmin, but you're probably going to have the read the data with some sort of code and iterate through updating the values. PhpMyAdmin isn't really the best tool for importing data that's not already in .sql format.


text:
Q: Drop down menu WordPress widget <form id="promacform" onsubmit="return protein_calculator(this);" method="post">
    Weight: <input type="text" name="protein_weight" id="protein_weight" size="5"; /> lbs.

    Activity level (1.1-1.4): <input type="text" name="protein_activity" id="protein_activity" size="5"; />

<input type="submit" name="submit" id="submit" value="Calculate" />

</form>

Im trying to add a drop down menu for the activity level which will have 4 options:

*

*Lightly active (moderate exercise but sedentary job)

*Moderately active (intense exercise but sedentary job)

*Very active (moderate exercise and active job)

*Extra active (intense exercise and active job)

im not quite sure how to set it up, because the way it is set up now the user has to input a number ranging from 1.1-1.4(activity level range) and from there it calculates it.

A: From my comment, you presumably want just this:
Activity level
<select name="protein_activity">
    <option value="1.1">Lightly Active</option>
    <option value="1.2">Moderately Active</option>
    <option value="1.3">Very Active</option>
    <option value="1.4">Extra Active</option>
</select>

Another possibility you may be interested is a range slider, but you would have to modify your PHP side to accommodate that the form would send from 1-4 instead of 1.1-1.4 but it might add a user experience. This is just a quick and dirty example of a range. Note range is only available in HTML5:

<form>
<input type="range" min="1" max="4" value="2" id="slider" name="protein_activity">

Light

Moderate

Heavy

Extreme

</form>


text:
Q: Add images to Bitmap ArrayList with a method? ArrayList<Bitmap> images = new ArrayList<Bitmap>();
images.add(BitmapFactory.decodeResource(getResources(), R.drawable.uzayli_1));
images.add(BitmapFactory.decodeResource(getResources(), R.drawable.uzayli_2));

mForeground = images.get(0);
mBackground = images.get(1);

I can add pics to ArrayList but I want to use the class also in other classes so I have to write a method for it.
public void addImages(ArrayList<Bitmap> images){
    for (int i = 0; i < images.size(); i++) {
        images.get(i);
        mPages.add(BitmapFactory.decodeResource(getResources(), R.drawable.));
    }
}

I want something like this but how can I define the drawable image after R.drawable. in a method?

A: You already decoded it once, so use the one from the ArrayList:
Bitmap bmp = images.get(i);
mPages.add(bmp); //assuming that's legal

Or keep the resource id's in a list of Integer:
ArrayList<Integer> images = new ArrayList<Integer>();
images.add(R.drawable.uzayli_1);
images.add(R.drawable.uzayli_2);

And decode later:
public void addImages(ArrayList<Integer> imageIds){
    for (int i = 0; i < imageIds.size(); i++) {
        Integer resourceId = imageIds.get(i);
        mPages.add(BitmapFactory.decodeResource(getResources(), resourceId));
    }
}

But you can't do both.


text:
Q: Cloud Formation: Environment failed to launch as it entered Terminated state I am building an elastic beanstalk environment. I get the above error when I run the template. I have added the IAM roles giving full EC2 access to cloud formation
 Resources:
  TestApp:
    Type: 'AWS::ElasticBeanstalk::Application'
    Properties: {}
    Metadata:
      'AWS::CloudFormation::Designer':
        id: 53bb2af6-3a68-487a-8048-34f111147171

  EBE1RNK0:
    Type: 'AWS::ElasticBeanstalk::Environment'
    Properties:
      ApplicationName: !Ref TestApp
      Description: AWS Elastic Beanstalk Environment running Node Sample Application
      EnvironmentName: NodejsEnvironment
      SolutionStackName: 64bit Amazon Linux 2 v5.0.1 running Node.js 12
      OptionSettings:
        - Namespace: aws:autoscaling:launchconfiguration
          OptionName: InstanceType
          Value: t1.micro

A: Looking at the screen shot, it failed just after trying to access S3 - theres your suspect. AWS Docs say beanstalk will require access to S3, Xray and CloudWatch Logs and provide below example policy. Do your roles include these permissions?
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "BucketAccess",
      "Action": [
        "s3:Get*",
        "s3:List*",
        "s3:PutObject"
      ],
      "Effect": "Allow",
      "Resource": [
        "arn:aws:s3:::elasticbeanstalk-*",
        "arn:aws:s3:::elasticbeanstalk-*/*"
      ]
    },
    {
      "Sid": "XRayAccess",
      "Action": [
        "xray:PutTraceSegments",
        "xray:PutTelemetryRecords"
      ],
      "Effect": "Allow",
      "Resource": "*"
    },
    {
      "Sid": "CloudWatchLogsAccess",
      "Action": [
        "logs:PutLogEvents",
        "logs:CreateLogStream",
        "logs:DescribeLogStreams",
        "logs:DescribeLogGroups"
      ],
      "Effect": "Allow",
      "Resource": [
        "arn:aws:logs:*:*:log-group:/aws/elasticbeanstalk*"
      ]
    }
  ]
}

A: SOLVED: I have missed out on adding the instance profile, as that would enable me to pass information to an EC2 when the instance starts running.
This should be below your options settings. Show below.
OptionSettings:
    - Namespace: 'aws:autoscaling:launchconfiguration'
      OptionName: IamInstanceProfile
      Value: aws-elasticbeanstalk-ec2-role


text:
Q: What is wrong with declaring 2 classes public in java? // The "Tester" class.

import java.applet.*;
import java.awt.*;

public class Tester

{

        public static void main (String[] args)
        {
            ThreadTest ex1 = new ThreadTest ();
            ThreadTest2 ex2 = new ThreadTest2 ();
            ex1.start ();
            ex2.start ();
        }
} //Tester class

public class ThreadTest extends Thread

{

       public ThreadTest ()

       {
       }

       public void run ()
       {
          while (true)
          {
              System.out.println ("Hello");
              delay (1000);
          }
       }

        public void delay (int num)
        {
            Thread.currentThread ().setPriority (Thread.MIN_PRIORITY);
            try
            {
                Thread.sleep (num);
            }
            catch (InterruptedException ex)
            {
                ex.printStackTrace ();
            }
            Thread.currentThread ().setPriority (Thread.MAX_PRIORITY);
        }
} // ThreadTest class

public class ThreadTest2 extends Thread //This is where the error is

{

        public ThreadTest2 ()
        {
        }

        public void run ()
        {
            while (true)
            {
                System.out.println ("Hello2");
                delay (1000);
            }
        }

        public void delay (int num)
        {
            Thread.currentThread ().setPriority (Thread.MIN_PRIORITY);
            try
            {
                Thread.sleep (num);
            }
            catch (InterruptedException ex)
            {
                ex.printStackTrace ();
            }`enter code here
            Thread.currentThread ().setPriority (Thread.MAX_PRIORITY);
        }
} // ThreadTest2 class

I don't understand the error that pops up every time i try to run the code. The error that pops up is

"The type "ThreadTest2" is declared public in compliation unit "G:/Java/newstuff/Tester.java" which also contains the public type, "Tester""

A: Java rules are that you can have only one top level public class in a file, and its name must match that of the file. Why this is so, I don't know, but I do know that it is the rules that must be obeyed.
See the Java 1.7 JLS 7.6 for more details.

A: You should have only one public class per file in Java. The filename should be the same as class name plus .java extension.
In your case you should have 2 files:

*

*Tester.java with Tester class

*ThreadTest.java with ThreadTest class

A: It's a matter of style and readability. The only public class in a .java file also has to be the name of the file.
Read more:
Can a java file have more than one class?


text:
Q: how to run an external script from a Ruby on Rails application I'd like to run an external script from my RoR app, within my controller (by passing a boolean parameter) :
 if (:run)
system(Dir.pwd+'\test.sh')
flash[:error] = "Script Running"
 end

2 options here :

*

*best one : we can run it anywhere on the filesystem /etc/myscripts/test.sh or C:\scripts\test.sh

*worst one : I can run it from the /var/www/myapp/scripts/test.sh folder

any ideas ? thanks


text:
Q: GNU Screen on MacOS 10.8 says "Be careful! New screen tonight" GNU Screen on MacOS 10.8 says "Be careful! New screen tonight" when it starts up screen sometimes. Any ideas what causes this, or is there a way to disable it and/or change the text to something else?
Screen version 4.00.03 (FAU) 23-Oct-06
OS X version 10.8.2

A: You are using screen with the option #NETHACK defined.
Nethack is a old text based game with many surprising twists, including dependency on the phase of the moon. If it is full moon the in game were-monsters are stronger.
Screen has an option to translate some of the normal messages into 'nethack-ish' messages.
One of the Nethack messages is "Be careful, new moon today". The screen version of that is "Be careful!  New screen tonight.")
A list of the messages from the screen source:

#ifdef NETHACK
static struct nlstrans nethacktrans[] = {
{"Cannot lock terminal - fork failed",
     "Cannot fork terminal - lock failed"},
{"Got only %d bytes from %s",
     "You choke on your food: %d bytes from %s"},
{"Copy mode - Column %d Line %d(+%d) (%d,%d)",
    "Welcome to hacker's treasure zoo - Column %d Line %d(+%d) (%d,%d)"},
{"First mark set - Column %d Line %d",
    "You drop a magic marker - Column %d Line %d"},
{"Copy mode aborted",
    "You escaped the dungeon."},
{"Filter removed.",
    "You have a sad feeling for a moment..."},
{"Window %d (%s) killed.",
    "You destroy poor window %d (%s)."},
{"Window %d (%s) is now being monitored for all activity.",
    "You feel like someone is watching you..."},
{"Window %d (%s) is no longer being monitored for activity.",
    "You no longer sense the watcher's presence."},
{"empty buffer",
    "Nothing happens."},
{"switched to audible bell.",
    "Suddenly you can't see your bell!"},
{"switched to visual bell.",
    "Your bell is no longer invisible."},
{"The window is now being monitored for %d sec. silence.",
    "You feel like someone is waiting for %d sec. silence..."},
{"The window is no longer being monitored for silence.",
    "You no longer sense the watcher's silence."},
{"No other window.",
    "You cannot escape from window %d!"},
{"Logfile \"%s\" closed.",
    "You put away your scroll of logging named \"%s\"." },
{"Error opening logfile \"%s\"",
    "You don't seem to have a scroll of logging named \"%s\"."},
{"Creating logfile \"%s\".",
    "You start writing on your scroll of logging named \"%s\"."},
{"Appending to logfile \"%s\".",
    "You add to your scroll of logging named \"%s\"."},
{"Detach aborted.",
    "The blast of disintegration whizzes by you!"},
{"Empty register.",
    "Nothing happens."},
{"[ Passwords don't match - checking turned off ]",
    "[ Passwords don't match - your armor crumbles away ]"},
{"Aborted because of window size change.",
    "KAABLAMM!!!  You triggered a land mine!"},
{"Out of memory.",
    "Who was that Maude person anyway?"},
{"getpwuid() can't identify your account!",
    "An alarm sounds through the dungeon...\nThe Keystone Kops are after you!"},
{"Must be connected to a terminal.",
    "You must play from a terminal."},
{"No Sockets found in %s.\n",
    "This room is empty (%s).\n"},
{"New screen...",
    "Be careful!  New screen tonight."},
{"Child has been stopped, restarting.",
    "You regain consciousness."},
{"There are screens on:",
    "Your inventory:"},
{"There is a screen on:",
    "Your inventory:"},
{"There are several screens on:",
    "Prove thyself worthy or perish:"},
{"There is a suitable screen on:",
    "You see here a good looking screen:"},
{"There are several suitable screens on:",
    "You may wish for a screen, what do you want?"},
{"%d socket%s wiped out.",
    "You hear %d distant explosion%s."},
{"Remove dead screens with 'screen -wipe'.",
    "The dead screen%s touch%s you. Try 'screen -wipe'."},
{"Illegal reattach attempt from terminal %s.",
    "'%s' tries to touch your session, but fails."},
{"Could not write %s",
    "%s is too hard to dig in"},

If you wish to get the normal messages then uncomment #define NETHACK from your profile or recompile screen without support for it.


text:
Q: Firefox not reading DTD? I have an XML file (diploma.xml) that looks like this:
<?xml version="1.0" standalone="no" ?>
<!DOCTYPE Diploma SYSTEM "diploma.dtd">
<Diploma>
    &students;
    &Registrations;
    &Courses;
</Diploma>

And the DTD looks like this:
<!ENTITY students SYSTEM "students.xml">
<!ENTITY Registrations SYSTEM "registrations.xml">
<!ENTITY Courses SYSTEM "courses.xml">

When I try to open diploma.xml in IE8 it properly includes all the other XML files, but in Firefox 3.5 I get a syntax error about &students; not being defined. Why is this?

A: Firefox does not read external entities at all (except in a few internal special cases). This is partially because it would be likely to flood sites like W3 with DTD requests, partly because it's another source of potential cross-site scripting, but mostly due to laziness, because few people use Firefox as a raw XML viewer, and few of those people use old-school DTD any more.


text: Q: Maximal Ideals of $\mathbb{C}[x,y]/(x^3-x^2y, xy^2+xy+x+1)$ To find the ideals of this ring, I was hinted to write $x^3-x^2y = x^2(x-y)$ and $xy^2+xy+x+1 = x(y^2+y+1) + 1$. My broad understanding is that I should try to mod out one variable at a time, but I'm not sure how to proceed.


text:
Q: Clojure: reduce with three parameters I often find myself in need of a kind of expanded reduce whenever I must process an item at time (like reduce), accumulate some kind of result (like reduce) but do the process based on the previous item of the sequence (unlike reduce).
For example (a silly one), add 1 to the accumulator if both the current item and the previous one are even and subtract one of they're odd. This is just a stupid case, but I've run into this kind of problems often. I generally make a vector as accumulator, so that the first item is the real aggregation and the second one is the previous item. This is not very elegant and certainly verbose.
Is there a core function to help in those cases? What is the most idiomatic way to deal with such problem? Thanks

A: partition to the rescue.
(reduce (fn [i [a b]]
          (cond
            (and (even? a) (even? b)) (inc i)
            (and (odd? a) (odd? b))   (dec i)
            :else i))
        0 (partition 2 1 input))

Or a little more concise:
(reduce (fn [i pair]
          (condp every? pair
            even? (inc i)
            odd?  (dec i)
            i))
        0 (partition 2 1 input))

A: For this particular problem, I recommend kotarak's solution, using partition to track previous elements. But in the general case, where you need to manage some state in addition to your reduce's eventual "answer", you can simply reduce over a pair, or a map or whatever, and at the end get out the accumulator value. For example:
(defn parity [coll]
  (first (reduce (fn [[acc prev] x]
                   [(cond (and (even? prev) (even? x)) (inc acc)
                          (and (odd? prev) (odd? x)) (dec acc)
                          :else acc)
                    x])
                 [0 (first coll)], (rest coll))))


text:
Q: Wordpress Visual Composer Strech Row and Direction RTL When I try to strech row in the row settings in Visual Composer, the row streches, but the position of the row is all wrong.
It happens only when body direction has direction:rtl css setting.
Website is online: http://ono.devurl.net/?page_id=871
Any way of fixing that?
Yuval.

A: Could be easier to resolve it with css, and it will work when page is resized too.
Find a class for row before [data-vc-full-width="true"] and add such css to your rtl.css
.before-fullwidth-row {
    direction: ltr;
}
.before-fullwidth-row > div {
    direction: rtl;
}

Seems to work...

A: Yuval Hey !
Try this script to fix your problem.

    if( jQuery('html').attr('dir') == 'rtl' ){
        jQuery('[data-vc-full-width="true"]').each( function(i,v){
            jQuery(this).css('right' , jQuery(this).css('left') ).css( 'left' , 'auto');
        });
    }

Put this script code in jQuery(window).load.
hope this'll help you :)

A: If you want to fix VC Row also on window resize use this solution:
    $(window).on( 'resize', function() {
        $( '.rtl [data-vc-full-width="true"]' ).each( function(){
            $( this ).css( 'right' , $( this ).css( 'left' ) ).css( 'left' , 'auto' );
        });
    }).resize();

A: WordPress Visual Composer full width row ( stretche row ) fix for RTL
jQuery(document).ready(function() {

function bs_fix_vc_full_width_row(){
    var $elements = jQuery('[data-vc-full-width="true"]');
    jQuery.each($elements, function () {
        var $el = jQuery(this);
        $el.css('right', $el.css('left')).css('left', '');
    });
}

// Fixes rows in RTL
jQuery(document).on('vc-full-width-row', function () {
    bs_fix_vc_full_width_row();
});

// Run one time because it was not firing in Mac/Firefox and Windows/Edge some times
bs_fix_vc_full_width_row();
});

Source


text:
Q: javascript - check if array contains any of another array of strings strings_to_check = ["a", "b", "c"]

test_arrrays = [ [ "a", "c", "e", "g"], [ "v", "x", "y", "z"] ]

What is the right way to check if each array in test_arrays contains any of the strings in strings_to_check array - ie. a, b or c
I could do the following, but it has its downside that even if one of the strings is present, it still check's for the rest.
for(let i = 0; i < test_arrrays.length; i++){
  for(let j = 0; j < strings_to_check.length; j++){
      if(test_arrrays[i].indexOf(strings_to_check[j]) > -1) {
          console.log("matched");
      }
  }
}

A: This can be much more simply done with higher order functions, instead of devolving to using for loops and a slew of indices.

*

*We want to see if all test_arrrays elements meet some criteria, so we know we should use every:
test_arrrays.every(/* some criteria */);

*Now we just have to find out what that criteria is. "contains any of the strings in strings_to_check" Sounds like we need to use some on test_array, to find out if any of its strings are contained in strings_to_check. So our "criteria" will be:
test_arrray => test_arrray.some(s => strings_to_check_set.includes(s))

putting it together, we get:
test_arrrays.every( test_arrray =>
    test_arrray.some(s => strings_to_check_set.includes(s))
  )

*includes has linear time complexity, so we can improve this algorithm by using a Set, and replacing includes with has, which has constant time complexity., to obtain this final result:
strings_to_check = ["a", "b", "c"]

test_arrrays = [ [ "a", "c", "e", "g"], [ "v", "x", "y", "z"] ]

strings_to_check_set = new Set(strings_to_check)

test_arrrays.every(test_arrray =>
    test_arrray.some(s => strings_to_check_set.has(s))
)

A: Assuming that you want to check if every array from test_arrays contains at least one element from the strings_to_check array, you could use mix of Array#every and Array#some functions.

var strings_to_check = ["a", "b", "c"],
    test_arrrays = [ [ "a", "c", "e", "g"], [ "v", "x", "y", "z"] ],
    res = test_arrrays.every(v => v.some(c => strings_to_check.indexOf(c) > -1));

    console.log(res);

A: If you have multiple test_arrrays, it makes sense to convert the strings_to_check into a Set for constant time lookup. The overall time complexity then reduces from O(m n) to O(m + n log n) where n is the number of elements in strings_to_check and m is the total number of elements in all test_arrrays and O(n log n) is the Set setup time.
A generic check function would then look as follows:

// Check if each haystack contains at least one needle:
function check(needles, haystacks) {
  needles = new Set(needles);
  return haystacks.every(haystack => haystack.some(element => needles.has(element)));
}

// Example:
console.log(check(
  ["a", "b", "c"],
  [["a", "c", "e", "g"], ["v", "x", "y", "z"]]
));

A: If you only need to match one string just add break just like this :
for(/*loop settings*/){
  /*some code*/
  for(/*loop settings*/){
    /*some code*/
    if(/*some conditional statement*/){
      /*handling stuff*/
      break;
    }
  }
}


text:
Q: What happens to a returned object when there's nothing to return it to? This is just a fun thing that popped into my mind. Imagine a scenario, when you have
def returner():
    return 6

And then you call it:
six = returner()

Now 6 has been returned to six. But what happens to the 6 when you just call the function like the following?
returner()

Does the returned value just get discarded altogether? Or is it assigned to some hidden variable?

A: If you are on the interactive interpreter it gets printed out, if running standalone it gets discarded.


text:
Q: Make borders same length in a border collapsed table I have this code:

                Test
                This

                test
                this
                out

                test
                this

With the CSS:
table {
    border-collapse: collapse;
}
tr{
    border-top: 1px solid black;
}

fiddle
I am trying to get the borders to be the same length. So that the borders always use the full length of the table, instead of the td.
How would I do that?
My table is dynamic rendered with Vue so any fix that needs knowledge on how the table is visualized, I can't really use

A: colspan attribute might help.

    Test
    This

    test
    this
    out

      test
    this

JsFiddle


text:
Q: How to convert a polynomial in $GF(p^n)$ into the form $a(x)^k$, with $a(x)$ a generator polynomial. I basically have two questions:
Given $GF(p^n$) and $g(x)$ an irreducible polynomial:

*

*My textbook says that a polynomial is called primitive if $x$ is a generator of the field. The question now is, how can you check to see if an irreducible polynomial is a primitive polynomial?

*Assuming $x$ is a generator. When given a polynomial $a(x)$, how can one find the (minimal) power $j$ of $x$ so that $x^j \bmod g(x) = a(x)$? I know I can brute force this, i.e. by computing $x^j \bmod g(x)$ for $j$ in $\{0,1,\dots,p^n-2\}$, but I need a manner to find it without doing so.

A: The trivial method of checking primitivity would go as follows.
I am assuming that you know the factorization of $p^n-1$. Then you should check for each prime divisor $\ell$ of $p^n-1$ that $x^{(p^n-1)/\ell}\not\equiv1\pmod{g(x)}$. This will do it because we know that the order of $x$ in the multiplicative group $GF(p^n)^*$ is a factor of $p^n-1$, so if it is not a factor of any of maximal divisors $(p^n-1)/\ell$, then it must be the maximum.
Let us do the example from your comment: $p^n=3^4$, $g(x)=x^4+x^2+x+1$.
I assume that you have already checked that $g(x)$ is irreducible, for otherwise
$\mathbb{Z}_3[x]/\langle g(x)\rangle$ won't be the field $GF(81)$.
Here finding the factorization is easy, as $80=16\cdot5=2^4\cdot5$. We are to check that neither $x^{80/2}=x^{40}$ nor $x^{80/5}=x^{16}$ is congruent to $1$ modulo $g(x)$.
Let's do repeated squaring. We get a flying start as
$$
x^4\equiv x^4-g(x)=-x^2-x-1
$$
Therefore
$$
x^8=(x^4)^2\equiv(-x^2-x-1)^2=x^4+2x^3+2x+1\equiv 2x^3+2x^2+x\pmod{g(x)}
$$
and continuing
$$
x^{16}\equiv(-x^3-x^2+x)^2=x^6+2x^5+2x^4+x^3+x^2\equiv x^3+2\pmod{g(x)}.
$$
So we know that the order is not a factor of 16. Still need to check $40$.
We calculate
$$
x^{32}\equiv (x^3-1)^2=x^6+x^3+1\equiv x+2\pmod{g(x)},
$$
and finally
$$
x^{40}=x^{32}\cdot x^8\equiv(x-1)(-x^3-x^2+x)=-x^4-x^2-x\equiv1\pmod{g(x)}.
$$
Bummer, this means that the polynomial $g(x)$ is not primitive.
We can check similarly that $x^{20}\equiv-1\pmod{g(x)}$, so the order of $x$ is exactly $40$ (not a factor of either 20 or 8).

In general the problem of your second question is difficult (agree with Yoni and Marc), so you should expect a trick to do the specific case of $g(x)=x^4+x^2+x+1$, $a(x)=x+2$.
In the first part we saw that $g(x)$ is not primitive, so the (coset of $x$) only generates a subgroup $H$ of order 40 containing exactly half of the non-zero elements of $GF(3^4)$. We can seek to solve the discrete logarithmg problem in this subgroup. WARNING: As $x$ is not a primitive element, we may not succeed. It may happen that $a(x)\notin H$, and then no $j$ works.
Indeed, the following trick gets us started.
$$
x^2+x+1=x^2-2x+1=(x-1)^2=(x+2)^2.
$$
So if we have
$$
a(x)\equiv x^j\pmod{x^4+x^2+x+1},
$$
we also have
$$
x^{2j}=a(x)^2=x^2+x+1\equiv-x^4.
$$
Given that $x$ is of order $40$ we get that
$$x^{20}\equiv-1,$$
as $x^{20}$ is of order two, and $-1$ is the only element of multiplicative
order two.
Therefore
$$
x^{2j}\equiv x^{24}\pmod{g(x)}.
$$
As the discrete logarithm is defined modulo $\operatorname{ord}(x)=40$, we get
$$
2j\equiv 24\pmod{40}\Leftrightarrow j\equiv 12\pmod{20}.
$$
This leaves two choices $j=12$ and $j=32$.
While checking out primitivity of $g(x)$ we actually saw that $j=32$ works.
Didn't want to draw any attention to that earlier.