text:
Q: Sorting zend object When I do print_r($this->paginator); I get:
> Zend_Paginator Object ( [_cacheEnabled:protected] => 1
> [_adapter:protected] => Zend_Paginator_Adapter_DbSelect Object (
> [_countSelect:protected] => Zend_Db_Select Object ( [_bind:protected]
> => Array ( ) [_adapter:protected] => Zend_Db_Adapter_Pdo_Mysql Object ( [_pdoType:protected] => mysql [_numericDataTypes:protected] => Array
> ( [0] => 0 [1] => 1 [2] => 2 [INT] => 0 [INTEGER] => 0 [MEDIUMINT] =>
> 0 [SMALLINT] => 0 [TINYINT] => 0 [BIGINT] => 1 [SERIAL] => 1 [DEC] =>
> 2 [DECIMAL] => 2 [DOUBLE] => 2 [DOUBLE PRECISION] => 2 [FIXED] => 2
> [FLOAT] => 2 ) [_defaultStmtClass:protected] => Zend_Db_Statement_Pdo
> [_config:protected] => Array ( [host] => localhost [username] =>
> zagadkikinowe [password] => rdh2jhyTs [dbname] => zagadkikinowe
> [charset] => utf8 [persistent] => [options] => Array ( [caseFolding]
> => 0 [autoQuoteIdentifiers] => 1 ) [driver_options] => Array ( [1002] => SET NAMES 'utf8' ) ) [_fetchMode:protected] => 2 [_profiler:protected] => Zend_Db_Profiler Object (
> [_queryProfiles:protected] => Array ( ) [_enabled:protected] =>
> [_filterElapsedSecs:protected] => [_filterTypes:protected] => )
> [_defaultProfilerClass:protected] => Zend_Db_Profiler
> [_connection:protected] => PDO Object ( ) [_caseFolding:protected] =>
> 0 [_autoQuoteIdentifiers:protected] => 1
> [_allowSerialization:protected] => 1
> [_autoReconnectOnUnserialize:protected] => ) [_parts:protected] =>
> Array ( [distinct] => [columns] => Array ( [0] => Array ( [0] =>
> user_answer [1] => Zend_Db_Expr Object ( [_expression:protected] =>
> COUNT(1) AS `zend_paginator_row_count` ) [2] => ) ) [union] => Array (
> ) [from] => Array ( [user_answer] => Array ( [joinType] => from
> [schema] => [tableName] => user_answer [joinCondition] => ) ) [where]
> => Array ( [0] => (edition_id='22') [1] => AND (answer_type = "close") ) [group] => Array ( ) [having] => Array ( ) [order] => Array ( )
> [limitcount] => [limitoffset] => [forupdate] => )
> [_tableCols:protected] => Array ( ) ) [_select:protected] =>
> Zend_Db_Select Object ( [_bind:protected] => Array ( )
> [_adapter:protected] => Zend_Db_Adapter_Pdo_Mysql Object (
> [_pdoType:protected] => mysql [_numericDataTypes:protected] => Array (
> [0] => 0 [1] => 1 [2] => 2 [INT] => 0 [INTEGER] => 0 [MEDIUMINT] => 0
> [SMALLINT] => 0 [TINYINT] => 0 [BIGINT] => 1 [SERIAL] => 1 [DEC] => 2
> [DECIMAL] => 2 [DOUBLE] => 2 [DOUBLE PRECISION] => 2 [FIXED] => 2
> [FLOAT] => 2 ) [_defaultStmtClass:protected] => Zend_Db_Statement_Pdo
> [_config:protected] => Array ( [host] => localhost [username] =>
> zagadkikinowe [password] => rdh2jhyTs [dbname] => zagadkikinowe
> [charset] => utf8 [persistent] => [options] => Array ( [caseFolding]
> => 0 [autoQuoteIdentifiers] => 1 ) [driver_options] => Array ( [1002] => SET NAMES 'utf8' ) ) [_fetchMode:protected] => 2 [_profiler:protected] => Zend_Db_Profiler Object (
> [_queryProfiles:protected] => Array ( ) [_enabled:protected] =>
> [_filterElapsedSecs:protected] => [_filterTypes:protected] => )
> [_defaultProfilerClass:protected] => Zend_Db_Profiler
> [_connection:protected] => PDO Object ( ) [_caseFolding:protected] =>
> 0 [_autoQuoteIdentifiers:protected] => 1
> [_allowSerialization:protected] => 1
> [_autoReconnectOnUnserialize:protected] => ) [_parts:protected] =>
> Array ( [distinct] => [columns] => Array ( [0] => Array ( [0] =>
> user_answer [1] => * [2] => ) ) [union] => Array ( ) [from] => Array (
> [user_answer] => Array ( [joinType] => from [schema] => [tableName] =>
> user_answer [joinCondition] => ) ) [where] => Array ( [0] =>
> (edition_id='22') [1] => AND (answer_type = "close") ) [group] =>
> Array ( ) [having] => Array ( ) [order] => Array ( [0] => Array ( [0]
> => time [1] => ASC ) ) [limitcount] => 25 [limitoffset] => 0 [forupdate] => ) [_tableCols:protected] => Array ( ) )
> [_rowCount:protected] => 6 ) [_currentItemCount:protected] => 6
> [_currentItems:protected] => ArrayIterator Object ( [0] => Array (
> [id] => 9611 [edition_id] => 22 [uid] => 1429046328 [city_id] => 41
> [time] => 1346330264 [answer] => [answer_type] => close [winner] => 0
> [canwin] => 1 [name] => xxx ) [1] => Array ( [id] => 9613
> [edition_id] => 22 [uid] => 100002892496926 [city_id] => 41 [time] =>
> 1346330506 [answer] => [answer_type] => close [winner] => 0 [canwin]
> => 1 [name] => xxx ) [2] => Array ( [id] => 9618 [edition_id] => 22 [uid] => 1321291427 [city_id] => 41 [time] =>
> 1346352999 [answer] => [answer_type] => close [winner] => 0 [canwin]
> => 1 [name] => xxxi ) [3] => Array ( [id] => 9648 [edition_id] => 22 [uid] => 100002256926555 [city_id] => 41 [time] =>
> 1346673357 [answer] => [answer_type] => close [winner] => 0 [canwin]
> => 1 [name] => xxx ) [4] => Array ( [id] => 9649 [edition_id] => 22 [uid] => 1362180726 [city_id] => 41 [time] =>
> 1346674240 [answer] => [answer_type] => close [winner] => 0 [canwin]
> => 1 [name] => xxxk ) [5] => Array ( [id] => 9650 [edition_id] => 22 [uid] => 1047795693 [city_id] => 41 [time] =>
> 1346675955 [answer] => [answer_type] => close [winner] => 0 [canwin]
> => 0 [name] => xxx ) ) [_currentPageNumber:protected] => 1 [_filter:protected] => [_itemCountPerPage:protected] => 25 [_pageCount:protected] => 1 [_pageRange:protected] => 10
> [_pages:protected] => stdClass Object ( [pageCount] => 1
> [itemCountPerPage] => 25 [first] => 1 [current] => 1 [last] => 1
> [pagesInRange] => Array ( [1] => 1 ) [firstPageInRange] => 1
> [lastPageInRange] => 1 [currentItemCount] => 6 [totalItemCount] => 6
> [firstItemNumber] => 1 [lastItemNumber] => 6 ) [_view:protected] => )

And I need to sort it asc by [time] where [canwin]==1
How to do it? I'm not good at zend, and it takes me a lot of hours, and still and don't have idea how to do it

A: Zend_Paginator uses a db adapter, so you can just add an order() statement to the adapter:
$adapter = new Zend_Paginator_Adapter_DbSelect($db->select()->from('posts'));
    $adapter->setRowCount(
        $db->select()
           ->from(
                'item_counts',
                array(
                   Zend_Paginator_Adapter_DbSelect::ROW_COUNT_COLUMN => 'post_count'
                )
             )->order(...order criteria here...)
    );

    $paginator = new Zend_Paginator($adapter);


text:
Q: How can I determine when a record is being inserted/updated from AIF? I have a customer-sync built that syncs AX customers with an external system's customers.
When an update/insert is performed on the external system, it dumps an AIF file that gets processed.
I want to put some logic in the table method CustTable.insert() and CustTable.update() so that when anything is inserted/updated it will push up the the external system, which works fine.
The problem is when a user makes a change in the external system, it makes the AIF file, which then inserts/updates in AX, then pushes a change back up to the external system.
How can I determine when a custTable insert/update is being performed from an AIF process?  Pseudo code I'm looking for would be like this in the Tables\CustTable\Methods\insert():
// Pseudo code
if (this.isFromAIF() == false)
{
   this.syncRecordToExternalSystem();
}

A: This is a very difficult question.  As @ian_socho said you can create a custom flag that only the AIF sets.  The "createdby" user wouldn't work because the AIF does impersonation.
I did experiment and found some interesting properties.  It seems like AIF operations execute in the CIL as a worker thread, but the worker thread seems to be spun up by the AOS, so there is no masterSessionId that I can tell.
This code will tell you if something has maybe been called from the AIF.  I tested with SysOpFramework that spins up worker threads, and they all have a master thread. I tested with a visual studio project and it has a master session.
xSession    xSession = new xSession(sessionId());

