text:
Q: Type 'ns1:Budget' is not validly derived from the type definition, 'Campaign', of element 'ns1:operand' Using this package for laravel: https://github.com/nikolajlovenhardt/laravel-google-ads
When i try to write a campaign, the following error occur:

SoapFault in AdsSoapClient.php line 115: Unmarshalling Error:
  cvc-elt.4.3: Type 'ns1:Budget' is not validly derived from the type
  definition, 'Campaign', of element 'ns1:operand'.

soap.log: http://pastebin.com/raw/TmU6XSfp

[2017-03-10 14:33:57] AW_SOAP.INFO: clientCustomerId=556-905-2150
  operations=1 service=BudgetService method=mutate responseTime=145
  requestId=00054a61407809890a378107c00d151f server=adwords.google.com
  isFault=0 faultMessage=   [2017-03-10 14:33:58] AW_SOAP.WARNING:
  clientCustomerId=556-905-2150 operations= service=CampaignService
  method=mutate responseTime= requestId= server=adwords.google.com
  isFault=1 faultMessage=Unmarshalling Error: cvc-elt.4.3: Type
  'ns1:Budget' is not validly derived from the type definition,
  'Campaign', of element 'ns1:operand'.    [2017-03-10 14:33:58]
  AW_SOAP.NOTICE: POST /api/adwords/cm/v201609/CampaignService?wsdl
  HTTP/1.1 Host: adwords.google.com Connection: Keep-Alive User-Agent:
  PHP-SOAP/7.1.2-3+deb.sury.org~xenial+1 Content-Type: text/xml;
  charset=utf-8 SOAPAction: "" Content-Length: 1436 Authorization:
  REDACTED
 556-905-2150REDACTEDunknown
  (AwApi-PHP, googleads-php-lib/25.2.0,
  PHP/7.1.2-3+deb.sury.org~xenial+1)falsefalseADDInterplanetary Cruise Budget
58c2b955417e250000000STANDARDADDInterplanetary Cruise
58c2b955cc997PAUSED1050511653DISPLAYMANUAL_CPC
HTTP/1.1 500 Internal Server Error Content-Type: text/xml;
  charset=UTF-8 Date: Fri, 10 Mar 2017 14:33:58 GMT Expires: Fri, 10 Mar
  2017 14:33:58 GMT Cache-Control: private, max-age=0
  X-Content-Type-Options: nosniff X-Frame-Options: SAMEORIGIN
  X-XSS-Protection: 1; mode=block Server: GSE Alt-Svc: quic=":443";
  ma=2592000; v="36,35,34" Accept-Ranges: none Vary: Accept-Encoding
  Transfer-Encoding: chunked
soap:ClientUnmarshalling
  Error: cvc-elt.4.3: Type 'ns1:Budget' is not validly derived from the
  type definition, 'Campaign', of element 'ns1:operand'.

Copied from the "Basic Operations Samples"
$customerClientId = 'xxx-xxx-xxxx';

$adWordsService = new AdWordsService();

/** @var BudgetService $budgetService */
$budgetService = $adWordsService->getService(BudgetService::class, $customerClientId);

// Create the shared budget (required).
$budget = new Budget();
$budget->setName('Interplanetary Cruise Budget #' . uniqid());
$money = new Money();
$money->setMicroAmount(50000000);
$budget->setAmount($money);
$budget->setDeliveryMethod(BudgetBudgetDeliveryMethod::STANDARD);

$operations = [];

// Create a budget operation.
$operation = new BudgetOperation();
$operation->setOperand($budget);
$operation->setOperator(Operator::ADD);
$operations[] = $operation;

// Create the budget on the server.
$result = $budgetService->mutate($operations);
$budget = $result->getValue()[0];

// Create a campaign with only required settings.
$campaign = new Campaign();
$campaign->setName('Interplanetary Cruise #' . uniqid());
$campaign->setAdvertisingChannelType(AdvertisingChannelType::DISPLAY);

// Set shared budget (required).
$campaign->setBudget(new Budget());
$campaign->getBudget()->setBudgetId($budget->getBudgetId());

// Set bidding strategy (required).
$biddingStrategyConfiguration = new BiddingStrategyConfiguration();
$biddingStrategyConfiguration->setBiddingStrategyType(
        BiddingStrategyType::MANUAL_CPC);
$campaign->setBiddingStrategyConfiguration($biddingStrategyConfiguration);

$campaign->setStatus(CampaignStatus::PAUSED);

// Create a campaign operation and add it to the operations list.
$operation = new CampaignOperation();
$operation->setOperand($campaign);
$operation->setOperator(Operator::ADD);
$operations[] = $operation;

/** @var CampaignService $campaignService */
$campaignService = $adWordsService->getService(CampaignService::class, $customerClientId);

$result = $campaignService->mutate($operations);

foreach ($result->getValue() as $campaign) {
    printf("Campaign with name '%s' and ID %d was added.\n",
        $campaign->getName(),
        $campaign->getId()
    );
}

Receiving campaigns with the sample code works...

A: I fink, it's because, you make  $campaignService->mutate($operations); with budget operation
$operations = [];
// Create a budget operation.
$operation = new BudgetOperation();
$operation->setOperand($budget);
$operation->setOperator(Operator::ADD);
$operations[] = $operation;

And
// Create a campaign operation and add it to the operations list.
$operation = new CampaignOperation();
$operation->setOperand($campaign);
$operation->setOperator(Operator::ADD);
$operations[] = $operation;

$result = $campaignService->mutate($operations);

You need to do $operations = []; again before $campaignService->mutate($operations);
$operations = [];
// Create a campaign operation and add it to the operations list.
$operation = new CampaignOperation();
$operation->setOperand($campaign);
$operation->setOperator(Operator::ADD);
$operations[] = $operation;

/** @var CampaignService $campaignService */
$campaignService = $adWordsService->getService(CampaignService::class, $customerClientId);
$result = $campaignService->mutate($operations);


text:
Q: Regarding customizing sorting the list In an interview an question was asked , that there is a list containg few strings like below shown, have to do character by character comparison
cDgHkJ----------->index 0
bAgHtR----------->index 1
aBEfgj----------->index 2

Now I have to sort the list , in a way that i should ignore the case that is case insensitive it should be but in the from like this
comparision between index 2 and index 1 as shown below
aAEfgj----------->index 1
bBgHtR----------->index 2

then comparison between index 1 and index 2
cDgHkJ----------->index 0
aAEfgj----------->index 1   ( which we first sorted in first step)

-------Final Sorted List---------------
aAEfgJ---------> ultimately final sorted list , I want to achieve
cDgHkj----------->index 1
aBEfgj----------->index 2

Please advise how to achieve this.

A: You can do this easily by defining your own comparator which compares both strings after they have been forced to either lower or upper case:
List<String> strings = new ArrayList<>();

// fill with strings

Collections.sort(strings,
                 new Comparator<String>() {
                     @Override
                     public int compare(String s1, String s2) {
                         return s1.toLowerCase().compareTo(s2.toLowerCase());
                     }
                 }
);

redpajama_set_name: RedPajamaStackExchange


