text:
Q: groovy.lang.MissingPropertyException: No such property: jenkinsproject for class: groovy.lang.Binding I have to start using shared library for my jenkins pipeline jobs. I have make seprate git repo as well.
But i am getting error as mentioned above while build jenkins job?
Have any idea why its showing me error?
groovy.lang.MissingPropertyException: No such property: xxx for class: groovy.lang.Binding
at groovy.lang.Binding.getVariable(Binding.java:63)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:271)
at org.kohsuke.groovy.sandbox.impl.Checker$7.call(Checker.java:353)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:357)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:29)
at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20)
at WorkflowScript.run(WorkflowScript:4)
at cps.transform(Native Method)
at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.get(PropertyishBlock.java:74)
at com.cloudbees.groovy.cps.LValueBlock$GetAdapter.receive(LValueBlock.java:30)
at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.fixName(PropertyishBlock.java:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
thanks in advance


text:
Q: How to change CMAKE_C_COMPILER without losing configuration? When you change the CMAKE_C_COMPILER / CMAKE_CXX_COMPILER.
CMake detects this and re-generates the cache, loosing any manually defined options.
I can see why the CMake project chose this behavior, In most cases it makes sense,
however it's not necessarily useful when...

*

*Using a wrapper (typically a shell script which calls the compiler).

*Using a prefix command such as distcc or ccache.

For example. I don't need distcc enabled all the time, and I would like to be able to enable it, only when I'm bisecting.

Is it possible to change the compiler command in CMake without re-generating the cache?

redpajama_set_name: RedPajamaStackExchange


text:
Q: sqlite sqlite3_column_text returning variable is not NSString error this is my sqlite statement:
NSString *queryString = @"SELECT email.pk, email.sender_name, email.sender_address, search_email.subject, email.datetime, "
"LENGTH(email.attachments), SUBSTR(search_email.body,0,150), email.folder_num, t.threadid, t.numThreads FROM "
"email, search_email ,(select  threadid, min( docid) as docid, count(*) as numThreads from search_email group by threadid) as t       "
"WHERE t.docid = email.pk AND (email.folder_num = ? OR email.folder_num_1 = ? OR email.folder_num_2 = ? OR email.folder_num_3 = ?) AND email.pk = search_email.docid "
"ORDER BY email.datetime DESC;";

all the values i fetch using sqlite3_column_text and sqlite3_column_int work fine.. but for some reason it fails on the threadid:
NSString* temp = @"";
const char *sqlVal = (const char *)sqlite3_column_text(folderSearchStmt, 1);

...
temp = @"";
sqlVal = (const char *)sqlite3_column_text(folderSearchStmt, 8);
if(sqlVal != nil)
    temp = [NSString stringWithUTF8String:sqlVal];
[res setObject:temp forKey:@"threadID"];

if i set a breakpoint on sqlVal, it returns sqlVal = (const char*) 0x266c0a30 "1-87"
but then temp returns (__NSCFString*)0x27f7bff0 @<variable is not NSString>
any ideas?

A: Have to reject invalid entries like this:
      const char *_abc = (char *) sqlite3_column_text(statement, 1);

   NSString *_abcTemp;

      if (_abc)
          _abcTemp = _abc == NULL ? nil : [[NSString alloc] initWithUTF8String:_abc];
     else
        _abcTemp = [[NSString alloc] initWithString:@"Not a valid string"];


text:
Q: When do zigzags of weak equivalences detect isomorphisms in the localization? The usual way to prove that two model categories are equivalent is to construct a zigzag of Quillen equivalences between them, but is it always possible? We can ask a more general question.

Question: Suppose that objects $X$ and $Y$ of a category with weak equivalences $(\mathcal{C},\mathcal{W})$ are isomorphic in its localization. Under which conditions on $(\mathcal{C},\mathcal{W})$ is there a zigzag of weak equivalences between $X$ and $Y$?

This is true if $(\mathcal{C},\mathcal{W})$ is a model category, but is there a weaker condition? It is not true in general. The counterexample is the category $A \to B \to C \to D$ in which $A \to C$ and $B \to D$ are weak equivalences. It is also not enough to assume that $(\mathcal{C},\mathcal{W})$ satisfies 2-out-of-6. The counterexample is the simplest category with a retract of a weak equivalence. So, here are some natural conditions on $(\mathcal{C},\mathcal{W})$ which might be sufficient:

*

*$(\mathcal{C},\mathcal{W})$ satisfies 2-out-of-6 and is closed under weak retracts (a weak retract is like an ordinary retract, but identity maps are replaced with weak equivalences).

*$\mathcal{W}$ is saturated (this implies the previous condition).

*$(\mathcal{C},\mathcal{W})$ has the structure of a category of fibrant objects.

*$\mathcal{C}$ is the category of (small) model categories and Quillen adjunctions between them and $\mathcal{W}$ is the class of Quillen equivalences.


text:
Q: How to show specific element in table cells using angularjs Based on my searches when you want to hide the visibility of element in html using angularjs just used ng-show or ng-hide. In my page I have a table generated using ng-repeat.Each row have a button "show check". When  the button is clicked the word "CHECK" should display beside the ID. Ng-show is working fine except when I clicked the button in the row with ID 1 all the rows display CHECK the, CHECK word should be display only in a row where I have click the button. What is missing? I try to passed the key parameter but it's not work. Any advice and suggestions would be appreciated. Thanks
My fiddle is : https://jsfiddle.net/DharkRoses/wydyagao/
I used this code so far:
$scope.myVar = true;
$scope.toggleShow = function(key){
  alert(key);
  $scope.myVar =!$scope.myVar;
};

A: You should add myVar for each user in the ng-repeat list.

CHECK
{{user.id}}
            {{user.name}}
            {{user.stat}}
            <button id ="btn" ng-click = "toggleShow(user)">show check</button>

Then in your controller
$scope.toggleShow = function(user){
  alert(user.myVar);
  user.myVar =!user.myVar;
};


text:
Q: Bootstrap typeahead not Working inside the Bootstrap Modal I am using codeigniter framework and i am using bootstrap typeahead and all is fine but my problem is when i put it inside the bootstrap modal the bootstrap typeahead will not work. can someone help me? please. this is my code
<a data-target="ajaxify" data-toggle="modal" href="<?php echo base_url()?>task/add_task" class="no-u quick-task">

Task

    This is a simple description

and inside my add_task controller i call the view task_view.php and task.js but it seems that the typeahead is not working inside the bootstrap modal.
this is the content of task.js
$(document).ready(function(){
$("#assign_to").typeahead({
    source: [{value: 'Charlie'}, {value: 'Gudbergur'}]
});
});

this is the content of task_view.php : just a sample.

  ×

Modal Heading

<form><input type="text" name="assign_to" id="assign_to" /></form>

  Close
  Save

A: Edit bootstrap-typeahead.js:
  this.$menu.css({
    top: pos.top + pos.height,
    left: pos.left,
    'z-index': 9999 //maximum z-index
  })

Find the highest z-index: http://archive.plugins.jquery.com/project/TopZIndex

A: I don't know if I'm running into a version-specific issue that's slightly different, but I'm using bootstrap 2.3.2 and no version of z-index was working for me.  I found another solution that ended up working:
.modal-body{overflow-y: inherit;}

Found at https://github.com/twbs/bootstrap/issues/1078, answer by jgutix

A: You need to put a z-index of 1051 on .typeahead to get it to appear above the modal div.

A: make sure to remove typeahead-append-to-body="true"
https://github.com/angular-ui/bootstrap/issues/3262

A: I'm using in my custom css following
.modal-body{overflow-y: inherit;}

.modal-open .dropdown-menu {
  z-index: 2050;
}

working example of use


text:
Q: php directory with square brackets doesn't work I want to grab the jpg file. My directory is ../database/CWBRadar/CWB05Radar[Wufenshan]/.
The codes are below:
$files = glob("../database/CWBRadar/CWB05Radar\[Wufenshan\]/*.jpg");
var_dump($files);

I can't get anything when I call var_dump($files) that print array(0) {}.

A: Follow the article Eddie mentioned, try this please. It should work.
$files = glob("../database/CWBRadar/CWB05Radar[[]Wufenshan[]]/*.jpg");
var_dump($files);


text:
Q: Oracle case when NOT null? I see a lot of queries made for Oracle using CASE columnX WHEN NULL
how to design query if
CASE columnX WHEN NOT NULL ?
SQL developer throws an error on the query so how to make condition query using CASE... WHEN...?
WITH dates_list AS
  (SELECT TO_DATE('02-19-2018','MM-dd-yyyy') + ROWNUM - 1 AS DAY,
    rownum                                                AS row_num
  FROM dual
    CONNECT BY LEVEL <= (TO_DATE('03-29-2018','MM-dd-yyyy') - TO_DATE('02-19-2018','MM-dd-yyyy')+1)
  )
SELECT dates1.day, dates2.*, count(case dates2.day when null then 1 else 0 end)
              over (partition by dates2.day order by dates1.day) as cnt
FROM dates_list dates1
LEFT JOIN
  (SELECT *
  FROM dates_list
  WHERE TO_CHAR(DAY,'D') NOT IN (7,1)
  ) dates2 ON dates1.day = dates2.day
ORDER BY dates1.day;

above query gives error when I change when null to when not null

A: You can't use the CASE sentence in that way with NULL values, because columnX is never "equal" to NULL. You should use instead:
CASE WHEN columnX IS NULL THEN

or
CASE WHEN columnX IS NOT NULL THEN

A: You now have a function NVL that can turn this:
CASE WHEN columnX IS NOT NULL THEN columnX ELSE 'No value' END

Into this:
NVL(columnX, 'No value')

If columnX is a select, it make everything a lot cleaner


text:
Q: Need a Complex SQL Query I need to make a rather complex query, and I need help bad. Below is an example I made.
Basically, I need a query that will return one row for each case_id where the type is support, status start, and date meaning the very first one created (so that in the example below, only the 2/1/2009 John's case gets returned, not the 3/1/2009). The search needs to be dynamic to the point of being able to return all similar rows with different case_id's etc from a table with thousands of rows.
There's more after that but I don't know all the details yet, and I think I can figure it out if you guys (an gals) can help me out here. :)

ID   |  Case_ID   |   Name   |   Date   |  Status  |  Type

48   |    450     |   John   | 6/1/2009 |  Fixed   | Support
47   |    450     |   John   | 4/1/2009 |  Moved   | Support
46   |    451     |   Sarah  | 3/1/2009 |          |
45   |    432     |   John   | 3/1/2009 |  Fixed   | Critical
44   |    450     |   John   | 3/1/2009 |  Start   | Support
42   |    450     |   John   | 2/1/2009 |  Start   | Support
41   |    440     |   Ben    | 2/1/2009 |          |
40   |    432     |   John   | 1/1/2009 |  Start   | Critical
...

Thanks a bunch!
Edit:
To answer some people's questions, I'm using SQL Server 2005. And the date is just plain date, not string.
Ok so now I got further in the problem. I ended up with Bliek's solution which worked like a charm. But now I ran into the problem that sometimes the status never starts, as it's solved immediately. I need to include this in as well. But only for a certain time period.
I imagine I'm going to have to check for the case table referenced by FK Case_ID here. So I'd need a way to check for each Case_ID created in the CaseTable within the past month, and then run a search for these in the same table and same manner as posted above, returning only the first result as before. How can I use the other table like that?
As usual I'll try to find the answer myself while waiting, thanks again!
Edit 2:
Seems this is the answer. I don't have access to the full DB yet so I can't fully test it, but it seems to be working with the dummy tables I created, to continue from Bliek's code's WHERE clause:

WHERE RowNumber = 1 AND Case_ID IN (SELECT Case_ID FROM CaseTable
      WHERE (Date BETWEEN '2007/11/1' AND '2007/11/30'))

The date's screwed again but you get the idea I'm sure. Thanks for the help everyone! I'll get back if there're more problems, but I think with this info I can improvise my way through most of the SQL problems I currently have to deal with. :)