if (xSession.masterSessionId()  == 0        &&
    xSession.isWorkerThread()   == true     &&
    xSession.clientKind()       == ClientType::WorkerThread)
{
    // Appears to have been called from AIF
    return true; // AIF call
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to reverse-convert a vector of time zones I have this database of time stamps (AlertTime), and I know what time zone these are in (TimeZone). I know how to set these date to POSIXCT or if they were all UTC, but I'm struggling to get them identified as their local time stamps because most functions don't accept a vector for tz.
I do need both the local time stamp properly formatted (AlertTimeLocal) and the UTC equivalent (AlertTimeUTC).
AlertTime               TimeZone                AlertTimeLocal (desired)  AlertTimeUTC (desired)
11 May 2020, 06:22 PM   America/Denver          2020-05-11 18:22:00 MDT   2020-05-12 00:22:00 MDT
11 MAY 2020, 04:11 AM   America/Los_Angeles     2020-05-11 04:11:00 PDT   2020-05-11 11:11:00 UTC
10 MAY 2020, 03:38 PM   America/Chicago         2020-05-10 15:38:00 CDT   2020-05-10 20:38:00 CDT

I was using this code but it doesn't seem to do anything anymore:
FreshAir$AlertTimeLocal <- mapply(function(x,y) {format(x, tz=y, usetz=TRUE)}, FreshAir$AlertTime, FreshAir$TimeZone)

Would a hacky solution be to set all the RAW time stamps to UTC, then convert them to the equivalent time zone in the other direction?

A: We can use force_tzs from lubridate
library(lubridate)
library(dplyr)
df1 %>%
    mutate(AlertTimeLocal = dmy_hm(AlertTime),
           AlertTimeUTC = force_tzs(AlertTimeLocal, tzones = TimeZone))
# AlertTime            TimeZone      AlertTimeLocal        AlertTimeUTC
#1 11 May 2020, 06:22 PM      America/Denver 2020-05-11 18:22:00 2020-05-12 00:22:00
#2 11 MAY 2020, 04:11 AM America/Los_Angeles 2020-05-11 04:11:00 2020-05-11 11:11:00
#3 10 MAY 2020, 03:38 PM     America/Chicago 2020-05-10 15:38:00 2020-05-10 20:38:00

Update
If we need to store as separate time zones, we can use a list column
library(purrr)
df2 <- df1 %>%
         mutate(AlertTime2 = dmy_hm(AlertTime),
         AlertTimeUTC = force_tzs(AlertTime2, tzones = TimeZone),
         AlertTimeLocal = map2(AlertTime2, TimeZone, ~ force_tz(.x, tzone = .y)))

df2$AlertTimeLocal
#[[1]]
#[1] "2020-05-11 18:22:00 MDT"

#[[2]]
#[1] "2020-05-11 04:11:00 PDT"

#[[3]]
#[1] "2020-05-10 15:38:00 CDT"

data
df1 <- structure(list(AlertTime = c("11 May 2020, 06:22 PM",
       "11 MAY 2020, 04:11 AM",
"10 MAY 2020, 03:38 PM"), TimeZone = c("America/Denver",
"America/Los_Angeles",
"America/Chicago")), class = "data.frame", row.names = c(NA,
-3L))

A: I think a tidy solution might look cleaner, but if you want a base R solution, here's an alternative using @akrun's df1:
df1$AlertTimeLocal <- df1$AlertTimeUTC <-
  c.POSIXct(Map(as.POSIXct, df1$AlertTime, tz = df1$TimeZone, format = "%d %b %Y, %I:%M %p"))
attr(df1$AlertTimeUTC, "tzone") <- "UTC"
attr(df1$AlertTimeLocal, "tzone") <- "US/Mountain"
df1
#               AlertTime            TimeZone        AlertTimeUTC      AlertTimeLocal
# 1 11 May 2020, 06:22 PM      America/Denver 2020-05-12 00:22:00 2020-05-11 18:22:00
# 2 11 MAY 2020, 04:11 AM America/Los_Angeles 2020-05-11 11:11:00 2020-05-11 05:11:00
# 3 10 MAY 2020, 03:38 PM     America/Chicago 2020-05-10 20:38:00 2020-05-10 14:38:00

Something that has not been discussed, though: in R, you cannot have different time zones within one vector of POSIXt. That is, in a vector, time zone is an attribute of the vector, not of the element. If you need individual time zones for each time in that column, you'll need to do a list-column. This works but is not always supported well by utilities/functions that work on data.frame.


text:
Q: How to handle (Google Forms - Spreadsheet) "Checkboxes" answers in SPSS I am analyzing an electronic survey I made using Google Forms and I have the following problem.
One of the questions can take multiple answers in the form of Checkboxes as shown in the picture below. The question is in Greek so I have added some Choice1, Choice2, Choice3 etc next to each answer in order to facilitate my question.

In my data when someone chose lets say Choice1 and Choice2,
I will have an answer which is the concatenation of the strings he checked seperated with commas.
In this case it would be:

Choice1, Choice2

If someone else checked Choice1, Choice2 and Choice4
his answer in my data would be:

Choice1, Choice2, Choice4

The problem is SPSS has no way of seperating the substrings (seperated by commas) and understanding which Choices each case has in common. Or maybe there is a way but I don't know it :)
When I, for example, do a simple frequency analysis for this question it produces a table that perceives

Choice1, Choice2

as a completely different case from

Choice1, Choice2, Choice4

Ideally I would like to somehow tell SPSS to count the frequency of each unique Choice (Choice1, Choice2, Choice3 etc etc) rather than each unique combination of those Choices.
Is that possible? And if it is can you point me to the documentation I need to study to make it happen?
Thx a lot!

A: Unfortunately there is no easy "built-in" way to achieve this, but it is certainly achievable with spreadsheet formulae, or Google Apps Script.
Using formulae, assuming your check box question lands in column D, this will produce a "normalised" list:
=ArrayFormula(TRANSPOSE(SPLIT(CONCAENATE(D2:D&",");",")))
and you can turn that into a two-column list and QUERY it to return a table of frequencies:
=ArrayFormula(QUERY(TRANSPOSE(SPLIT(CONCATENATE(D2:D&",");","))&{"",""};"select Col1, count(Col2) group by Col1 label Col1 'Item', count(Col2) 'Frequency'";0))
If your locale uses a comma as a decimal separator, replace {"",""} with {""\""}.

A: Imagine you are working with the following data, which is a CSV file you have downloaded from your online form. Copy and paste the text below and save it to a text file named "CourseInterestSurvey.CSV".
Timestamp,Which courses are you interested in?,What software do you use?
12/28/2012 11:57:56,"Research Methods, Data Visualization","Gnumeric, SPSS, R"
12/28/2012 11:58:09,Data Visualization,"SPSS, Stata, R"
12/28/2012 11:59:09,"Research Dissemination, Graphic Design",Adobe InDesign
12/28/2012 11:59:27,"Data Analysis, Data Visualization, Graphic Design","Excel, OpenOffice.org/Libre Office, Stata"
12/28/2012 11:59:44,Data Visualization,"R, Adobe Illustrator"

Read it into SPSS using the following syntax:
GET DATA
  /TYPE=TXT
  /FILE="path\to\CourseInterestSurvey.CSV"
  /DELCASE=LINE
  /DELIMITERS=","
  /QUALIFIER='"'
  /ARRANGEMENT=DELIMITED
  /FIRSTCASE=2
  /IMPORTCASE=ALL
  /VARIABLES=
  Timestamp A19
  CourseInterest A49
  Software A41.
CACHE.
EXECUTE.
DATASET NAME DataSet2 WINDOW=FRONT.
LIST.

It currently looks like the image below--three columns (one timestamp, and two with the data we want):

Working with some syntax from here, we can split the cells up as follows:
* We know the string does not excede 50 characters.
* We got that information while we were reading our data in.
STRING #temp(a50).
* We're going to work on the "CourseInterest" variable.
COMPUTE #temp=CourseInterest.
* We're going to create 3 new variables with the prefix "CourseInterest".
* You should modify this according to the actual number of options your data has
* and the maximum length of one of the strings in your data.
VECTOR CourseInterest(3, a25).
* Here's where the actual variable creation takes place.
LOOP #i = 1 TO 3.
.  COMPUTE #index=index(#temp,",").
.  DO IF   #index GT 0.
.    COMPUTE CourseInterest(#i)=LTRIM(substr(#temp,1, #index-1)).
.    COMPUTE #temp=substr(#temp, #index+1).
.  ELSE.
.    COMPUTE CourseInterest(#i)=LTRIM(#temp).
.    COMPUTE #temp=''.
.  END IF.
END LOOP IF #index EQ 0.
LIST.

The result:

This only addresses one column at a time, and I'm not familiar enough to modify it to work over multiple columns. However, if you were to switch over to R, I already have some readymade functions to help deal with exactly these kinds of situations.

A: It is easy to split the fields into separate variables as described above.  Now define these variables as a multiple response set (Analyze > Tables > Multiple Response Sets), and you can analyze these with the CTABLES or MULT REPONSE procedures and graph them using the Chart Builder


text:
Q: How to prove the number of unlabeled binary trees is the same as the number of BSTs possible How to prove that the number of unlabeled binary trees is the same as the number of Binary Search Tree possible. I know the number of binary search tree is equal to nth catalan number but how would I prove that this is equal to the number of unlabeled binary tree.

A: HINT: There are a couple of reasonable approaches.

*

*You could show that if $T$ is a binary tree with $n$ nodes, there is only one way to label the nodes $1,\ldots,n$ that makes $T$ a binary search tree. This isn't too hard. Start at the root. If there are $\ell$ nodes in its left subtree, the only possible number to assign to it is $\ell+1$; why?

*You could show directly that there are $C_n$ binary trees on $n$ nodes. This is most easily done by induction on the number of nodes, using the fact that $C_{n+1}=\sum_{k=0}^nC_kC_{n-k}$, with $C_0=1$.


text:
Q: Dependency Checker with TeamCity and SonarQube for .Net Framework and .Net Core I'm having an issue sending the Dependency Checker output from the build agent to the SonarQube server.
I'm not sure if it's the commands I use with Dependency Checker or the SonarQube setup on the server / client side. I get scan outputs reported into SonarQube for .cs, .js, .css etc .. but the output from the dependency scan is not visible in the dependency checker widget. However, if I check the work folder for the particular build, there are three files that has been created from the owasp dependency checker which haven't been picked up.
What I've done to prepare before doing the scan:

*

*Downloaded OWASP dependency-check-cli from https://jeremylong.github.io/DependencyCheck/dependency-check-cli/index.html

*Extracted OWASP dependency-check-cli to a directory and added the Path as an environment value on the build agent server

*Installed the Dependency checker plugin on SonarQube via the marked place

*Installed the sonarscanner on the build agent server via the build agent
service account

*Removed the ${Workspace}/ value from the report fields in the dependency check plugin in SonarQube

*

*The value is now just dependency-check-report.html/json/xml (pending on the field).

The command I used to install the dotnet-sonarscanner via .Net Core:
dotnet tool install --global dotnet-sonarscanner

The OWASP dependency-check-cli command (running from the root of checkoutDir on the build agent):
dependency-check.bat --project "%system.teamcity.projectName%" --scan . -f ALL --log D:\DependencyLogs\verbose.log

In order for the RetireJs functionality to work, I had to debug the log and download directly the json file which couldn't be retrieved directly. I think I need to add overrides for the proxy for https as well by using java parameters (/d:)
The Sonar Scanner begin command:
dotnet sonarscanner begin /k:%ProjectKey% /n:"%ProjectName%" /d:sonar.login=%SonarQube.UserToken% /d:sonar.host.url=%SonarQube.Host.Url%"

If I f.ex add the parameter /d:sonar.dependencyCheck.xmlReportPath=%system.teamcity.checkoutDir%/dependency-check-report.xml, it is resolved to the checkoutdir with an added /src/ behind of dependency-check-report.xml
The Sonar Scanner end command:
dotnet sonarscanner /d:sonar.login=%SonarQube.UserToken% end

If I add
%system.teamcity.build.workingDir%/dependency-check-report.html

to html, xml or json field in the plugin properties in sonarqube:
[23:19:08]  [Step 1/1] INFO: Dependency-Check JSON report does not exists. Please check property sonar.dependencyCheck.jsonReportPath:D:\TeamCityBuildAgent\work\a7450333ae6fcf0c\%system.teamcity.build.workingDir%\dependency-check-report.json
[23:19:08]  [Step 1/1] INFO: JSON-Analysis skipped/aborted due to missing report file
[23:19:08]  [Step 1/1] INFO: Using XML-Reportparser
[23:19:08]  [Step 1/1] INFO: Dependency-Check XML report does not exists. Please check property sonar.dependencyCheck.xmlReportPath:D:\TeamCityBuildAgent\work\a7450333ae6fcf0c\%system.teamcity.build.workingDir%\dependency-check-report.xml
[23:19:08]  [Step 1/1] INFO: XML-Analysis skipped/aborted due to missing report file
[23:19:08]  [Step 1/1] INFO: Dependency-Check HTML report does not exists. Please check property sonar.dependencyCheck.htmlReportPath:D:\TeamCityBuildAgent\work\a7450333ae6fcf0c\%system.teamcity.build.workingDir%\dependency-check-report.html
[23:19:08]  [Step 1/1] INFO: HTML-Dependency-Check report does not exist.

if I remove the workingdir, so it looks like this in sonarqube:
dependency-check-report.html

The output looks like this:
[23:26:38]  [Step 1/1] INFO: Sensor Dependency-Check [dependencycheck]
[23:26:38]  [Step 1/1] INFO: Process Dependency-Check report
[23:26:38]  [Step 1/1] INFO: Using JSON-Reportparser
[23:26:39]  [Step 1/1] WARN: JSON-Analysis aborted
[23:26:39]  [Step 1/1] INFO: Using XML-Reportparser
[23:26:39]  [Step 1/1] INFO: We doesn't found any Project configuration file e.g. pom.xml, gradle.build, build.gradle.kts, package-lock.json and can not link dependencies
[23:26:39]  [Step 1/1] INFO: Linking 662 dependencies to project
[23:26:39]  [Step 1/1] INFO: Upload Dependency-Check HTML-Report
[23:26:39]  [Step 1/1] INFO: Process Dependency-Check report (done) | time=959ms
[23:26:39]  [Step 1/1] INFO: Sensor Dependency-Check [dependencycheck] (done) | time=960ms

So that should have worked. The Dependency-Check HTML is completed and uploaded, but when I look at the dependencies reported in SonarQube, the view is empty. What am I missing ..?
The output is there though:

A: Currently the official plugin to SonarQube (version 2.0.2), has a bug which does not show the html result.
If you want it to work, you currently need to get the latest snapshot from this branch
https://github.com/dependency-check/dependency-check-sonar-plugin/tree/rewrite_javascript


text:
Q: EXC_BAD_ACCESS when assigning an Objective-C pointer to a member of a C struct Sometimes but not always I'm getting an EXC_BAD_ACCESS crash assigning an NSMutableDictionary to a struct. I'm obviously doing something wrong but I have no idea what.
typedef struct {

    ...
    NSMutableDictionary* headers;
    ...

} custom_data_t;

...

- (void)method {

    custom_data_t* customData = malloc(sizeof(custom_data_t));
    customData->headers = [NSMutableDictionary new]; // <- EXC_BAD_ACCESS (code=EXC_I386_GPFLT)

}

A: First, avoid allocating any C structure which has pointers to Objective-C objects with malloc. It tends to be a problem, because ARC tries to release whatever is set to an ARC-managed pointer when it's not nil upon assigning new values (and since malloc does not zero member variables of the structure object, the pointers may point to some garbage, which ARC will try to release. This is where EXC_BAD_ACCESS error happens). Instead you should use calloc which ensures that all member variables are zero-initialised:
custom_data_t* customData = calloc(1, sizeof(custom_data_t));

Second, while using calloc you should be advised that ARC cannot properly release member variables (because it doesn't know exact length of the pointer), so before freeing a C structure memory, you also need to nullify all its ARC managed pointers:
customData->headers = [NSMutableDictionary new];
// .. some time later ..
customData->headers = nil;
free(customData);


text:
Q: Путь до html файла на хостинге Как я могу определить путь до html файла на хостинге через инструменты разработчика, особенно когда сайт интегрирован в какую нибудь запутанную CMS, это становится проблемой для меня,
до css и js файлов добираюсь относительно легко, а с html проблемы.


text:
Q: Standard input file format and parser for Java? I am trying to use Java to read the parameters for a problem instance from an input file.
for example, suppose a problem is defined by the three parameters seasonality, prices and elasticity, each of which are arrays.
Is there a standard file format for input files? It could look like the one below, or it could have another standard format.
seasonality
10 11 12 13 14 15
prices
10 9 8 7
elasticity
-4 2 1

Is there a standard library or parser which will automatically parse such input files?
Clarification in response to comments
For my purposes, it would be perfect if the Reader class returns a List mapping each parameter to the parameter value which can be either an array or a scalar.
A second class can read the Reader class to create a Problem instance using the parameters defined in the Reader class.

A: For this problem, I suggest using a Map<String,List<Integer> and the sample format you showed. Open a Scanner on your input file, read a String to be the key, and then read ints until you run out. Repeat until EOF.

A: Based on chrylis answer, I created a class that parses such files with each parameter and value separated by whitespace.
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

/**
 * Read an input file which has multiple parameters, where the
 * name of each is a string not equal to a number, and is followed
 * by the a scalar or array of integers or doubles.
 * Each parameter and number is separated by white space.
 */
public class NumberParser {

    public static Map<String, Object> parse(String file) throws Exception {
        Scanner scanner = new Scanner(new File(file));

        Map<String, Object> map = new HashMap<String, Object>();

        while (scanner.hasNext()) {
            String parameter = scanner.next();

            if (scanner.hasNextInt()) {
                List<Integer> list = new LinkedList<Integer>();
                while (scanner.hasNextInt()) {
                    list.add(scanner.nextInt());
                }
                map.put(parameter, listToIntArray(list));
            } else { // double array
                List<Double> list = new LinkedList<Double>();
                while (scanner.hasNextDouble()) {
                    list.add(scanner.nextDouble());
                }
                map.put(parameter, listToDoubleArray(list));
            }
        }

        scanner.close();

        return map;
    }

    private static int[] listToIntArray(List<Integer> list) {
        int[] array = new int[list.size()];
        int i = 0;
        for (Iterator<Integer> itr = list.iterator(); itr.hasNext(); ++i) {
            array[i] = itr.next();
        }
        return array;
    }

    private static double[] listToDoubleArray(List<Double> list) {
        double[] array = new double[list.size()];
        int i = 0;
        for (Iterator<Double> itr = list.iterator(); itr.hasNext(); ++i) {
            array[i] = itr.next();
        }
        return array;
    }

}


text:
Q: Jquery attr() funciton returning "undefined" for GetCapabilities Request On my webpage where I am displaying my maps, I want to add a link to the metadata of the selected map.
I have specified the link in GeoServer in the MetaDataURL field, and should be able to retrieve it with a GET request and finding it in the XML(See below for XML and Jquery code)
But every time I test it I get "undefined"...which is very strange, it seems as if the attribute doesn't even exist. Does anyone have a clue why it returns "undefined"
$.ajax({
        type: "GET",
        url: "http://fast.openearth.eu/geoserver/wms?service=wms&version=1.1.1&request=GetCapabilities",
        dataType: "xml",
                       success: function(xml) {
                                               $(xml).find('Layer').each(function(){
                                                     if ($(this).children("Title").text() == layer.name) {
MetaDataURL = $(this).children("MetadataURL").children("OnlineResource").attr("xlink:href");
}});}});

<Layer queryable="1">
                                                                                <Name>Global:wcmc-010-mangroveusgs2011</Name>
<Title>Mangrove USGS2011</Title>
<Abstract>Giri C, Ochieng E, Tieszen LL, Zhu Z, Singh A, Loveland T, Masek J, Duke N (2011).
    Status and distribution of mangrove forests of the world using earth observation
    satellite data. Global Ecology and Biogeography 20: 154-159. URL:
    http://onlinelibrary.wiley.com/doi/10.1111/j.1466-8238.2010.00584.x/abstract ;
    http://data.unep-wcmc.org/datasets/4</Abstract>
<KeywordList>
<Keyword>wcmc-010-mangroveusgs2011</Keyword>
<BoundingBox CRS="CRS:84" minx="-180.537994384766" miny="-35.6819496154785" maxx="181.735992431641" maxy="30.3975315093994"/>
<BoundingBox CRS="EPSG:4326" minx="-35.6819496154785" miny="-180.537994384766" maxx="30.3975315093994" maxy="181.735992431641"/>
<MetadataURL type="ISO19115:2003">
<Format>text/plain</Format>
<OnlineResource xlink:type="simple" xlink:href="http://fast.openearth.eu/geonetwork/srv/eng/metadata.show?id=39&currTab=simple"/>
</MetadataURL>


text:
Q: How to generate different sizes of icons from .psd? iOS app needs different sizes of icons to fit different screens, so after we design an icon with psd format, we will have to generate many icons(29px*29px,40px*40px,...), which is a tedious task.
How to batch generate them at a time?

A: You can do this by Actions...
in Actions tab click record and do the task... photoshop will record it and next time you went to do this again just click on "Play" icon
Hope its helpful

A: If you have Photoshop CC you can generate image assets  from Layers.
For example if you set this name to a Layer:
29px x 29px icon29x29.png, 40px x 40px icon40x40.png, 128px x 128px icon128x128.png

Will generates these image assets:

*

*icon29x29.png

*icon40x40.png

*icon128x128.png

With these specific sizes.


text:
Q: API tracking code integration in front-end orderdetails (Woocommerce) I have a woocommerce shop and have a third-party logistic company with API. By this API I will receive a tracking code for the shipped order. I have a php file for getting a tracking code through API. Does anybody know how can I use this file to add this tracking code to the customer's front-end account in Order details section. (The tracking code already appears in order details of admin panel).
The code is:
    // print_r($order_ids);die;
$tracking_header = array('Content-Type:application/x-www-form-urlencoded', 'apikey:' . API_KEY,);
$tracking_url = "http://";
$tracking = _curlRequest($tracking_url, "POST", json_encode($order_ids), $tracking_header);
$tracking = json_decode($tracking, true);

if ( empty($tracking['data']) || $tracking['code'] == 4  ) {
echo json_encode(array("code" => 4, "msg" => "There are no orders to sync!", "data" => null));return;
} elseif ($tracking['code']) {
echo json_encode(array("code" => 5, "msg" => "There was an error getting the order information!", "data" => null));return;
}
// print_r($tracking);die;
$error = "";
foreach($tracking['data'] as $k=>$v){
$info = json_decode($v['info'],true);
$order_id = $v['order_id'];
if(empty($info)){
continue;
}
if(PREFIX !== 'your prefix' && PREFIX !== ''){
$order_id = substr($order_id,strlen(PREFIX));
}
$sql = "SELECT pm.meta_value as sku FROM {$db_prefix}postmeta as pm WHERE pm.meta_key='_sku' AND pm.post_id in (SELECT oim.meta_value FROM {$db_prefix}woocommerce_order_itemmeta as oim LEFT JOIN {$db_prefix}woocommerce_order_items as oi ON (oi.order_item_id = oim.order_item_id AND (oim.meta_key='_product_id' OR oim.meta_key='_variation_id')) WHERE oi.order_item_type='line_item' AND oi.order_id ={$order_id})";
$order_sku = $wpdb->get_results($sql,ARRAY_A);
if(!empty($order_sku)){
$new_sku = array();
foreach($order_sku as $val){
if(!empty($val['sku'])){
$new_sku[] = $val['sku'];
}
}
$sync_sku = array();
foreach($info as $ik=>$iv){
if($iv['sku']&& in_array($iv['sku'],$new_sku)){
$sync_sku[] = $iv['sku'];
}
}
if(!empty($sync_sku)){
if($v['shipping_method']){
if(!$wpdb->get_row("SELECT * FROM {$db_prefix}woocommerce_order_items WHERE order_id={$order_id} AND order_item_type='shipping' ", ARRAY_A)){
$data = array(
'order_item_name'=>$v['shipping_method'],
'order_item_type'=>'shipping',
'order_id'=>$order_id
);
$wpdb->insert("{$db_prefix}woocommerce_order_items",$data);
}
}
if($v['tracking_number']){
$order_items = $wpdb->get_row("SELECT * FROM {$db_prefix}woocommerce_order_items WHERE order_id={$order_id} AND order_item_type='shipping' ", ARRAY_A);
if($order_items && !$wpdb->get_row("SELECT * FROM {$db_prefix}woocommerce_order_itemmeta WHERE order_item_id={$order_items['order_item_id']} AND meta_key='tracking_number' ", ARRAY_A)){
$data = array(
            'order_item_id'=>$order_items['order_item_id'],
            'meta_key'=>'tracking_number',
            'meta_value'=>$v['tracking_number']
        );
        if(!$wpdb->insert("{$db_prefix}woocommerce_order_itemmeta",$data)){
          $error .= $v['order_id'].",";
        }

      }

    }
  }else{

    $error .= $v['order_id'].",";
  }

}

}

if($error){
 $errorders = substr($error,0,-1);
echo json_encode(array("code" => 6, "msg" => "Can synchronize but synchronize failed orders:{$errorders}", "data" => null));return;
}

echo json_encode(array("code" => 0, "msg" => "Success", "data" => null));return;

A: I found the solution:
Add the following code in order-details-item.php
foreach( $order->get_items('shipping') as $item ){
    echo $item->get_meta('tracking_number');
}

But now I have a question, how to make this tracking_number wrapped in URL?
In the following manner that the URL contain https://someaddres&=tracking_number
I resolved this issue.


text:
Q: Is there any performance penalty building go program using -race flag? Hi I was wondering if there any performance penalty running a go program in production built using
go build -race

A: You can read about it in the article post that describes the go race detector at https://go.dev/doc/articles/race_detector
Quoting from that article (the last paragraph) :

Runtime Overhead
The cost of race detection varies by program, but for a typical program, memory usage may increase by 5-10x and execution time by
2-20x.
The race detector currently allocates an extra 8 bytes per defer and
recover statement. Those extra allocations are not recovered until the
goroutine exits. This means that if you have a long-running goroutine
that is periodically issuing defer and recover calls, the program
memory usage may grow without bound. These memory allocations will not
show up in the output of runtime.ReadMemStats or runtime/pprof.


text:
Q: Tempvars resetting to null when multithreading I have a function that I use to multithread some Access VBA routines. It does this by writing a vb script which saves a copy of the main Access database then opens it in another instance of access. when open it runs a defined routine specified in the vb script. this works well but I have some routines where I need to pass variables to them from the main function. I was intending to use Tempvars to do this.
the main function sets up the tempvar (complete with initial values), but when the new access instance goes to read it the tempvar has been set to null. I have no idea why this is happening. It does not error when it refers to the tempvar, so Im assuming that it can see it. but I cann't see the tempvars objects in the locals window anyway. is there a way to monitor the tempvar objects?
I have used tempvars in the past in a similar capacity successfully. the main difference is the new new instance writes to the tempvar and the main function reads them. the issue that Im having is the main function writing to them and the new instance reads them (which is opposite).

A: TempVars are properties of the Application object, not the database. A new Access.Application will not have access to the TempVars set in an old one.
In my opinion, the better approach is to use forms, timers and COM to achieve this. That way you can pass variables from one Access.Application object to another (including, but not limited to TempVars)
A quick sample (I'm working on a more full approach to multithreading in Access)
Using a blank database with a single form, MTForm, which has a form module:
In MTForms form module:
Private strTask As String
Private Sub Form_Timer()
    Application.Run strTask
    Application.Quit
End Sub
Public Property Let Task(Value As String)
    strTask = Value
End Property

And in a separate module:
Public Sub RunAsync(strFunction As String)
    Dim A As New Access.Application
    A.OpenCurrentDatabase Application.CurrentProject.FullName
    A.DoCmd.OpenForm "mtForm"
    A.Forms("mtForm").Task = strFunction
    A.Forms("mtForm").TimerInterval = 1
End Sub

Use: RunAsync "MyFunction" will run function MyFunction asynchronously on a separate Access.Application instance of the same database, that quits once execution is done (note that you can't have an exclusive lock on the database, else this will fail).
This can be easily adapted to add parameters, pass values from one thread to another, etc.


text:
Q: Parsing Content-Type text/html with AFNetworking I have to implement a version checker in my app. The app will check the version (which was manually set) from the server. Thing is, the server return the response in neither JSON or XML. It returns in plain text/html, which I'm not familiar with.
eg. If the app need to be updated, it will return response as below.
<checkversion>
    <update>TRUE</update>
    <status>MINOR</status>
    <alert></alert>
    <version>1.0.0</version>
    <ituneslink>0</ituneslink>
</checkversion>

Else, it will return response as below.
<checkversion>
    <update>FALSE</update>
</checkversion>

After looking at some similar SO posts such as this and this, I manage to get the response in format of string. Below is the snippets of my code.
- (void)slurpVersionChecker
{
    NSString *versionURL = @"api";
    NSDictionary *params = @{@"api_key":@"key"};

    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    [requestManager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
    [requestManager POST:versionURL parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"version: %@", string);

    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
        NSLog(@"failed to check version: %@", error);
    }];

}

Question is, how do I parse each of the responses? and is it there any way where I can parse the response through responseObject directly without converting it to String?

A: Okay. I already managed to solve this so I might as well post the solution here for others.
Here's what I basically do.
I use XMLReader to parse the response into NSDictionary. So, add the library to my project and import XMLReader.h in the header. Then, I only need to call the dictionaryForXMLDAta method to use it which returns:
checkversion = {
version: {
    alert =     {
        text = "";
    };
    ituneslink =     {
        text = 0;
    };
    status =     {
        text = MINOR;
    };
    text = "";
    update =     {
        text = TRUE;
    };
    version =     {
        text = "1.0.0";
    };
}

The NSDictionary return is not that pretty though. So, I had to use objectForKey a few times to retrieve the value.
[requestManager POST:versionURL parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData * data = (NSData *)responseObject;
        NSError *error = nil;
        NSDictionary *dict = [XMLReader dictionaryForXMLData:data
                                                     options:XMLReaderOptionsProcessNamespaces
                                                       error:&error];
        NSDictionary *version = [dict objectForKey:@"checkversion"];
        update = [[version objectForKey:@"update"] objectForKey:@"text"];
        ...
    }

Bonus: I want to notify the user if there's a new update available. So, I check if the update variable is equal to TRUE and if it's TRUE, it will link the user to the app store.
if([update isEqualToString:@"TRUE"]) {
            number = [[version objectForKey:@"version"] objectForKey:@"text"];
            itunesURL = [[version objectForKey:@"ituneslink"] objectForKey:@"text"];

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"New Version Available" message:nil delegate:self cancelButtonTitle:@"Not Now" otherButtonTitles:@"Download", nil];
            [alert show];

        }

And that's pretty much how I solved it.

A: Please try the following code:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager new];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];


text:
Q: OpenGL "motion dragging" effect - Not clearing screen every frame I have an OpenGL game that works fine, except I want to apply the "dragging" effect to moving objects: where you see their trails from their previous positions as they move.
What I tried was to clear the color buffer only every few frames instead of every frame, yet that doesn't work: The trails don't get erased at all, even though I do call glClear every 50 frames or so.
 This image shows the extremely annoying flicker it has.
Can someone explain either why this happens in OpenGL and how to fix it or perhaps an alternate method?

A: Google for "motion blur + opengl".  This is a full-screen post processing effect.  Another way  of doing it would to be to store trails for each object in a dequeue, where you push the current position at one end and take it off the other, drawing an effect for each item in the queue (perhaps making the item more and more opaque as you go).
Otherwise without code it's very hard to know what you're doing.  I'm pretty sure just not clearing the colour buffer won't work!


text:
Q: PySide Signal "duplicating" behavior from PySide.QtCore import *

class Eggs(QObject):
    evt_spam = Signal()
    print "Loaded"

a = Eggs()
b = Eggs()
print a.evt_spam
print b.evt_spam
print a.evt_spam is b.evt_spam

outputs:
Loaded
<PySide.QtCore.Signal object at 0xa2ff1a0>
<PySide.QtCore.Signal object at 0xa2ff1b0>
False

"Loaded" only printing once (as expected; it is a class variable), but why are 2 instances of the signal being created (if it is also a class variable)?

A: It's not being printed when you create a class instance, but rather when the class scope is executed. This code will print "Loaded", even though I never made an instance of "Test".
class Test:
    print "Loaded"

If you want to run code when the class is initialized, take a look at __init__(). This code will print "Loaded" when an instance is made, instead of when the class itself is defined.
class Test:
    def __init__(self):
        print "Loaded"

QT's QObject metaclass appears to be rewriting the class attributes to prevent duplicate signals when you initialize a new instance of the class. Perhaps you can assign the attribute like this:
class Test(QObject):
    def __init__(self, signal):
        self.evt_spam = signal

sig = Signal()
a = Test(sig)
b = Test(sig)

Or this:
class Test(QObject):
    def signal(self, signal):
        self.evt_spam = evt_spam
        return self

evt_spam = Signal()
a = Test().signal(evt_spam)
b = Test().signal(evt_spam)


text: Q: Mutual Information - Correlation, Continuous Random Variables For the Gaussian case $I(X,Y)=f( \varrho )$ where $\varrho $ is the correlation coefficient, and $f$ is a known increasing function. Is there any known joint distribution where the $f$ is not strictly increasing, so for big values of  $\varrho $ the  $I(X,Y)$ might be small. Is there any way to construct such a distribution by applying a transformation on a random variable and by using a known distribution?


text:
Q: Adding Option Group to Query I am trying to add an Option Group to this select box.  I am getting the rows and the count of the number of options in the record set.  I can either get the count or set the group.  I have yet to do both!
<select name="DETAILS">
<?php
include("config.php");
$sql = "SELECT tblDetails.DetailType AS type, CONCAT(tblDetails.DetailName,' (', Count(tblLocDet.DetailID),')') AS DetailName
FROM tblLocations INNER JOIN (tblLocDet INNER JOIN tblDetails ON tblLocDet.DetailID = tblDetails.DetailID) ON tblLocations.LocationID = tblLocDet.LocationID
GROUP BY tblDetails.DetailType, tblDetails.DetailName, tblLocations.CityID, tblLocations.AreaID, tblLocations.CuisineID
HAVING (((tblLocations.CityID)=16) AND ((tblLocations.AreaID)=131) AND ((tblLocations.CuisineID)=3));";

$result = mysql_query($sql) or die(mysql_error());

while ($row = mysql_fetch_assoc($result)) {
   echo "<optgroup label='{$row['type']}'>";
   $DetailNames = explode('|', $row['DetailName']);
   foreach($DetailNames as $DetailName) {
      echo "<option value='".$DetailName."'>".$DetailName."</option>";
   }
   echo "</optgroup>";
}
?>
</select>

Help is appreciated.


text:
Q: read files from different directories and split file name to create variables in R I am trying to read data from a nested Directory into R for Analysis. I have tried
list.files(pattern = "*.mass", recursive =T) # .mass is the file Extension I´m interested in.

which creates a list of all files
> head(list.files(pattern = "*.mass", recursive = T))
[1] "No_Vegetation/Rain17_45/No_MT/1/Test1_out.mass" "No_Vegetation/Rain17_45/No_MT/2/Test1_out.mass"
[3] "No_Vegetation/Rain17_45/No_MT/4/Test1_out.mass" "No_Vegetation/Rain17_45/No_MT/5/Test1_out.mass"
[5] "No_Vegetation/Rain17_45/No_MT/6/Test1_out.mass" "No_Vegetation/Rain17_60/No_MT/1/Test1_out.mass"
> tail(list.files(pattern = "*.mass", recursive = T))
[1] "vegetation/Rain20_45/No_MT/6/Test1_out.mass" "vegetation/Rain20_60/No_MT/1/Test1_out.mass"
[3] "vegetation/Rain20_60/No_MT/2/Test1_out.mass" "vegetation/Rain20_60/No_MT/4/Test1_out.mass"
[5] "vegetation/Rain20_60/No_MT/5/Test1_out.mass" "vegetation/Rain20_60/No_MT/6/Test1_out.mass"

Then I try reading the files using
dt <- list.files(pattern = "*.mass", recursive = T) %>% map_df(~fread(.))
str(dt)
Classes 'data.table' and 'data.frame':  39814 obs. of  14 variables:
 $ time_[s]           : num  0 64.7 125.5 186.2 247.1 ...
 $ dt_[s]             : num  60 5.18 4.47 2.92 2.48 ...
 $ massDomain_[m3]    : num  0 6.18 11.78 17.34 22.88 ...
 $ massBound_[m3]     : num  0 -0.00923 -0.01781 -0.01316 -0.0127 ...
 $ massSource_[m3]    : num  0 0.496 0.428 0.28 0.238 ...
 $ massError_[-]      : num  0.00 1.72e-13 1.44e-15 1.76e-14 -1.11e-14 ...
 $ BoundaryFlow_[m3/s]: num  0 -0.00178 -0.00398 -0.0045 -0.00511 ...
 $ RainRate_[mm/hr]   : num  0 17 17 17 17 17 17 17 17 17 ...
 $ accumRain_[m3]     : num  0 7.22 13.99 20.77 27.56 ...
 $ inf_[m3/s]         : num  0 0.0158 0.0158 0.0158 0.0158 ...
 $ accumInf_[m3]      : num  0 1.02 1.98 2.94 3.9 ...
 $ perc_[m3/s]        : num  0 0 0 0 0 0 0 0 0 0 ...
 $ bc1_[m3/s]         : num  0 0 -0.000257 -0.003607 -0.004206 ...
 $ bc1Acum_[m3]       : num  0 -0.0166 -0.2356 -0.4913 -0.7855 ..

and it combines all the files into one data.frame or data.table, without differentiating the files.
What I would like to do is to to create new string variables from the file names and add to the data.
for example, I would like to create variables like this:
veg <- c("vegetation", "No_Vegetation")
Rain <- c("Rain17_45", "Rain17", "Rain20_45", "Rain20_60")
Roughness <- c("MT", "No_MT")
Geom <- c("1", "2", "3", "4", "5", "6")

the new variables are veg, Rain, Geom and Rougness, while the Vector entries are the data data that should span the entire dt. therefore, I want that for each new variable, the corect string should be assigned, depending on whether or not it finds the string in the file Name.
Any help will be appreciated. Thanks

A: You could edit the .fpart of map_df to add the filename as a column. Then tstrsplit could be invoked to make the new columns and add them in e.g below
list.files(pattern = "*.mass", recursive = T) %>%
  map_df(., .f = function(x){
    dt <- fread(x)
    dt$file <- x
    dt
  })

tstrsplit("No_Vegetation/Rain17_45/No_MT/1/Test1_out.mass",
          "/")[1:4]


text:
Q: Parallelization (Java 8) vs Concurrency (Java 7) I want to parse multiple files to extract the required data and then write the output into an XML file. I have used Callable Interface to implement this. My colleague asked me to use Java 8 feature which does this job easily. I am really confused which one of them I should use now.
list.parallelStream().forEach(a -> {
            System.out.println(a);
        });

A: Using concurrency or a parallel stream only helps if you have independent tasks to work on.  A good example of when you wouldn't do this is what you are locking on a shared resources e.g.
// makes no sense to use parallel here.
list.parallelStream().forEach(a -> {
        // locks System.out so only one thread at a time can do any work.
        System.out.println(a);
    });

However, as a general question, I would use parallelStream for processing data, instead of the concurrency libraries directly because;

*

*a functional style of coding discourages shared mutable state. (Actually how are not supposed to have an mutable state in functional programming but Java is not really a functional language)

*it's easier to write and understand for processing data.

*it's easier to test whether using parallel helps or not.  Most likely ti won't and you can just as easily change it back to being serial.

IMHO Given the chances that using parallel coding will really help is low, the best feature of parallelStream is not how simple it is to add, but how simple it is to take out.
The concurrency library is better if you have ad hoc work which is difficult to model as a stream of data. e.g. a worker pool for client requests might be simplier to implement using an ExecutorService.


text:
Q: Pushing an element to every fourth place of a Float32Array efficiently in JS/TS I want to push a 1 to every fourth element of a Float32Array. My current solution is to convert said Float32Array into an array, iterating through it and applying .splice on every fourth element like so (I also convert the array to a buffer afterward but that is not relevant for this question):
function pushToEveryFourthAndConvertToBuffer(floatArray: Float32Array): Buffer {
  const array: number[] = [...floatArray];
  for (let i: number = 3; i <= array.length; i += 4) array.splice(i, 0, 1);
  return Buffer.from(array);
}

while this works, it is not performant at all. My Float32Array has 660000 entries (thus, the returned buffer has 880000) and this function gets called with about 100 different Float32Arrays. If I remove the for-loop from the function, it runs much faster so I can be very sure my method of applying the elements is causing the bottle neck.
Is there a more efficient way or does my CPU just have to suffer and do I have to wait really long since I don't want to implement a multi-threaded solution?
Edit:
I'll provide some input and expected output here to clarify my question:
new Float32Array([0, 0, 0,    0, 0, 0,    0, 0, 0]); // ← input
new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]); // ← output

new Float32Array([1, 2, 3,    4, 5, 6,    7, 8, 9]) // ← input
new Float32Array([1, 2, 3, 1, 4, 5, 6, 1, 7, 8, 9]) // ← output

new Float32Array([0.2321, 0.294, 0.1246,    0.9352, 0.87423, 0.11]); // ← input
new Float32Array([0.2321, 0.294, 0.1246, 1, 0.9352, 0.87423, 0.11, 1]); // ← output

A: A non concurrent way to do this might be something like this

const initial_array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];