text: Q: estimating coefficients of multiple regression with keraregressor I used a sequential model and kerasregressor to create multiple regression for the variables x1 and x2. the model worked successfully and I could predict y for test data correctly but now I want to derive coefficients of this regression. what do I do?`


text:
Q: Unistall Realtek USB Ethernet Network Adapter I would like to uninstall the "Realtek USB Ethernet Network Adapter"
I can find it under System Information -> Software -> Installations in a list but don't know how to get rid of it.

A: Check the Realtek site for the latest driver of your USB Ethernet adapter and download it. The driver zip file should contain an uninstall.zip. Unzip this also and double-click the resulting uninstall.command file. Enter the admin (root) password and reboot your Mac.
Using an uninstaller provided with the driver installer is recommended.
Provided it's a RTL8153 chip you can also pour the following content into a uninstall.command file and execute it:
#!/bin/sh
. /etc/rc.common

echo "                                                                  "
echo "Please type the password of \"root\" to Uninstall ..."
FROM=`dirname "$0"`

echo "Removing Apple USB Ethernet Driver..."

sudo kextunload /System/Library/Extensions/IONetworkingFamily.kext/Contents/PlugIns/AppleRTL815X*.kext
sudo kextunload /Library/Extensions/AppleRTL815X*.kext

sudo rm -rf /System/Library/Extensions/IONetworkingFamily.kext/Contents/PlugIns/AppleRTL815X*.kext
sudo rm -rf /Library/Extensions/AppleRTL815X*.kext

sudo touch /System/Library/Extensions/
sudo touch /Library/Extensions/

echo "Uninstall Complete."

Depending on your system version you have to disable SIP.
In Catalina you have to disable SIP in Recovery Mode first and mount the system volume read-write after rebooting: sudo mount -rw /. Additionally you have to chmod +x uninstall.command and add it to System Preferences > Security & Privacy > Privacy > Full Disk Access.
Enable SIP after uninstalling the driver!

If your kext has a different name (e.g. AppleUSBRealtek8153Patcher.kext) or paths have changed, you have to adjust it respectively in the file uninstall.command (e.g. AppleRTL815*.kext). Use at your own risk!


text:
Q: Disk based HashMap Does Java have (or is there a library available) that allows me to have a disk based HashMap?  It doesn't need to be atomic or anything, but it will be accessed via multiple threads and shouldn't crash if two are accessing the same element at the same time.
Anyone know of anything?

A: Sounds like you need something close to a lightweight db. Have you looked at/considered Java DB? A light db with a single, indexed table would basically be a disk-based, thread-safe hash map.

A: JDBM2 is exactly what you are asking. It provides a HashMap backed up by disk storage (among other maps). Its fast, thread-safe and the API is really simple.

A: Chronicle Map implements ConcurrentMap and persists data to disk via mapping it's memory to a file.
Chronicle Map is conceptually very similar to MapDB (provides similar builder API and Map interface), but Chronicle Map is times faster than MapDB and has much better concurrency (Chronicle Map uses highly striped multi-level spin locks).

A: Project Voldemort is also a really fast/scalable/replication "Hashmap". It is used at LinkedIn an performance is also pretty good:
A quote from their site:

Here is the throughput we see from a
  single multithreaded client talking to
  a single server where the "hot" data
  set is in memory under artificially
  heavy load in our performance lab:
Reads: 19,384 req/sec
   Writes: 16,559 req/sec

A: MapDB
MapDB provides concurrent TreeMap and HashMap backed by disk storage or off-heap-memory. It is a fast, scalable and easy to use embedded Java database engine. It is packed with features such as transactions, space efficient serialization, instance cache and transparent compression/encryption. It also has outstanding performance rivaled only by native embedded db engines.
http://www.mapdb.org/
jdbm2
Embedded Key Value Java database.
https://code.google.com/p/jdbm2/

A: So the year is now 2016. And if anyone's looking to tackle this problem, I found out that the low level environments API in Xodus from JetBrains works for this same purpose, using their computeInTransaction store lambdas.
Granted, it's not as slick as having a pure Map instance, but it worked for my use case.
Another recent option is to use H2's MVStore storage engine which does the same thing, but I think it's more tailored towards the database itself.
Cheers!

A: In 2018 the lightest persistent key value store is the H2 Database with it's MVStore:

The MVStore is a persistent, log structured key-value store. It is
  planned to be the next storage subsystem of H2, but it can also be
  used directly within an application, without using JDBC or SQL.

*

*MVStore stands for "multi-version store".

*Each store contains a number of maps that can be accessed using the java.util.Map interface.

*Both file-based persistence and in-memory operation are supported.

*It is intended to be fast, simple to use, and small.

*Concurrent read and write operations are supported.

*Transactions are supported (including concurrent transactions and 2-phase commit).

*The tool is very modular. It supports pluggable data types and serialization, pluggable storage (to a file, to off-heap memory), pluggable map implementations (B-tree, R-tree, concurrent B-tree currently), BLOB storage, and a file system abstraction to support encrypted files and zip files.

h2-mvstore has no dependencies and version 1.4.200 is a single jar of 0.3 Mb
I also looked at:

*

*MapDB (13 meg dependencies)

*chronicle-map (5.5 meg dependencies - fast optionally distributed)

*lmdbjava (2 meg java dependencies + lmdb C library) - fastest implementation but not thread safe out of the box.

A: Either properties files or Berkeley DB might be what you're looking for. The java.util.Properties itself implements java.util.Map and provides methods to load from and store to a file. The Berkeley DB is often been recommended as a lightweight key-value pair datastore.


text:
Q: Best way to upload/deploy jar files in Github I've used Google code in the past and had the ability to upload runnable jar files for download, now I am using GitHub and understand it had a download tab where developers were able to upload files (i.e. a runnable jar file), unfortunately it is deprecated now.
For non developers to download the whole project as a zip file and compile it, is a bit complicated. Is there another/better way to deploy/upload a runnable jar files on GitHub for download?

A: Since 2d July 2013, you now have a new way to "upload runnable jar files for download" , through a release.

Releases, a workflow for shipping software to end users.
  Releases are first-class objects with changelogs and binary assets that present a full project history beyond Git artifacts. They're accessible from a repository's homepage:

*

*Releases are accompanied by release notes and links to download the software or source code.

*Following the conventions of many Git projects, releases are tied to Git tags. You can use an existing tag, or let releases create the tag when it's published.

*You can also attach binary assets (such as compiled executables, minified scripts, documentation) to a release. Once published, the release details and assets are available to anyone that can view the repository.

That now replaces the old binary upload service, which was removed in December 2012.

A: You would have to include them in the repo, which is not wise because Git does best with source code, not binary files.
Perhaps a better option is
to use S3
as they recommend, or Google Code.

A: Github used to have a download link where you could upload your binaries.
As of the end of 2012, the download option has been removed.
My personal favorite is to use source forge.
Instructions on integrating github with source forge can be found here
http://sourceforge.net/publish/?source=github
Here is an example of an arduino project that uses github for source, and source forge for binaries.
https://sourceforge.net/projects/all-spark-cube/
https://github.com/spudstud/All-Spark-Cube


text:
Q: how to download hackerrank problems in pdf? When we open up a problem on http:www.hackerrank.com, there is an option to download the problem in pdf format. Here I want to download all the hackerrank problems from algorithm domain. It will take near about 3-4 hours if I download them all one by one by clicking the button again and again and it will be the most tedious work I'd have ever done. Is there any way to download them all at once using either a program or some other way?

A: From a command line prompt you can do this with a simple one-liner:
for i in `seq -f "%03g" 1 79` ; do curl -L "https://www.hackerrank.com/rest/contests/projecteuler/challenges/euler$i/download_pdf?language=English" > hr_euler_$i.pdf ; done

Just change 1 and 79 to the numbers of the first and last problems you want to download.
This will save all the PDFs in the current directory with filenames of the form hr_euler_001.pdf, hr_euler_002.pdf, etc.


text:
Q: Node.js filesystem сделать цикл для каждой строки Всем привет. Есть файл users.txt, он содержит следующее:
email@asdasd.ru:ashasdjh
email@asdhs.ru:gjdfgjdf
asddfj@asdf.ru:sjsdfk

Сделал банальный fs.watch, который отслеживает любое изменение в файле. Подскажите, пожалуйста, как сделать цикл, который будет делать следующие действия:
*открыть файл*
 *цикл для каждой строки*
  *записываем все, что было до : в массив users[i].email, что после - users[i].password
*закрываем файл*

Как правильно сделать такой цикл? Как работать со строками в файлах?
P.S. скрипт fs.watch:
fs.watchFile('users.txt', function(curr, prev) {
  var file_handle = fs.openSync("users.txt", "r", 0644);
  var data = fs.readSync(file_handle, 10000, null, 'ascii');
  console.log(data);
fs.closeSync(file_handle);
});

A: const fs = require('fs');
const filename = 'users.txt';
const users = [];
fs.watch(filename, () => {
    const text = fs.readFileSync(filename).toString();
    users.push(...text.split('\n').map(str => {
        email: str.split(':')[0].trim(),
        password: str.split(':')[1].trim()
    }));
    console.log(users);
});


text:
Q: What exactly does $(document).ready guarantee? Running my (rather complex) JavaScript/jQuery application in Google's Chrome browser, it would appear that $(document).ready fires while some of the JavaScript files have not yet loaded.
The relevant code (simplified):
In my HTML file
<script>var httpRoot='../../../';var verifyLoad = {};</script>

<script src="../../../globalvars.js"></script>
<script src="../../../storagekeys.js"></script>
<script src="../../../geometry.js"></script>
<script src="../../../md5.js"></script>
<script src="../../../serialize.js"></script>
...
<script src="../../../main.js"></script>

As the last statement of each of the .js files except main.js:
verifyLoad.FOO = true; // where FOO is a property specific to the file

e.g.
verifyLoad.jquerySupplements = true;

verifyLoad.serialize = true;

In main.js:
$(document).ready(function() {
    function verifyLoadTest (scriptFileName, token) {
        if (!verifyLoad.hasOwnProperty(token)) {
            console.log(scriptFileName + ' not properly loaded');
        };
    };
    verifyLoadTest('globalvars.js', 'globalvars');
    verifyLoadTest('storagekeys.js', 'storagekeys');
    verifyLoadTest('geometry.js', 'geometry');
    verifyLoadTest('md5.js', 'geometry');
    verifyLoadTest('serialize.js', 'serialize');
    ...
}

Much to my amazement, I see some of these trigger. This does not match my understanding of $(document).ready. What am I missing?

A: The document's ready event is fired when the browser has parsed the HTML file from beginning to end and converted it into a DOM structure. It does not in any way guarantee that any other resources (e.g. stylesheets, images or, as in this case, scripts) will have loaded. It only refers to the DOM structure, and is fired irrespective of the loading status of the page's resources.
If you want to wait for resources to load, use the window's load event, which is fired only when every element on the page has finished loading.
See:

*

*.load

*.ready


text:
Q: Calculating Orbital Vectors in the Future For the 2D space simulator that I am writing (please note, it is not at all homework), I require formulas that will give me the location and velocity of a spaceship, relative to the parent celestial body, at a specific time in the future.
There is only one planetary mass that provides a gravitational attraction for the spaceship, and the spaceship's mass is negligible. From the initial $\vec{r}$ and $\vec{v}$ relative to the planet, I already know how to compute many things, such as:

*

*standard gravitation parameter $\mu = G M$

*eccentricity $e$

*specific angular momentum $h$

*semi-major axis $a = \frac{h^2}{\mu(1 - e^2)}$ (is this even correct?)

*longitude of periapsis $\varpi$

*eccentric anomoly $E$ from true anomaly $\theta$ (an angle the describes an offset from $\varpi$), and vice versa

So using all these values, or possible more (or less), what formulas can I use to compute the position and velocity in $t$ seconds? I have already tried using the following formulas to compute the position in the future:

*

*mean anomaly $M(E) = E - e sin E$

*mean anomaly at periapsis $M_0 = M(E = \theta = 0)$

*mean anomaly at a certain time $M(t) = M_0 + t \sqrt{\frac{\mu}{a^3}}$

However, those formulas don't work for certain orbits (such as hyperbolic orbits, where $a < 0$). Also, I may have just programmed the formulas incorrectly, but using mean anomaly, my simulator does not correctly determine position in the future.
So, I have already tried several approaches to computing position and velocity in the future, and they didn't work. What are the correct formulas?
Thanks!

A: There's no closed form solution for the eccentric anomaly as a function of time. But there are series solutions that converge rather well. This is actually why Bessel functions were discovered! See here or here. You will  have to solve the relationship between the eccentric anomaly and mean anomaly, i.e., $M =  E - e \cdot \sin E$ numerically, e.g., using Newton's method or the like.
If you take a look at the following plot of $E$ vs $M$ (at left),

you can see that inverting this function can be done very quickly (and very stably) using Newton's method or bisection, since it is monotonic and single-valued.
So once you have $E$ in terms of $M(t) = M_0 - \omega t$ numerically, you can find $r$ and $\theta$,
$r = a(1-e \cos E)$,
and $\theta$ which you said you already have.
If you are just interested in speed, use the Vis-Viva equation
$v^2 = GM \left({{ 2 \over{r}} - {1 \over{a}}}\right)$
however, with the position of the particle known in polar coordinates, it is just a matter of differentiation to get it's velocity vector, and substituting the eccentric anomaly back in. The meat of it is on the last page of this link, although it's easy to find in most texts on classical mechanics. I won't repeat it here because I will probably just make a typo and it will have to be repeated anyway.
For anyone who is still interested, here is another treatment of the problem in detail:
Convert Kepler elements to Cartesian coordinates
This is pretty much the canonical way of approaching this problem, and has been for hundreds of years.
This method can also be used in the hyperbolic case (hyperbolic Kepler's equation) or in the parabolic case (Baker's equation), although the equations are somewhat different.
If you're simulating things you might want to consider using a numerics library anyway because then you can start to deal with multibody problems like orbital transfers, and of course, thrust :)

A: First of your equation of your semi-major axis seems correct to me.
Secondly there is no explicit equation of your position as a function of time. However there is one the other way around, so an equation for time as a function of your position:
$$
t(\theta_0,\theta_1)=\sqrt{\frac{a^3}{\mu}}\left[2\tan^{-1}\left(\frac{\sqrt{1-e^2}\tan{\frac{\theta}{2}}}{1+e}\right)-\frac{e\sqrt{1-e^2}\sin{\theta}}{1+e\cos{\theta}}\right]^{\theta_1}_{\theta_0}
$$
For small steps in time you could use a polynomial, since you can find any order time derivative of the true anomaly $\theta$:
$$
\omega(\theta)=\frac{\delta}{\delta t}\theta=\frac{\delta \theta / \delta \theta}{\delta t / \delta \theta}=\frac{1}{\delta t / \delta \theta}=\sqrt{\frac{\mu}{a^3\left(1-e^2\right)^3}}\left(1+e\cos{\theta}\right)^2,
$$
$$
\alpha(\theta)=\frac{\delta^2}{\delta t^2}\theta=\frac{\delta}{\delta t}\omega=\frac{\delta \omega / \delta \theta}{\delta t / \delta \theta}=\frac{-2e\mu\sin{\theta}}{a^3(1-e^2)^3}(1+e\cos{\theta})^3,
$$
$$
ect.
$$
So:
$$
\theta(t_0+\Delta t)=\theta_{t_0}+\Delta t\omega(\theta_{t_0})+\frac{1}{2}\Delta t^2\alpha(\theta_{t_0})+O(\Delta t^3)
$$
However for big steps in time this will not be an accurate method, but you could use it to construct an iterative numerical method by calculating the time from $\theta(t_0+\Delta t)$ to determine the new $\Delta t$:
$$
\theta_{n+1}=\theta_n+\Delta t_n\omega(\theta_n)+\frac{1}{2}\Delta t_n^2\alpha(\theta_n)
$$
$$
\Delta t_{n+1}=\Delta t_n-t(\theta_n, \theta_{n+1})
$$
In certain cases it might be that this method would be unstable (when $|\Delta t_{n+1}|>|\Delta t_n|$) in that case you could split up your time step into multiple steps, or increase the order of the polynomial. There are probably a lot of other numerical methods which are better/faster, but I am not an expert in this area, and this should work and give you in idea of how to solve this.
For closed orbits you might also be able to reduce the size of your time step by taking a modified modulo operation: $\Delta t_{new}=\Delta t-round\left[\frac{\Delta t}{T}\right]T$, where $T$ is equal to the period of the orbit.
Edit I
I was messing with this myself in MATLAB and noticed that I often encountered a problem. I think most of the time because the calculated time was complex because $\theta_{n+1}$ exceeded the maximum range, for example a hyperbolic orbit will never be able to reach $\theta=\pi$. This range is determined by the $\tan^{-1}$, so when $e\ge 1$ than $\theta_{max}=2\tan^{-1}\left(\frac{1+e}{\sqrt{e^2-1}}\right)$. Now it does seems to work reliable, unless I try to calculate something which is getting near the machine accuracy. By the way I do not know in which computer language you are programming this simulator, but there is a big change that it will not be able to handle complex numbers. So you would have to keep this in mind when performing calculations, since each calculation should return real numbers, but certain sub-results will imaginary.
Edit II
I also looked into other methods to solve this, such as Runge–Kutta, however I was not able to prevent unstable behavior (when the time step is to big). However a method which would always be stable is a sort of binary search algorithm, in which check if an angle $\theta_{n+1}=\theta_n + \Delta\theta$ would yield a step in time smaller than you desired step and if so save that value. And after each iteration the step $\Delta\theta$ will be divided by two. For this you do have to choose the initial $\Delta\theta$ correctly, namely $\Delta\theta_0=\tan^{-1}\left(\frac{1+e}{e^2-1}\right)$ when $e\ge 1$ and $\Delta\theta_0=\pi$ when $e<1$. The convergent rate is not as good as that of the previous methods, especially when $e$ is big and the desired time step will result in a very high radius. So you might want to switch methods there, but I do not know when the other method will be stable. Another option might be to use the first method, but to perform the calculations relative to the radius, $r$, instead $\theta$:
$$
t(r)=\sqrt{\frac{a^3}{\mu}}\left(2\tan^{-1}{\sqrt{\frac{r-a(1-e)}{a(1+e)-r}}}-\sqrt{e^2-\left(\frac{r}{a}-1\right)^2}\right)
$$
$$
\dot{r}=\sqrt{\frac{\mu}{a}}\frac{\sqrt{e^2a^2-(r-a)^2}}{r}
$$
$$
\ddot{r}=\mu\left(\frac{a(1-e^2)}{r^3}-\frac{1}{r^2}\right)
$$
$$
\dddot{r}=\sqrt{\frac{\mu^3}{a}}\frac{\sqrt{e^2a^2-(r-a)^2}}{r^5}(2r-3a(1-e^2))
$$


text:
Q: Code for Discord.js bot responds with error "TypeError:" I'm testing sending embed messages for a Discord Bot using Discord.js which is basically a node.js module used to interact with Discord's API. This is the code i'm using for the bot to send the embed message:
const Discord = require('discord.js');
const embed = new Discord.RichEmbed()
    .setTitle("This is your title, it can hold 256 characters")
    .setAuthor("Author Name", "https://i.imgur.com/lm8s41J.png")
    .setColor(0x00AE86)
    .setDescription("This is the main body of text, it can hold 2048 characters.")
    .setFooter("This is the footer text, it can hold 2048 characters", "http://i.imgur.com/w1vhFSR.png")
    .setImage("http://i.imgur.com/yVpymuV.png")
    .setThumbnail("http://i.imgur.com/p2qNFag.png")
    .setTimestamp()
    .setURL("https://discord.js.org/#/docs/main/indev/class/RichEmbed")
    .addField("This is a field title, it can hold 256 characters",
        "This is a field value, it can hold 1024 characters.")
    .addField("Inline Field", "They can also be inline.", true)
    .addBlankField(true)
    .addField("Inline Field 3", "You can have a maximum of 25 fields.", true);

  message.channel.send({embed});

When I run the code I get this error in the Visual Studio Code IDE:

TypeError: (intermediate
  value).setTitle(...).setAuthor(...).setColor(...).setDescription(...).setFooter(...).setImage(...).setThumbnail(...).setTimestamp(...).setURL(...).addField(...).addField(...).addBlankField
  is not a function

A: There is not addBlankField() function in MessageEmbed class when you look at documentation, check your discord.js version.
As of v12.0.0 they changed RichEmbed to MessageEmbed.

A: If you want to add a blank field in another way, because .addBlankField() isn't supported in discord.js v12. You can write this:
.addField("** **", "** **")

This will add a field with an almost empty title and description (They both contain one space after you sent the embed)

A: Try this :
    const Discord = require('discord.js');
    const client = new Discord.Client();
    client.login('Your bot\'s token here');
    client.on('ready', () => console.log('I\'m ready !');
    client.on('message', message => {
        const embed = new Discord.MessageEmbed()
            .setTitle("This is your title, it can hold 256 characters")
            .setAuthor("Author Name", "https://i.imgur.com/lm8s41J.png")
            .setColor('WHITE')
            .setDescription("This is the main body of text, it can hold 2048 characters.")
            .setFooter("This is the footer text, it can hold 2048 characters", "http://i.imgur.com/w1vhFSR.png")
            .setImage("http://i.imgur.com/yVpymuV.png")
            .setThumbnail("http://i.imgur.com/p2qNFag.png")
            .setTimestamp()
            .setURL("https://discord.js.org/#/docs/main/indev/class/RichEmbed")
            .addField("This is a field title, it can hold 256 characters",
        "This is a field value, it can hold 1024 characters.")
            .addField("Inline Field", "They can also be inline.", true)
            .addField("Inline Field 3", "You can have a maximum of 25 fields.", true);

  message.channel.send(embed);

If that doesn't work, I would suggest checking the official documentation clicking here

A: .addField('\u200B', '\u200B');


text:
Q: Oracle Apex - Interactive GRID Word wrap for headers and cells without HTML tag I have an interactive grid in Oracle Apex tool. I need to wrap the heading without html tag.
Is it possible to do a word wrap on headers and cells ?

A: Try this CSS (you can put it in the page Inline CSS attribute):
.a-GV-table td, .a-GV-headerLabel {
    white-space: normal;
}

That works for me.


text:
Q: What does "rack" mean in "rack of lamb" The word "rack" is likely one the words with the most meanings, like "dull" or "jag".
Aside from a kind of shelf and a verb, it appears to mean something related to food. What is this meaning?

A: A rack of lamb is made from the rib cage of the sheep.
A rack is (originally) a type of framework with bars on which you can place or hang things.  In a rack of lamb, the ribs form something that looks like a rack in the framework sense.


text:
Q: Update ListView Item TextView I am unable to update TextView item on ListView row.
        @SuppressLint("ResourceAsColor")
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
        row=convertView;
        if(row==null)
        {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.lv_lineup_single, parent, false);
        }

.
            ibCheckbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                strArtistClicked = ls_Artist.get(position);
                accessWebService_GetDBData_FollowUnfollow();

                strArtistCheckbox = ls_FollowingValue.get(position);

                if (strArtistCheckbox.equals("1")){

                    ls_FollowingValue.set(position, "0");
                    ibCheckbox.setImageResource(R.drawable.checkbox_empty);

                    //View followersCountUpdate = lv.getChildAt(position);
                    View followersCountUpdate = lv.getAdapter().getView(position, null, lv);

                    tvArtistFollowersCount = followersCountUpdate.findViewById(R.id.tvArtistFollowersCount);

                    int FollowingCount = Integer.parseInt(tvArtistFollowersCount.getText().toString());
                    String f = String.valueOf(FollowingCount-1);
                    tvArtistFollowersCount.setText(f);

TextView updates with this code BUT only for visible items:
View followersCountUpdate = lv.getChildAt(position);

So I use this code instead to access invisible listview items:
View followersCountUpdate = lv.getAdapter().getView(position, null, lv);

This line is where I do the textview update but it doesn't update text:
tvArtistFollowersCount.setText(f);

Additional Info (Printing View Logs)
lv.getChildAt(position));
getView: 01: android.widget.LinearLayout{3bb40c4 VFE...C.. .......D 0,0-1080,210 #7f07009c app:id/ll_main}

lv.getAdapter().getView(position, null, lv))
getView: 02: android.widget.LinearLayout{4a78ee2 VFE...C.. ......I. 0,0-0,0 #7f07009c app:id/ll_main}


text:
Q: Boolean algebra Simplify the expression Simplify the expression using the rules in Boolean algebra.
(a+b')(a'+b)(a+b)
Here's a list of the rules I got.
enter image description here
My thinking is that the rule B18 is relevant here. But I can't get it to work.

A: You guess the rules:
$$(a+b')(a'+b)(a+b) = (aa'+ab+b' a' +b'b)(a+b)=(ab+b'a')(a+b)=$$$$=aba + abb + b'a'a + b'a'b = ab+ab = ab$$


text:
Q: OpenResty auto_ssl too long lua code block error I'm using OpenResty with nginx to auto-obtain SSL certs from Let's Encrypt. There's a lua function where you can allow certain domains. In this function, I have a regex to whitelist my domains. After I add a certain amount (not sure the exact amount), I start getting this error:
nginx: [emerg] too long lua code block, probably missing terminating characters in /usr/local/openresty/nginx/conf/nginx.conf:60.

Shrinking down that string makes the error go away.
I'm not familiar with lua, but here's the example code. I have a few hundred domains to add in here.
auto_ssl:set("allow_domain", function(domain)
  return ngx.re.match(domain, "^(domain1.com|domain2.com|domain3.com....)$", "ijo")
end)

Do I need to define this string ahead of time, or maybe specify it's length somewhere?
EDIT ok, so I was thinking about this another way. Does anyone see an issue if I were to try this? Any sort of performance issues, or lua related things? Maybe there's a more efficient way of doing this?
auto_ssl:set("allow_domain", function(domain)
  domains = [[
    domain1.com
    domain2.com
    domain3.com
    -- continues up to domain300.com
  ]]
  i, j = string.find(domains, domain)
  return i ~= nil
end)

A: OpenResty allows for loading more complex lua code through files. https://github.com/openresty/lua-nginx-module#init_by_lua_file That is just one directive. There are multiple ways you can load lua code. This way worked for me.


text:
Q: RVM error with Requirements installation failed with status:1 I tried to install ruby 1.9.3 using command rvm install 1.9.3 --with-gcc=clang. But I got error saying
No binary rubies available for: osx/10.9/x86_64/ruby-1.9.3-p448.
Continuing with compilation.
Please read 'rvm help mount' to get more information on binary rubies.
Requirements installation failed with status: 1.

While I look into the installing log, I found it's saying
config/: Can't update time for config
doc/: Can't update time for doc
m4/: Can't update time for m4
Mk/: Can't update time for Mk

I tried many ways to install, but get the same error again and again, so what the problem is? And how should I do?

A: You're running this on Mavericks/10.9, a prerelease OS. RVM checks the OS version and then looks for ruby binary packages that match that specific OS version on the server. There aren't yet any such binary packages.
If you install homebrew first, RVM should be able to get a working 1.9.3 ruby from there.

A: Bypass your macports:
Use  sudo mv /opt/local ~/macports
Then make sure your Xcode is current and that should work.


text:
Q: WNetAddConnection2 Reconnections fail on subsequent attempts with error 1312 Background
I have a service that runs on windows 7 (64bit Professional) clients that checks in to a server for updates on a regular interval, it checks for new files to copy down local if they are not present. The way that I have it set up, each file on the server is represented with an object treated as a completely separate entity from the rest.
since the files can come from different locations with different credentials each file is processed as its own transaction. The connection is opened, the file is transferred, the connection is closed. Hundreds of files are processed on each update without a problem.
The problem does not occur until another update runs right behind the first one (within a few minutes of the previous one completing), when this happens the first attempt to connect to the remote resource errors out with an error 1312. The service automatically retries after 30 seconds until it gets a good connection, which takes several minutes, but after that time it goes through and completes without a problem again.
I have tried using both WNetAddConnection2 and WNetUseConnection with the same results, i close the connection using WNetCancelConnection2.
All of this takes place in a BackgroundWorker thread (maybe that is not being cleaned up before the next one starts?)
Definitions
[DllImport( "Mpr.dll" )]
private static extern int WNetUseConnection( IntPtr hwndOwner, NETRESOURCE lpNetResource, string lpPassword, string lpUserID, int dwFlags, string lpAccessName, string lpBufferSize, string lpResult );

[DllImport( "Mpr.dll" )]
private static extern int WNetAddConnection2( NETRESOURCE lpNetResource, string lpPassword, string lpUsername, int dwFlags );

[DllImport( "Mpr.dll" )]
private static extern int WNetCancelConnection2( string lpName, int dwFlags, bool fForce );

[StructLayout( LayoutKind.Sequential )]
private class NETRESOURCE {
  public int dwScope          = 0;
  public int dwType           = 0;
  public int dwDisplayType    = 0;
  public int dwUsage          = 0;
  public string lpLocalName   = "";
  public string lpRemoteName  = "";
  public string lpComment     = "";
  public string lpProvider    = "";
}
const int RESOURCETYPE_DISK           = 0x00000001;
const int CONNECT_TEMPORARY           = 0x00000004;

Use Examples
WNetUseConnection was used for a long time, I just tried WNetAddConnection2 tonight
NETRESOURCE cNetworkResource  = new NETRESOURCE();
cNetworkResource.dwType       = RESOURCETYPE_DISK;
cNetworkResource.lpRemoteName = @"\\192.168.5.254\packages";
cNetworkResource.lpLocalName  = "";

//int iReturnValue = WNetUseConnection( IntPtr.Zero, cNetworkResource, "Password", "Username", 0, null, null, null );
int iReturnValue = WNetAddConnection2( cNetworkResource, "Password", "Username", CONNECT_TEMPORARY );

And in a different method i close it with
int iReturnValue = WNetCancelConnection2( @"\\192.168.5.254\packages", CONNECT_UPDATE_PROFILE, true );

note: i use variables for path, username, and password not string literals, updated for example only
The target server is a linux box, and for this example assume the username and password are literally "Username" and "Password" that is the format of them. I have tried adding the server name to the user name such as "192.168.5.254\Username" which causes a 1219 error.
If i reboot the client system it will not error on the first try, which leads me to believe this is something being cached or not properly disposed of on the client side vs the server, I also observe the same behavior with two different linux servers as the remote location with different versions of samba running.
If any more information is needed I can provide it, i'm kind of at my wits-end here so any help is greatly appreciated. TIA


text:
Q: How to get user input into this piece of code using scanner I can get the program to add the preset values into the csv file but I want to adjust it so the user can enter the student ID Char(6) and the Student Mark (max 100) and also ensuring a minus mark cant be entered. How would I go about doing this?
public class Practicalassessment {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {

       System.out.println("Enter the Students ID:  ");
       scanner scanner = new scanner (System.in);
       String ID = scanner.nextline();
       System.out.println("You have selected Student" + ID);

       System.out.println("Enter the Students Mark");
       scanner scanner1 = new scanner(System.in);
       String mark = scanner1.nextLine();
       System.out.println("You Have Entered" + mark);

       String filepath = ("marks.txt");

       newMarks(ID,mark,filepath);
    }

    public static void newMarks (String ID, String mark, String filepath) throws IOException
    {
        try
        {
            FileWriter fw = new FileWriter(filepath,true);
            BufferedWriter bw = new BufferedWriter (fw);
            PrintWriter pw = new PrintWriter (bw);

            pw.println(ID+","+mark);
            pw.flush();
            pw.close();

            JOptionPane.showMessageDialog(null, "Records Updated Sucessfully");
        }
        catch (Exception E)
        {
            JOptionPane.showMessageDialog(null, "Records Unable to Be Updated");
        }
    }
}

A: Personally, I would keep to a single User Experience approach. If one is going to use JOptionPane to display a dialog, then one should collect information using a GUI as well.
I'd do (note that by convention Java variables are camelCase starting with a lower case):
String id = JOptionPane.showInputDialog("Enter Student's ID:");
// NOTE: need to check for null if canceled
// NOTE: should verify the input/format

The Error message noted in the comment is because the Java Scanner is with a capital letter. Not sure what that other thing is.
However, if one wants to use a Scanner, then instantiate only one:
Scanner scanner = new Scanner(System.in);

System.out.println("Enter the Students ID:  ");
String ID = scanner.nextline();
System.out.println("You have selected Student" + ID);

System.out.println("Enter the Students Mark");
String mark = scanner.nextLine();
System.out.println("You Have Entered" + mark);

...

Note that the same constraints of input validation exist as well with the Scanner input.


text:
Q: execute php script with argument in phing First, let's say that I have a php script , I use this script in command line , and I call this one with some arguments.
In my script I use
if(isset($argv)&&(isset($argv[1])))
{
}

but is not that the problem , I can use the php script in cmd (I use Windows)
I want to use the same command in my build.xml with phing
example of the command
php /path/indexCLI.php  arg1=arg1value arg2=arg2Value ...

How can i have the same behavior using phing
I want to get something like this:
<target name="lala" >
    <exec command="php path\indexbin.php  arg1=arg1value arg2=arg2Value" escape="false" />
</target>

Or something better if that is available.

A: Yes, you can have this. It already works the way you described it in the code example.


text:
Q: Embedded - SIM7600E not responding to any AT commands I have sim7600E on my project PCB and I am using STM32F103 to communicate with it, I have a level logic level shifter that shifts 3.3V UART down to 1.8V UART. I used a digital analyzer to confirm that the message (for example AT\r\n) is indeed arriving at the RX pin of SIM7600E. I can also confirm that the PWR signal of the module is HIGH and I have also inserted a sim card in the sim slot and the NET light is flashing.
I am quite lost because I have searched the internet for answers and couldn't find any.
Sorry for the lack of information but I really have nothing else to provide.
If anyone has had any experience with sim7600e and could provide me with some guidance it will be extremely appreciated,

A: Ok so it wasn't a software issue, there was a problem with logic level converter (3.3v to 1.8v)


text:
Q: Adding button to header of Gutenberg editor in Wordpress through plugin I am developing a plugin for wordpress and I want to add the button to the header of gutenberg editor just like the one added by Elementor plugin "Edit with Elementor"

Can anyone guide me what should i do to achieve this... Thanks in Advance

A: I've checked Guternberg source code on header toolbar and unfortunately right now there's only not a beautiful solution possible. You can have 'custom' buttons but they are only done through calling registerPlugin with PluginSidebar component which creates sidebar and button appears on right side for pinned\starred sidebars (like Yoast SEO does).
Elementor does it this way: it subscribes to wp.data store changes and whenever something happens it injects it's button if it's not yet injected. Just because React rerenders DOM it may eventually wipe button out, so subscribing to changes is important so if it wipes out custom button js code just reinjects it.
Below is simplified ES5 code to inject a custom link\button or really any custom HTML into it (just as Elementor does).
// custom-link-in-toolbar.js
// wrapped into IIFE - to leave global space clean.
( function( window, wp ){

    // just to keep it cleaner - we refer to our link by id for speed of lookup on DOM.
    var link_id = 'Your_Super_Custom_Link';

    // prepare our custom link's html.
    var link_html = 'Custom Link';

    // check if gutenberg's editor root element is present.
    var editorEl = document.getElementById( 'editor' );
    if( !editorEl ){ // do nothing if there's no gutenberg root element on page.
        return;
    }

    var unsubscribe = wp.data.subscribe( function () {
        setTimeout( function () {
            if ( !document.getElementById( link_id ) ) {
                var toolbalEl = editorEl.querySelector( '.edit-post-header__toolbar' );
                if( toolbalEl instanceof HTMLElement ){
                    toolbalEl.insertAdjacentHTML( 'beforeend', link_html );
                }
            }
        }, 1 )
    } );
    // unsubscribe is a function - it's not used right now
    // but in case you'll need to stop this link from being reappeared at any point you can just call unsubscribe();

} )( window, wp )

So create a js file in your theme or plugin and then link it this way:
add_action( 'enqueue_block_editor_assets', 'custom_link_injection_to_gutenberg_toolbar' );

function custom_link_injection_to_gutenberg_toolbar(){
   // Here you can also check several conditions,
   // for example if you want to add this link only on CPT  you can
   $screen= get_current_screen();
   // and then
   if ( 'cpt-name' === $screen->post_type ){
      wp_enqueue_script( 'custom-link-in-toolbar', get_template_directory_uri() . '/assets/js/custom-link-in-toolbar.js', array(), '1.0', true );
   }

}

Again this solution isn't perfect because we just inject our custom HTML into DOM which is managed by Gutenberg(React) but at this point it seems like the only way to achieve it, may be in future we'll have something like filters or hooks which will allow us to inject our custom components being rendered in toolbar  but not yet.
Still Elementor does it this way. you can check it's code at
https://github.com/elementor/elementor/blob/master/assets/dev/js/admin/gutenberg.js

A: Now there is a slot for the Main dashboard button you can use that one
import { registerPlugin } from '@wordpress/plugins';
import {
    __experimentalFullscreenModeClose as FullscreenModeClose,
    __experimentalMainDashboardButton as MainDashboardButton,
} from '@wordpress/edit-post';
import { close,image } from '@wordpress/icons';

const MainDashboardButtonIconTest = () => (
    <MainDashboardButton>
        <FullscreenModeClose icon={ close } href="http://wordpress.org" />

          <Button variant="primary" icon={image}>
                My Button
          </Button>

    </MainDashboardButton>
);

registerPlugin( 'main-dashboard-button-icon-test', {
    render: MainDashboardButtonIconTest,
} );

ref: https://developer.wordpress.org/block-editor/reference-guides/slotfills/main-dashboard-button/


text:
Q: Receiving a json response in Symfony 2 I have a javascript event listener on the search.html.twig page that will trigger an ajax request. In the example below, my goal is for the ajax call to be successful so the alert() message is executed.
I am used to the flat PHP approach:
echo json_encode($myAry);
Symfony's routing system makes returning an json response to ajax confusing. I am currently getting an internal server error 500.
I appreciate any advice on how to troubeshoot this. Thank in advance!
DefaultController
     public function showCompanyAction($id)
    {
        $repository = $this->getDoctrine()->getRepository('TestBundle:Company');
        //get company based on id

        //prepare json object

        //return it to search.html.twig
        return new JsonResponse(array('name' => 'hello'));
    }

JQuery (search.html.twig)
{% block jquery %}
    <script>
        $(function(){

            $.ajax({
                type: "POST",
                url: "../company/booth/2",
                dataType: 'json',
                success: function(msg){
                    alert(msg);
                }
            })
        });
    </script>

{% endblock %}

A: Jivan's answer is good, here is a more maintainable alternative:
use Symfony\Component\HttpFoundation\JsonResponse;

class YourController
{
    public function yourAction()
    {
        $response = new JsonResponse();
        $response->setData(array('message' => 'hello'));

        return $response;
    }
}

With this solution, you don't need to encode the array and specify the response headers (Content-Type and all). If the specificity of JSON responses change then you won't have to worry about updating your code.

A: To return a json response in Symfony2, you have to return this from the controller called by the route defined for company/booth/2:
use Symfony\Component\HttpFoundation\Response;

class YourController
{
    public function YourAction()
    {
        $response = json_encode(array('message' => 'hello'));

        return new Response($response, 200, array(
            'Content-Type' => 'application/json'
        ));
    }
}

The 200 in the response is the Http Status Code. 200 means "the request was fulfilled".

A: To process a JsonResponse with jQuery, you can do it with the "each" function:
public function showCompanyAction($id)
{
    return new JsonResponse(
        array(
            array('name' => 'hello'),
            array('name' => 'bye'),
        )
    );
}

{% block jquery %}
<script>
    $(function() {
        $.ajax({
            type: "POST",
            url: "../company/booth/2",
            dataType: 'json',
            success: function(data) {
                $.each(data, function (index, element) {
                    alert(element.name);
                });
            }
        })
    });
</script>
{% endblock %}


text:
Q: Bisectors in symmetric spaces In William Goldman's book Complex Hyperbolic Geometry, bisector hypersurfaces play an important role. Given two points $x,y$, the bisector is the set of points equidistant from $x$ and from $y$. Do they also play an important role in the study of higher rank symmetric spaces, and do they admit concrete descriptions, say in the Siegel upper half-plane? References are especially welcome.

A: Although I cannot address your specific question, of whether bisectors "play an important role in the study of higher rank symmetric spaces,"
I can say that
bisectors are the essence of Voronoi diagrams.
So the
2009 paper by
Frank Nielsen and Richard Nock, entitled
"Hyperbolic Voronoi diagrams made easy"
(arXiv link), could well be relevant:

We present a simple framework to compute hyperbolic Voronoi diagrams of finite point sets as affine diagrams. We prove that bisectors in Klein's non-conformal disk model are hyperplanes that can be interpreted as power bisectors of Euclidean balls. [...]


text:
Q: ManyToMany Query in Django I can't get to work which should be so easy, reverse querying.
I looked at the documentation and at other examples on here but my "items" stays empty.
my models
class Keyword(models.Model):
    name = models.CharField(max_length=100)

def __unicode__(self):
    return self.name
class Item(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()
    keywords = models.ManyToManyField(Keyword)

    class Meta:
        ordering = ('name','description')

    def __unicode__(self):
        return self.name

in my views I'm looking for all Items with the keyword:
def related(request, word):
    try:
        kw = Keyword.objects.get(name=word)
    except Keyword.DoesNotExist:
        raise Http404("Keyword does not exist")
    items = kw.item_set.all()
    return render(request, 'index/related.html', {'items': items, 'kw': kw})

Querying an Item and using keywords.all() works fine, but the other way around not.


text:
Q: Easiest way to self-join one table to create "AND-filter"? I have the following (very simple) table:
| A | Z |
|---|---|
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 5 |

Now I want to filter the values in this table by Z and find all As that match my filter.
The Z-Filter should behave like an AND-filter. Here are some examples with matching queries:
-- filter z= 1
-- expect a = 1,2
select a from data where z = 1;

-- filter z= 5
-- expect a = 2
select a from data where z = 5;

-- filter z= -
-- expect a = 1,2
select a from data;

Now here comes the problem:  I want to filter by z=1 AND z=5
-- filter z: 1,5
-- expect a = 2

Using "in" will not give the result I want. It's like saying z=1 OR z=5.
select a from data where z in (1,5);

I want an AND-join to the z-filter. I know it can be done like this:
select d1.a from data d1
  left join data d2 on (d1.a = d2.a)
  where d1.z = 1
  and d2.z = 5;

The thing is that the z-filter-list can grow dynamically and for every z-value I have to add another join. So my question is: Is there an easier way to do this?
SQLFiddle with the above examples: http://sqlfiddle.com/#!2/03d07/4

A: You can use GROUP BY/HAVING:
SELECT  a
FROM    data
WHERE   z IN (1,5)
GROUP BY a
HAVING COUNT(DISTINCT z) = 2; -- NUMBER OF ITEMS IN THE IN CLAUSE

So although you are saying z can be 1 or 5, your HAVING limits this to only values of a that have both.
Example on SQL Fiddle


text:
Q: iOS Objective C NSString.length not returning expected value I'm having the most basic of problems with an objective C method.
Based on a suggestion from:
How can I truncate an NSString to a set length?
I am trying to write a method to return a truncated NSString.  However, it is not working.  When I send in "555" for example, the length (as shown by the variable 'test') comes back as 0.  I determined this by setting a break point after the line int test and hovering over the variables fullString and test.  Do I somehow need to dereference the pointer to fullString or some other thing?  I am a complete newbie in objective C.  Many thanks
-(NSString*) getTruncatedString:(NSString *) fullString {

    int test = fullString.length;
    int test2 = MIN(0,test);
    NSRange stringRangeTest = {0, MIN([@"Test" length], 20)};

    // define the range you're interested in
    NSRange stringRange = {0, MIN([fullString length], 20)};

    // adjust the range to include dependent chars
    stringRange = [fullString rangeOfComposedCharacterSequencesForRange:stringRange];

    // Now you can create the short string
    NSString* shortString = [_sentToBrainDisplay.text substringWithRange:stringRange];

    return shortString;

}

Based on comments and research, I got it working.  Thank you everyone. In case anyone is interested:
-(NSString*) getTruncatedString:(NSString *) fullString {

if (fullString == nil || fullString.length == 0) {
    return fullString;
}
NSLog(@"String length: %d", fullString.length);

// define the range you're interested in
NSRange stringRange = {MAX(0, (int)[fullString length]-20),MIN(20, [fullString length])};

// adjust the range to include dependent chars
stringRange = [fullString rangeOfComposedCharacterSequencesForRange:stringRange];

// Now you can create the short string
NSString* shortString = [fullString substringWithRange:stringRange];

return shortString;

}

A: Check if you are passing @"555" to this method, not "555".
Also, better way is to
NSLog(@"String length: %d", fullString.length).


text:
Q: Attribute changed for parent outside of ShadowDom (display: none -> display: flex -> display: none) My Angular-Component lives inside a flexbox (id="log") The flexbox can be displayed or hidden.
Inside of my component there is a scrollable area which displays log messages. (id="message-list") The height of message-list has to be set programmatically set according to the parents size. (And YES - it has to be set programmatically, worked on this several hours)
The problem is - I don't know when the parent (log (outside of component)) is changing it's state. onShadowRoot does not help because it's called when the Component is inserted into SR which has nothing todo with its visibility.
thx for a hint.

A: I built a Decorator/Directive that generates events when an element changes it's size. You could apply this to the parent.
See my answer to How to scrollTop a div whose content is managed by AngularDart? for more details.


text:
Q: Embed youtube VEVO videos I've been having troubles embedding youtube VEVO videos. VEVO blocks the embedding on website but somehow directlyrics.com can manage to do that. Example link: http://www.directlyrics.com/jessie-j-flashlight-lyrics.html
As you can see the video top right is a vevo video.
I found that the iframe gets the video from the website of the owner, example: http://c.yvoschaap.com/yt.html#id=DzwkcbTQ7ZE
Do you guys have any ideas how this is done?

A: *

*Go to YouTube's Video that you want to embed.

*Click Share

*Click Embed

*Copy paste the iFrame to your site.

Example iFrame:
<iframe width="560" height="315" src="https://www.youtube.com/embed/DzwkcbTQ7ZE" frameborder="0" allowfullscreen></iframe>

JSFiddle:
https://jsfiddle.net/8Lxtsdkn/


text:
Q: Mac equivalent of /etc/nsswitch.conf for PHP chroot I've setup a chroot for my PHP server running behind nginx on mac.
It works except for any call to a CURL request fails with an error like cURL resource: Resource id #43; cURL error: Couldn't resolve host 's3.amazonaws.com'
Most guides to setting up a chroot environment say that you should map certain files to be available inside the chroot. The only file I can't find to map is /etc/nsswitch.conf which apparently doesn't exist on Mac.
What is the equivalent file on a Mac? Or what file/socket should be made available to the chroot environment to allow DNS lookups to work?

A: It turns out that on OSX the DNS lookup is done through the service mDNSResponder service which is running as a socket at /var/run/mDNSResponder.
It does not use /etc/nsswitch.conf or /etc/resolv.conf so there is no way of mapping those files into a chroot. Instead it's a better idea to use a localhost proxy.


text:
Q: Optimize brute force with permutations EXPLAINING WHAT THE SCRIPT DOES
I made a python script where the goal is to balance marbles on a circular board. Marble 1 weighs 1 Unit, 2 weighs 2 Units, and so on. The goal is to find the best order so it's a balanced as possible.
PROBLEM
I also made a method that tries all the possibilities with permutations. I get a memory error if I try with more than 10 marbles (3628800 possibilites).
Is there any way to optimize the code with either multi threading/ multiprocessing, maybe a better way than permutations?
CODE
    # balance_game.py
    # A program used to your skills in balancing marbles on a board
from itertools import permutations
from math import cos, radians, pow, sin, sqrt
from time import time

# Checks if marbles will balance on a circular board
# Marble 1 weighs 1 unit, 2 weighs 2 units, and so on
def test_your_might(NUMBER_OF_MARBLES, marbles):
    angle = 360 / NUMBER_OF_MARBLES
    angles = [angle * n for n in range(1, NUMBER_OF_MARBLES + 1)]

    X = []
    Y = []
    Fx = []
    Fy = []

    i = 0
    for n in range(0, NUMBER_OF_MARBLES):
        angle = radians(angles[i])
        X.append(cos(angle))
        Y.append(sin(angle))
        i += 1

    for n in range(0, NUMBER_OF_MARBLES):
        Fx.append(X[n] * marbles[n])

    for n in range(0, NUMBER_OF_MARBLES):
        Fy.append(Y[n] * marbles[n])

    return sqrt(pow(sum(Fx), 2) + pow(sum(Fy), 2))

def brute_force_solution(NUMBER_OF_MARBLES):
    possibilities = permutations([x for x in range(1, NUMBER_OF_MARBLES + 1)])
    solutions = {}
    for possibility in possibilities:
        possibility = list(possibility)
        solution = test_your_might(NUMBER_OF_MARBLES, possibility)
        solutions[str(possibility)] = solution
    return solutions

# print(test_your_might(5, [5, 1, 4, 3, 2]))
t0 = time()
solutions = brute_force_solution(10)
t1 = time()

best_order = min(solutions, key=solutions.get)
lowest_score = solutions[best_order]

print(f"Lowest score: {lowest_score}\nOrder: {best_order}")
print(f"It took {t1-t0} seconds to find the best possibility")
print(f"There were {len(solutions)} possibilities")

FYI
The method is brute_force_solution

A: Since the bottleneck is CPU usage, multithreading won't do a lot to help here, but multiprocessing should. Not an expert but have been experimenting with parallelism recently so will have a play around and update this answer if I get anywhere. (EDIT: I have tried a number of attempts at using multiprocessing but I've only succeeded in increasing the run time!)
It might be that you need to store all solutions, but if not, one small optimisation in terms of time, but huge in terms of memory, would be to not store all the possible results and just store the best result, so you're not creating another very long array needlessly. Ideally you could calculate number of solutions directly since it only depends on NUMBER_OF_MARBLES but have included it in the function to be consistent.
def brute_force_solution(NUMBER_OF_MARBLES):
    possibilities = permutations([x for x in range(1, NUMBER_OF_MARBLES + 1)])
    # count the number of solutions
    number_of_solutions = 0
    best_solution_so_far = None

    for possibility in possibilities:
        number_of_solutions += 1
        possibility = list(possibility)
        solution = test_your_might(NUMBER_OF_MARBLES, possibility)
        # If this solution is the best so far, record the score and configuration of marbles.
        if (best_solution_so_far is None) or (solution < best_solution_so_far[1]):
            best_solution_so_far = (str(possibility), solution)

    # Return the best solution and total number of solutions tested.
    return (best_solution_so_far, number_of_solutions)

t0 = time()
one_solution = brute_force_solution(11)
t1 = time()

best_order = one_solution[0][0]
best_score = one_solution[0][1]
number_of_solutions = one_solution[1]

It took a while but it ran with 11 marbles:
>>>Lowest score: 0.00021084993450850984
>>>Order: [10, 7, 3, 4, 11, 1, 8, 9, 5, 2, 6]
>>>It took 445.57227993011475 seconds to find the best possibility
>>>There were 39916800 possibilities

and was marginally quicker when run for 10 (and note that you aren't including the sorting of your results in your timing which is not needed with this new method and adds almost another second to your time to get the best solution):
Old
Lowest score: 1.608181078507726e-17
Order: [1, 7, 3, 10, 4, 6, 2, 8, 5, 9]
It took 43.81806421279907 seconds to find the best possibility
There were 3628800 possibilities

New
Lowest score: 1.608181078507726e-17
Order: [1, 7, 3, 10, 4, 6, 2, 8, 5, 9]
It took 37.06034016609192 seconds to find the best possibility
There were 3628800 possibilities


text:
Q: How to only render a view when an image inside of it has finished rendering, while showing a rendering indicator? Let's say we have this block of code:
  <View>
    <Image
      source={{uri: this.props.image}}
      renderIndicator={() => <SimpleLoader />}
    />
    <Text>{this.props.title}</Text>
  </View>

It currently shows a rendering animation on the image, but shows the View as well as text, and then eventually renders the image.
I would like to:
1) Have the View itself have <SimpleLoader /> be displayed while any child item is rendering
2) identify when all the children have finished rendering (or the image, in particular), and then fade the view in.
I was reading around on potentially using a callback with componentDidMount but I'm not entirely sure how to achieve this.

A: An easy way would be to use react-native-image-progress
One way to do it manually would be to have a loaded: false property in the state initially, then set the onLoad prop of Image to a function that calls setState({loaded: true}). Then create a function, say showImage() that returns a view of either the image, or the loading indicator depending on whether state.loaded is true or false respectively. In render(), you can then call {this.showImage()}
To fade the image, you can use Animated to animate the opacity of the image inside the style from 0 to 1.


text:
Q: Why is opening String class inside thor file not working? I know I can open a class like String and add functionality. This test script camelize.rb works pretty well.
#!/usr/bin/env ruby
class String
  def camelize
    self.split("_").map(&:capitalize).join
  end
end

class Test
  def test
    p "test_me".camelize
  end
end

Test.test

Prints "TestMe"
However inside a thor file this doesn't work. E.g. test.thor
p "TEST ONE"
class String
  p "TEST TWO"
  def camelize
    self.split("_").map(&:capitalize).join
  end
end

class Test < Thor
  p "TEST THREE"
  desc "camel", "A test"
  def camel
    p "test_me".camelize
  end
end

Installing it via thor install test.thor, running
$ thor test:camel
"TEST ONE"
"TEST TWO"
"TEST THREE"
/Users/Kassi/.thor/ba3ea78d7f807c4c13ec6b61286788b5:13:in `camel': undefined method `camelize' for "test_me":String (NoMethodError)