A: Maybe something like:
select Case_ID, Name, MIN(date), Status, Type
from table
where type = 'Support'
 and status = 'Start'
group by Case_ID, Name, Status, Type

EDIT: You haven't provided a lot of details about what you really want, so I'd suggest that you read all the answers and choose one that suits your problem best. So far I'd say that Tomalak's answer is closest to what you're looking for...

A: SELECT
  c.ID,
  c.Case_ID,
  c.Name,
  c.Date,
  c.Status,
  c.Type
FROM
  CaseTable c
WHERE
  c.Type = 'Support'
  AND c.Status = 'Start'
  AND c.Date = (
    SELECT MIN(Date)
    FROM CaseTable
    WHERE Case_ID = c.Case_ID AND Type = c.Type AND Status = c.Status)
/* GROUP BY only needed when for a given Case_ID several rows
   exist that fulfill the WHERE clause */
GROUP BY
  c.ID,
  c.Case_ID,
  c.Name,
  c.Date,
  c.Status,
  c.Type

This query benefits greatly from indexes on the Case_ID, Date, Status and Type columns.
Added value though the fact that the filter on Support and Status only needs to be set in one place.
As an alternative to the GROUP BY clause, you can do SELECT DISTINCT, which would increase readability (this may or may not affect overall performance, I suggest you measure both variants against each other). If you are sure that for no Case_ID in your table two rows exist that have the same Date, you won't need GROUP BY or SELECT DISTINCT at all.

A: In SQL Server 2005 and beyond I would use Common Table Expressions (CTE). This offers lots of possibilities like so:
With ResultTable (RowNumber
                 ,ID
                 ,Case_ID
                 ,Name
                 ,Date
                 ,Status
                 ,Type)
AS
(
    SELECT Row_Number() OVER (PARTITION BY Case_ID
                                  ORDER BY Date ASC)

          ,ID
          ,Case_ID
          ,Name
          ,Date
          ,Status
          ,Type
      FROM CaseTable
     WHERE Type   = 'Support'
       AND Status = 'Start'
)
    SELECT ID
          ,Case_ID
          ,Name
          ,Date
          ,Status
          ,Type
      FROM ResultTable
     WHERE RowNumber = 1

A: Don't apologize for your date formatting, it makes more sense that way.
    SELECT ID, Case_ID, Name, MIN(Date), Status, Type
    FROM caseTable
    WHERE Type = 'Support'
       AND status = 'Start'
    GROUP BY ID, Case_ID, Name, Status, Type


text:
Q: The normalizer problem for group rings I recently studied about The Normalizer problem (NP) which states that given an integral group ring $\Bbb{Z}G$, $N_{\cal{U}}(G)=G\frak{z}$ where $\frak{z}$ denotes centre of $\cal{U}$ = $\cal{U}$$(\Bbb{Z}G)$.
I found that this has been proved for finite nilpotent groups , groups of odd order and for groups having a normal sylow 2-subgroup i.e. $2$-closed groups
Jesper proved it for locally nilpotent groups and F.C. groups with commutator a $p$- group. This paper was received in 2000
Then there is one by Labao which proves it for complete monomial groups. This paper was received in 2001
What are some other groups or classes of groups for which  this problem has been established? What is the latest work done on NP and current status of problem?


text:
Q: Multiple Database Connections PHP I'm having trouble figuring out a good solution to this problem. I have multiples classes on my site that all handle different things. I have a comment class, a profile class, a login class and so on and so forth. I;m happy with my code design so far because basically all the logic is out of my html template. So I just have very minimal logic in my template. The only problem is, I have a single class for a database connection, and I extend every class from the database class and use the parent constructor to connect to the database. The only problem is every page has at least 2 separate classes on it and now that the site is getting more complicated and I'm having 4 or 5 classes per page, it's noticeably effecting the load time since i have to reconnect to the database each time.
My question is what's the best way to use database connections in a class. I'm thinking maybe database queries will have to be handled in the html, or I could create a whole function file that is included on every page that has a database connection loaded with it. But I'd like to know how more experienced programmers do it so I can fix it the right way.
Thanks for the advice.

A: Although you could use a singleton to be sure that only one connection is used, it seems that a holy war is declared on Stack Overflow to this honest pattern.
Nevertheless, extending application classes from DB class is a bad idea. These classes have nothing in common. Database class is just a service - so, use it as a service. Some of your classes have to send emails too for sure - don't you extend your classes from email class too?
You have to instantiate your DB class once, and then pass this object to other classes in their constructors. The easiest way would be to use just global $db;, or you can bother passing them in constructor parameters. Or use that widely advertized dependency injection approach.
Anyway, you should use single connection (with same credentials) throughout whole script execution. Opening and closing connection many times is no better than having multiple simultaneous connections.

A: If using MySQli:
$Con_1 = new mysqli ("host","user","password","database");
$Con_2 = new mysqli ("host","user","password","database");
$Con_3 = new mysqli ("host","user","password","database");

Then interact with:
$PreparedStatement_1 = $Con_1->prepare(); // Connect to database instance specified in $con_1
$PreparedStatement_1->bindparam('',);
$PreparedStatement_1->execute();
$PreparedStatemet_1->close(); // close to free up other statements
$PreparedStatement_2 = $Con_2->prepare(); // Connect to database instance specified in $con_2
$PreparedStatement_2->bindparam('',);
$PreparedStatement_2->execute();
$PreparedStatemet_2->close(); // close to free up other statements

If using PDOMysql
$Con_1 = new PDO('mysql:dbname=testdb;host=127.0.0.1', 'dbuser', 'dbpass');
$Con_2 = new PDO('mysql:dbname=testdb;host=127.0.0.1', 'dbuser', 'dbpass');
$Con_3 = new PDO('mysql:dbname=testdb;host=127.0.0.1', 'dbuser', 'dbpass');

Examples are more or less the same  with the MySQli Examples.
Not advised, By mysql
$Con_1 = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$Con_2 = mysql_connect('localhost', 'mysql_user', 'mysql_password');

Interact with:
$Query = mysql_query("",$Con_1);
$Query2 = mysql_query("",$Con_2);

If you wish to hand code, you may do so.. But multiple database instances can be done with PHP, and there are frameworks available:

Codeigniter, CakePHP, Symphony, Wordpress

A: I think that using a sinlgeton or global is the best for this situation. It is considered a bad practice to use singletons and globals for the reason that they are easily misused. But in this case, the benefits overcome the disadvantages.
Additionally, it is a common practice over the open source platforms to use singleton or global for DB connections:
 - Singleton is used in Magento for getting/setting the PDO object
 - Global is used in Wordpress in order to maintain the resource returned by mysql_connect function.
You can avoid the class dependency, by adding a factory behavior to the connector.
Thus, I suggest you to write something like this:
class DBconnector
{
    private static $_connections = array();

    private static createConnection($type)
    {
        switch($type){
            case 'pdo':
            default:
                return new PDO('mysql:dbname=testdb;host=127.0.0.1', 'dbuser', 'dbpass');
        }
    }

    public static getConnection($type)
    {
        if(!isset(self::_connections[$type])){
            self::_connections[$type] = self::createConnection($type);
        }
        return self::_connections[$type];
    }
}


text:
Q: System.Diagnostics.Process pipe (vertical bar) not accepted as argument I'm trying to execute this code using System.Diagnostics.Process. It works fine in command line. But in C# it's failing on the | character.
var myProcess = new Process();
var p = new ProcessStartInfo();

var sArgs = " -i emp.mp3 -f wav - | neroAacEnc -ignorelength -q 0.5 -if - -of emp.mp4";
p.FileName = "ffmpeg.exe";
p.CreateNoWindow = false;
p.RedirectStandardOutput = false;
p.UseShellExecute = false;
p.Arguments = sArgs;

myProcess.StartInfo = p;

myProcess.Start();
myProcess.WaitForExit();

It gives the following error:

Unable to find a suitable output format for '|': Invalid argument

I've looked around on stackoverflow and found the following hint but it is also not working:
var psi = new ProcessStartInfo("ffmpeg.exe");
psi.Arguments =
    "\"-i emp.mp3 -f wav -\" | \"neroAacEnc -ignorelength -q 0.5 -if - -of emp.mp4\"";
psi.CreateNoWindow = false;
psi.UseShellExecute = false;

var process = new Process { StartInfo = psi };

process.Start();
process.WaitForExit();

gives the following error:

Unrecognized option 'i emp.mp3 -f wav -'
  Failed to set value '|' for option 'i emp.mp3 -f wav -'

A: Thanks to Lee his comments, the problem has been resolved. Just invoke cmd.exe and pass it the full command:
var myProcess = new Process();
var p = new ProcessStartInfo("cmd.exe");
var sArgs = "/C ffmpeg.exe -i emp.mp3 -f wav - | neroAacEnc -ignorelength -q 0.5 -if - -of emp.mp4";
p.CreateNoWindow = false;
p.RedirectStandardOutput = false;
p.UseShellExecute = false;
p.Arguments = sArgs;
myProcess.StartInfo = p;
myProcess.Start();
myProcess.WaitForExit();


text: Q: how to configure atom with anaconda virtual environment interpreter I am trying to run my code in atom using a pre-defined conda venv interpreter, however, i could not open the interpreter venv in the atom terminal due to "un authorized.. security" thing, and when i tried to run the code from cmd there happens to be syntax errors. Although the same code with same interpreter were working in spyder. what could be the reason?


text:
Q: UISegmented Controller I have a segmented controll set up PROGRAMATICALLY
im trying to save the result into a String for further use
The code for the segmented Control is Below
Im having issues
Can anyone help?
let genderSelector: UISegmentedControl = {
   let genderSelect = UISegmentedControl()
    genderSelect.insertSegment(withTitle: "Male", at: 0, animated: true)
    genderSelect.insertSegment(withTitle: "Female", at: 1, animated: true)
    genderSelect.tintColor = UIColor.black
    return genderSelect
}()

A: Try like this:-
let items = ["Male", "Female"]
let customSC = UISegmentedControl(items: items)
customSC.selectedSegmentIndex = 0
let frame = UIScreen.mainScreen().bounds
customSC.frame = //Your Frame
customSC.tintColor = UIColor.blackColor()
customSC.addTarget(self, action: "yourMethod:", forControlEvents: .ValueChanged)
self.view.addSubview(customSC)