//  from now on we only work with Float32Array. No conversion until the end
const old_floats = new Float32Array(initial_array);

//  pre-allocate your new Float32Array because you know how big it needs to be
const new_floats = new Float32Array( Math.ceil(initial_array.length * 4 / 3) );

//  fill it with ones
new_floats.fill(1, 0);

//  for performance, simple loops are better than array methods
for (let i=0; i<old_floats.length/3; i++) {
  let read_start = i*3;
  let read_end = read_start+3;
  let write_start = i*4;
  let four_elements = old_floats.slice(read_start, read_end);
  new_floats.set(four_elements, write_start);
}

//  now let's convert back to numbers
console.log(new_floats);

For a concurrent way I would create 4 asynchronous functions. Function one would take every 3rd value, function two every 3rd+1, function three every 3rd+2, function 4 would simply inject "1" in every 4th value of the new array.
At the end, you would bring them together with Promise.all()

A: Is there a reason you want to use array.splice? Compared to other array operations splice is very slow.
You can perform this same process by creating a new array with the expected size of your current one, and then assigning the values from the old array.

function fillArray(floatArray) {
  const array = [];
  array.length = Math.floor(floatArray.length * 4/3 );

  for (let index = 0, negativeIndex = 0; index < array.length; index++) {
    if ((index + 1) % 4 === 0) {
      array[index] = 1;
      index++;
      negativeIndex--;
    }
    array[index] = floatArray[index + negativeIndex];
  }
  return Buffer.from(array);
}