Why and how to fix it?

A: Why?
The problem is here:
Thor::Sandbox.class_eval(content, path)

So what it does is take your file and load it inside of an empty module, thus namespacing it (not sure if qualifies as "sandboxing").
class Thor
  module Sandbox
  end
end

So, your attempt at reopening the String actually creates a new class Thor::Sandbox::String which no one knows about. String literals continue to create instances of String.
How to fix?
Open the top-level string instead of creating a nested one.
class ::String
  def camelize
    self.split("_").map(&:capitalize).join
  end
end

Bonus content
Thor actually already includes method for camelizing strings, Thor::Util.camel_case:
  def camel_case(str)
    return str if str !~ /_/ && str =~ /[A-Z]+.*/
    str.split("_").map { |i| i.capitalize }.join
  end


text:
Q: How would this transistor diagram be drawn if we draw it with all the closed circuits? In a book about computers I have this transistor diagram:

the first two transistors are p types and the second two are n types. I am wondering how it should have been drawn if we close the circuits, because as far as I know we must ahve closed curicuits to get electricity.
1.
The first idea I have is that we must close the the ground with the power supply, is this correct? This part would look like this? Notice the top here, I have drawn the red line above the horisontal line, but maybe it should be just below the horistontal line?

*Secondly they talk about C beeing connected to ground or 1,2 Volts, does that mean that we close the curicuit C like this:?