text:
Q: Retrofit 2: Use cached response then network response I don't know if it's possible at all without building a wrapper around Retrofit.
I would like my request to go trough the callback 2 times, once with the cached / disk response, and once from the network (if available).
For the moment I use a custom okHttpClient with a custom Interceptor as follow:
OkHttpClient okHttpClient = new OkHttpClient.Builder()
    .readTimeout(60, TimeUnit.SECONDS)
    .connectTimeout(60, TimeUnit.SECONDS)
    .writeTimeout(60, TimeUnit.SECONDS)
    .addInterceptor(new Cache()).build();

And here is the Cache interceptor
public class Cache implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (request.method().equals("GET")) {
            if (Network.isConnected()) {
                Response response = chain.proceed(request);
                byte[] buffer = response.body().bytes();
                NetworkCache.cacheResponse(request, buffer);
                return new Response.Builder()
                        .code(response.code())
                        .request(request)
                        .protocol(response.protocol())
                        .headers(response.headers())
                        .body(ResponseBody.create(MediaType.parse(RestClient.MEDIA_TYPE), buffer))
                        .build();
            } else {
                Response cachedResponse = NetworkCache.getResponse(request);
                if (cachedResponse != null) {
                    return cachedResponse;
                }
            }
        }
        return chain.proceed(request);
    }
}

It works, but my cached response are only triggered if the device is offline (as excepted by this code). Now I would like to have a chance to respond two times, even if the device is online, to respond with the cached response first, and then with the networked one if available.
Is that possible with an Interceptor?


text:
Q: STM32F407 Assembly, STR not writing into memory I am trying to program my STM32F407 in pure assembly (learning purposes).
I have narrowed my debugging down to the curious issue, that the STR command is simply not writing the contents of a register into memory. The code is below. Essentially it is supposed to write a 0x4 into a memory location (which sets up the GPIO ports), but doesn't.
Here's the code:
    /*SCiFI statements*/
    .syntax unified
    .cpu cortex-m4
    /*.fpu fpv4-sp-d16*/
    .thumb

    /*Vector Table Symbols*/
    .global vtable
    .global reset_handler

    /*vtable setup*/
    .type vtable, %object
vtable:
    .word _estack
    .word reset_handler
    .size vtable, . - vtable

    /*reset handler setup*/
    .type reset_handler, %function
reset_handler:
    /*Stack Pointer reset*/
    LDR r0, =_estack
    MOV sp, r0

    /*GPIOC is at 0x4002 0800 - 0x4002 0BFF*/
    LDR r2, =0x40020800 /*Address register*/
    /*Set up GPIOC as output*/
    /*Set to GPIO output mode*/
    LDR r1, =0x04
    STR r1, [r2] /*******HERE'S THE ISSUE LINE*******/

dummy_loop:
    B dummy_loop
    .size reset_handler, . - reset_handler

Linker Script for completeness
estack = 0x2001c000; /*End of RAM*/

MEMORY{
    FLASH ( rx  ) : ORIGIN = 0x08000000, LENGTH = 1M
    SRAM  ( rxw ) : ORIGIN = 0x20000000, LENGTH = 112K
    GPIO  ( rw  ) : ORIGIN = 0x40020000, LENGTH = 36020400
}

Am compiling it with
arm-none-eabi-gcc -x assembler-with-cpp -c -O0 -mcpu=cortex-m4 -mthumb -Wall core.s -o core.o -g
arm-none-eabi-gcc core.o -mcpu=cortex-m4 -mthumb -Wall --specs=nosys.specs -nostdlib -lgcc -T./stm32f407.ld -o pintoggle.bin -g

where the .s and .ld files are the ones I pasted above.
Relevant gdb output for doubters
(gdb) break 30
Breakpoint 1 at 0x8000012: file core.s, line 30.
Note: automatically using hardware breakpoints for read-only addresses.
(gdb) continue
Continuing.

Breakpoint 1, reset_handler () at core.s:30
30              STR r1, [r2]
(gdb) x 0x40020800
0x40020800:     0x00000000
(gdb) s
33              B dummy_loop
(gdb) x 0x40020800
0x40020800:     0x00000000
(gdb) info registers
r0             0x2001c000          536985600
r1             0x4                 4
r2             0x40020800          1073874944
r3             0x0                 0
r4             0x0                 0
r5             0x0                 0
r6             0x0                 0
r7             0x0                 0
r8             0x0                 0
r9             0x0                 0
r10            0x0                 0
r11            0x0                 0
r12            0x0                 0
sp             0x2001c000          0x2001c000
lr             0xffffffff          -1
pc             0x8000014           0x8000014 <reset_handler+12>
xpsr           0x41000000          1090519040
msp            0x2001c000          0x2001c000
psp            0x0                 0x0
control        0x0                 0 '\000'
faultmask      0x0                 0 '\000'
basepri        0x0                 0 '\000'
primask        0x0                 0 '\000'
fpscr          0x0                 0

I'm not sure what I'm doing wrong. The program isn't particularly complex. Manipulating CPU-Registers works just fine, but writing into memory doesn't work at all.
The chip/board are fine. I threw some old C code I had lying around on it through the Keil environment and it worked just nicely. My goal is not to use any C at all, and just stick to assembly and gcc. This is what I want to learn.
EDIT:
Since someone is bound to run into this question and ask even more. https://www.efton.sk/STM32/gotcha/index.html has a bunch of STM32 gotchas listed, where this question is #1 interestingly.

A: You need to enable gpioc first in the RCC.
read-modify-write RCC_AHB1ENR 0x40023830 and set bit 2:
ldr r0, =0x40023830
ldr r1, [r0]
orr r1, #2
str r1, [r0]

Then you can:
LDR r2, =0x40020800
LDR r1, =0x04
STR r1, [r2]

Note/FYI this is likely NOT to work due to a race condition:
ldr r0, =0x40023830
ldr r1, [r0]
orr r1, #2
ldr r2, =0x40020800
ldr r3, =0x4
str r1, [r0]
str r3, [r2]

One needs some number of clocks between the enable and that clock enable spinning up the gpio, but this should work
ldr r0, =0x40023830
ldr r1, [r0]
orr r1, #2
ldr r2, =0x40020800
ldr r3, =0x4
str r1, [r0]
ldr r4, [r2]
str r3, [r2]

Or just do things sequentially as above (prep the write with a few instructions).
ldr r0, =0x40023830
ldr r1, [r0]
orr r1, #2
str r1, [r0]

LDR r2, =0x40020800
LDR r1, =0x04
STR r1, [r2]

Just use binutils there is no reason to mess with gcc at all.
flash.s
.thumb
.syntax unified

.global _start
_start:
.word 0x20001000
.word reset
.word loop
.word loop

.thumb_func
loop:   b .

.type reset, %function
reset:
    ldr r0, =0x40023830
    ldr r1, [r0]
    orr r1, #2
    str r1, [r0]

    LDR r2, =0x40020800
    LDR r1, =0x04
    STR r1, [r2]

    ldr r0, =0x40020818
    ldr r1, =0x00000002
    ldr r2, =0x00020000
loop_top:
    str r1,[r0]
    bl delay
    str r2,[r0]
    bl delay
    b loop_top

.thumb_func
delay:
    ldr r3,=0x200000
delay_loop:
    subs r3,#1
    bne delay_loop
    bx lr

flash.ld
MEMORY
{
    rom : ORIGIN = 0x08000000, LENGTH = 0x1000
    ram : ORIGIN = 0x20000000, LENGTH = 0x1000
}
SECTIONS
{
    .text   : { *(.text*)   } > rom
    .bss    : { *(.bss*)    } > ram
}

build:
arm-none-eabi-as --warn --fatal-warnings -mcpu=cortex-m4 flash.s -o flash.o
arm-none-eabi-ld -nostdlib -nostartfiles -T flash.ld flash.o -o flash.elf
arm-none-eabi-objdump -D flash.elf > flash.list
arm-none-eabi-objcopy -O binary flash.elf flash.bin

check:
Disassembly of section .text:

08000000 <_start>:
 8000000:   20001000    andcs   r1, r0, r0
 8000004:   08000013    stmdaeq r0, {r0, r1, r4}
 8000008:   08000011    stmdaeq r0, {r0, r4}
 800000c:   08000011    stmdaeq r0, {r0, r4}

08000010 <loop>:
 8000010:   e7fe        b.n 8000010 <loop>