Running this via jsbench in my browser shows that your splice version is 3 to 8 ops/sec, while my version is 1,500 to 1,600 ops/sec. (jsbench doesn't support buffers so you have to skip that last step)
If you want simpler code you could use array.push instead of defining the array length and keeping track of the negativeIndex, but that only performs 500 to 600 ops/sec and you were specifically looking for efficiency.


text:
Q: Noun to describe a person who wants to please everybody, but sort of in an obsessed manner I'm trying to describe a character who dances for her husband so that he doesn't get mad, apologizes profusely even if she hasn't done anything wrong. However, she is also strong-willed and determined.
I considered using the word "altruist", but the character is not selfless.

A: Lapdog would be one, but that has more of a political connotation.
People-pleaser gets more at the personal dynamic, but that is usually general, not specific to one particular relationship.
It seems like you are describing a dysfunctional / abusive relationship, so what the wife is doing in an immediate sense is "placating" and as a long-term psychological strategy is  "fawning".  There aren't really good noun forms of those; calling the wife a "placater" or "fawner" would be accurate, but awkward.

A: People pleaser describes such a person, even the obsession part.

A: Based the original description, appeaser or placater is appropriate.
More context might be needed, but the character in question is "strong-willed and determined," though "not selfless." Most of the suggested nouns are pejorative because people have assumed that the character is weak, relative to her husband. However, she might actually be more mature and wise compared to him.

A: sycophant
a self-seeking, servile flatterer; fawning parasite.
sycophant in dictionary.com

A: A happiness pump is defined by Simple English Wikipedia as

someone who will do anything to make other people happy even if it
makes them very unhappy themselves

The term is taken from a thought experiment intended to illustrate problems with the philosophy of utilitarianism.

A: If the woman is constantly appeasing the husband, and the husband isn't contributing equally to the relationship or even downright abusive, then she would be codependent.
She then might still be strong willed in other regards (particularly if someone speaks badly of her husband)
And as nick012000 suggests, this can be a sign of abuse, but it might not be current abuse and instead someone who was raised in an dysfunctional family.  (see https://adultchildren.org/ )

A: This is a hard one. Calling them a doormat might be appropriate, although that usually tends to mean they do what they are told without resisting, rather than taking initiative.

A: I don't think there's a one-word answer.
The personality is very peculiar and may not exist as you think.  I'm concerned that your character may not be believable.
Understanding the motivation (ie why people do things) especially odd or 'irrational' things is important.  The behaviour/attitudes described is not one but two contradictory ones.  She needs some 'reason' to give-up her inner driving role for subservience.  That depends on him.  ie a relationship.  There are a lot of words at https://en.wikipedia.org/wiki/Transactional_analysis#Outline but don't be put off.
In short people do things because of some perceived reward.  Love or triumph at being a victim, or gloating at another's discomfort.  Couples often argue and both feel they've won something.  For some it's the only excitement they get and plot for when they can do it again.  You'll have noticed in the replies many references to abuse and so on.  (That's a relationship of course.) That's what people are taking away from your thumbnail sketch.  That relationship is double-ended and will change as things develop.  Lots of potential so long as you can make it believable.

A: A more offensive word could be "ass-kisser", or "Kiss-ass"  as in "why is she always kissing (his) ass for no reason?"
I fear that in many parts of the world she would be "an obedient wife" or "respectful
servant".
Also  a "passive" or "submissive" person would behave as described

A: adulator: One who lavishes excessive praises or flattery, one who adulates. (Your dictionary)
the verb to adulate means:

to show excessive admiration or devotion to; flatter or admire servilely. (Free Dictionary)

A: Abuse victim.
Frankly, the scenario describe sounds like the character is the victim of domestic violence, to me, and is taking actions to placate their abuser.


text:
Q: Как значение из динамического файла передать переменной на стороне клиента.[JS, jQuery] Имеется файл (url) который динамически обновляет значение токенов при каждом обновлении (запросе) и содержит внутри примерно такое:

[{
    "_id": "someidlikewewsdw",
    "type": 1,
    "name": "Channelname1",
    "logo": "/static/logos/channellogo1.png",
    "thread": "https://somesite.com/Channelname1/video.m3u8?token=33121",
    "enabled": true
}, {
    "_id": "someidlikewewesq",
    "type": 1,
    "name": "Channelname2",
    "logo": "/static/logos/channellogo2.png",
    "thread": "https://somesite.com/Channelname2/video.m3u8?token=13121",
    "enabled": true
}, {
    "_id": "someidlikewewesd",
    "type": 1,
    "name": "Channelname3",
    "logo": "/static/logos/channellogo3.png",
    "thread": "https://somesite.com/Channelname3/video.m3u8?token=23121",
    "enabled": true
}]

Мне надо присвоить значение "thread" к переменной.
Допустим создать переменные Channel1token, Channel2token, Channel3token и присвоить им значения из theard каждого по отдельности.
var Channel1token = https://somesite.com/Channelname1/video.m3u8?token=33121 и тд.
Все это нужно в js что бы запросы шли от клиента, так как каждому клиенту присваивается отдельный токен.

A: Если я правильно понял, то нужно из JSON выдрать отдельные threads. Проще всего их положить в массив. В этом случае для хрома/мозилы код будет выглядеть примерно так:
var channelTokens = [];

$.ajax({url: "feeds.json"})
 .done(function( data ) {
     data.forEach(feed => {
        channelTokens.push(feed.thread)
     });

console.log("We have tokens", channelTokens)
        });

Вместо console.log - можно уже обрабатывать дальше полученный результат.


text:
Q: How to add a prefix to a lot of existing swift files and classes in Xcode I'm working on a project and I created a lot of swift classes. As you know with swift you do not need to add a prefix in front of the class or file name; and so I didn't.
Now I was required to add a prefix to them (let's say "KK" in front of each file and class)
I was wandering if someone managed to do this with a single command, I would like to avoid renaming and refactoring each class one by one.
example:
a file called FridgeView.swift containing a class FridgeView
should be renamed KKFridgeView.swift and the class KKFridgeView
P.S. I know we do not need prefix in swift but it is a requirement of my company I really have no choice :)

A: Step One Click the Project Name
]1
Then you can find Class Prefix on you right Side

Add your prefix and then Create all you viewController and Class

A: It can be set from file inspection menu but it will only new files added into project. it will not impact already added files.


text:
Q: C# Rectangle point registry I have some code here that is not registering to ever be true and I have been lost for a few hours. I apologize if its just a stupid mistake.
bool Bdrag;
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
    Point Floater = new Point(e.X, e.Y);
    Rectangle Rect = new Rectangle(200, 200 ,40 , 40);
    Rectangle Rect2 = new Rectangle(250, 250, 40, 40);
    if(Rect.Contains(Floater))
    {
        if(e.Button == MouseButtons.Left)
        {
            Bdrag = true;
        }
        else
        {
            Bdrag = false;
        }
        Console.WriteLine("success 1");
        if(Rect2.Contains(Floater) && Bdrag == true)
            {
                Console.WriteLine("success 2!!")
            }
     }
}

I am unable to ever reach writeline("success 2!!") even if I render the rectangles and make sure I am hitting them in the order I created.
Thanks again guys.

A: Assuming I understand correctly what you are trying to do this won't work like this. Let me show this with an example:
Your rectangles don't touch each other (according to your coordinates):
      __________
     |          |
     |    1     |
     |          |
     |__________|
                   __________
                  |          |
                  |    2     |
                  |          |
                  |__________|

The event is triggered when you move the mouse inside Rect1. Let's go trough your code:
if(Rect.Contains(Floater)) is definitly true.
Assuming that the left mouse button is pressed Bdrag is set to true.
Console.WriteLine("success 1"); is triggered.
if(Rect2.Contains(Floater) && Bdrag == true) is definitly false, because Floater will always be inside Rect1 as it's position is only set when your mouse is inside Rect1.
When you move your mouse indise Rect2 now nothing happens. Why?

*

*Your event is probably not triggered. I can't tell if it really is so as I can't see it in your code but it's likely because of the event's name.

*Even if the event is triggered it will never pass the first if-statement, because obviously it is not in Rect1 any more.

Solution:

*

*Make one method connected to both events with the following code:
bool Bdrag;
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
    Rectangle Rect = new Rectangle(200, 200 ,40 , 40);
    Rectangle Rect2 = new Rectangle(250, 250, 40, 40);
    if(Rect.Contains(new Point(e.X + Rect.Location.X, e.Y + Rect.Location.Y)))
    {
        if(e.Button == MouseButtons.Left)
        {
            Bdrag = true;
        }
        else
        {
            Bdrag = false;
        }
    }
    if(Rect2.Contains(new Point(e.X + Rect2.Location.X, e.Y + Rect2.Location.Y)) && Bdrag == true)
    {
         //is executed when Rect2 has been hit after Rect1
    }
}