*Now I must draw the line in the subtrate in the transistors, here I have two options. I only draw one p transistor and one n transistor. Option 3a)

Or 3b:

Are wither 3a oe 3b correct?
And maybe they would be short-curcuited if I draw it like I did, so maybe I should have added some resistors aswell? If the drawing are wrong, could you please explain how we would draw the full circuit?

A: *

*Your first picture is almost correct, but you can't connect the top and ground parts directly. If you would connect them you would build a short circuit and you had no voltage over your transistor circuit anymore.
The way the diagram in the book is drawn is a typical way to show where the (+) and the (-) of the voltage source is connected. I have drawn a battery (red) in the circuit to show what exactly that means. At the top you have the positive voltage of say 1.2V and the ground symbols are connected to the negative terminal and are interpreted as 0V.

*C is not connected to 1.2V or ground at the output (like you have drawn it), but by the transistors. That's the whole purpose of this circuit. C is the output that (dependent on the input signals) is either connected by the upper two transistors to the positive terminal (1.2V) or the negative terminal (0V). I have drawn these two paths in blue and green.
This way the circuit fulfills the role as a logic gate: The two inputs A and B both have to be at LOW potential for the upper two transistors to be conductive. So with both inputs LOW, the output C is connected to logic HIGH (the supply voltage). The lower two transistors are not conductive in this case. But if one of the inputs is at HIGH potential, one of the two upper transistors does not conduct anymore, so the output is not connected to the supply. Instead one of the lower transistors gets conducting and the outputs is "pulled LOW".
The circuit is representing a NOR gate.