08000012 <reset>:
 8000012:   480d        ldr r0, [pc, #52]   ; (8000048 <delay_loop+0x8>)
 8000014:   6801        ldr r1, [r0, #0]
 8000016:   f041 0102   orr.w   r1, r1, #2
 800001a:   6001        str r1, [r0, #0]
 800001c:   4a0b        ldr r2, [pc, #44]   ; (800004c <delay_loop+0xc>)
 800001e:   f04f 0104   mov.w   r1, #4
 8000022:   6011        str r1, [r2, #0]
 8000024:   480a        ldr r0, [pc, #40]   ; (8000050 <delay_loop+0x10>)
 8000026:   f04f 0102   mov.w   r1, #2
 800002a:   f44f 3200   mov.w   r2, #131072 ; 0x20000

0800002e <loop_top>:
 800002e:   6001        str r1, [r0, #0]
 8000030:   f000 f804   bl  800003c <delay>
 8000034:   6002        str r2, [r0, #0]
 8000036:   f000 f801   bl  800003c <delay>
 800003a:   e7f8        b.n 800002e <loop_top>

0800003c <delay>:
 800003c:   f44f 1300   mov.w   r3, #2097152    ; 0x200000

08000040 <delay_loop>:
 8000040:   3b01        subs    r3, #1
 8000042:   d1fd        bne.n   8000040 <delay_loop>
 8000044:   4770        bx  lr
 8000046:   38300000    ldmdacc r0!, {} ; <UNPREDICTABLE>
 800004a:   08004002    stmdaeq r0, {r1, lr}
 800004e:   08184002    ldmdaeq r8, {r1, lr}
 8000052:   Address 0x0000000008000052 is out of bounds.

Vectors look good, it will not hang immediately
I hate the unified syntax with a passion, certainly with binutils, but writing this:
delay_loop:
    sub r3,#1
    bne delay_loop

without the unified syntax under gnu assembler, actually produces the subs not sub and that confuses people (and they comment).  So I used unified syntax above.  If you are starting out probably should just enable unified syntax and learn it that way, sigh. (for where you are now, just enable it with that one line up front somewhere and keep doing what you are doing).
I have no use for gdb but perhaps it works there too, but if you telnet into openocd you can certainly do this:  Either defeat your code by having reset go right into an infinite loop, or depending on the debug tool just reset and not start the code, but then you can write these control registers over the debug interface and see them work before you write the code to do the same thing. One can save some time (or can take longer, depends on your coding/debugging style).
mdw 0x40023830
mww 0x40023830 0x00000002 (need to read-modify-write any other ones in there from the prior read)
mdw 0x40020800
mww 0x40020800 0x4
mdw 0x40020800

and you should see the 0x4 there.
Then mess with 0x40020818 to change the state of the output pin.

DMA is not relevant here.  You have the processor then its main ahb/etc bus and that goes through memory controller and other busses probably and such until it hits the logic that handles that control register.  Then the enable for that clock goes through some number of gates to get to the clock enable for that logic block (gpioc in this case).  It might take at least one clock for the enable to be latched and then probably at least another peripheral clock cycle to enable the clock gate to allow the clock through to the gpio.  Now a particular contributor here would normally make this comment when seeing code like this.  And some but not all of the STM32 documents specifically tell you how many us or ms you have to delay.
Writes can be fire and forget, the address and data is part of the transaction, and the first level memory controller closest to the chip can technically take those two items and tell the processor the write is complete (even though it is not) allowing it to do the next thing (another STR for example).  Something like the clock control logic and a peripheral like a GPIO may or may not be down the same set of busses, but eventually they split off.
Just like sending two letters from your house to two addresses in the same town, you write the addresses on the envelope, put them in the mailbox, as far as you are concerned they are sent, you can go back in the house and do something else.  These two might ride in the same trucks and planes all the way to the same post office in that destination town, but eventually will get split up and take different paths which can take a different amount of time.
This is called a race condition and they are very real and they happen more than we would like, but this is not something to start to panic about or worry about every time something does not work.  In general the vendor will indicate in the docs or an errata that there is a race condition.  Race as in track and field in the Olympics, a marathon, NASCAR, two or more things trying to get to the finish line first or in this case in order.
This is why simply removing a printf in some code, can have devastating results, as that printf caused a big delay between the thing before and after.  Removing the delay, can cause a race.
It is not uncommon to have this specific situation where you have a control block, like a clock enable or something that controls address decoding (say you had a region of the processors address space that you can per their design point at something, but if you change what it points at then immediately try to talk the thing you just told it to point at you might have a race condition).
Writes are fire and forget, but reads have to go all the way to the peripheral and back, so the worst case time/path.  Now I have worked on logic where the read path and write path split and you can have a race there too, but more of an exception not the rule.  So if you for example write some control register, then read it back, one would hope the designers serialize this and the read happens after the write, it does a complete trip to the peripheral and back, so by the time it comes back and lets the processor continue, that register is definitely written.
In this case you have the possibly delay for the write to the rcc plus possibly different buses to get at the rcc vs the gpio causing possible timing differences, allowing for this race.
On the part you have or on other stm32 parts, you can try the experiment hinted to above.  do the rcc enable with a STR, then the next instruction do a STR to moder to change the pin to an output, then you can take your time to change the state of the pin to say turn an led on.  If it does work when you have some number of clocks delayed between the stores, but does not work when they are back to back.  There you go.
The great mystery is why does the read work, STR, LDR, STR worked on the chips I found a race condition for.  That does not make sense.  The next great mystery is that if you read the moder registers that are non-zero, ones that you can get a good feel that you are actually reading that register (GPIOA and GPIOB moder in this case), with the gpio disabled in the rcc clock enable.  The correct value comes back.  This seems like a hack to me to get around the race condition.  This could very well be a case of they had some number of chips they had a library that is already out there being used, then the next chip is in design and does not work, not going to go and force a new update of the hal for everyone for this one part when you can make a quick solution in the design.
So I only tested a handful of different parts but
STR (the write that enables the clock)
LDR (of the moder)
STR (of the moder)

Worked for the parts where
STR (the write that enables the clock)
STR (of the moder)

Failed.

DMA, direct memory access.
So let us think about say a PWM controller or a UART that have a small buffer, maybe only one value being used for that transaction/period and one value sitting in a transmit buffer waiting to be next.  You as the programmer MIGHT depending on the design, have a few choices, have a loop of code that polls status registers waiting for an indication that says the holding register value is now being transmitted, and is now "empty".  And then you ideally want/need to write the new value before the prior value is completely transmitted or that time period of the pwm or whatever happens.
You need to burn a lot of processing time if you want to keep the output of the peripheral at line rate or with no gaps or repeats or whatever that peripheral does.  Now if your application is not doing anything else, and I will strongly argue if you are learning to use this peripheral, this is where you start.  But the next option might be an interrupt you setup a handler and when the interrupt happens you pull from a larger buffer you are maintaining (in ram) to feed this peripheral, if you can insure that the handler is fast enough and no other higher priority things delay the handler starting (real time) then this will work.
The third thing which is not always available is DMA.  You in some way tell the peripheral or a third party dma controller, that here is the block of data I want to send, and here is where I want it sent, the logic has to be designed with a connection to trigger the dma, causing one or whatever number of items to move into the peripheral.  There can still be contention that causes delays and a race condition, but this is your best bet if you want/need to feed something into a peripheral every cycle.
A same similar concept where you hear about dma and folks also think this one is free to as it magically happens in the background and does not affect the processor.  Say a memory transfer, setup a DMA engine that may be part of some system to do a transfer or data from one place to another, rather than having to do a memcpy or some other such thing (often used for things like moving a frame of pixel data to a video card or some other such thing, these days the video cards do a lot of the work for you generating pixels).  Some systems this was free, many others it was not as it uses the same buses, so it causes the processor to have to stall if the bus is being used by the dma engine, definitely affecting the processor.
I have seen some where the processor is stopped/stalled completely while the dma transfer is happening, and I saw one wasteful one where the bus was some three quarters thing, at all times there was a clock cycle every so many that was reserved for dma if you happened to want to do a transfer and that cycle/block of time would then get used.  Basically you were always being affected by the dma even if it was not happening (that was a DSP where execution consistency is very important and clearly more important than having code go as fast as you can).
DMA is used for many things, the m is wrong it does not always mean memory, it might be from one fifo (okay technically an sram) to some peripheral.  It generally means, despite the name, another bus controller that can initiate bus transactions so that you do not have to create those transactions through the main processor via code.
Honestly you are not ready for DMA yet, nor interrupts.  Poll your way through, create lots of throwaway code, even if you are working toward a specific project.  For each peripheral for each feature you are going after, create one or more ad-hoc applications and figure out how that thing works.  If you get into a mystery situation where everything is working and you add or remove even a single line of code that should have absolutely nothing to do with it and the thing breaks then if it were compiled code then question the output of the compiler, examine it.
If it is asm (or high level) it could be a race condition of some sort (it could be something else).  They really are rare, often documented (eventually), BUT when they strike they can take a long time to figure out and sometimes you never are really sure but adding a delay fixed it, or reading the thing three times and taking the two that match, or whatever hack, and you move on with life.  I was just warning you about something very real about a percentage of these STM32 designs.  That could lead you to the same head scratching as what brought you here in the first place.


text:
Q: Best practices on cache implementation I would need to implement cache, which would need to perform SQL queries and cache results. So, I would love to read something about best practices of doing that; how do properly, staling cache results, checking, etc.
Particularly, I would probably benefit from learning how Hibernate is doing that? Or some other good players :-)

A: One approach in the Java world is to use the OpenSymphony Cache.  This is a distributed cache (like memcached) that lets you store any Java objects and set expiration policies.
If you use iBatis as your Java persistence manager, you can leverage its integration with OSCache.  The Hibernate ORM also has an OSCache integration.

A: The best practice is to not cache database queries, but things you do with database queries.  That is, you do a database query because you want an object that is represented by the data the query gives you.  That's what you should cache.
Hibernate does some of this, and you can of course mix hibernate and memcached to get the benefits of memcached.


text:
Q: React/JS - Certain files don't get imported during testing with Mocha I am having issue with imports during my testing. The test framework is Mocha, and I am using chai and sinon. I think this is an issue with my understanding with how scope works in Javascript. Nonetheless.
Here's my test file:
test/action/forgot-password
const middlewares = [ thunk];
const mockStore = configureMockStore(middlewares);

describe('forgot password async actions', () => {
    afterEach(()=> {
        nock.cleanAll();
    });
    it('should show a request for a password reset and that it succeeded ', (done) => {
        nock('http://localhost:8080/')
        .post('/password-reset-requests')
        .reply(200);
        var email = "test@email.com";
        const expectedActions= [
            {type: REQUEST_ADD_PASSWORD_RESET_REQUEST},
            {type: REQUEST_ADD_PASSWORD_RESET_REQUEST_SUCCESS}
        ];
        const store = mockStore({}, expectedActions, done);
        store.dispatch(Actions.addPasswordResetRequest(email));
              });

});

Here is the api call my action makes
api/users.js
'use strict';

export const addPasswordResetRequest = (email) => {
    console.log(NC_SETTINGS.API_ROOT);
    return fetch(
        NC_SETTINGS.API_ROOT + '/password-reset-requests',
        {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                email: email,
                code: NC_SETTINGS.GROUP.code
            })
        }
    )
        .then(handleResponse);
};

So when I run it normally, in a browser, I get no errors. Fetch gets called just fine, and the file knows where the NC_SETTINGS file is.
I should mention the file structure of my project.
-project

--app folder
---js folder
----api folder
-----users.js(this makes the call to fetch)

--settings folder
---settings.js file(this has nc_settings)
--test folder
---testing file

They get imported just fine when on local_web.
But when I am testing, neither fetch nor nc_settings is found.
To get around fetch, I did import isomorphic fetch in my api/users.js, which fixes the fetch issue during testing. I then tried to import app/settings/settings, and it does find the file. However it still doesn't solve the issue. It now comes up as undefined.
What's the reasoning behind this? Is this a hoisting scope issue? How is this resolved?


text:
Q: webview loads webpage, but some contents get vanished after loading (Android Studio) I tried to view http://artikelweb.com in a webview. The web page appears nicely. But, whenever I go to any author link from "Popular Authors" section, the web page appears, but, after loading, the quotes aren't showing.
In Google Chrome Browser(mobile) the quotes appear after loading,

but, in my app, the quotes are not showing in web view.

Code Snippet:
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_web);

    myWebView = (WebView)findViewById(R.id.webView);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    myWebView.loadUrl("http://www.artikelweb.com");
    myWebView.setWebViewClient(new WebViewClient());

}

@Override
public void onBackPressed() {
    if(myWebView.canGoBack()) {
        myWebView.goBack();
    } else {
        super.onBackPressed();
    }
}

A: In your particular case you must enable the DOM Storage API
webSettings.setDomStorageEnabled(true);

So your code must become:
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_web);

    myWebView = (WebView)findViewById(R.id.webView);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    myWebView.loadUrl("http://www.artikelweb.com");
    myWebView.setWebViewClient(new WebViewClient());
}

That becouse the javascript that use the website you are accessing needs it in its javascript.

Of course you could take advantage of a third party library, but again you won't know why this exact case works in the third party one and not in the default webview.
The library you are using has this initial settings:
https://raw.githubusercontent.com/delight-im/Android-AdvancedWebView/master/Source/library/src/main/java/im/delight/android/webview/AdvancedWebView.java
final WebSettings webSettings = getSettings();
        webSettings.setAllowFileAccess(false);
        setAllowAccessFromFileUrls(webSettings, false);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        if (Build.VERSION.SDK_INT < 18) {
            webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        }
        webSettings.setDatabaseEnabled(true);
        if (Build.VERSION.SDK_INT < 19) {
            webSettings.setDatabasePath(databaseDir);
        }
        setMixedContentAllowed(webSettings, true);

        setThirdPartyCookiesEnabled(true);

Enabling by default many options that the default webview has disable for security reason.

A: Set UserAgent to your Webview settings and try
webSettings.setUserAgentString("Mozilla/5.0 (Linux; <Android Version>; <Build Tag etc.>) AppleWebKit/<WebKit Rev> (KHTML, like Gecko) Chrome/<Chrome Rev> Mobile Safari/<WebKit Rev>");


text:
Q: Парсинг информации и её сортировка по убыванию (цифры) Доброго времени суток!
Нужно, чтобы PHP скрипт заходил на страницу http://site1.ru/, парсил информацию из тегов
10000 $

    2

*

*10000 $ - инфа, которую необходимо спарсить.
А потом, заходил на http://site2.ru/, также парсил информацию и сортировал по убыванию.

A: Материалы по данной теме:
curl/fsockopen (для получения инфы)
preg_match_all и мануал по регуляркам (для парсинга)
инфа по сортировке массивов
mysql_* (для сохранения)
Это самая частая связка, а алгоритм чуть ли не из этих функций с параметрами и в правильном порядке собирается. Получили текст - вытащили подходящие значения - рассортировали - записали в базу.


text:
Q: Drag and drop zone in JS - File input I have problem with uploading files in my existing form.
What I am looking for is script that will make possible to add multiple files (max 5) and you can add at once from one to five files. If you add one by one, I need it to add new, not replace the previous one.
I got form looking like this:
Name
LastName
Email
Phone number
Interests
Files

and filenames are created like this: name+lastname+phonenumber+filename
And I add entry to database with path of everyfile - this is done and I need only good drag and drop zone.
I need it to show added filename and make it possible to delete added file from queue.
But I don't want files to upload when I add them. I want it to upload when I submit my whole form so filename can be created and path to DB can be added.
Could anyone please provide me good script to that, or based on my scripts from two topics I mentioned before make it avaiable to do what I want?
I was able to add 5 files one by one and I described it here:
HTML Add multiple file to the input
Also I was able to add more at once what I described here:
https://stackoverflow.com/questions/30499388/dropzone-js-into-another-form

A: I think that this example help you.
This app allow drag and drop files to gray zone (1 or 5)
If you click on the file name, it removes file from the list.

function init() {
    //get dragdrop element
    var dd = document.getElementById("dragdrop");
    //get files element
    $files = document.getElementById("files");
    dd.ondragover = stop;
    dd.ondragleave = stop;
    if ('FileReader' in window) {
        document.ondrop = dragAccept;
    }

    //get form
    var $form = document.querySelector("form");
    //catch on submit
    $form.onsubmit = function (e) {
        stop(e);
        var fd = new FormData();
        //apend files to FormData
        for (var i in files){
            var file = files[i].file;
            var filename = file.name;
            var name = "file";
            fd.append(name, file, filename);
        };
        //append inputs to FormData
        var $inputs = $form.querySelectorAll("input");
        for (var i = 0; i < $inputs.length; i++) {
            var $input = $inputs[i];
            fd.append($input.getAttribute("name"), $input.value);
        }
        //Send data
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/echo/html/', true);
        xhr.send(fd)
    }
}

function stop(e) {
    e.stopPropagation();
    e.preventDefault();
}

function dragAccept(e) {
    stop(e);
    if (e.dataTransfer.files.length > 0)
        for (var i = 0; i < e.dataTransfer.files.length; i++) {
            addFile(e.dataTransfer.files[i]);
        }
}

//file list store
var files = {};
// html element of file list
var $files = null;
//add file to file list
function addFile(file) {
    //add files with diferent name, max files count 5
    if (!(file.name in files) && Object.keys(files).length < 5) {
        var div = createFile(file.name);
        $files.appendChild(div);
        files[file.name] = {
            file: file,
            element: div
        }
    }
}

//create html element with file name
function createFile(name) {
    var div = document.createElement("div");
    div.innerText = name;
    var input = document.createElement("input")
    //remove on click
    div.addEventListener("click", function () {
        $files.removeChild(this);
        delete files[name];
    })
    return div;
}

window.addEventListener("load", init);
<form method="post" enctype="multipart/form-data" action="">
    Name<input name="name" />
    Last name<input name="lastName" />
    Email<input name="email" />

Drag drop zone

    <button type="submit">Send</button>
</form>


text:
Q: callback.customMessage is not a function I am working on implementing custom authentication. This is the code -
cognitoUser.initiateAuth(authenticationDetails, {
        onSuccess: async (result) => {
            console.log('initiateAuth result -', result);
            authenticateUser.initiateAuth(params, (err, data) => {
                if(err) {
                    console.log('initiateAuth err 1 -', err);
                } else {
                    console.log('initiateAuth result 1 -', data)
                }
            })
        },
        onFailure: async (err) => {
            console.log('initiateAuth err -', err)
        },
        customChallenge: async (challengeParameters) => {
            // User authentication depends on challenge response
            var challengeResponses = 'challenge-answer';
            cognitoUser.sendCustomChallengeAnswer(challengeResponses, {
                onSuccess: async (result) => {
                    console.log('challenge result -', result)
                },
                onFailure: async (err) => {
                    console.log('challenge err -', err)
                }
            });
        },
    })

But I am still getting callback error.
Can someone please help me on this?


text:
Q: Roslaunch cannot open shared object file: No such file or directory I'm having problems with opening a shared library when using roslaunch.
I have a ROS package with a c++ script containing the line:
handle = dlopen("./rk4.so", RTLD_LAZY);

This shared library resides inside my ROS package. I managed to build the package with catking build, having in my CMakeLists.txt the lines
add_library(RK4 SHARED IMPORTED)
set_target_properties(RK4 PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/SharedLibs/rk4.so)

target_link_libraries(simulator_node
  RK4
  ${CMAKE_DL_LIBS}
  ${catkin_LIBRARIES}
)

The problem is when I try to run my executable. Since the library is not in a folder where libraries usually are, I added the path to that folder to LD_LIBRARY_PATH and exported it.
However I don't understand why I don't get the error in the title only when I use rosrun while I'm inside the exact folder in which the library is.
My issue is that I want to launch that node with a launch file, but using roslaunch I get the error in the title anyway, even if I run it from inside the folder of that library.

A: This code:

handle = dlopen("./rk4.so", RTLD_LAZY);

will succeed if and only if there is rk4.so in the current directory. In particular, it will ignore any LD_LIBRARY_PATH setting.
This is working as designed.
If you want dlopen to respect LD_LIBRARY_PATH, change it like so:
  handle = dlopen("rk4.so", RTLD_LAZY);

A better approach is to make above change and avoid the need to set LD_LIBRARY_PATH by using -Wl,-rpath=/dir/where/rk4.so/is/installed at link time of the application.

A: I think the most portable way of doing so is to supply dlopen with the full path to the shared library file by using ros::package::getPath("your_package_name") as follows (and not modifying LD_LIBRARY_PATH!). This way you can easily get your package up and running on another computer!

*

*Modify your node to load the shared library using the absolute path to the shared library by using the function ros::package::getPath from the ros/package.h header:
std::string const library_path = ros::package::getPath("your_package") + "/relative/path/to/libyourlib.so";
auto* handle = ::dlopen(library_path.c_str(), RTLD_LAZY);

This for example would be a minimal working example for a node your_node :
#include <cstdlib>
#include <iostream>
#include <string>

#include <dlfcn.h>

#include <ros/ros.h>
#include <ros/package.h>

int main (int argc, char** argv) {
  ros::init(argc, argv, "your_node");
  ros::NodeHandle n;

  std::string const package_path = ros::package::getPath("your_package");
  std::string const library_path = package_path + "/src/libyourlib.so";
  auto* handle = ::dlopen(library_path.c_str(), RTLD_LAZY);

  if (!handle) {
    std::cerr << "Error: could not load shared library!" << std::endl;
  } else {
    std::cout << "Library successfully loaded!" << std::endl;
  }
  return EXIT_SUCCESS;
}

*Modify your CMakeLists.txt to include the roslib library which contains the ros::package::getPath function:
find_package(catkin REQUIRED COMPONENTS
  roscpp
  roslib
)

include_directories(
  ${catkin_INCLUDE_DIRS}
)

add_executable(your_node src/your_node.cpp)
target_link_libraries(your_node ${catkin_LIBRARIES} ${CMAKE_DL_LIBS})


text:
Q: Can I write to different jetty databases using JPA that is using the same "entity class" I am using Java persistance and there EntityManager class and have it assigned to storage a class object that shall be written to the database. My problem is that I want to write to different databases using the same storage class. My solution to that was to write a StorageManagerfactory that has a Map holding all EntityManagers. The solution looked good until I looked at the databases and realized that all information (undepending of the Map, which gets the correct value) was written to the same database (one of the initialised in the Map).
So my question is:
Can I write to different databases using JPA that is using the same storage class (the class holding the structure of my database)?
Thanks

A: Yes, define multiple persistence units in persistence.xml. Then, when injecting your @PersistenceContext specify the unitName attribute.

A:
My solution to that was to write a StorageManagerfactory that has a Map holding all EntityManagers

I don't think a Map of EntityManager is a good idea.
However, it should be possible to use
Persistence.createEntityManagerFactory(String, Map) to create N EntityManagerFactory pointing to N databases (the mentioned factory method allows to pass additional properties that override values that may have been configured elsewhere, for example a connection url) and to these EntityManagerFactory in a Map.
Then, simply get the "right" EntityManagerFactory from the Map (use the whatever key you want) and get an EntityManager.


text:
Q: PHP XML: How to display XML with PHP How would i retrieve what is inside these XML tags in php?
I can get it to work when they don't have a ':' inside the tags. But for this, it doesn't seem to work:
$description = $item->getElementsByTagName('desc');
$description = $description->item(0)->firstChild->nodeValue;

<sql:time>21:00</sql:time>
<sql:event> Empty </sql:event>
<sql:desc>This field is empty</sql:desc>

thanks

A: Use the namespace equvilant of the function you are currently using:
The colon in the element name deneotes the namespace it is within. So you will get the information out of sql:time by calling as:
$description = $item->getElementsByTagNameNS( 'sql', 'time' );

A: Alternatively you could use xpath...
$xp = new DOMXpath($dom);

$xpath->registerNamespace('sql', "http://URI");

$xpath_str = '//sql:desc/text()';

$titles = $xpath->evaluate($xpath_str);

print $titles->item(0)->nodeValue ."\n";

( Assuming I didn't make any mistakes which I might have.. )
http://www.php.net/manual/en/domxpath.registernamespace.php


text:
Q: Is it possible to include JButton in a JTable? I have a JTable that stores the results of a database query, so far so good. What I want is for the last column in each table to have a clickible JButton that will open the edit screen for the object represented in that row, and that means the button will need to know the details of the first column in the table from its own row (the ID from the database).
Any advice? I already tried just adding JButtons but they turned into Text when I tried to run it.

A: Contrary to the tutorial above, there is a way to do this without a complicated positioning math, custom mouse listeners, and custom table models. Instead, it can be done with a single simple custom class following the pattern described here:
http://web.archive.org/web/20100623105810/http://ivolo.mit.edu/post/A-Simple-Pattern-for-Embedding-Components-into-a-Swing-JTable.aspx

A: You may also find my tutorial on a similar subject (in this case, using a JPanel) helpful as well: Custom JPanel cell with JButtons in JTable

A: Take a look at Sun's introduction to the JTable component, specifically, the section about Editors and Renderers. It discusses the use of alternative CellRenderers, and CellEditors. What you'd need to do is create (or borrow) a ButtonCellRenderer and a ButtonCellEditor and then apply them to the column in question in your JTable. The examples found in the linked articles should give you all the information you need.


text:
Q: MemoryStream instance timing help Is it ok to instance a MemoryStream at the top of my method, do a bunch of stuff to it, and then use it?
For instance:
public static byte[] TestCode()
{
  MemoryStream m = new MemoryStream();
  ...
  ...
  whole bunch of stuff in between
  ...
  ...

  //finally

  using(m)
  {
     return m.ToArray();
  }
}

Updated code
public static byte[] GetSamplePDF()
{
    using (MemoryStream m = new MemoryStream())
    {
        Document document = new Document();

        PdfWriter.GetInstance(document, m);

        document.Open();

        PopulateTheDocument(document);

        document.Close();

        return m.ToArray();
    }
}

private static void PopulateTheDocument(Document document)
{
    Table aTable = new Table(2, 2);
    aTable.AddCell("0.0");
    aTable.AddCell("0.1");
    aTable.AddCell("1.0");
    aTable.AddCell("1.1");

    document.Add(aTable);

    for (int i = 0; i < 20; i++)
    {
        document.Add(new Phrase("Hello World, Hello Sun, Hello Moon, Hello Stars, Hello Sea, Hello Land, Hello People. "));
    }

}

My point was to try to reuse building the byte code. In other words, build up any kind of document and then send it to TestCode() method.

A: Technically, this is possible, but it's pointless.  If you really want to avoid using the "using" statement around that code, just call Dispose() directly.
You should put the entire work that's using the MemoryStream into the using statement.  This guarantees that the MemoryStream's Dispose method will be called, even if you receive an exception during your "whole bunch of stuff in between" code.  The way you have it now, exceptions will prevent your MemoryStream from having Dispose() called on it.
The proper way to handle this would be:
public static byte[] TestCode()
{
  MemoryStream m = new MemoryStream();
  using(m)
  {
      // ...
      // ...
      // whole bunch of stuff in between
      // ...
      // ...

     return m.ToArray();
  }
}

Or, in the more common form:
public static byte[] TestCode()
{
  using(MemoryStream m = new MemoryStream())
  {
      // ...
      // ...
      // whole bunch of stuff in between
      // ...
      // ...

     return m.ToArray();
  }
}

A: When seeing questions like these, I often wonder if we wouldn't have been better off using the Java model.  There's an extraordinary amount of agony that .NET programmers suffer over that doggone IDisposable.  After thousands of questions on SO (et al), it still remains poorly understood.
It is a memory stream.  There's nothing that needs to be disposed when you use memory, the garbage collector already takes care of it.  It is not some kind of special memory just because the class has a Dispose() method, there's only one kind.  The other kind is wrapped by UnmanagedMemoryStream.  The fact that MemoryStream inherits a do-nothing Dispose() method from Stream is a sad OOP liability.
It is up to you to decide to slovenly call a do-nothing method because it is there.  Or you could take charge of your code and refuse to call methods that you know don't do anything useful now, nor will ever do anything useful for the rest of your career.  Clearly I'm in the second camp, our life-expectancy must be better.  I hope anyway.  Then again, this post might have knocked a day off.


text:
Q: Proper way to exit command line program? I'm using mac/linux and I know that ctrl-z stops the currently running command in terminal, but I frequently see the process is still running when i check the system monitor. What is the right way to stop a command in terminal?
Typically I run into this issue when running python or ruby apps, i'm not sure if that has something to do with it, just thought I would add that.

A: Using control-z suspends the process (see the output from stty -a which lists the key stroke under susp).  That leaves it running, but in suspended animation (so it is not using any CPU resources).  It can be resumed later.
If you want to stop a program permanently, then any of interrupt (often control-c) or quit (often control-\) will stop the process, the latter producing a core dump (unless you've disabled them).  You might also use a HUP or TERM signal (or, if really necessary, the KILL signal, but try the other signals first) sent to the process from another terminal; or you could use control-z to suspend the process and then send the death threat from the current terminal, and then bring the (about to die) process back into the foreground (fg).
Note that all key combinations are subject to change via the stty command or equivalents; the defaults may vary from system to system.

A: if you do ctrl-z and then type exit it will close background applications.
Ctrl+Q is another good way to kill the application.

A: Take a look at Job Control on UNIX systems
If you don't have control of your shell, simply hitting ctrl + C should stop the process. If that doesn't work, you can try ctrl + Z and using the jobs and kill -9 %<job #> to kill it. The '-9' is a type of signal. You can man kill to see a list of signals.


text:
Q: Source Control Explorer hanging I have an issue with Source Control Explorer. When it loads all it does is show "Working..."

I have tried:
Visual Studio 2017 Explorer
Visual Studio 2019 Enterprise (what I normally use)
Visual Studio 2022 Enterprise

Update 1: I cleared my TFS Cache completely with no luck.
Update 2: I uninstalled all Visual Studio Versions and installed the latest version of SQL Server 2022 Enterprise

How can this be resolved?

Note: Bounty was inadvertanly put in to show needing authoritative
answer. It just needs more exposure but I couldnt find a way to edit
it.


text:
Q: Convert weighted direct cyclic graph to equivalent acyclic graph I have a cyclic weighted directed graph and the goal is to remove the cycle present in the path.
eg: the paths are as below,
from | to | weight
------------------
a    -> b | 0.5
a    -> c | 0.5
c    -> e | 1
b    -> d | 1
d    -> a | 0.25
d    -> f | 0.75

the cycle in the graph is introduced by the path d -> a. Can anyone suggest an algorithm to remove the cycle d -> a by adjusting the weights of the other nodes. The resulting acyclic graph to be equivalent in terms of passing on the weights to the end nodes e, f.
Thanks,
Vivek

A: Sleator–Tarjan call this the acyclic flow problem and describe an O(m log n)-time solution on page 389 of their first paper on dynamic trees. If you don't need the fastest algorithm, repeatedly use depth-first search to find one flow cycle and then send in reverse the minimum amount of flow that cancels one or more arcs.
On your graph:
a    -> b | 0.5
a    -> c | 0.5
c    -> e | 1
b    -> d | 1
d    -> a | 0.25
d    -> f | 0.75

DFS finds a cycle a -0.5> b -1> d -0.25> a. Send -0.25 on that same cycle.
a    -> b | 0.5 - 0.25 = 0.25
a    -> c | 0.5
c    -> e | 1
b    -> d | 1 - 0.25 = 0.75
d    -> f | 0.75

We delete
d    -> a | 0.25 - 0.25 = 0

The flow is acyclic, so we stop.

A: From your comment to David's answer and from the weights of the graph, it looks to me like the weights are probabilities to move from one node to the other (or percentage of a unit that moves from on node to another, either way the math is the same). If so, this can be modeled as a Markov chain, and more specifically as an absorbing Markov chain. But first, we need to add two paths to fit the formal definition:
e -> e | 1.0
f -> f | 1.0

I'm not sure if you need a general algorithm for multiple graphs similar to this one or this is the only graph you need to solve. I'll give an overview of the math involved for this particular graph, and hopefully you can generalize it into an algorithm if you need it.
The arithmetic is pretty cumbersome, follow along on the absorbing Markov chain link.
First, we need the adjacency matrix, more commonly called the state transition matrix when dealing with Markov chains:
  |  a     b     c     d  |  e     f
--+-----------------------+------------
a |  0     0.5   0.5   0  |  0     0
b |  0     0     0     1  |  0     0
c |  0     0     0     0  |  1     0
d |  0.25  0     0     0  |  0     0.75
--+-----------------------+------------
e |  0     0     0     0  |  1     0
f |  0     0     0     0  |  0     1

The top left portion of the matrix are the transitions between the transient (non-ending) states (symbolized by Q), the bottom right are the absorbing states. The top right will be symbolized by R.
The fundamental matrix, is calculated as N = (I - Q)-1. While the absorbing probabilities (i.e. given infinite time, the percentage that will end up in each of the absorbing states) is given as B = NR. Using my best ASCII matrices, the numbers for this graph are:
         +-          -+             +-    -+
         | 8  4  4  4 |             | 4  3 |
         | 2  8  1  8 |             | 1  6 |
N = (1/7)| 0  0  7  0 |    B = (1/7)| 7  0 |
         | 2  1  1  8 |             | 1  6 |
         +-          -+             +-    -+

The top row of the B matrix is read, starting from state a, there's a 4/7 (approx. 0.5714) chance of ending up in state e, and a 3/7 (approx. 0.4286) chance of ending up in state f. You can ignore the other three rows, since those are the probabilities when starting in states b, c, and d.
Therefore if you want an equivalent graph where the end chance of ending up in states e and f are the same, but without the cycle, you can remove the d -> a path, and use the following weights:
a -> b | 0.4286
a -> c | 0.5714


text:
Q: When is it appropriate to create a new table in the WordPress database? For a client we'll need 29,000 terms (all the highschool's in the US) and each term needs 6 meta items (address, phone...). My initial thought was to store the term meta information as suggested in this post but after looking through it again I will be using lots of terms and I wonder if it will overload the options table.
Is there a good time to create a new table? Would this qualify? Other thoughts on how to relate the HS that a person attends to the 'post' that will be their academic profile?
It was suggested that I make the 'terms' a Custom Post Type. I'm not opposed to that either but I fail to see how I'll relate the CPT to multiple 'authors' since a school will have more than one student that attends it. Because of the multiple ownership of the content terms just seemed to fit better.

A: As the article mentions, using wp_options is not a good idea when you have thousands of terms, mainly because there's:

*

*a lot of serialization involved OR

*long option names (the limit is 64 characters)

In this particular case, yes, it's appropriate to create some custom tables.
To save time, you can use this plugin (update more recently than Simple Term Meta):
http://wordpress.org/extend/plugins/taxonomy-metadata/
Having said that, it looks to me like a custom post type would be better suited for this.
Take a look at my Posts 2 Posts plugin for relating highschools to whatever you were planning on relating them to.


text: Q: Cohomology with compact support for determinant varieties I wonder if anyone knows anything about the cohomology with compact supports for determinantal varieties, such as the varieties of $m \times n$ matrices of full rank.


text:
Q: How to enable Android emulator (AVD) microphone on OSX? This question was somewhat asked previously but it doesn't appear there was a resolution.
For testing purposes, I am trying to use an app on the Android emulator that records from the mic. I believe this is possible -- but correct me if I'm wrong.
Using the following combinations, I have been unsuccessful in running the Speech Recognition app (app closes when I hit record with Sorry! message):
host os - OSX lion / Fedora
android os - 2.0, 4.3
My mic is working on the host machine. I have enabled audio recording and playback in the AVD.


text:
Q: Is it possible to disable individual list box items in WPF? Is it possible to disable individual list box items in WPF? It should appear greyed out and the user should not be possible to select it.

A: Here's a short program to show you what to do. It compares the Listbox items with a List<> and if the listbox item is not found in it, it gets disabled.
XAML code:
<Grid x:Name="LayoutRoot">
    <ListBox  x:Name="listbox_xaml" HorizontalAlignment="Left" Margin="52,53,0,0" VerticalAlignment="Top" Width="157" Height="141">
    <ListBoxItem>Fred</ListBoxItem>
    <ListBoxItem>Joe</ListBoxItem>
    <ListBoxItem>Mandy</ListBoxItem>
    </ListBox>
</Grid>

C# code behind: (run on window's load event)
bool flag_active = false;
List<string> data_list = new List<string>();
data_list.Add("Fred");
data_list.Add("Mandy");

for(int i = 0;i<listbox_xaml.Items.Count; i++)
{
   ListBoxItem LBI = (ListBoxItem) listbox_xaml.Items[i];
   for(int x = 0 ; x < data_list.Count ; x++)
   {
      //if element from listbox exists in the list of data..
      //it will be active..
      //else it will be flagged inactive..
      if (LBI.Content.ToString() == data_list[x].ToString())
      {
         flag_active = true;
      }
   }
   if (flag_active == false)
   {
      // deactivate element in listbox
      LBI.IsEnabled = false;
   }
   flag_active = false;
}

A: It certainly is - and was answered here.


text:
Q: Point a partical on a sphere geometry in three.js Below is my snippet, For now i want to position a single particle on the sphere. How can i combine partical and sphere geometries together ? Once this is achieved i want to render particles on top of the sphere dynamically
      init();
      animate();

      function init() {
        camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 2000 );
        camera.position.z = 500;

        renderer = new THREE.WebGLRenderer();
        renderer.setClearColor( 0x000000 );
        renderer.setPixelRatio( window.devicePixelRatio );
        renderer.setSize( window.innerWidth, window.innerHeight );

        document.body.appendChild( renderer.domElement );

        scene = new THREE.Scene();

        loader = new THREE.TextureLoader();
        loader.load( '<%= image_path('earthmap1k.jpg') %>', function ( texture ) {
          geometry = new THREE.SphereGeometry( 200, 20, 20 );
          material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5, wireframe: true } );
          mesh = new THREE.Mesh( geometry, material );
          scene.add( mesh );
        } );

  function addPartical() {
    var distance = 200;
    ggeometry  = new THREE.Geometry();
    vertex     = new THREE.Vector3();
    theta      = THREE.Math.randFloatSpread(360);
    phi        = THREE.Math.randFloatSpread(360);

    vertex.x = distance * Math.sin(theta) * Math.cos(phi);
    vertex.y = distance * Math.sin(theta) * Math.sin(phi);
    vertex.z = distance * Math.cos(theta);

    ggeometry.vertices.push(vertex);

    particles = new THREE.Points(ggeometry, new THREE.PointsMaterial({color: 0xffffff}));
    particles.boundingSphere = 50;
    scene.add(particles);
  };

      }

      function animate() {
        requestAnimationFrame( animate );
        addParticle();
        render();
      }

      function render() {
        renderer.render( scene, camera );
      }