*Or make two seperated events:
bool Bdrag;
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
    Rectangle Rect = new Rectangle(200, 200 ,40 , 40);
        if(e.Button == MouseButtons.Left)
        {
            Bdrag = true;
        }
        else
        {
            Bdrag = false;
        }
}

private void panel2_MouseMove(object sender, MouseEventArgs e)
{
    Rectangle Rect2 = new Rectangle(250, 250, 40, 40);
    if(Rect2.Contains(new Point(e.X + Rect2.Location.X, e.Y + Rect2.Location.Y)) && Bdrag == true)
    {
        //is executed when Rect2 has been hit after Rect1
    }
}


text:
Q: How can I get the Session values after payment? (CakePHP-Paypal Hosted Solution) I am using CakePHP for my application and I was able to integrate the Paypal hosted solution. Users are successfully redirected to Paypal to complete their payment. Once they have completed, they are returned to my website.
At first, it was taking the user to the login page (as the session was getting removed). To prevent this, I have opened the Paypal page in a new window. Now they are not being asked to login again and keeping the $this->Session->read('Auth.User') intact. However, it is not remembering any other session data. For example, I had a session variable 'invoice_number' which is not available after they are returning from the Paypal website.
I have noticed that the session id doesn't stay the same before and after they completed the payment.
I have changed the core.php to reduce the session security by setting it to low, increased the session time, and I have also modified so that it will only start the session if no session id was found (saw this on a CakePHP ticket/bug).
Interestingly, no in Chrome, it remembers all the session variable, the session ids are same and works fine. But in Firfox, it's not working!
Is there anyway to keep the session alive with the same id/ session variables alive so that even after the payment when they are returning, my application knows what the invoice number for this payment was.
Any help would be really appreciated.
Kind regards,
Tasin