A: To make the circuit complete, first add an ideal voltage source for each of the inputs (A and B). The positive end of the voltage source connects to the input signal and the negative end connects to ground. These sources represent the logic input signals, and may have values of 1.2V or 0V.
Another ideal voltage source is the power supply. Its positive end connects to the horizontal bar at the very top and its negative end connects to ground. It has a value of 1.2V
All of the PMOS substrates are connected to the positive end of the power supply voltage. All of the NMOS substrates are connected to ground. This is not strictly required but it is the most common situation for logic circuits.
All of the signals described as "ground" are connected together. You can draw an actual wire to do this but generally we connect them to a special ground symbol, such as triangle in your diagram, and understand that these symbols are actually connected together.
All of the additional components and connections I described have been intentionally omitted from your schematic, because most readers will understand that they are implied and the drawing would just be cluttered if they are all drawn out.

A: The "bubble" on the PMOS device gates, indicate that these are "active-low" inputs. With A and B low, the top two PMOS are "on", meaning that there is a direct connection between their drain and source (top and bottom) terminals. Since one end of this series connects to the supply voltage, and the other end to output C, A and B being low makes C high because it is connected.
Likewise, the bottom two NMOS devices do not have a bubble on their gate, indicating that they are "active high" devices. When A and/or B are high, either or both of these are on, connecting output C to ground.