A: If you want to treat the two objects as one use a THREE.Object3D() and manipulate that.


text:
Q: Expanding a Proof of Induction on $\Bbb N $ to $\Bbb Q $ (Linear Algebra) My problem is the following:
I have an $\Bbb R$ Vectorspace called $V$ and had to show via induction that $\langle nv, w \rangle=n \langle v, w \rangle$ for $v,w \in V$ and $ n\in \Bbb N$. (it's not already given that $\langle \rangle$ is an inner product.) I've already shown this, but now i have to expand the prove for $n\in \Bbb Q$ and after that, for $n \in \Bbb R$. I would do the last step with the knowledge that Q is dense in R and just use a series in Q that converges to the $n\in \Bbb R$. My problem is the second step. How can i get from $n\in \Bbb N$ to $n\in \Bbb Q$. Does someone have an idea?
Thanks in advance
Edit: The definition for  $\langle \rangle$ ist given via $$ \langle v,w\rangle := \frac 1 2(||v+w||^2-||v||^2-||w||^2)$$ where $||. ||$ is a norm on $V$

A: First, extend the statement from the natural numbers to the integers by negation, simple enough. Now use the statement for integers to prove it directly for rationals. No further induction is necessary.
Proof: Let $v, w$ be vectors in $V$, let $p/q$ be a rational number. Then
$\langle{p\over q}v, w\rangle = {q\over q}\langle{p\over q}v, w\rangle = {1\over q}q\langle p({1\over q}v),w\rangle = {1\over q}qp\langle {1\over q}v,w\rangle = {1\over q}p\langle q({1\over q}v),w\rangle = {p\over q}\langle v,w\rangle$.
The third equality follows from the integer case for $n = p$, the fourth follows from the integer case for $n = q$.

A: If $v'=\frac pq v$, then $qv'=pv$ and therefore $$q \langle v',w\rangle = p\langle v,w\rangle $$
This shows your goal for positive rational multipliers.
You need negative ones too, but it will be enough if you can can show $\langle -v,w\rangle = -\langle v,w\rangle$.


text:
Q: Why is there a relocation needed if calling function in same translation unit So I have two files one is my library and one is a main prog executable.
Library:
static int internal1(int a, int b){
  return a + b;
}

namespace {
  int internal2(int a, int b){
    return a + b;
  }
}

void external2(int qq, int zz){

}

void external(int a, int b){
  external2(a, b);
  internal1(a, b);
  internal2(a, b);
}

Compiled with
g++ -c -O0 -fPIC -o libtest.o libtest.cpp and
g++ -shared -o libtest.so libtest.o
Main prog:
extern void external(int a, int b);

int main(){
  external(1, 2);
  return 0;
}

Compiled with g++ -O0 -L. -ltest -o tester tester.cpp
Now if I dump the relocation information for tester I get what I expect:
Relocation section '.rela.dyn' at offset 0x4d0 contains 1 entries:
  Offset          Info           Type           Sym. Value    Sym. Name + Addend
000000600a48  000100000006 R_X86_64_GLOB_DAT 0000000000000000 __gmon_start__ + 0

Relocation section '.rela.plt' at offset 0x4e8 contains 3 entries:
  Offset          Info           Type           Sym. Value    Sym. Name + Addend
000000600a68  000300000007 R_X86_64_JUMP_SLO 0000000000000000 __libc_start_main + 0
000000600a70  000400000007 R_X86_64_JUMP_SLO 0000000000000000 _Z8externalii + 0
000000600a78  000a00000007 R_X86_64_JUMP_SLO 0000000000400578 __gxx_personality_v0 + 0

and external is on the relocation list since it has to find the address and put it in.
However what I don't understand is when I dump the relocation list of the shared object why I see external2 on the relocation list of the shared object. Why is it not just automatically putting the address in like it did for the functions with internal linkage.
Relocation section '.rela.dyn' at offset 0x460 contains 5 entries:
  Offset          Info           Type           Sym. Value    Sym. Name + Addend
0000002007d8  000000000008 R_X86_64_RELATIVE                    00000000002007d8
000000200990  000200000006 R_X86_64_GLOB_DAT 0000000000000000 __gmon_start__ + 0
000000200998  000300000006 R_X86_64_GLOB_DAT 0000000000000000 _Jv_RegisterClasses + 0
0000002009a0  000400000006 R_X86_64_GLOB_DAT 0000000000000000 __cxa_finalize + 0
0000002009d0  000500000001 R_X86_64_64       0000000000000000 __gxx_personality_v0 + 0

Relocation section '.rela.plt' at offset 0x4d8 contains 2 entries:
  Offset          Info           Type           Sym. Value    Sym. Name + Addend
0000002009c0  000400000007 R_X86_64_JUMP_SLO 0000000000000000 __cxa_finalize + 0
0000002009c8  000600000007 R_X86_64_JUMP_SLO 0000000000000646 _Z9external2ii + 0

The calls to internal1 and internal2 don't require relocation, why does external2 being an external symbol mean it has to now do a look up via GOT an plt even though the symbol is within the same translation unit? Why can't it just do a normal offset call like it does for the internals

A: Out of curiosity, let's see what the compiler does when you try to just compile (not even link) the same code with most optimizations enabled. This often exposes situations where the compiler's hands are tied. Also, compilers can afford to be very sloppy/lazy in O0, so I avoid reading too much into it.
Compiling libtest.cpp with -O3 -fPIC -c yields:
external2(int, int):
        ret
external(int, int):
        jmp     external2(int, int)@PLT

see on godbolt: https://gcc.godbolt.org/z/CnRVEX
This is very interesting: GCC can obviously tell that external2() is a no-op, yet it still calls it under O3.
What can we conclude from this? That invoking external2() will not necessarily execute the code in the TU's version of external2(). But how is this possible? ODR should allow us to assume that any external2() in the same binary is at worse equivalent to the one in this TU.
This is true at the C++ level, but Linux does not load C++ code. It loads elfs, which play by a different set of rules. One of these rules is that you can use LD_PRELOAD to load symbols before the executable in order to intercept them. And by making the symbol external in PIC code, the linker interprets it as an overloadable symbol, which prevents inlining (in my example), as well as local jumps (in yours).


text:
Q: How to cast a Long value into a LongFilter? I am trying to cast a Long value (id) into the LongFilter of the class TagCriteria that uses private LongFilter postId; to create an object that I can use to query
public ResponseEntity<List<TagDTO>> getAllTags(TagCriteria criteria, Pageable pageable)

BUT I do not see how to do it as the Java Doc is not really clear to me.
public class TagCriteria implements Serializable {
    private static final long serialVersionUID = 1L;
    private LongFilter id;
    private StringFilter tagName;
    private LongFilter postId;

    public TagCriteria() {
    }
}

Filter class for Comparable types, where less than / greater than / etc relations could be interpreted. It can be added to a criteria class as a member, to support the following query parameters:
  fieldName.equals = 42
  fieldName.specified = true
  fieldName.specified = false
  fieldName.in = 43,42
  fieldName.greaterThan = 41
  fieldName.lessThan = 44
  fieldName.greaterOrEqualThan = 42
  fieldName.lessOrEqualThan = 44

Due to problems with the type conversions, the descendant classes should be used, where the generic type parameter is materialized.
Type parameters:
<FIELD_TYPE> the type of filter.

See also:
IntegerFilter
DoubleFilter
FloatFilter
LongFilter
LocalDateFilter
InstantFilter

Thanks for your help!

A: Try this:
Long longValue = 1L;
LongFilter longFilter = new LongFilter();
longFilter.setEquals(longValue);

If you need to call a REST Service, you can specify the value using queryParam.
For example, if you have a resource 'Person' with an attribute 'name', and you need to retrieve all people with name 'John':
api/person?name.equals=John


text:
Q: equilateral triangle in an ellipse A high-schooler I know was given the following problem:

In the ellipse $x^2+3y^2=12$ is inscribed an equilateral triangle. One of the triangle's vertices is at the point $(0,-2)$. Find the triangle's other vertices.

The book has one answer: $(\pm1.2\sqrt3,1.6)$. But I know of two more answers: $(0,2)$ and $(\pm\sqrt{12},0)$. Are there any more?

A: First of all, let's suppose that the points on the ellipse $(x_1,y_1),(x_2,y_2)$ are of the same distance from $(0,-2)$. We will get three equations from this assumption:
$$
\begin{cases}
x_1^2+3y_1^2=12 & (1)\\\\
x_2^2+3y_2^2=12 & (2)\\\\
x_1^2+(y_1+2)^2=x_2^2+(y_2+2)^2 & (3)
\end{cases}
$$
After substituting $x_1^2,x_2^2$ with $12-3y_1^2,12-3y_2^2$ in equation $(3)$ respectively, we will get $-2y_1^2+4y_1+16=-2y_2^2+4y_2+16$, which is equivalent to $(y_1-1)^2=(y_2-1)^2$. Now we will divide to two separate cases.
Case 1:
If $(y_1-1),(y_2-1)$ are of the same sign (positive or negative), we can infer that $y_1=y_2$, and after equating $(1),(2)$ we will get $x_1^2+3y_1^2=x_2^2+3y_2^2$, Hence $x_1^2=x_2^2$. So there are two options again
Subcase 1:
if $x_1=x_2$, then the two points are that same point. In this case the answer will depend on your definition of an equilateral triangle. if you consider a line as an equilateral triangle, then  every point on the ellipse will be a solution. If you will demand that the distance between all three (if we will consider the same point we got as two solutions) points will be the same, there is only one solution, that all the points will be $(0,-2)$. If you consider only triangles with three distinct points, we will have no solution in this case.
Subcase 2:
if $x_1=-x_2$, for simplicity i will denote $x_1=x\ y_1=y,\ x_2=-x,\ y_2=y$. The distance between the points $(x,y)$ and $(-x,y)$ is $2x$, and the distance between those two points to $(0,-2)$ is $\sqrt{x^2+(y+2)^2}$, so if we will require that this two length will be equal we will get the equation $4x^2=x^2+(y+2)^2$, and after substituting $x^2$ with $12-3y^2$ we will get
$$
0=9y^2-36+y^2+4y+4=10y^2+4y-32=2(y+2)(5y-8)
$$
If $y=2$, then we will be at the last case, other wise we will have $y=\frac{8}{5}=1.6$, $|x|=\sqrt{12-3y^2}=\frac{6}{5}\sqrt{3}=1.2\sqrt{3}$, so the two points will be $(\pm 1.2\sqrt{3},1.6)$ as in the book.
Case 2:
If the signs of $(y_1-1),(y_2-1)$ are opposite, we will get $y_1=2-y_2$. From equations $(1),(2)$ we will get $x_1^2-x_2^2=3(y_2^2-y_1^2)=3(y_2+y_1)(y_2-y_1)=12(y_2-1)=12(1-y_1)$. Now, if we will require that the distance between $(x_1,y_1),(x_2,y_2)$ equals to the distance between $(x_1,y_1),(0,-2)$ we could write
$$
\begin{align}
(x_1-x_2)^2+(y_1-y_2)^2 & =x_1^2+(y_1+2)^2\\\\
x_1^2+x_2^2-2x_1x_2+(2y_1-2)^2 & =x_1^2+y_1^2+4y_1+4\\\\
x_2^2-2x_1x_2+4y_1^2-8y_1+4 & =y_1^2+4y_1+4\\\\
-2x_1x_2+x_2^2+3y_1^2-12y_1 & =0\ \ /  {\color{gray}{because}\ 3y_1^2=12-x_1^2\ we\ will\ get}\\\\
-2x_1x_2+12+x_2^2-x_1^2-12y_1 & =0\ \ /  {\color{gray}{remember\  that}\ x_1^2-x_2^2=12(1-y_1)}\\\\
-2x_1x_2-12(1-y_1)+12(1-y_1) & =0\\\\
-2x_1x_2 & =0
\end{align}
$$
Thus $x_1$ or $x_2$ are vanishing. Without loss of generality i will assume that $x_1=0$.  From that we will get that $y_1=\pm 2$. Because $y_1+y_2=2$ and $y_2\leq 2$, we will conclude that $y_1\geq 0$ so $y_1=2$. Because $y_1+y_2=2$ we will get that $y_2=0$, so $x_2=\pm\sqrt{12}$, as you got as well.
Conclusion: All the solutions are $\left\{(1.2\sqrt{3},1.6),(-1.2\sqrt{3},1.6)\right\},\ \left\{(0,2),(\sqrt{12},0)\right\},\ \left\{(0,2),(-\sqrt{12},0)\right\}$.


text:
Q: How to make a popover point to a tableview cell I want a popover to point to a tableview, more specifically to the cell i have just selected.
I can get a popover to appear but dont know what to enter in the
CGRect popRect = CGRectMake();
to get it to point to the cell.
thanks

A: Try this:
[popover presentPopoverFromRect:cell.frame inView:tableView permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

Which asks for the popover to be presented from the cells frame in the context of the table view (the table view coordinate system).


text:
Q: Excel formula for first day of previous month I'm trying to write a formula for the first day of the previous month.
I'm using: =DATE(YEAR(TODAY()),MONTH(TODAY())-1,1)
It works today, but I don't think it will work in January, because the formula would then return the year as 2016, and I need it to return the previous year in that case.  Does anyone have a suggestion for how I can modify this so it will return Dec 1 of the previous year if the current date is sometime in January?

A: You could try
=EOMONTH(TODAY(),-2)+1


text:
Q: jQuery auto complete on select event not working I am using jQuery auto complete in my web site. I want go to the search result page when user click on the drop down option.. For that I used the "Select" event , but it doesn't fire during select event.
Any ideas ? here is the code
 $(function(){
var availableTags = [
            "ActionScript",
            "AppleScript",
            "Asp",
            "BASIC",
            "C",
            "C++",
            "Clojure",
            "COBOL",
            "ColdFusion",
            "Erlang",
            "Fortran",
            "Groovy",
            "Haskell",
            "Java",
            "JavaScript",
            "Lisp",
            "Perl",
            "PHP",
            "Python",
            "Ruby",
            "Scala",
            "Scheme"
        ];

         $('#autocomplete').autocomplete({
            source: availableTags,
                select: function(event,ui){
                    alert("Selected ");
                }
         });

A: Your missing the closing brackets for your $(function() { - you need to add }); at the end ..
$(function() {
    var availableTags = [
        "ActionScript",
        "AppleScript",
        "Asp",
        "BASIC",
        "C",
        "C++",
        "Clojure",
        "COBOL",
        "ColdFusion",
        "Erlang",
        "Fortran",
        "Groovy",
        "Haskell",
        "Java",
        "JavaScript",
        "Lisp",
        "Perl",
        "PHP",
        "Python",
        "Ruby",
        "Scala",
        "Scheme"
        ];
    $('#autocomplete').autocomplete({
        source: availableTags,
        select: function(event, ui) {
            alert("Selected ");
        }
    });
});  // added this

Then it works fine
Also ensure you have added the correct JS libraries and CSS
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.8.22/jquery-ui.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/smoothness/jquery-ui.css">


text:
Q: File Validation using ArcPy? I have a script which scans a directory and outputs basic raster data information such as the file name, format, number of bands, and etc. I need a way to make it so if the directory does not contain raster data (i.e., anything other than raster data), a message is displayed stating that the directory doesn't have the correct data type.
I know ArcPy has a Describe() function that I could use to determine the type of data in a folder, but am not sure how to implement it. This is what I have so far:
rasterList = arcpy.ListRasters("*", "ALL")
filesType = arcpy.DataType('RasterDataset') # Can use `DatasetType` as well.
                                            # I've tested this function to describe
                                            # raster data and ArcPy prints out
                                            # 'RasterDataset', that is why I have it
                                            # there in the brackets.
for name in rasterList:
    if rasterList == filesType:
        print ("\nFilename:"), name
    else:
        print ("This directory does not contain any raster data.")

Any suggestions?

A: How about something simple like:
if len(rasterList) == 0:
    print ("This directory does not contain any raster data.")
else:
    # Your raster processing code

The len() function calculates the length of the returned string/list, so if it returns 0 then you know nothing in the folder matched the criterion (in this case, being a raster). This way, if the folder contains any rasters (even if not every file is a raster) they will be processed.


text:
Q: react - componentWillReceiveProps not running So I am new to react and was wondering how I would create a page that passes in a few parameters and get a document according to those parameters.  However, when I try to use componentWillReceiveProps, I find that it does not run and I don't know why.  So can someone please explain in the simplest terms they can what is componentWillReceiveProps, when it runs and its purpose?  I have spent many hours on trying to read up on the react page but all of it seems like a whole new language to me since I only recently started react.  Can you also edit the code below so it works and I can see for myself how it works together with the other stuff (it helps me understand better when I see it for myself).
Below is the code for my page:
import React from "react";
import { Tracker } from "meteor/tracker";
import { Link } from "react-router-dom"

import Menu from "./Menu"
import { Notes } from "../methods/methods";

export default class fullSize extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      doc: {}
    };
  }
  componentwillMount() {
    Meteor.subscribe("notes");
  }
  componentWillReceiveProps(nextProps) {
    this.tracker = Tracker.autorun(() => {
      const doc = Notes.findOne(nextProps.match.params.noteId);
      this.setState({ doc })
    })
  }
  renderNote(){
    console.log(this.state.doc)
  }
  render(){
    return (

{this.renderNote()}

    )
  }
}

is it because I am trying to render the state before there is anything in it?  It feels like I am...thats my guess at least as to I get an empty object as the doc state.

A: Basic concept is we have these types of lifecycle methods:
1- Mounting Methods: (will get called only once for lifecyle of that component)
2- Updating Methods: (will get called whenever any update happen in the component)
3- Unmounting Method: (when component will unmount)

componentWillReceiveProps is a updating method, and will run only when any change happens to props values, it will not run on initial rendering, so you need to use both componentWillReceiveProps and componentDidMount method. componentDidMount will fetch the initial data and if that page receive new props then componentWillReceiveProps will fetch the new data.
componentWillReceiveProps:

componentWillReceiveProps() is invoked before a mounted component
  receives new props. React doesn't call componentWillReceiveProps with
  initial props during mounting. It only calls this method if some of
  component's props may update.

componentDidMount:

componentDidMount() is invoked immediately after a component is
  mounted. Initialization that requires DOM nodes should go here. If you
  need to load data from a remote endpoint, this is a good place to
  instantiate the network request. Setting state in this method will
  trigger a re-rendering.

Write it like this:
export default class fullSize extends React.Component{

  constructor(props){
    super(props);
    this.state = {
      doc: {}
    };
  }

  componentwillMount() {
    Meteor.subscribe("notes");
  }

  componentDidMount() {
    this.tracker = Tracker.autorun(() => {
      const doc = Notes.findOne(this.props.match.params.noteId);
      this.setState({ doc })
    })
  }

  componentWillReceiveProps(nextProps) {
    if(this.props.match.params.noteId != nextProps.match.params.noteId)
      this.tracker = Tracker.autorun(() => {
        const doc = Notes.findOne(nextProps.match.params.noteId);
        this.setState({ doc })
      })
  }

  renderNote(){
    console.log(this.state.doc)
  }

  render(){
    return (

{this.renderNote()}

    )
  }
}


text:
Q: Getting VLOOKUP() to default to closest date I have two tables shown in the link here.  I am trying to calculate columns J and K in the second table based on the row that has the closest date match in the first table.  To give you a better idea of what I'm trying to do, I have this formula for column J:
=F3-VLOOKUP(C3,'Agency Comps2'!B:G, 5, TRUE)
And this formula for column K:
=H3-VLOOKUP(C3,'Agency Comps2'!B:G,5,TRUE)
Where Agency Comps2 is the name of the first sheet that I'm trying to look up values in.
As you can see, the values I'm getting are either wrong, or #N/A.  I have been trying to find a way to make VLOOKUP() default to the closest date, but I can't seem to do so.  Can anyone help me get the values I'm looking for?

A: TRUE as the last parameter in Vlookup only works if the lookup range is sorted ascending.
From the screenshot it looks as if the dates may not be real dates. The green warning triangles raise some concerns.
Make sure that the dates are real dates, then the formula will work.