A: try turn off referer checks in core.php, that should do the trick.

A: Try setting Security.level to something other than high in core.php.

A: As I wasn't able to find a suitable solution for this problem, I had to find a work around for this.
As I mentioned, when redirecting, the 'Auth.User' information was still intact. I used this to retrieve information which I stored into the database before sending the users to the PayPal website.
Once the payment is completed and the user is returned to the confirmation page on my site, I am retrieving the data from the database based on 'Auth.User' session data.
Not the perfect solution, but for the time being, it is kind of working.
If welcome any solution that is better than this. Please let me know.
Many thanks,
Tasin


text:
Q: Парсинг XML в объект Имеем XML документ:
<?xml version="1.0"?>

    <metadata>
        <title><![CDATA[Title]]></title>

    </metadata>
    <data>
        <text><![CDATA[This is simple text for this data]]></text>
        <![CDATA[http://www.fullhdoboi.com/wallpapers/thumbs/6/kartinka-apelsiny-1885.jpg]]>
        <codes>
            <data_code><![CDATA[sH37Djcd]]></data_code>
            <document_code><![CDATA[lnbtyuJBTc11933774]]></document_code>
        </codes>
    </data>

Есть php код:
$xml_file = simplexml_load_file($data); /// $data - наш XML документ
/// Распечатка свойств объекта
echo "
";
print_r($xml_file);
echo "
";
/// Вывод script со значением атрибута (name) b
echo $xml_file->metadata->script[1];

*

*Я не получаю при распечатке объекта данных из CDATA, как исправить?

*Как вы можете видеть есть два одинаковых тега, но с разным содержимым атрибута, как сделать так чтобы я мог вызывать не по индексу, а по ключу?


text:
Q: Is it possible to get the tasks whose status changes in django viewflow? HI is it possible to get the tasks whose status changed on performing a task in django-viewflow?

A: You can examining activation.task.leading chain after calling activation.done()


text:
Q: how to set static url in angular4 routing. this.router.navigate('http://xxxxxx.com/abx/xyz') like this , how to set static url in angular4 routing.  this.router.navigate('https://xxxxxx.com/abx/xyz')
 like this , Which means i want to navigate to another website from my angular
 application.

A: You can use window.location.href = '...';

A: Use this code to redirect to external link
window.location.href = "url";


text:
Q: custom_variables value not in quotes I have just downloaded a get_survey_details.json and note that the question_id value is not quoted. I would have expected "623478675" Is this a change?
{"status": 0, "data": {"custom_variables": [{"variable_label": "User Agent", "question_id": 623478675}


text:
Q: Two ways to define complexification of a representation Let $G$ be a finite group and let $V$ be a finite dimensional real representation of $G$. I'm thinking of $V$ as a module over $\mathbb{R}[G]$.
Here are two ways to make a $\mathbb{C}[G]$-module out of $V$.

*

*Take the tensor product of $\mathbb{C}[G]$ with $V$ over $\mathbb{R}[G]$ (where $\mathbb{C}[G]$ is viewed as a $\mathbb{C}[G]$-$\mathbb{R}[G]$-bimodule.

*Take the tensor product of $\mathbb{C}$ with $V$ over $\mathbb{R}$, and equip it with an action of $g$ given by $g\cdot(z\otimes v)=z\otimes(gv)$ (and show that this rule really does extend to a well-defined additive action of $\mathbb{C}[G]$).
I think that I was able to show that both representations are isomorphic. I showed that the module in (2) satisfies the universal property required from the tensor product in (1).

Am I correct? Are these two modules really isomorphic?

A: Yes. This also follows by composing the canonical isomorphisms
$$\mathbf{C} \otimes_\mathbf{R} V \leftarrow \mathbf{C} \otimes_\mathbf{R} \mathbf{R}[G] \otimes_{\mathbf{R}[G]} V \rightarrow \mathbf{C}[G] \otimes_{\mathbf{R}[G]} V.$$


text:
Q: "sqlite3.h" missing when pushing Rails app to Heroku I'm following this tutorial, but it fails when I try to push to Heroku.  It seems "sqlite3.h" is missing.  I'm new to development so I'm not sure what information will help people diagnose the problem, so here's everything :).  I'm running on Mac OS X 10.7 Lion.  Here are the versions of everything I'm working with:
Amits-MacBook-Air-2:demo_app amitgupta$ ruby -v
ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin11.3.0]
Amits-MacBook-Air-2:demo_app amitgupta$ rails -v
Rails 3.2.3
Amits-MacBook-Air-2:demo_app amitgupta$ sqlite3 -version
3.7.11 2012-03-20 11:35:50 00bb9c9ce4f465e6ac321ced2a9d0062dc364669
Amits-MacBook-Air-2:demo_app amitgupta$ heroku -v
2.25.0
Amits-MacBook-Air-2:demo_app amitgupta$ port -v
MacPorts 2.0.4
Entering interactive mode... ("help" for help, "quit" to quit)
[RailsApps/demo_app] > quit
Goodbye

When I try to push to Heroku:
Amits-MacBook-Air-2:demo_app amitgupta$ heroku create --stack cedar
Creating floating-stream-8009... done, stack is cedar
http://floating-stream-8009.herokuapp.com/ | git@heroku.com:floating-stream-8009.git
Amits-MacBook-Air-2:demo_app amitgupta$ git push heroku master

Here's what I get:
Counting objects: 119, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (104/104), done.
Writing objects: 100% (119/119), 33.74 KiB, done.
Total 119 (delta 17), reused 0 (delta 0)

-----> Heroku receiving push
-----> Ruby/Rails app detected
-----> Installing dependencies using Bundler version 1.1.2
       Running: bundle install --without development:test --path vendor/bundle --binstubs bin/ --deployment
       Fetching gem metadata from https://rubygems.org/.......
       Installing rake (0.9.2.2)
       .
       .
       .
       Installing sqlite3 (1.3.6) with native extensions
       Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.
       /usr/local/bin/ruby extconf.rb
       checking for sqlite3.h... no
       sqlite3.h is missing. Try 'port install sqlite3 +universal'
       or 'yum install sqlite-devel' and check your shared library search path (the
       location where your sqlite3 shared library is located).
       *** extconf.rb failed ***
       Could not create Makefile due to some reason, probably lack of
       necessary libraries and/or headers.  Check the mkmf.log file for more
       details.  You may need configuration options.
       Provided configuration options:
       --with-opt-dir
       .
       .
       .
       --disable-local
       Gem files will remain installed in /tmp/build_2l2dn7bx7lu34/vendor/bundle/ruby/1.9.1/gems/sqlite3-1.3.6 for inspection.
       Results logged to /tmp/build_2l2dn7bx7lu34/vendor/bundle/ruby/1.9.1/gems/sqlite3-1.3.6/ext/sqlite3/gem_make.out
       An error occured while installing sqlite3 (1.3.6), and Bundler cannot continue.
       Make sure that `gem install sqlite3 -v '1.3.6'` succeeds before bundling.
 !
 !     Failed to install gems via Bundler.
 !
 !     Heroku push rejected, failed to compile Ruby/rails app

To git@heroku.com:blazing-mountain-3659.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@heroku.com:blazing-mountain-3659.git'

When I do:
Amits-MacBook-Air-2:demo_app amitgupta$ sudo port install sqlite3 +universal

I get:
Password:
--->  Computing dependencies for sqlite3
--->  Cleaning sqlite3

Next I tried:
Amits-MacBook-Air-2:demo_app amitgupta$ sudo gem install sqlite3 -v '1.3.6'

And get:
Building native extensions.  This could take a while...
Successfully installed sqlite3-1.3.6
1 gem installed
Installing ri documentation for sqlite3-1.3.6...
Installing RDoc documentation for sqlite3-1.3.6...

Then:
Amits-MacBook-Air-2:demo_app amitgupta$ bundle install

gives:
Using rake (0.9.2.2)
.
.
.
Using sqlite3 (1.3.6)
Using uglifier (1.2.4)
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.

Then I try pushing to Heroku again, but get the same problem.  Perhaps it has something to do with the discrepancy between the first command "Creating floating-stream-8009" and the second command "failed to push some refs to 'git@heroku.com:blazing-mountain-3659.git'"?

A: gem 'sqlite3', :group => [:development, :test]
group :production do
  gem 'pg'
end

*

*edit Gemfile as above

*remove Gemfile.lock

*run bundle install --without production

*git add .

*git commit -am "bundle updating sqlite3"

*git push heroku master

A: I had a similar problem and I wasn't even using sqlite3 for anything but after removing it from the gem file I still got that error
what solved it for me was a commit command
git commit -am

that I found on this tutorial

A: Heroku uses postgresql so you want to remove sqlite3 or move it into a development group in your Gemfile.
Check you Gemfile.lock for any other gems that may have dependencies on sqlite3, as this can also cause problems.

A: What happened to me was, I was following along the Heroku tutorial and when I used git push heroku master it was pushing from my latest Git commit (obviously!)
What I forgot was that in the eyes of Git, I was still using sqlite in the gemfile! Silly me!
So I used git add . followed by a git commit -m "Changed to Postgres." so Git knew about these changes. Pushing after that worked fine for me.

A: Yes, as these answers suggest, most of the time you will want to avoid using SQLite in production due to the constraints of the Heroku platform. However, you may have a perfectly acceptable use case (ex. read-only config) for using SQLite anyway. My recommendation is to:

*

*Add the heroku-buildpack-apt buildpack

*Add to your Aptfile:
libsqlite3-dev
libsqlite3-0


text:
Q: Menu Bar to change content in only one div I have a basic webpage. At the top, there is a menu bar with 3 links. I want to change the content in only one div, depending on what link is selected. All i know is html and php. How do i link the links to change only the content div?

A: This is not perfect but it changes a 'div' or in this case a 'tr'

    ...

home

home

home


text:
Q: Does an ip catch all exist? I'm trying to block specific ip address traffic using this:
sudo iptables -A INPUT -s 192.148.10.209 -j DROP

Does an ip address catch all exist where I could block all addresses on 192.148.10.* using the above command?

A: yes, use cidr notation in iptables
192.148.10.0/24


text:
Q: New Theorem: Custom Title Possibly a duplicate.. I'm sorry if so.
Problem
Given the beamer class.
Is it possible to define a new theorem environment with title: "Type (Optional)"
Example
Here is a minimal example:
\documentclass{beamer}
\newtheorem{type}{Type}
\newenvironment<>{type}[1]{\begin{block}#2{#1}}{\end{block}}

\begin{document}
\begin{frame}
\begin{type}
Theorem Text
\end{type}
\end{frame}
\end{document}

A: Something like this?
\documentclass{beamer}

\newtheorem{type}{Type}
\newenvironment<>{type}[2][]{%
  \begin{block}#3{#2\ #1}%
    \par%
  }{%
  \end{block}%
}

\begin{document}
\begin{frame}
\begin{type}<1>[(explained)]{Type A}
Theorem Text
\end{type}%
\begin{type}<2>{Type B}
Other Text
\end{type}
\end{frame}
\end{document}


text:
Q: Python - how do I force the use of a factory method to instantiate an object? I have a set of related classes that all inherit from one base class.  I would like to use a factory method to instantiate objects for these classes. I want to do this because then I can store the objects in a dictionary keyed by the class name before returning the object to the caller.  Then if there is a request for an object of a particular class, I can check to see whether one already exists in my dictionary.  If not, I'll instantiate it and add it to the dictionary.  If so, then I'll return the existing object from the dictionary.  This will essentially turn all the classes in my module into singletons.
I want to do this because the base class that they all inherit from does some automatic wrapping of the functions in the subclasses, and I don't want to the functions to get wrapped more than once, which is what happens currently if two objects of the same class are created.
The only way I can think of doing this is to check the stacktrace in the __init__() method of the base class, which will always be called, and to throw an exception if the stacktrace does not show that the request to make the object is coming from the factory function.
Is this a good idea?
Edit: Here is the source code for my base class.  I've been told that I need to figure out metaclasses to accomplish this more elegantly, but this is what I have for now.  All Page objects use the same Selenium Webdriver instance, which is in the driver module imported at the top.  This driver is very expensive to initialize -- it is initialized the first time a LoginPage is created.  After it is initialized the initialize() method will return the existing driver instead of creating a new one.  The idea is that the user must begin by creating a LoginPage.  There will eventually be dozens of Page classes defined and they will be used by unit testing code to verify that the behavior of a website is correct.
from driver import get_driver, urlpath, initialize
from settings import urlpaths

class DriverPageMismatchException(Exception):
    pass

class URLVerifyingPage(object):
    # we add logic in __init__() to check the expected urlpath for the page
    # against the urlpath that the driver is showing - we only want the page's
    # methods to be invokable if the driver is actualy at the appropriate page.
    # If the driver shows a different urlpath than the page is supposed to
    # have, the method should throw a DriverPageMismatchException

    def __init__(self):
        self.driver = get_driver()
        self._adjust_methods(self.__class__)

    def _adjust_methods(self, cls):
        for attr, val in cls.__dict__.iteritems():
            if callable(val) and not attr.startswith("_"):
                print "adjusting:"+str(attr)+" - "+str(val)
                setattr(
                    cls,
                    attr,
                    self._add_wrapper_to_confirm_page_matches_driver(val)
                )
        for base in cls.__bases__:
            if base.__name__ == 'URLVerifyingPage': break
            self._adjust_methods(base)

    def _add_wrapper_to_confirm_page_matches_driver(self, page_method):
        def _wrapper(self, *args, **kwargs):
            if urlpath() != urlpaths[self.__class__.__name__]:
                raise DriverPageMismatchException(
                    "path is '"+urlpath()+
                    "' but '"+urlpaths[self.__class.__name__]+"' expected "+
                    "for "+self.__class.__name__
                )
            return page_method(self, *args, **kwargs)
        return _wrapper

class LoginPage(URLVerifyingPage):
    def __init__(self, username=username, password=password, baseurl="http://example.com/"):
        self.username = username
        self.password = password
        self.driver = initialize(baseurl)
        super(LoginPage, self).__init__()

    def login(self):
        driver.find_element_by_id("username").clear()
        driver.find_element_by_id("username").send_keys(self.username)
        driver.find_element_by_id("password").clear()
        driver.find_element_by_id("password").send_keys(self.password)
        driver.find_element_by_id("login_button").click()
        return HomePage()

class HomePage(URLVerifyingPage):
    def some_method(self):
        ...
        return SomePage()

    def many_more_methods(self):
        ...
        return ManyMorePages()

It's no big deal if a page gets instantiated a handful of times -- the methods will just get wrapped a handful of times and a handful of unnecessary checks will take place, but everything will still work.  But it would be bad if a page was instantiated dozens or hundreds or tens of thousands of times.  I could just put a flag in the class definition for each page and check to see if the methods have already been wrapped, but I like the idea of keeping the class definitions pure and clean and shoving all the hocus-pocus into a deep corner of my system where no one can see it and it just works.

A: In Python, it's almost never worth trying to "force" anything. Whatever you come up with, someone can get around it by monkeypatching your class, copying and editing the source, fooling around with bytecode, etc.
So, just write your factory, and document that as the right way to get an instance of your class, and expect anyone who writes code using your classes to understand TOOWTDI, and not violate it unless she really knows what she's doing and is willing to figure out and deal with the consequences.
If you're just trying to prevent accidents, rather than intentional "misuse", that's a different story. In fact, it's just standard design-by-contract: check the invariant. Of course at this point, SillyBaseClass is already screwed up, and it's too late to repair it, and all you can do is assert, raise, log, or whatever else is appropriate. But that's what you want: it's a logic error in the application, and the only thing to do is get the programmer to fix it, so assert is probably exactly what you want.
So:
class SillyBaseClass:
    singletons = {}

class Foo(SillyBaseClass):
    def __init__(self):
        assert self.__class__ not in SillyBaseClass.singletons

def get_foo():
    if Foo not in SillyBaseClass.singletons:
        SillyBaseClass.singletons[Foo] = Foo()
    return SillyBaseClass.singletons[Foo]

If you really do want to stop things from getting this far, you can check the invariant earlier, in the __new__ method, but unless "SillyBaseClass got screwed up" is equivalent to "launch the nukes", why bother?

A: it sounds like you want to provide a __new__ implementation:  Something like:
class MySingledtonBase(object):
    instance_cache = {}
    def __new__(cls, arg1, arg2):
        if cls in MySingletonBase.instance_cache:
            return MySingletonBase.instance_cache[cls]
        self = super(MySingletonBase, cls).__new__(arg1, arg2)
        MySingletonBase.instance_cache[cls] = self
        return self

A: Rather than adding complex code to catch mistakes at runtime, I'd first try to use convention to guide users of your module to do the right thing on their own.
Give your classes "private" names (prefixed by an underscore), give them names that suggest they shouldn't be instantiated (eg _Internal...) and make your factory function "public".
That is, something like this:
class _InternalSubClassOne(_BaseClass):
    ...

class _InternalSubClassTwo(_BaseClass):
    ...

# An example factory function.
def new_object(arg):
    return _InternalSubClassOne() if arg == 'one' else _InternalSubClassTwo()

I'd also add docstrings or comments to each class, like "Don't instantiate this class by hand, use the factory method new_object."

A: You can also just nest classes in factory method, as described here:
https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html#preventing-direct-creation
Working example from mentioned source:
# Factory/shapefact1/NestedShapeFactory.py
import random

class Shape(object):
    types = []

def factory(type):
    class Circle(Shape):
        def draw(self): print("Circle.draw")
        def erase(self): print("Circle.erase")

    class Square(Shape):
        def draw(self): print("Square.draw")
        def erase(self): print("Square.erase")

    if type == "Circle": return Circle()
    if type == "Square": return Square()
    assert 0, "Bad shape creation: " + type

def shapeNameGen(n):
    for i in range(n):
        yield factory(random.choice(["Circle", "Square"]))

# Circle() # Not defined

for shape in shapeNameGen(7):
    shape.draw()
    shape.erase()

I'm not fan of this solution, just want to add this as one more option.


text:
Q: Php url shortener with static htmls My htaccess:
RewriteEngine On
RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ index.php?l=$1 [L]

and php:
<?php
$links = parse_ini_file('links.ini');

if(isset($_GET['l']) && array_key_exists($_GET['l'], $links)){
header('Location: ' . $links[$_GET['l']]);
}
else
    include ('index.html');
?>

In the links.ini I have short url and website url:
youtube1 = "https://www.youtube.com/watch?v=9bZkp7q19f0"
youtube2 = "https://www.youtube.com/watch?v=wcLNteez3c4"
etc.

These files are in the root and url shortening works.
In the index.html I have menu with static html pages:
Home page
page1
page2
etc.

But when I click on them it only reloads index.html?
Any help will be appriciated!
I tried to put static html links into links.ini:
page1 = page1

but that doesn't work either... I get the Page isn't redirecting properly error.

A: When you look into error messages, you will notice

PHP Warning:  syntax error, unexpected '=' in links.ini on line 1\n in /var/www/example.com/index.php on line 2

and when looking at links.ini, you will see a second equal sign = in the URL

youtube1 = https://www.youtube.com/watch?v=9bZkp7q19f0

So quoting the value, e.g.
youtube1 = "https://www.youtube.com/watch?v=9bZkp7q19f0"

should make it work as expected.

A: So i changed the php to this:
<?php
$links = parse_ini_file('links.ini');

if(isset($_GET['l']) && array_key_exists($_GET['l'], $links)){
header('Location: ' . $links[$_GET['l']]);
}

else if($_GET['l'] == 'index' | $_GET['l'] == 'page1' | $_GET['l'] == 'page2')
    include($_GET['l']. '.html');

else if($_GET['l'] == '')
    include('index.html');

else
    include('404.html');

?>

I don't know how elegant this is...
If someone knows a better way...

A: You might want to look at this simple url shortener, it's very similar to what you are doing, but with a json instead of an ini file.
The core is the .htaccess file:
Options +SymLinksIfOwnerMatch
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^((?!index\.php).+)$ /index.php?short=$1 [NC,L,QSA]


text:
Q: AWS Lambda static IP I'm trying to access a external MyQSL database (Not AWS RDS), and I need to have a static IP in order to open up the firewall for accepting connections. Is it possible to set a static IP with a Lambda instance? If not what are some other options?

A: In order to do that, you need to deploy your Lambda function into a VPC and within the VPC, provide NAT Gateway. Then assign an Elastic IP (static IP) to the NAT Gateway. These two links describe it step-by-step:

*

*AWS: How to Create a Static IP Address Using a NAT Gateway (Medium)

*How do I give internet access to my Lambda function in a VPC? (AWS Knowledge Center

A: I have to do this every year or two and always forget how to do it :) Fortunately, I've discovered the AWS now has a wizard that steps you through this process: https://ap-southeast-2.console.aws.amazon.com/vpc/home?region=ap-southeast-2#wizardFullpagePublicAndPrivate:
The wizard didn't pick up my Elastic IP Allocation ID so I had to manually paste it in from the Elastic IP section of the VPC console but after that everything works. https://ap-southeast-2.console.aws.amazon.com/vpc/home?region=ap-southeast-2#Addresses:sort=PublicIp
Then you just set up your lambda function to use that VPC. The only remaining gotcha is to select the Private Subnet that the wizard created rather than the public subnet (of course).
If you are deploying your Lambda functions using SAM rather than the console you can direct your function to use the VPC by including Policy and VpcConfig sections in your SAM template as shown below.

In another year or two when I have to do this again, I'll hopefully find this answer :)

A: No, this is not possible.
What you should do instead is:

*

*deploy the Lambda function into the private subnet of a VPC

*deploy a NAT Gateway (or NAT instance) into a public subnet of the VPC

*deploy an Internet Gateway into the VPC

*give the NAT an Elastic IP

*make the NAT be the default route for the Lambda subnet

*whitelist the NAT's Elastic IP at the remote firewall


text:
Q: Install4j: how to implement tooltips for a list component in a form I've tried a few different ways to implement tooltips support for a list component in a form. Following is code that I think should be close but it does not work.
The code is placed in the initialization script for the list component in a simple form and the list is the only component in the form.
My workaround is to display what would be the contents of the tooltip in static text below the listbox and change the static text as the selection in the list changes. I have this working but it's not the best way to present the information.
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

ToolTipManager.sharedInstance().registerComponent(configurationObject);

configurationObject.addMouseMotionListener(new MouseMotionAdapter()
{
    @Override
    public void mouseMoved(MouseEvent e) {
        JList<?> l = (JList<?>) e.getSource();
        Integer i = l.locationToIndex(e.getPoint());
        ListModel<?> m = (ListModel<?>) l.getModel();
        if (i >= 0) {
            String item = m.getElementAt(i).toString() + i.toString();
            l.setToolTipText(item);
        }
    }

});

I believe I could do this by subclassing the list and overriding getToolTipText but I'm not sure how to do this in install4j.


text:
Q: Determine the set of all complex number z satisfying following conditions I'm having some troubles of calculating complex numbers where I need to deal with absolute values and inequalities.
Here is an example I've been working on but I get stuck
Re(2/z)+Im(4/z)<1
I use z=x+iy
And find 1/z = (x-iy)/(x^2+y^2)
So
Re(2/z) = 2x/(x^2+y^2) and
Im(4/z) = (-4y)/(x^2+y^2)
If I just forget about the inequality and make it equal to 1. I get:
2x-i4y = x^2+y^2
Which is a circumference with a complex radius.
Now I'm not sure what to do or if I'm going in the correct direction.
I hope you can help me.

A: That factor of $i$ you added is spurious. You should get $2x-4y<x^2+y^2$, which is the inside of a circle of real radius.

A: Solve $$\frac{2x}{x^2+y^2}-\frac{4y}{x^2+y^2}<1$$

A: Your equation is slightly wrong: that $i$ should not be there. It should be
$$2x - 4y = x^2 + y^2
$$
Now its radius is a real number, and you should have no trouble plotting it.
To solve the inequality, just check a point on the inside of the circle, and another point on the outside. That will tell you whether the inside is part of the solution, and whether the outside is part of the solution.


text:
Q: Is it better to loop through a 2D array of n pairings of values or have n if statements? - Java I need to assess objects adjacent to my current object. There may be one above, below, left and right of my current position. If my current position is (x, y), then my adjacent objects are at positions: (x-1, y), (x+1, y), (x, y-1), (x, y+1).
Is it better to calculate these 4 positions and then store them in a 2D array, traversing them with a for... in loop:
int[][] adjacentObjects = {
          {x-1, y},
          {x+1, y},
          {x, y-1},
          {x, y+1} };

for (int[] adjacent : adjacentObjects) { ...
  if (adjacent[0] == ...) // x coordinate
  if (adjacent[1] == ...) // y coordinate

Or am I better off just having 4 near-identical if statements? Each would be 4 lines, where the x and y coordinates are the only difference.
My current mindset is that the for... in loop is cleaner, though not as readable, but I don't really know which is 'better.'
I've also thought about using another method where I'd pass the values of x and y but I also need access to another two 2D arrays in the current method, and it seems wasteful to send those as parameters to the new method as well.
I'm using Java, but I don't feel this is specific to any one language. Any help is greatly appreciated!


text:
Q: Check for SQL Server existence before connection We need to check for the existence of a SQL server across all domains prior to attempting to connect to the server. We can loop through the list of servers on the local domain use SQLDataSourceEnumerator, but that takes a few seconds to load up and it only gets the local domain. We are using SQL Server 2005 and 2008 servers as well as .Net 2010. We don't want to attempt to connect and wait for the 30 second or more timeout that appears to be standard if the server doesn't exist.
Any suggestions would be helpful.

A: Try to connect with a smaller timeout. You can set the timeout in the connection string:
Connect Timeout=2;

You can't check faster than this. If there is no SQL Server at the remote endpoint the TCP connection does not receive a response and times out. Because there is no (negative) response you can't tell if there is no server at all or just a very slow one.
So a timeout is the best you can do to determine if there is a server listening or not.


text:
Q: Map Reduce by date with RockMongo admin panel I am trying to find the best way to clean my Mongo DB from old rows. This is the row structure:
{
    "_id": ObjectId("52adb7fb12e20f2e2400be38"),
    "1": "2013-12-15 06: 07: 20",
    "2": "1",
    "3": "",
    "4": "",
    "5": "ID",
    "6": "139.195.98.240",
    "7": "",
    "8": "youtube",
    "9": NumberInt(0),
    "10": "",
    "11": ""
}

The date field is this.1. So I want to set a delte method for all rows older then 30 days.
So I figured out that a map can help with this task, if there are any other suggestion please feel free to suggest.
This is the map function that i am trying to run:
{
    mapreduce : "delete_rows",
    map : function () {
        var delete_date = new Date();
        delete_date.setDate(delete_date.getDate()-7);
        row_date = new Date(this.1);
        if(row_date <  delete_date){
            emit(this._id,{date: this.1}, {all_data: this});
        }
    },
    out : {
        "delete_rows"
    },
    keeptemp:false,
    jsMode : false,
    verbose : false
}

I get the following error at rockmongo query window:
Criteria must be a valid JSON object

Can anyone jelp me with this syntax?
Thanks


text:
Q: Node.js script appears to be synchronous even though I would expect it to be asynchronous? I'm doing a Node.js exercise (from Nodeschool.io) which reads:
 # LEARN YOU THE NODE.JS FOR MUCH WIN!

 ## JUGGLING ASYNC (Exercise 9 of 13)

  This problem is the same as the previous problem (HTTP COLLECT) in that
  you need to use http.get(). However, this time you will be provided with
  three URLs as the first three command-line arguments.

  You must collect the complete content provided to you by each of the URLs
  and print it to the console (stdout). You don't need to print out the
  length, just the data as a String; one line per URL. The catch is that you
  must print them out in the same order as the URLs are provided to you as
  command-line arguments.

In order to test my implementation, I made a little Flask app like so:
from flask import Flask
import time

app = Flask(__name__)

@app.route("/1")
def hello1():
    time.sleep(1)
    return "Hello 1! "

@app.route("/2")
def hello2():
    time.sleep(0.5)
    return "Hello 2!"

@app.route("/3")
def hello3():
    return "Hello 3!"

To get me started on the Nodeschool exercise, I wrote the following Javascript code (jugglingAsync.js):
var http = require('http');
var bl = require('bl');

var handler = (response) => {
    response.pipe(bl(function (err, data) {
    if (err) {
        return console.error(err)
    }
    console.log(data.toString())
    }))
}

http.get(process.argv[2], handler)
http.get(process.argv[3], handler)
http.get(process.argv[4], handler)

However, If I run this script, I see the responses 1-3 printed in that order, instead of the reverse order:
Kurts-MacBook-Pro:learnyounode kurtpeek$ node jugglingAsync.js http://localhost:5000/1 http://localhost:5000/2 http://localhost:5000/3
Hello 1!
Hello 2!
Hello 3!

If these commands are run asynchronously, however, I would actually expect the results to be printed in reverse order. Can someone explain why this is not the case?

A: It turns out Theodor B is right: by default, the underlying Werkzeug server of Flask runs in a single thread and can only process one request at a time. In order to run it multi-threaded, one has to pass threaded=True to app.run() (cf. http://werkzeug.pocoo.org/docs/0.14/serving/#werkzeug.serving.run_simple):
if __name__ == "__main__":
    app.run(threaded=True)

Now the Node.js script prints the expected output:
Kurts-MacBook-Pro:learnyounode kurtpeek$ node jugglingAsync.js http://localhost:5000/1 http://localhost:5000/2 http://localhost:5000/3
Hello 3!
Hello 2!
Hello 1!


text:
Q: Simple proof for a continuous-time linear system and impulse $\delta$? From Schaum's Outlines of Signals & Systems:
Let's work with continuous-time signals.
Let $T$ be a linear time-invariant system (LTI).
Input $x(t)$ can be expressed as $x(t) = \int_{-\infty}^{\infty} x(\tau) \delta(t-\tau) d \tau$.
Then output $y(t)$ can be expressed as $y(t) = \int_{-\infty}^{\infty} x(\tau) T\{\delta(t - \tau)\}d\tau$
I'm not sure how they arrived at the last bolded statement without showing how.  My first thought is to break down the integral into a sum, but not sure if you can do that when working with $\delta$, and it seems like a non-elegant approach.  Please lucidate on a better approach.  Thanks.


text:
Q: LOAD DATA LOCAL INFILE cannot find path Im using MySQL Workbench and tried using load data local infile. I have my table "mysample" with three columns: id, names, age.
Im trying to load a csv file and import it inside my table. id is auto_increment so I will insert the datas to names and age.  This is my query:
load data local infile 'C:\Users\vissia18\Desktop\sample.csv' into table mysample fields terminated by ','
enclosed by '"'
lines terminated by '\n'
(names, age)

But the problem is I'm having an error like this:
Error Code: 2. File 'C:\Users\vissia18\Desktop\sample.csv' not found

Why is that? How should I fix this?

A: According to MySQL documentation:

The file name must be given as a literal string. On Windows, specify backslashes in path names as forward slashes or doubled backslashes.