A:
simulate this circuit – Schematic created using CircuitLab
Figure 1. Consider the CMOS transistors as simple pairs of complimentary switches.
In all cases except one the output is pulled low by the ground-side switches. These effectively connect the output to ground and will sink any current provided by the load.
In the first case when both inputs are on the ground is disconnected and the output is connected to positive supply. The output goes high and will source any current demanded by the load.


text:
Q: how to change password in android using mysql (Registration and Login is perfectly working fine but issues in change password) class DbOperations{
    private $con;

    function __construct(){
        require_once dirname(__FILE__).'/db_connected.php';
        $db = new DbConnect();
        $this->con = $db->connect();
    }

    public function changePassword($pass){
        $password = md5($pass);
        $stm = $this->con->prepare("UPDATE `student` SET `password` = ?
            WHERE `username` = ?);");
        $stm->bind_param("s",$password);
        $stm->execute();

        if ($stm) {
            return true;
        }
        else {
            return false;
        }
    }

Now this is the function which i want to call for change password in android studio using php script.
All other file are not wrong the main problem is in this script name DbOperations function changePassword
This is change password script userChangePassword.php
<?php

    require_once '../include/db_operations.php';

    $response = array();
    if ($_SERVER['REQUEST_METHOD']=='POST') {
        if (isset($_POST['password'])){
            $db = new DbOperations();
            if ($db->changePassword($_POST['password'])){
                $response['error'] = false;
                $response['message'] = "Change Password Successfully";
            }
            else{
                $response['error'] = true;
                $response['message'] = "Password not changed";
            }
        }
        else{
            $response['error'] = true;
            $response['message'] = "Fill all the feilds";
        }
    }
    else{
        $response['error'] = true;
        $response['message'] = "Invalid Request";
    }
    echo json_encode($response);

Error is :

Fatal error: Call to a member function bind_param() on a non-object in C:\xampp\htdocs\Android\include\db_operations.php on line 69

A: Your error seems to suggest that $stm is not set correctly.
   $stm = $this->con->prepare("UPDATE `student` SET `password` = ?
    WHERE `username` = ?);");

did not return a valid object. Are all the variables in your __construct function valid?
Edit: duskwuff is right, the closing parenthesis in WHERE username = ?) is incorrect

A: $stm = $this->con->prepare("UPDATE `student` SET `password` = ?
            WHERE `username` = ?);");
                                ^

This SQL statement is invalid -- the closing parenthesis I've marked (after `username` = ?) doesn't have a matching opening parenthesis anywhere. This causes the prepare call to fail.
 $stm->bind_param("s",$password);
 $stm->execute();

You haven't bound a value to the second parameter, corresponding to username. Nor is there a username argument to the function, or even to the userChangePassword.php script -- how is it supposed to know which user's password to update?


text:
Q: CSVParser.getRecords() yields zero results I have been using apache.commons.CSVParser for a while without any issues. I know this sounds silly like the dog ate my homework but, the parser doesn't yield any records suddenly for the past two days now. Records size shows up with a non zero value in the debugger but the list returned from CSVParser.getRecords() is zero. Elsewhere I had read the correct way to access the list is to call the size() method on the getRecords(), which I have done.
To reemphasize, the code was working fine.
I was using commons:commons-csv:jar:1.5 for a while, it stopped working and I tried upgrading to 1.9.0 and the behavior is still the same
CSVParser records = CSVFormat.DEFAULT.withDelimiter(DELIMITER).withHeader(blah).
                  withFirstRecordAsHeader().
                  parse(fileReader);
log.info("Size:"+records.getRecords()); //shows up as 125, say
List<CSVRecord> recordList = records.getRecords();//0 size!

I have written some test code to validate my sanity, and this code works fine
FileReader fReader = new FileReader("/tmp/tempexport.csv");
CSVParser records =
           CSVFormat.DEFAULT.withDelimiter(DELIMITER).
             withHeader("").withFirstRecordAsHeader().parse(fReader);
File file = new File("/tmp/tempexport.csv");
System.out.println(Files.lines(file.toPath()).count());
for (CSVRecord record: records.getRecords()) {
            System.out.println(record.get(0)  +
 "::"+record.get(1));

A: Naming is a bit misleading
(Both: your variables and their method-name)
A parser (even of class CSVParser) is a parser.
The records are a collection of records, that can be obtained using parser.getRecords() - as a List or Iterable.
Actually, the method is more than an idempotent getter. So getRecords() should be renamed to nextRecords() to be semantically exact .
Note the docs emphasize the streaming character of getRecords():

The returned content starts at the current parse-position in the stream.

In conclusion, getRecords() advances the parse-position with each reading invocation. Once you read the records for logging as "Size:"+records.getRecords(), the position in CSV stream advances and may be at end-of-file (EOF) already.
When you want the size or count of records, use the header-names as approximation: parser.getHeaderNames().size().
See also

*

*Java Developer Central: Read CSV files using Apache Commons CSV, tutorial


text:
Q: Rails 4: Routing with partials I get the following error when navigating in my Rails application:
No route matches
{:action=>"startnew", :controller=>"tickets", :ticket_id=>4} missing required keys: [:id]

The problem is, I have a route for:
  post   'tickets/:id/startnew' => 'tickets#startnew', as: :start_new

This works fine, when I navigate to the URL http://localhost:3000/tickets
But the error occurs when I load the URL http://localhost:3000/tickets?id=4, which in my case needs to work, because I render tickets#list and tickets#show in two partials on tickets#index, where the error above occurs.
When I click on a link on a different page the tickets#index is loaded and  the tickets#show is only rendered when I have the parameters in the url (http://localhost:3000/tickets?id=4).
In show I have this part, which causes the problem:
<%= link_to 'Book time', start_new_path(ticket_id: @ticket.id), method: :post, class: "button info block-shadow-info text-shadow", remote: true %>

Can you please give me a hint!

A:
No route matches {:action=>"startnew", :controller=>"tickets",
  :ticket_id=>4} missing required keys: [:id]

You have
post   'tickets/:id/startnew' => 'tickets#startnew', as: :start_new

It means it expects :id as a key, but you are sending :ticket_id. Changing your link to below should work.
<%= link_to 'Book time', start_new_path(id: @ticket.id), method: :post, class: "button info block-shadow-info text-shadow", remote: true %>


text:
Q: Automate build of the script to update DB in postgres We have a system made in java using a postgres database.
This database changes often, and once a week or less we are updating it. These changes are in the struture of the DB (DDL), usually in functions and fields to add new functionality.
For the changes in the DB we usually use navicat as follows:
1- We made the change in the structure of the DB using navicat and we copy the SQL that gives us to an XML file for each change we made.
2- When we have to update the DB in production we check files, identified by a version number, and update the DB.
3- Then we repeat this for each DB installed (30 in total)
The problem that we are having is that as the whole process is manual and is very easy to forget to copy a change to the XML so when we use it the script does not work or even worse when the system needs this change fails.
Therefore we are looking for a way to automate this task and we came with the following idea:
1- We make changes in navicat
2- Configure the postgres to LOG the changes in the DDL into a CSV file
3- Later we read the CSV file and pass the changes to the XML to update the producction DB
The problem we are having is that the LOG will save all attempts to change the structure, including errors so if we use that script to update it will fail too.
Is there some way to save only successful DDL changes in the log in postgres?
Is there a script or application to get the DDL changes and put it in script automatically?
Is there a better way to automate this process?

A: there are many answers for the questions above :-) i have managed rapidly changing databases using a number of schemes.  one way to do it is maintain a master database (like you have).  Use dbtoyaml to create a yaml description of the database.  Then use yamltodb on all of the (30) targets, which will do everything necessary to make the target databases look exactly like the master.  I have used this software for about 6 months, it is fantastic.  pyrseas. -g


text:
Q: Duplicate rows if certain columns has values and copy to next sheet with duplicated rows So I have this problem where if there is a value in a column, the row should be duplicated and copied to the next sheet. I will show a scenario to understand better.
This is sheet1

As you can see from the table above, there is a certain item name that doesn't have the three quantity columns. Some only have good quantity, some have both good and bad, and some have the three quantity. Now I want to copy this data to the other sheet with some modifications.
This should be the result in the next sheet:

As you can see, the data are duplicated based on the quantity columns if there is data or not. The status column is based on the quantity columns in sheet1. Status 0 is GOOD QTY, Status 1 is BAD QTY and Status 2 is VERY BAD QTY.
This is my current code:
    Set countsheet = ThisWorkbook.Sheets("Sheet1")
    Set uploadsheet = ThisWorkbook.Sheets("Sheet2")

    countsheet.Activate
    countsheet.Range("B11", Range("F" & Rows.Count).End(xlUp)).Select
    Selection.SpecialCells(xlCellTypeVisible).Select
    Selection.Copy
    uploadsheet.Activate
    uploadsheet.Range("B2").PasteSpecial xlPasteValues

I know this code only copies data from sheet1 to sheet2. How to modify this code and achieve the result above?

A: *

*Select your data range > Data tab in the ribbon > From Table/Range

*Select the Item Code and Item Name columns > right-click > Unpivot Other Columns

*Select the Attribute column > right-click > Replace Values.  You can type in two dummy values: Value To Find = abc, Replace With = xyz

This code will appear in the formula bar:
= Table.ReplaceValue(#"Unpivoted Other Columns","abc","xyz",Replacer.ReplaceText,{"Attribute"})

Replace it with this:
= Table.ReplaceValue(#"Unpivoted Other Columns", each [Attribute], each if Text.Upper([Attribute]) = "GOOD" then 0 else if Text.Upper([Attribute]) = "BAD" then 1 else 2,Replacer.ReplaceValue,{"Attribute"})

*

*I used the Text.Upper function because Power Query is case sensitive.

*Now all you need to do is rename the columns and select Close & Load > Close & Load To > Table

*This is a beneficial technique because as you add, edit, or remove data from your source table you can just refresh and the PQ table will update accordingly.


text:
Q: Splash Screen scrolling up after about one second with phonegap 3.0.0 in iOS I've a problem with iOS splashscreen I use phonegap 3.0.0, jquery mobile, backbone.
My config.xml out of www folder is:
<preference name="DisallowOverscroll" value="true" />
<preference name="KeyboardDisplayRequiresUserAction" value="true" />
<preference name="SuppressesIncrementalRendering" value="false" />
<preference name="UIWebViewBounce" value="false" />
<preference name="TopActivityIndicator" value="gray" />
<preference name="EnableLocation" value="true" />
<preference name="EnableViewportScale" value="false" />
<preference name="AutoHideSplashScreen" value="false" />
<preference name="ShowSplashScreenSpinner" value="true" />
<preference name="MediaPlaybackRequiresUserAction" value="false" />
<preference name="AllowInlineMediaPlayback" value="false" />
<preference name="OpenAllWhitelistURLsInWebView" value="false" />
<preference name="BackupWebStorage" value="cloud" />
<preference name="permissions" value="none" />
<preference name="orientation" value="default" />
<preference name="target-device" value="universal" />
<preference name="fullscreen" value="true" />
<preference name="webviewbounce" value="true" />
<preference name="prerendered-icon" value="true" />
<preference name="stay-in-webview" value="false" />
<preference name="ios-statusbarstyle" value="black-opaque" />
<preference name="detect-data-types" value="true" />
<preference name="exit-on-suspend" value="false" />
<preference name="show-splash-screen-spinner" value="true" />
<preference name="auto-hide-splash-screen" value="true" />
<preference name="disable-cursor" value="false" />
<preference name="android-minSdkVersion" value="7" />
<preference name="android-installLocation" value="auto" />

in index.html I've
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />

<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);

        // Cordova is ready

        function onDeviceReady() {
            setTimeout(function() {
                       navigator.splashscreen.hide();
                       }, 2000);

        }
</script>

For first second I've fullscreen splashsreen

for the next two seconds, splashscreen scroll up about 20px

I have tested it in all iOS simulator:iPhone, iPhone retina, iPhone retina 4-inch...
and in iOS 5.1/7.0
Solutions?

A: Best bet is to update to 3.1, they've fixed the splash screen plugin at that level to resolve this issue.
Or check our this post here


text:
Q: jquery js and jquery mobile js not working I am using phonegap with atom editor and My jquery and jquery mobile is not working. All .js file are in a folder named js and the root are properly link. I have try the online code.jquery.com version and it still doesnt work. These are the 2 version I tried:
Version 1
 `<link rel="styleheet" type="text/css" href="css/jquery.mobile-
 1.4.5.min.css">
 <link rel="styleheet" type="text/css" href="css/jquery.mobile-1.4.5.css">
 <link rel="stylesheet" type="text/css" href="css/index.css" />
 <script type="text/javascript" src="cordova.js"></script>
 <script type="text/javascript" src="js/index.js"></script>
 <script type="text/javascript"> app.initialize();</script>
 <script type="text/javascript" src="js/jquery.mobile-1.4.5.min.js">
 </script>
 <script type="text/javascript" src="js/jquery.mobile-1.4.5.js"></script>
 <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
  `

version2
 <link rel="stylesheet"
  href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css"/>
  <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-
   1.4.5.min.js"></script>
  <script
   src="https://code.jquery.com/jquery-3.2.1.min.js"
   integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
   crossorigin="anonymous"></script>
   <link rel="stylesheet" type="text/css" href="css/index.css" />
   <script type="text/javascript" src="cordova.js"></script>
  <script type="text/javascript" src="js/index.js"></script>
   <script type="text/javascript">app.initialize();</script>

i use this code to test if my jquery is working
   `<script>
 window.onload = function(){
  if (window.jquery){
    alert("YES");
  }else {
    alert("ERROR");
  }
 }
  </script>
   `

and everytime it turn up to be error. I programmed and never turn out YES ERROR:

A: For test if Jquery is Load use like this :
<script>
     window.onload = function(){
      if (jQuery) {
        alert("jquery is loaded");
       } else {
        alert("Not loaded");
        }
     }
  </script>

A: jQuery and jQuery mobile are not working within your project because version 1.4.5 of jQuery mobile doesn't support jQuery version 3.x.
Try using jQuery version 2.x within your application and see if this fixes the problem. To quickly test this you can use Google's hosted jQuery just to make sure before you go downloading all the files:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

jQuery mobile 1.5.0 was released in May this year which actually supports jQuery 3.x. Switching to the new version of jQuery mobile could also be a fix, but keep in mind that 1.5.0 is an Alpha version. You can read more about the latest version of jQuery mobile here

A: What do the browser console errors look like? Get there by right clicking on page > Inspect Element > Console


text:
Q: Getting defined substring with help of sed or egrep Everyone!!
I want to get specific substring from stdout of command.
stdout:

{"response":
  {"id":"110200dev1","success":"true","token":"09ad7cc7da1db13334281b84f2a8fa54"},"success":"true"}

I need to get a hex string after token without quotation marks, the length of hex string is 32 letters.I suppose it can be done by sed or egrep. I don't want to use awk here. Because the stdout is being changed very often.

A: grep's nature is extracting things:
grep -Po '"token":"\K[^"]+'

*

*-P option interprets the pattern as a Perl regular expression.

*-o option shows only the matching part that matches the pattern.

*\K throws away everything that it has matched up to that point.

Or an option using sed...
sed 's/.*"token":"\([^"]*\)".*/\1/'

A: This is an alternate gnu-awk solution when grep -P isn't available:
awk -F: '{gsub(/"/, "")} NF==2&&$1=="token"{print $2}' RS='[{},]' <<< "$string"
09ad7cc7da1db13334281b84f2a8fa54

A: With sed:
your-command | sed 's/.*"token":"\([^"]*\)".*/\1/'

A: YourStreamOrFile | sed -n 's/.*"token":"\([a-f0-9]\{32\}\)".*/\1/p'

doesn not return a full string if not corresponding


text:
Q: Text extraction using itext7: garbage characters for some pdf documents I have a problem extracting text from pdf documents using iText7. For documents coming from a specific source textRenderInfo.GetText() returns only garbage chars (0xfdff) in the event handler of my extraction strategy:
internal class CustomExtractionStrategy : ITextExtractionStrategy
{
    public virtual void EventOccurred(IEventData data, EventType type)
    {
        if (!type.Equals((object)EventType.RENDER_TEXT))
        {
            return;
        }

        var textRenderInfo = (TextRenderInfo)data;
        bool currentResultEmpty = _result.Length == 0;
        bool isInNewLine = false;

        var baseline = textRenderInfo.GetBaseline();
        var startPoint = baseline.GetStartPoint();
        var  endPoint = baseline.GetEndPoint();

        var currentText = textRenderInfo.GetText(); // returns garbage for specific pdfs

        // further processing below
        ...
    }
}

I'm not very familiar with the way text/glyph encoding words in PDF but I try to give some details when comparing the problematic pdfs with an example where extraction works. For the pdfs with issues:

*

*textRenderInfo.gs.font is MS-UIGothic

*textRenderInfo.gs.font.fontProgram.codeToGlyph contains only mapping (key: 0 to a Glyph with width 1000, unicode -1, code 0)

*textRenderInfo.gs.font.fontProgram.unicodeToGlyph contains no records

These are the most obvious discrepancies. If there's any thing else I should look out for please let me know. I would have provided an example of the PDF in question but it might have sensitive information that I must not disclose.
Note: the PDFs can be correctly read in Acrobat Reader and I can copy text from the reader into notepad. Other libraries (pdfium based or ports of PDFBox) can properly extract text from the document. So I think the document as such is "valid".
If this is a known issue for iText7, is there any workaround (other than using a different library altogether)?
Update
With the link provided in the comment and the following code (in addition to the custom extraction strategy snippet shown above) I get garbage chars see VS screenshot:
    internal class PdfExtractor
    {
        internal void ExtractFromPath(string path)
        {
            PdfReader reader = new PdfReader(path);
            var document = new iText.Kernel.Pdf.PdfDocument(reader);
            for (int pageNum = 1; pageNum <= document.GetNumberOfPages(); pageNum++)
            {
                var page = document.GetPage(pageNum);

                string text = PdfTextExtractor.GetTextFromPage(page, new CustomExtractionStrategy());
            }
        }
    }


text:
Q: How to cancel a chrome download before it starts and get the download url? I want to integrate my C# download manager using a Chrome Extension and I am new in extension development.
So I need to detect when a download request is sent in chrome. Then I need to get the url and pass it to my program to download. I tried it but couldn't get any response.
My code:
manifest.js
{
  "manifest_version": 2,

  "name": "ADM",
  "description": "This extension shows a Google Image search result for the current page",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png"
  },
  "permissions": [
    "downloads",
    "https://ajax.googleapis.com/"
  ],

  "content_scripts": [{
    "matches" : ["http://*/*", "https://*/*"],
    "js" : ["myscript.js"]
  }]
}

myscript.js
chrome.downloads.onDeterminingFilename.addListener(function (item) {
    chrome.downloads.cancel(item.id);
    alert(item.url);
});

As I said, this code didn't cancel the download and show the url for test. How can I do it?

A: You are trying to access privileged Chrome apis from a content script, which is not permitted for security reasons. You need to move your code to an event page.
"background": { "scripts": ["myscript.js"], "persistent": false }

Also, read the architecture overview: https://developer.chrome.com/extensions/overview#arch


text:
Q: Responsive just active when insert code
A: You should use the proper functions to enqueue scripts and stylesheets.  I've added a dependency for bootstrap in this function so that is loads after bootstrap has loaded its stylesheet.  Place this code in your functions.php file, I've added in the Bootstrap CSS from a CDN as an example.
add_action( 'wp_enqueue_scripts', 'child_enqueue_styles');

function child_enqueue_styles() {

    wp_enqueue_style( 'bootstrap', 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css' );
    wp_enqueue_style( 'responsive', get_template_directory_uri() . '/responsive.css', array('bootstrap') );

}


text:
Q: How to convert a specific cell in an SQLite database into a string inside a WinForms textbox? Hi I am currently making a budgeting program for a school project and am having trouble with inputting a string converted from the SQLite table it is connected to externally. Here is my code:
'''
public entGlobalBUD()
        {
            InitializeComponent();

            SQLiteConnection sqlConnection = new SQLiteConnection();
            sqlConnection.ConnectionString = "DataSource = SubjectTable.db";

            //Deifine a SELECT statement
            string commandText = "SELECT * FROM SubjectTable";

            //Create the data table
            DataTable datatable = new DataTable();

            //Create SQLiteDataAdapter
            SQLiteDataAdapter myDataAdapter = new SQLiteDataAdapter(commandText, sqlConnection);

            sqlConnection.Open();
            myDataAdapter.Fill(datatable);
            sqlConnection.Close();

            dataGridView1.DataSource = datatable;
            budgetBox.Text = dataGridView1.SelectedRows[23].Cells[5].Value.ToString();

        }

'''
The last line is the one causing the problem as if removed the program runs fine but leaves the Budget Box empty. With this last line in the code the program will not run. After debuggin the problem occurs because the 'Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index' my table is 24x6 and still fails even if something like [2], [2] is inputted.
Any help would be greatly appreciated!

A: managed to solve it through a bit more research. Wasmy mistake needed to replace the last line of
budgetBox.Text = dataGridView1.SelectedRows[23].Cells[5].Value.ToString();

to
budgetBox.Text = dataGridView1.Rows[23].Cells[5].Value.ToString();

Hopefullly this helps if anyone comes across something similar in the future.


text:
Q: Drupal 7 Comment Not Posting I'm having a heck of time trying to get comments to post to my nodes. I've done all the obvious:
Enable comment module,
set appropriate permissions,
etc.
But every time I try to enter a comment it simply redirects to a "Add new comment" page and nothing gets posted. There is no comment in the Content -> Comments section and my database comment table is empty.
The only thing I can find relating to the issue is an error report in my log messages which displays a warning "page not found." I'm using the Drupal Busy theme.

*

*Type: Page not found

*Location: http://mysite/public://color/busy-0970ccd8/style.css?m

*Message: public://color/busy-0970ccd8/style.css

*Severity: Warning

I've ran the schema module and nothing is funky in with my database. Any thoughts on this? Much appreciated.

A: It's looking for a stylesheet from the Color module.  It would normally be at sites/default/files/color/busy-0970ccd8/style.css
Do you have a sites/default/files directory?  Check that you have one at that the directory is writable.  Also check to be sure that the color module is enabled.  Save your theme settings and clear your cache in configuration -- performance.
I'm not sure if a problem retrieving a style sheet from the color module could be causing this.  Seems very unlikely.
You might consider not using the busy theme.  It's current status is "minimally maintained" and the theme authors have left a note on the project page that there will be no further development at this time.
I recommend looking for a theme that is actively maintained and has good support.  It looks like Busy is a pretty standard 960 grid, you might like Omega.