Where can I find legendary crafting materials?

Question: My boulder barbarian would love some Reaper's Wraps but they require Reaper's Fear. I've found various other crafting plans that require legendary materials.
Where can I find Reaper's Fear and other legendary crafting materials? Are there places to farm these materials or is it all luck of the draw?
Comment: As far as I can see, You can only pray to the RNG gods. Not 100% sure though.
Answer: This Diablo 3 Craftables Spreadsheet is particularly helpful when trying to figure out if you are in an area with a possible legendary crafting material drop.
Here is the same list in not so sortable form:
Legendary Crafting Materials:

Adventurer's Journal

Found in: Acts 1-4 - Various World Objects
Used For: Pender's Purchase

Angelic Shard

Found in:

Act 4 - The Great Span: Izaul
Act 4 - Multiple Areas: Corrupted Angel
Act 4 - The Silver Spire Level 1: Pyres the Damned
Act 5 - Pandemonium Fortress Level 2: Celic

Used For: Hallowed Protectors Set

Behistun Rune

Found in:

Act 1 - Leoric's Manor: Krailen the Wicked
Act 2 - Road to Alcarnus: Yeth

Used For: Mark of the Magi

Bloody Pincer

Found in:

Act 3 - Tower of the Damned Level 2: Crabbs
Act 3 - The Core of Arreat: Scorpitox
Act 5 - Ruins of Corvus: Balata

Used For: Demon Claw

Born's Key

Found in:

Act 1 - Cemetary of the Forsaken: Lucious the Depraved
Act 1 - Defiled Crypt: Digger O'Dell
Act 1 - Defiled Crypt: Dataminer
Act 1 - Defiled Crypt: John Gorham

Used For: Born's Command Set

Captured Nightmare

Found in:

Act 4 - The Silver Spire Level 2: Grimnight the Soulless
Act 4 - The Silver Spire Level 1/2: Terror Demons and Enslaved Nightmares

Used For: Night's Reaping

Captured Soul

Found in:

Act 3 - The Keep Depths Level 2: Aloysius the Ghastly

Used For: Lai Yui's Persuader

Cartographer's Toolkit

Found in:

Act 1 - Festering Woods: Grimsmack
Act 1 - Festering Woods: Enkidu (Ancient War Event)
Act 3 - Rakkis Crossing: Lavarinth (Blaze of Glory Event)
Act 3 - Tower of the Damned: Gholash

Used For: Board Walker's

Cultist Blood

Found in:

Act 1 - Halls of Agony: Cultist Grant Inquisitor
Act 2 - Alcarnus: High Cultist Murdos
Act 2 - Alcarnus: Jhorum the Cleric

Used For: Blood Magic Dagger

Defiled Doll

Found in:

Act 4 - The Silver Spire Level 1: Kysindra the Wretched
Act 5 - House of Deep Sorrow: Lady Victoria (Event Spawn)

Used For: Spite

Demon Skin

Found in:

Act 3 - The Core of Arreat: Axgore the Cleaver
Act 3 - Tower of the Damned Level 1: Haxxor
Act 4 - Gardens of Hope Tier 1: Khatun
Act 4 - Gardens of Hope Tier 2: Razorclaw

Used For: Demon's Hide Set

Element of Celerity

Found in:

Act 1 - The Weeping Hollow: Mange
Act 1 - Fields of Misery: Burrow Bile (The Forlorn Farm Event)
Act 1 - Fields of Misery: Dreadclaw the Leaper
Act 1 - The Lost Mine (Fields of Misery): Shanabi (Precious Ores Event)
Act 1 - Watch Tower Level 2: Armorer's Bane (Scavenged Scabbard Event)
Used For: Fleeting Strap

Essence of the Twin Seas

Found in:

Act 2 - Black Canyon Mines: Razormouth
Act 2 - Sewers of Caldeum: Moontooth Dreadshark

Used For: Captain Crimson's Trimmings Set

Eternal Power Capsule

Found in:

Act 1 - Whimsyshire: Evil Oliver

Used For: Arcane Barb

Eyes of the Dead

Found in:

Act 1 - Leoric's Passage: Headcleaver (Quest Spawn)
Act 1 - Cathedral Level 2: Merrium Skullthorn

Used For: War of the Dead

Frozen Blood

Found in:

Act 3 - Caverns of Frost: Chiltara

Used For: Utar's Roar

Glowing Ore

Found in:

Act 5 - Battlefields of Eternity: Sartor
Act 5 - Pandemonium Fortress: Soul Scavenger (The Souls of Angels Event)

Used For: Cosmic Strand

Griswold's Scribblings

Found in:

Act 1 - Cathedral: Bookshelves
Act 1 - Cemetery of the Forsaken: Gravedigger's Corpse
Act 1 - Festering Woods: Enmerkar (Last Stand of the Ancients Event)
Act 1 - Wortham Chapel: Bookshelves
Act 2 - Khasim Outpost: Cain's Lost Satchel
Act 2 - Khasim Outpost: Imperial Guard Supplies
Act 2 - Zoltun Kulle Dungeons: Bookshelves
Act 3 - Skycrown Battlements: Morgan's Satchel
Act 3 - The Keep Depths: Lore Objects
Act 4 - Multiple Areas: Angel Archives

Used For: Griswold's Perfection

Hilt of the Silver Wolf

Found in:

Act 3 - Arreat Crater Level 1: Growlfang
Act 3 - Tower of the Damned Level 1: Gnawbone

Used For: Golden Scourge

Human Cartilage

Found in:

Act 1 - Cathedral Level 2: Cudgelarm
Act 1 - Defiled Crypt Level 2: Mangelmaw

Used For: Wall of Man

Iron Wolves Doctrine

Found in:

Act 2 - Dahlgur Oasis: Ssthrass

Used For: Asheara's Vestment Set

Living Flame

Found in:

Act 4 - The Silver Spire Level 2: Sao'Thall
Act 4 - The Silver Spire Level 2: Rhau'Kye
Act 4 - Radiant Chapel: Malfeas the Abhorrent

Used For: Cinder Switch

Lyekurn's Diary

Found in:

Act 3 - The Heart of Sin: Azmodan

Used For: Corruption

Maghda's Tormented Soul

Found in:

Act 2 - Lair of the Witch: Maghda

Used For: Cain's Destiny Set

Mystical Source

Found in:

Act 1: Whimsyshire: Midnight Sparkle
Act 1: Whimsyshire: Nightmarity
Act 1: Whimsyshire: Team Unicorn
Act 1: Whimsyshire: Creampuff

Used For: Sage's Journey Set

Phial of Weakness

Found in:

Act 3 - The Battlefields: Deadgrasp
Act 3 - The Battlefields: Handible (Triage Event)

Used For: Atrophy

Quaking Vial

Found in:

Act 4 - Hellrift Level 1: Sledge
Act 4 - Hellrift Level 2: Hammermash

Used For: Sunder

Reaper's Fear

Found in:

Act 5 - Heart of the Fortress: Maltheal

Used For: Reaper's Wraps

Rydraelm Tome

Found in:

Act 2 - The Lost Caravan (Stinging Winds): Beyatt
Act 2 - Daulguhr Oasis: Ashangu

Used For: Mantle of the Rydraelm

Shard of the Ensteig Plate

Found in:

Act 1 - Defiled Crypt: Lord Dunhyld (The Matriarch of Bones Event)
Act 1 - Festering Woods: Feklar's Ghost
Act 1 - Festering Woods: Hawthorne Gable
Act 2 - Sewers of Caldeum: Shade of Nar Gulle
Act 2 - Unknown Depths: The Archivist (Event Spawn)
Act 2 - Tomb of Khan Dakab: Spirit of Khan Dakab (Event Spawn)

Used For: Aughild's Authority Set

Shattered Core

Found in:

Act 2 - Forgotten Ruins: Ancient Guardian
Act 2 - Unknown Depths: Rockgut
Act 2 - Realm of Shadow: Thrum

Used For: Devastator

Shimmering Quill

Found in:

Act 1 - Dank Cellar: Sarkoth
Act 1 - Musty Cellar: Gorathra
Act 3 - Keep Depths Level 1: Thornback

Used For: Unbound Bolt

Shuddering Demon Bone

Found in:

Act 4 - Gardens of Hope Tier 2: Koa' Ahn
Act 4 - Gardens of Hope Tier 2: Oah' Tash

Used For: Archfiend Arrows

Skeleton's Dice

Found in:

Act 4 - Gardens of Hope Tier 1: Torchlighter
Act 5 -  Battlefields of Eternity: Emikdeva
Act 5 -  Battlefields of Eternity: Korchoroth

Used For: Skeleton's Deceit

Skull of Raylend

Found in:

Act 3 - The Keep Depths Level 2: Bholen
Act 3 - Rakki's Crossing: Garganug
Act 3 - Core of Arreat: Gorog the Bruiser

Used For: The Helm of Rule
Sydyru Bone
Found in:

Act 1 - Cathedral Level 1: Gildewing
Act 1 - Cathedral Level 1: Firestarter
Act 1 - Fields of Misery: Sicklefang (Carrion Farm Event)
Act 3 - Unknown Depths: Hellscream

Used For: Sydyru Crust

Symbol of the Guardian Brotherhood

Found in:

Act 3 - Skycrown Battlements: Thromp the Breaker
Act 3 - Stonefort: Bashface the Truncheon
Act 3 - Stonefort: Dragus (Waiting for Reinforcements Event)
Act 3 - The Keep Depths Level 2: The Crusher
Act 3 - Rakkis Crossing: Busaw (Crazy Climber Event)

Used For: Guardian's Jeopardy Set

Torn Soul

Found in:

Act 1 - Southern Highlands: Lorzak the Powerful
Act 1 - Southern Highlands: Skehlinrath

Used For: Living Umbral Oath

Urn of Quickening

Found in:

Act 2 - Stinging Winds: Erach
Act 3 - Caverns of Frost Level 2: Chiltara
Act 3 - Caverns of Frost Level 2: Scathach the Savage
Act 3 - Icefall Caves: Zelusa the Grasping
Act 5 - Heart of the Fortress: Malthael (* May be a bug)

Used For: Kethryes' Splint

White Oak Splinter

Found in:

Act 1 - Secluded Grove (Fields of Misery): The Old Man

Used For: Rozpedin's Force

Wooden Stake

Found in:

Act 1 - Cathedral Level 4: Killian Damort
Act 3 - The Keep Depths Level 3: Belagg Pierceflesh

Used For: Blitzbolter

Woven Plate

Found in:

Act 1 - The Cathedral Level 4: Captain Cage
Act 1 - The Festering Woods: Enmerkar (The Last Stand of the Ancients Event)
Act 3 - The Keep Depths Level 1: Captain Donn Adams

Used For: Piro Marella

Infernal Machine Crafting Components:

Key of Bones

Found in:

Various Acts - Keywardens

Used For:

Infernal Machine of Bones
Infernal Machine of Evil
Infernal Machine of Gluttony
Infernal Machine of War

Key of Evil

Found in:

Various Acts - Keywardens

Used For:

Infernal Machine of Bones
Infernal Machine of Evil
Infernal Machine of Gluttony
Infernal Machine of War

Key of Gluttony

Found in:

Various Acts - Keywardens

Used For:

Infernal Machine of Bones
Infernal Machine of Evil
Infernal Machine of Gluttony
Infernal Machine of War

Key of War

Found in:

Various Acts - Keywardens

Used For:

Infernal Machine of Bones
Infernal Machine of Evil
Infernal Machine of Gluttony
Infernal Machine of War

Source for the various locations
Answer: According to this page on Diablofans, only Malthael himself drops this specific crafting material:

Acquired from: Act V, Heart of the Fortress, Malthael
Where to farm: Act V, Heart of the Fortress
Used for: Reaper's Wraps, Wrists, Health globes restore 25–30% of your primary resource, 5 random magic properties (as opposed to the 8
  properties according to Battle.net)
Note: Malthael also drops the Recipe for Reaper's Wraps.

This sounds pretty plausible to me as I also got the plan from him (which seems to be a guaranteed drop).


Using zxing on Google Glass

Question: I´m trying to use the zxing on the google glass, however i´m receiving the error above.
I using the zxing 2.2 core.jar
I also receive this error message on the device display "Sorry, the android camera encountered a problem. You may need to restart the device".
I´m lauching a intent on my oncreate activity
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}

Eclipse Error Message
12-16 15:29:24.578: I/PlatformSupportManager(2150): Using implementation class com.google.zxing.client.android.camera.open.GingerbreadOpenCameraInterface of interface com.google.zxing.client.android.camera.open.OpenCameraInterface for SDK 9

12-16 15:29:24.578: I/GingerbreadOpenCamera(2150): Opening camera #0

**12-16 15:29:24.585: W/CaptureActivity(2150): Unexpected error initializing camera**

12-16 15:29:24.585: W/CaptureActivity(2150): java.lang.RuntimeException: Fail to connect to camera service
12-16 15:29:24.585: W/CaptureActivity(2150):    at android.hardware.Camera.native_setup(Native Method)

12-16 15:29:24.585: W/CaptureActivity(2150):    at android.hardware.Camera.<init>(Camera.java:374)

12-16 15:29:24.585: W/CaptureActivity(2150):    at android.hardware.Camera.open(Camera.java:315)

12-16 15:29:24.585: W/CaptureActivity(2150):    at com.google.zxing.client.android.camera.open.GingerbreadOpenCameraInterface.open(GingerbreadOpenCameraInterface.java:57)

12-16 15:29:24.585: W/CaptureActivity(2150):    at com.google.zxing.client.android.camera.CameraManager.openDriver(CameraManager.java:78)

GDK Camera References (https://developers.google.com/glass/develop/gdk/reference/com/google/android/glass/media/Camera)
There is not a lot information about how use it, however there are other questions like this one
Google Glass preview image scrambled with new XE10 release
that make me think that is possible to use the zxing on glass.
Answer: I not including
<uses-permission android:name="android.permission.CAMERA"/>

at the top of my manifest.
This is blocking my camera to open.
If someone is trying to integrate zxing i suggest use this tutorial.
http://damianflannery.wordpress.com/2011/06/13/integrate-zxing-barcode-scanner-into-your-android-app-natively-using-eclipse/
Comment: Yes, i have only to adjust some settings on the camera.

http://stackoverflow.com/questions/19235477/google-glass-preview-image-scrambled-with-new-xe10-release
Comment: HI Jose, Are you able to successfully run zxing in google glass and scan a QR Code with the tutorial you mentioned ?
Comment: I could not get ZXing to compile at all with the above tutorial. Can you provide anymore insight about how you got it to work or provide an apk of working zxing for glass?
Comment: In which step are you having trouble? Be more specif, so i could help you.
Comment: I downloaded the code for zxing, and got the jar, but I can't get the code to compile because of errors with jave 1.6 vs 1.7. The ZXing code appears to use many features of 1.7, but my ADT (eclipse) won't let me compile for android with 1.7, so I am a little stuck on what to do.
Comment: On 2013/12/02, the zxing made the following commit that made the code no longer compatible with Eclipse 1.6 Java compiler limitation:
https://github.com/zxing/zxing/commit/a53c659b0e54646979649d550f9ab141c9826a67
While Eclipse is broken, it should compile fine in Android Studio.
Someone could also create a fork from an earlier commit and add back in the code required to make this compile on JDK 6 (1.6).
Comment: Actually, dex handles Java 7 bytecode just fine. (Just don't use `AutoCloseable`). Eclipse can most certainly be set to compile for Java 7.
Answer: This project BarcodeEye is a port of ZXing to Google glass that is working.
The source is online. It solved for my use case
https://github.com/BarcodeEye/BarcodeEye
Comment: Were you able to call BarcodeEye as an intent? I am having trouble integrating it with my app.
Comment: What are you trying to scan? Are you trying to get a standard type to invoke (phone, email, url).

I also looked into setting a custom mime-type for the scanner to handle.
http://stackoverflow.com/questions/5744944/how-to-add-custom-mime-type
Comment: This question was also very helpful on my understanding on intent integration http://stackoverflow.com/questions/4854442/embed-zxing-library-without-using-barcode-scanner-app
Comment: I wouldn't recommend barcode eye. First it's not easy to implement and then it has trouble to detect 1d barcodes on glass. At least in my setup. The barcode needed to be like 20 cm large to be recognized ...
Comment: @anthea those were my findings after a few weeks. I ran into the same zoom focus issues in the SDK. I went with a closed source solution http://www.scandit.com/  after.  This is many moons again on XE16 of glass and many other policies may of changed.
Comment: @stanzheng Thanks, for your reply after all this time :) What were your experiences with scandit? Did it work well on your glass?
Comment: Scandit worked great, they had gotten around the focus issue on their product and were gearing their product towards glass as a scanner tool. They're probably farther along or shelved their effort but what i was working on was similar to this: http://www.scandit.com/2014/04/22/barcode-scanning-with-google-glass-pick-by-vision-app-video/

Using zxing on Google Glass


Asp.Net MVC JavaScript doesn't work after loading page

Question: I'm developing Asp.Net MVC application.
I'm using partial view for menu in Layout form for some views. I need use JavaScript on this view, but its work only on first time - after view loaded. Later - doesn't. Partial View is like this:
@Scripts.Render("~/bundles/jquery")
@Html.CheckBox("IsChoosed", true, new { onclick = "FormReload();" })

LayoutForm:
@Html.Partial("_ViewPartial")

@RenderBody()

Alert message is displayed after loading of page, when checkbox value set. But after while i'm changing value - doesn't.
I tried to move JavaScritp methods to ***.js file and hook up it in view, but its worked the same way.
Where can be an error?
Answer: Your change event is not firing because you are trying to attach to the class .IsChoosed.
try changing your change handler to:-
$("#IsChoosed").on("onchange", function () {
     FormReload();
});

so #IsChoosed instead of .IsChoosed.
EDIT
Also, change:-
var FormReload = new function ()

to this:-
function FormReload()

Comment: ieaglle, BG101, thank you very much! I changed code like you told, but its still don't work. Also it strenge that alert message is displayed after pade loading and later not.
Comment: If they helped, give them an upvote and mark the relevant answer as correct  :^)
Comment: BG101, i'm sorry, it didn't help.
Answer: @Html.CheckBox("IsChoosed",... - first argument is name.
Selector $(".IsChoosed") looks for class IsChoosed. So onchange callback is not set.
To fix you can do the following:
@Html.CheckBox("IsChoosed", true, new { @class="IsChoosed", onclick = "FormReload();" })

Comment: ieaglle, thank you very much! I changed code like you told, but its still don't work. Also it strenge that alert message is displayed after pade loading and later not


C# Regex remove href

Question: So basically I want to remove href ie.:
Apdo Dog2

So I just want the Apdo Dog2 part of the text. Any idea?
Here's my code:
private void button1_Click(object sender, EventArgs e)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("SITE");
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    StreamReader stream = new StreamReader(response.GetResponseStream());

    string final_response = stream.ReadToEnd();

    Regex r = new Regex(@"\<[^\>]+\>(.[^\<]+)</[^\>]+\>", RegexOptions.Singleline);
    Match m = r.Match(final_response);

    richTextBox1.Text = m.Value;

Comment: You should really use something like [HtmlAgilityPack](http://www.nuget.org/packages/HtmlAgilityPack). There's a huge selection of HTML that will break plain regex.
Answer: You can use this regex:
(.*?)<\/a>

Working demo
Answer: Any Ideas? Yes, you should use a parser such as HtmlAgilityPack to extract these values.
You don't need to escape the bracket characters, these characters have no special meaning. But, the main problem is the dot . remove it. And then refer to the group using Match.Groups Property to access your match result.
Regex r = new Regex(@"<[^>]+>([^<]+)</[^>]+>");
Match m = r.Match(final_response);
richTextBox1.Text = m.Groups[1].Value;

Note: The dot . is removed and you are using negated classes, so you can remove the dotall modifier.
Working Demo
Comment: Thats good, what should I add if I want more than one line as output?
Comment: Use Regex.Matches method.
Comment: I tried with it and got this as output: http://i.imgur.com/wsho8Yo.png Do you know why? kinda strange
Comment: If you just want the content values, try `Regex r = new Regex(@"]*>([^<]+)");`
Answer: You can have a look at my answer here and do something similar I guess.
The only difference is that you'll delete/remove all the stuff including the brackets.
Other than that, keep in mind that the general consensus is to not mix RexEx with HTML :)
This should work :
void Main()
{
    // your input
    String input = @@"Apdo Dog2	";
    // temp variables
    StringBuilder sb = new StringBuilder();
    bool inside = false;
    bool delete = false;
    // analyze string
    for (int i = 0; i < input.Length; i++)
    {
        // Special case, start bracket
        if (input[i].Equals('<')) {
            inside = true;

        }
        // special case, close bracket
        else if (input[i].Equals('>')) {
            inside = false;
            continue;
        }

        // add if needed
        if (!inside)
                sb.Append(input[i]);
    }
    var result = sb.ToString(); // -> holds: "Apdo Dog2"
}

Comment: For what should this work? This doesn't seem to answer the question
Comment: For: `Apdo Dog2`, it'll give you `Apdo Dog2`

C# Regex remove href


Localizable.strings issue with SVN

Question: these are the steps i followed to create Localizable.strings file.
1) created a folder called "en.lproj"
2) ran the command from terminal genstrings -o en.lproj Classes/*.m
it generates correct file under "en.lproj".
now my question is how do i add that file to my project. i did drag n drop that file but its not giving me any option to add to repository.
am i doing something wrong.
Comment: I know it's a bit glib, but one thing you're doing wrong is using CVS. The world has moved on, CVS isn't even in the previous generation of version control systems. Check out Git or Mercurial.
Comment: oh sorry. actually i am using SVN.
Comment: Have you found a solution to your question? What I think I'll do is manually import the language.proj folders into my svn.
Comment: no luck yet. i can give a try
Answer: The method I use goes something like this:

Create the file to be localized (Localizable.strings)
Add that file to Xcode directly (no en.lproj folder or anything)
Select that file in Xcode, right click, "Get Info"
General tab, "Make file localizable"

This way, Xcode takes care of the folder stuff for you, and I would assume take care of the SCM management stuff too.  I personally don't like to use Xcode for SCM, I prefer using an external tool, for separation of concerns, etc.
Comment: but it does not give me an option to commit my changes after modification. and also after my initial checking(add to repository) my team mate didnt get file or English.lproj folder?

Localizable.strings issue with SVN


Queueing: N producers to N consumers

Question: The requirement is as follows:

There are N producers, that generate messages or jobs or whatever you want to call it.
Messages from each procuder must be processed in order and each message must be processed exactly once.
There's one more restriction: at any time for any given producer there must be not more than one message that is being processed.
The consuming side consists of a number of threads (they are identical in their functionality) that are spread across a number of processes - it is a WSGI application run via mod_wsgi.

At the moment, the queueing on the consuming side is implemented as a custom queue, that subclasses Queue, but it has its own problems that I won't get into, the main one being that upon process restart its queue is lost.
Is there a product, that will make it possible to fulfill the requirements I've outlined above? Support for persistency would've been great, though that is not so important (since the queue will not reside in the worker process' memory any more).
Comment: [celery](http://celeryproject.org/)
Answer: There are many products that do what you are looking for.  People with Django experience will probably tell you "celery", but that's not a complete answer.  Celery is a (useful) wrapper around the actual queuing system, and using a wrapper doesn't mean you don't have to think about your underlying technology.
ZeroMQ, Redis, and RabbitMQ are a few different solutions that come to mind.  There are of course more options.  I'm fairly certain that no queueing solution will support your "at any time for any given producer there must be not more than one message that is being processed" requirement as a configuration parameter; you should probably implement this requirement at the producer (i.e. do not submit job #2 until you receive confirmation that job #1 has completed).
Redis is not a real queueing system, but a very fast database with pub/sub features; you would not be able to use Redis pub/sub to satisfy the "job processed exactly once" requirement out of the box, although you could use Redis pub/sub to publish jobs to a single subscriber which then pushes them into the database as a list (a poor man's queue).  Your consumers would then atomically pull a job from the list.  It'll work if you want to go this route.
RabbitMQ is an "enterprise" queueing system, and would absolutely meet your requirements, but you'd have to deploy the RabbitMQ server somewhere, and it might be overkill.  For the record, I use RabbitMQ on numerous projects, and it gets the job done.  Set up a "direct"-type exchange, bind it to a single queue, and subscribe all your consumers to this queue.  You get pretty good persistence from RabbitMQ too.
ZeroMQ has a very very flexible queueing model, and ZeroMQ can absolutely be made to do what you want. ZeroMQ is basically just the transport mechanism though, so when it comes to making your publishers and subscribers and a broker to distribute them, you may end up rolling your own.

Queueing: N producers to N consumers


FAILED: IllegalArgumentException java.net.URISyntaxException: Relative path in absolute URI:

Question: My hive-site.xml configuration is
When I use hive:
show databases;
The exception that I'm getting is:
FAILED: IllegalArgumentException java.net.URISyntaxException:
Relative path in absolute URI: file:./tmp/hive-root/root/74dc7e51-1d24-4397-9321-9b8c651ee212/hive_2016-12-04_22-55-36_784_2074916962149947374-1

Comment:
hive.exec.scratchdir
/tmp/hive-${user.name}
HDFS root scratch dir for Hive jobs which gets created with write all (733) permission. For each connecting user, an HDFS scratch dir: ${hive.exec.scratchdir}/ is created, with ${hive.scratch.dir.permission}.

hive.exec.local.scratchdir
tmp/hive-${user.name}/root
Local scratch space for Hive jobs
Comment: Please specify your question
Answer: Change the hive-site.xml with below properties
<name>hive.exec.scratchdir</name>
<value>/tmp/hive</value>

 <name>hive.exec.local.scratchdir</name>
 <value>/tmp/hive</value>

<name>hive.downloaded.resources.dir</name>
<value>/tmp/hive/${hive.session.id}_resources</value>

<name>hive.scratch.dir.permission</name>
<value>733</value>


MySQL Subquery using SUM, WHERE, GROUP_BY

Question: I'm a beginner (not a DBA).
The simple version of my data ==> My hoped for result:
|ball |color|count|         |ball |Total Blue|Total Red|
-------------------         ----------------------------
|b1   |red  |   2 |  ====>  |b1   | 5       | 2        |
|b1   |blue |   3 |         |b2   | 3       | 1        |
|b1   |blue |   2 |
|b2   |red  |   1 |
|b2   |blue |   3 |
I want to tabulate each ball (b1, b2, etc).
Then the total instance of each color for each ball.
There are multiple entries for each color of each ball (in my real world data).
But here I show multiple entries for the blue #1-balls only.
I can easily do this:
SELECT ball,
SUM(count) AS 'Total Blue'
FROM t1
WHERE color = 'blue'
GROUP BY ball

To obtain the first (good) result:

|ball |Total Blue|
 -----------------
|b1   | 5        |
|b2   | 3        |
To go further, I think I need a subquery.
But I have not been able to get the subquery to process the same way as the regular query.
Below is the closest result I've gotten so far (simple attempt):
SELECT ball,
SUM(count) AS 'Total Blue',
(SELECT SUM(count) FROM t1 WHERE color = 'red') AS 'Total Red'
FROM t1
WHERE color = 'blue'
GROUP BY ball

I get this:
|ball |Total Blue| Total Red|
 ---------------------------
|b1   | 5        |  3       |
|b2   | 3        |  3       |
Total Red shows the total of all red balls regardless of ball number.
This more involved subquery (for red) produces the exact same result:
(SELECT SUM(cc) FROM
(SELECT DISTINCT count AS cc FROM t1  WHERE color = 'red') AS dd )
AS 'Total Red'

I've added GROUP BY to this subquery to no added effect.
This is as close as I've been able to get.
Many other tries have given a variety of results.
Answer: Try combining SUM and IF:
 SELECT
    ball,
    SUM(IF(color = 'blue', count, 0)) AS 'Total Blue'
    SUM(IF(color = 'red', count, 0)) AS 'Total Red'
 FROM t1
 GROUP BY ball

Comment: Wow that worked....You are a god....I've spent days on this, knowing that stackoverflow was just sitting here....Thank you!
Answer: I just want to offer the following, because CASE is standard SQL and IF is not:
select ball,
       sum(case when color = 'blue' then `count` else 0 end) as TotalBlue,
       sum(case when color = 'red' then `count` else 0 end) as TotalRed
from t
group by ball
order by 1

Also, having "count" as the name of a column is a bad idea, because it is an SQL reserved word.
Comment: `COUNT` is not a [reserved word](http://dev.mysql.com/doc/refman/5.6/en/reserved-words.html) in MySQL, but it is the name of an [aggregate function](http://dev.mysql.com/doc/refman/5.6/en/group-by-functions.html#function_count).
Comment: @MarkByers . . . You are correct that it is not in the list of MySQL reserved words.  COUNT is, however, on every list of ANSI SQL reserved words that I can find (I don't have a standard on hand to check).  I still think it is a bad idea to use such words for variables names.


Solving an equation in a special form

Question: I want to deduce the special form of $$w^2 = \frac{k_z^2}{2a^2}\left[b + \sqrt{b^2 - 4a^2T}\right]$$ from the equation
$$ \left(1+ \frac{k_z}{wk_x}\right){k_x}^2 = \left(T -\frac{ w^2a^2}{k_z^2}\right)\left(\frac{k_z^2}{w^2} - 1\right)$$
Also it is given that $k_x\gg k_z.$
And $b=T+a^2+k_z^2$.
So we have $\frac{k_z}{k_x}\approx0$.
And using this I tried to solve for the desired form, but I was unable to solve it.
Any help towards this will be appreciated. Thank you.
Answer: Under the assumption $k_z / k_x\approx 0$ the second equation becomes
$$
k_x^2 = \left(T - \frac{w^2a^2}{k_z^2} \right)\left(\frac{k_z^2}{w^2} - 1\right)
$$
Multiply by $w^2$ and expand
$$
k_x^2 w^2 = Tk_z^2 - Tw^2 - a^2 w^2 + \frac{w^4 a^2}{k_z^2}
$$
Rearranging
$$
w^4 \frac{a^2}{k_z^2} - \underbrace{(T + a^2 + k_x^2)}_{\color{blue}{b}} w^2 + Tk_z^2 = 0
$$
So you end up with
$$
\frac{a^2}{k_z^2} x^2 - b x + T k_z^2 = 0
$$
where I called $x = w^2$. This is just a quadratic equation in $x = w^2$.
\begin{eqnarray}
w^2 &=& \frac{b\pm\sqrt{b^2 - 4 (a^2/k_z^2)(Tk_z^2)}}{2a^2/k_z^2} \\
&=& \frac{k_z^2}{2a^2} \left[ b\pm\sqrt{b^2 - 4 a^2T}\right]
\end{eqnarray}

Solving an equation in a special form


understanding mapDispatchToProps in redux

Question: i want my code to listen the choice(on list page) and then display the data by getting data from node server on another page
import React from 'react'
import {Link} from 'react-router-dom'
import {connect} from 'react-redux'
import {loadBickes} from './../../reducers/itemsGet.js'
import axios from 'axios'
class Hello extends React.Component{

constructor(props){
    super(props)
    this.handleBick = this.handleBick.bind(this)
}

handleBick(){
    console.log("demanding bickes")
    //loadBickes();
    axios.get('/getBike')
        .then((response)=>{
        var dataP = response.data
        console.log("data set")
        console.log(response.data)
        console.log("redy to b dispatched set")
        {this.props.setState(response.data)}
    //    dispatch(setState(response.data))
    })
}
//
<Link to="Bike" onClick={this.props.Bike}>Bicycle</Link>

    render(){
        return(

Items

<button onClick={this.handleBick}>Bicycle</button>

<Link to="Calculator" onClick={this.props.Calculator}>Calculator</Link>

        )
    }
}

const mapStateToProps =(state)=>{
    console.log("state"+state.item.name)
    return {
       user : state.item
    }
}

const mapDispatchToProps =(dispatch)=>{
 return {
    Bike : () => dispatch({
      type : "LOAD_BIKE"
    }),
     Calculator : () => dispatch({
      type : "LOAD_CALC"
    }),
        setState:(data)=>dispatch({
            type : "setData",
            payload : data
        })
  }
}

export default connect(mapStateToProps,mapDispatchToProps)(Hello)

i mAke axios call to server and then i want to dispatch action to set state of my reducer and then i will try to redirect it to other page
is their any other way
or
i need 1) to give data of axios to dispatcher
2) way to redirect it after
help please
Comment: `this.props.history.push` is how you redirect to another route with React Router. See below.
Answer: import React, { Component } from 'react'
import {Link} from 'react-router-dom'
import {connect} from 'react-redux'
import {loadBickes} from './../../reducers/itemsGet.js'
import axios from 'axios'

class Hello extends Component {

    constructor(props){
        super(props);
        this.handleBick = this.handleBick.bind(this)
    }

    handleBick(){
        axios.get('/getBike').then( (response) => {
            let dataP = response.data;
            this.props.setState(response.data);
            this.props.history.push("/route_you_want_to_go_too");
        });
    }

    render() {
        return(

Items

                    <button onClick={this.handleBick}>Bicycle</button>

                    <Link to="Calculator" onClick={this.props.Calculator}>Calculator</Link>

        )
    }
}

const mapStateToProps = (state) => ({
        user : state.item
});

const mapDispatchToProps = (dispatch) => ({
        Bike : () => dispatch({
            type : "LOAD_BIKE"
        }),
        Calculator : () => dispatch({
            type : "LOAD_CALC"
        }),
        setState:(data)=>dispatch({
            type : "setData",
            payload : data
        })
});

export default connect( mapStateToProps,mapDispatchToProps )( Hello );

You should think about working on writing cleaner code, it will make it easier to help you.
Comment: thanku bro.this help me a lot and i will work on ur advice also


How do fix '404 page not found' error when running a php file?

Question: I am just starting to learn php and when I run my php file, no matter the browser, i get a 404 error. What is my code missing that is causing this? This file is supposed to display a message after a user submits a 'contact me' form.
<!DOCTYPE html>

    <title>Contact Form Submitted</title>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">

    Thank you, <?php echo $_POST["name"]; ?> for your comments

    You stated in your test Message:

    <?php echo $_POST["message"]; ?>
    We will respond to you at <?php echo $_POST["email"]; ?> when we make updates to the site.

Comment: what do you mean by running? visiting `/thefile.php`? how are you submitting it when there is no buttons?
Comment: There is a submit button on the 'contact me' html form. Should that all be in one file?
Comment: I'm using php storm and there is a run button
Answer: this code works. see this is firefox: https://i.stack.imgur.com/Ksw1N.png
<?php
// var    // variable value       // default value
$php_path = $_SERVER['PHP_SELF']  ?? "";
$name     = $_POST["name"]        ?? "name";
$message  = $_POST["message"]     ?? "message";
$email    = $_POST["email"]       ?? "email";

?>
<!DOCTYPE html>

    <title>Contact Form Submitted</title>

<form action="<?= $php_path ?>" method="POST">

    Thank you, <?= $name ?> for your comments

    You stated in your test Message:

    <?= $message ?>

    We will respond to you at <?= $email ?> when we make updates to the site.

</form>

if you don't specify a default value on your parameters from another form you could run into an unexpected error. This version is better ;)
I'm sure you get this error because you have a typo in one of your urls
Comment: That code gives me errors saying 'Coalesce operator is available in PHP 7 only'
Comment: you are not running version 7 or above? https://www.php.net/supported-versions.php
Comment: Im using PHP Storm by jetbrains, its the most recent version, I have an education license for it, so I don't think I can change the version.
Comment: https://stackoverflow.com/questions/4122585/how-can-i-set-the-php-version-in-phpstorm PHP 5 is old and bad. PHP7 was a huge improvement
Comment: Okay thanks, wish my professor would have mentioned that. Also my contact form is an html file. Does it have to be a php file for this to work, All I am trying to do is redirect the user to a blank page after they click submit that stats the thank you msg.
Comment: yes it has to be a php file and you need somthing like xampp in order to execute php because php gets just in time translated and is not compiled at once. If you want to redirect a user in php there is the `header("Location: /path/to/file.php");` function
Answer: First of all use htmlspecialchars in:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

you prevent XSS attack if user enter url like: http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E
If you are getting 404 error it's probably becouse your action of the form on contact me page don't point to right script.
If you have two separate files, one for form and second for thanks message you have to make sure than the urls are correct.
// form.php
...
<form action="thanks-message.php">
    ...
</form>
...

// thanks-message.php
<?php
$name = $_POST["name"] ?? "Joe";
$message = $_POST["message"] ?? "Lorem ipsum...";
$email = $_POST["email"] ?? "firstname.lastname@example.com";
?>
...

    Thank you, <?= $name ?> for your comments

    You stated in your test Message:

    <?= $message ?>

    We will respond to you at <?= $email ?> when we make updates to the site.

...

form element is not necessary on this page


Changing ID to something more friendly

Question: When creating a record the URL generated to view that record ends with its id
/record/21

I would like to be able to change that to something easier to read, such as my name and reference attributes from the model. I have looked at friendly_id but has trouble implementing a custom method to generate the URL
class Animal < ActiveRecord::Base
  extend FriendlyId
  friendly_id :name_and_ref

  def name_and_ref
   "#{name}-#{reference}"
  end
end

I ended up getting an error
PG::UndefinedColumn: ERROR: column animals.name_and_ref does not exist LINE 1: SELECT "animals".* FROM "animals" WHERE "animals"."name_an... ^ : SELECT "animals".* FROM "animals" WHERE "animals"."name_and_ref" = 'Clawd-A123456' ORDER BY "animals"."id" ASC LIMIT 1

def show
  @animal = Animal.friendly.find(params[:id])
end

I then come across the to_param method which Rails has available, in my model I have
def to_param
  "#{self.id}-#{self.name}"
end

which will generate a URL for me of
/19-clawd

This works, but when I do the following it throws an error
def to_param
  "#{self.name}-#{self.reference}"
end

My question though is how can I generate the URL to be name and reference without it throwing
Couldn't find Animal with 'id'=Clawd-A123456

Comment: you're rewriting RESTful design, I would highly advise you to not go down this road...
Comment: so you would advise to stick with the /id urls ?
Comment: Yes, take a look at [this](http://www.restapitutorial.com/lessons/restfulresourcenaming.html)
Comment: see the answers below.  Bu do you expect users to type in the URL by hand? or is your reason for doing it to look pretty?  If the latter. Just make sure to include the id as the first part of to_param and they will be prettier, and still work without having to rewrite your finds
Comment: its all for SEO and to look prettier(readable).
Comment: then `"#{self.id}-#{self.name}-#{self.reference}"` would be the path of least resistance in my mind
Comment: would removing the id in that path be to much effort and cause too many problems? or should i just deal with the fact that the id stays, as it is a quicker way of finding the record and i wont have to re index my model then will i ? performance will play a part further down the line
Comment: removing the ID, the you need to do all you finds by the name as @pete says below. and yes would need re-index your db (but if you are already searching by name and name is unique, it should probably  already be indexed).  by default rails just .to_i the :id, and searches for it as the primary key. If you change that, then you need to adjust your indexes as required (shouldn't be an slower,assuming you build them correctly for your db)
Answer: If you would like to use your own "friendly id" then you'll need to adjust the find statement in your controller to something like
id = params[:id].split(/-/, 2).first
@animal = Animal.find(id)

Similarly, for the name/reference combination
name, reference = params[:id].split(/-/, 2)
@animal = Animal.find_by(name: name, reference: reference)

The second choice is a little more difficult because you'll have to do some work in the model to guarantee that the name/reference pair is unique.
Answer: The easiest way, is to go with friendly_id and simply add the missing database column. Keep in mind that you will need to ensure this new column is unique for every record. It basically acts as primary key.

Changing ID to something more friendly


What does it mean to be known at compile time? Constant expressions

Question: I'm confused to what it means to be known at compile time. From the code below, can the compiler not calculate the value of n even if I have passed a constant literal value 90 as an argument? Why does it give me an error that expression must have a constant value
constexpr int MAX_expr = 100;
const int MAX = 90;

void foo(int n)
{
    constexpr int cExpr1 = MAX_expr + 7;
    constexpr int cExpr2 = n + 7;

    constexpr int cExpr1 = MAX + 7;
    constexpr int cExpr2 = n + 7;

    const int cExpr1 = MAX_expr + 7;
    const int cExpr2 = n + 7;

    const int cExpr1 = MAX + 7;
    const int cExpr2 = n + 7;
}

int main() {
    foo(90);
    const int i = factorials(90);
}

With that same logic, shouldn't  factorials(int i) give an error because it does not know what argument is going to be passed therefore, the compiler won't be able to compute what is going to be returned?
constexpr int factorials(int i) {
    return i > 1 ? i * factorials(i - 1) : 1;
    }

Answer: The constexpr keyword can be confusing. It can be applied to both variables and functions, but with totally different meanings, except that they both have something to do with constant expressions.
A variable declared with constexpr must be initialized by a constant expression. In your code, n + 7 is not a constant expression because the value of n is not known until the function is called and may vary from one call to the next. What if the user entered some integer, and then you passed that integer to foo? Obviously, that number plus 7 is not something you can call "known at compile time". Because of that, a function definition such as foo is not allowed. You cannot promise the compiler that you will only ever pass a constant expression argument. If you can, then promote n to a template parameter, and the code will work.
In contrast, constexpr applied to a function doesn't guarantee that calling the function produces a constant expression. It allows the function to be called in a constant expression, and places constraints on the definition in order to make this possible. While factorial will certainly not produce a constant expression if given a runtime argument, it will produce a constant expression if given an integer constant expression as an argument (assuming no overflow). Thus, unlike initializers of constexpr variables, a constexpr function is allowed to contain constructs that may or may not have compile-time constant values.


Sort using dynamic LINQ on a complex object

Question: I have a list of Objects on which I use dynamic LINQ to perform sorting.
The object is like this,
public class SampleDTO
    {
        public string Vendor { get; set;}
        public string Invoice { get; set; }
         ..
         ..

}

And I use Dynamic Linq library to sort this,
var list= new List<SampleDTO>();
list.OrderBy("Vendor");

This works fine if I pass a sort key with a valid property name of the list ( e.g. Vendor )
The problem is, how to do this for a complex object.
Assume I have a another object which is a property of the SampleDTO
public class SampleDTO
    {
        public string Vendor { get; set;}
        public string Invoice { get; set; }
        public OtherDTO OtherDTO{get;set; }
         ..

}

public class OtherDTO
{
        public string LineId{ get; set;}
        ..

}

And if I want to make the sorting dynamic enough so that I should be able to sort from a direct property of the SampleDTO or on a property of a OtherDTO ( e.g need to sort on OtherDTO.LineId )
What are the possible ways of achieving this?
/BB
Answer: why not use the lamba syntax.
list.OrderBy(sample => sample.OtherDto.LineId);
This has the advantage of not being reliant on hard coded strings
Comment: I guess there is a good reason for the OP to use dynamic LINQ in the first place.
Comment: because the column i need to do sorting on is not just the orderlineId, it can be someother column as well, that is why im using dynamic linq in the first place.
Answer: You can do this:
list.OrderBy("OtherDTO.LineId");

Comment: tkx, just took time to test it out
Comment: Sometimes the solution is so obvious that you don't see it :-)
Comment: How to achieve the above dynamically -- passing Sort column at run time.. ??


How to Store Audio into buffer and then reading it byte by byte

Question: I can make wav file by MediaRecord of android ...but I am interested to put the audio data in a buffer and read it byte by byte...I have to send audio chunks byte wise over TCP channel....Can any one help me please...thanks in advance,
szaman from austria
Answer: You can use AudioRecord to read the audio data byte by byte, here is some sample code.
// calculate the minimum buffer
int minBuffer = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT);

// initialise audio recorder and start recording
AudioRecord mRec = new AudioRecord(AUDIO_SOURCE, SAMPLE_RATE,
                CHANNEL_CONFIG, AUDIO_FORMAT,
                minBuffer);
mRec.startRecording();
byte[] pktBuf = new byte[pktSizeByte];
boolean ok;
// now you can start reading the bytes from the AudioRecord
while (!finished) {
    // fill the pktBuf
    readFully(pktBuf, 0, pktBuf.length);
    // make a copy
    byte[] pkt = Arrays.copyOf(pktBuf, pktBuf.length);
    // do anything with the byte[] ...
}

Since a single call to read() might not get enough data to fill the byte[] pktBuf, we might need to read multiple times to fill the buffer. In this case, I use an auxiliary function "readFully" to ensure the buffer is filled. Depending what you want to do with your code, different strategy can be used...
/* fill the byte[] with recorded audio data */
private void readFully(byte[] data, int off, int length) {
    int read;
    while (length > 0) {
        read = mRec.read(data, off, length);
        length -= read;
        off += read;
    }
}

Remember to call mRec.stop() to stop the AudioRecorder after finished. Hope that helps.


How do I turn off the Steam Controller keyboard when playing Rocket League?

Question: I don't like the Steam controller keyboard coming up while I'm playing Rocket League. I have to play in Big Picture, as I'm on a Mac, and it doesn't handle my PS4 controller very well unless I do. Big Picture also wants to bring up the Steam controller keyboard anytime I want to chat, and I find it terribly distracting. How can I turn it off?
Answer: According to the Pysonix forums:

If you'd like to get rid of this, go to Rocket League in your steam Library, then right click on it and go to properties.
  At the bottom left you'll see 'Set launch options...'
  open that and then add in -NoKeyboardUI
  Press ok and play RL as you normally would. This will revert it back to the normal chat box
-Dirkened on the Psyonix forums
Comment: Thanks for the edit! I just approved it. :D


How to evaluate this complex integral?

Question: I want to evaluate this integral

$$\displaystyle\oint \dfrac{x\,dx+(y-1)\,dy}{x^2+(y-1)^2}$$

using this $$\int \frac{1}{z-1}\,dz$$
where $z\in C, C:z(\theta)=2.e^{i\theta},0 \le \theta \le 2\pi$
My try : i tried to express the denominator in this form $|z-i|^2=x^2+(y-1)^2$ and $d(z-i)=dx+idy$ what to do after this ? this is where i got stuck
Answer: $\DeclareMathOperator{\Re}{Re}$Presumably you're intended to write $z = x + iy$, so that
$$
\Re \frac{dz}{z - i}
= \Re \frac{(\overline{z - i})\, dz}{|z - i|^{2}}
= \Re \frac{(x - (y - 1)i)\, (dx + i\, dy)}{x^{2} + (y - 1)^{2}}
= \frac{x\, dx + (y - 1)\, dy}{x^{2} + (y - 1)^{2}}.
$$
Comment: Well, the real part of $2\pi i$.... :)
Comment: so the answer will be $2\pi i$ ? @Andrew D. Hwang

How to evaluate this complex integral?


Ondemand javascript call on window unload using jquery

Question: I have tried for "unload" and "beforeunload" binding in following code, but none of the browser is sending a request:
$(window).bind('unload', function(){
       $.ajax({cache: false,
        dataType: "script",
            url: "test.php"
        });
    });

Any suggestion?
Comment: Which browser are you running this in? For a long time, Safari had issues with properly implementing `unload` handlers. Not sure if that's still true.
Answer: The browser doesn't wait for this code to finish...it's running just fine :) Add an alert('hi') to see it running.
The problem you're seeing is typical of unload issues, the browser navigates away well before a request gets fired off in your case...and it should really, no code you're running should have to complete before I'm allowed to move onto the next page.  This is just how unload behaves.  You could make the call synchronous to hold the user there, but please don't do this.
The unload event was created on window mainly to clean up anything left around in the DOM you needed to, more-so when garbage collection wasn't as good as it is now (and still isn't in IE)...it wasn't really designed with AJAX or metric tracking in mind.
Answer: Just set the option async to false.
$(window).bind('unload', function(){
   $.ajax({
    cache: false,
    async: false,
    dataType: "script",
        url: "test.php"
    });
});


Removing Adventurers

Question: Having just lost about a week of progress towards the Saoshyant achievement in my Crusader Kings 2 Ironman game, I am somewhat vexed.
Since adventurers are unbalanced, unrealistic and not remotely fun, I'd like to play without them. Unfortunately, I can't simply disable The Old Gods DLC as that would also disable Zoroastrians and the 867 start.
Is there a way to balance or remove adventurers while still being able to access Old Gods content and without disabling achievements?
Comment: No. Extra words for character limit.
Comment: The best advice is to just murder them before they arrive and take  the Dishonorable penalty on the chin.
Comment: @TheForestAndTheTrees Which is what I normally do, only it doesn't work when they're too far away or part of a revolt war (temporary title). Incidentally, the revolt war failed and the adventurer's father was imprisoned because his son didn't lend him the 30000 strong maintenance-free attrition-proof unsullied doomstack he found in a two county realm.
Answer: There is no way to disable adventurers, but the easiest solution is to kill/assassinate the ringleaders as soon as possible.
Comment: That used to work wonders before the 2.2 patch. Now you have to run a plot... And if you fail you just get a huge enemy stack that is bigger than the world's largest empire's combined forces.
Answer: Depending on the accessible CK2 code, i.e. events etc, which I don't know right now, it might be possible to alter or remove adventurers. (Could possibly also be hardcoded, in which case you're out of luck.)
However, this will change the game's checksum and thus disable achievements for you. So, to answer your question: No, that's not possible.

Removing Adventurers


Java executable converts / to a period

Question: I am trying to create a java program to find the users ip address. The prgram compiled fine, and my problem is that when i try to run it using the java command, i get an error saying it could not find or load the class file. i found that it was changing any '/' to a '.'. I have tried:
java /home/pi/Desktop/ip.class

and it returns:
Error: Could not find or load main class .home.pi.Desktop.ip.class
prefixing the escape character \ to all of the / had no effect.
the same thing occured to any path i tried, how can i get the java program to recieve / instead of . ?
Answer: When you want java to run a specific class, you pass the class name, not the location of the file containing that class.
If the .class file is in not in the current working directory, you need to specify the classpath argument (-cp). Something like:
java -cp <location of the class> <fully-qualified name of the class>

In your case, it might be:
java -cp /home/pi/Desktop ip

but you might need to qualify the ip class name with the package it is declared to be in, e.g.
package my.package;
class ip {}

would need to be
java -cp /home/pi/Desktop my.package.ip

Java executable converts / to a period


Proving set inclusion for $\{x \in X : f(x) < c\}$ and $f_n \to f$

Question: Let $(X, \mathcal{A}, \mu)$ be a measure space and $f_n : X \to \mathbb{R}$ sequence of $\mathcal{A}$-measureable functions converging pointwise to $f : X \to \mathbb{R}$.
The proof showing that $f$ is also $\mathcal{A}$-measureable used the following fact:
$$\{x \in X : f(x) < c\} = \bigcup_{k = 1}^{\infty} \bigcup_{n = 1}^{\infty} \bigcap_{m = n+1}^{\infty} \{x \in X : f_m(x) < c - \frac{1}{k} \}$$
I have also seen similar "trick" used a lot in lecture notes, but I can't prove the inclusion $\subset$. All I got from the pointwise convergence is that if $x \in X$ with $f(x) < c$ then there exists an $k \in \mathbb{N}$ and $n \in \mathbb{N}$ such that for all $m \geq n$ $$f_m(x) <  c + \frac{1}{k} $$
which is obvious, since $f(x) < c$. Can anyone clear this bit for me please? Thanks.
Answer: $f(x) <c$ implies $f(x) <c-\frac 1 k $ for some $k$: it is enough to take $k >\frac 1 {c-f(x)}$. Hence  there exists $n$ such that $m >n$ implies $f_m(x) <c-\frac  1 k$.


how long property is alive

Question: I have simple C# thread with lots of properties. How long property is alive becouse in properties i store some data.
Can be property alive more than 1 months and store data or is better to use DB.
thx
Answer: Theoretically, a variable is kept alive as long as it has at least one active reference. In your case, as long as the object containing your property remains "in scope", the value of your property is kept in memory. For a static variable, or one created in the main() function or belonging to an Application or Service base object, it will stay in memory as long as the program runs.
However, a month is a very long time to expect a thread to run. If the thread encounters an error it can't handle, it will terminate, and you lose everything that the thread hadn't persisted to the file system or a database. In addition, web applications are maintained in an "app pool", and even within the context of a user session, the app pool can be "recycled", and everything that was just hanging around in memory is lost. So, if this data is important to keep around after the thread has run, or between threads, save it somewhere as your thread goes along its business.
Answer: As long as your program can stay running for more than a month the data will be there.  It sounds like you should really use a database though.  What happens if you lose power or you need to restart the server for maintenance?
Answer: Your properties will remain alive as long as your app remains alive.  One month is a long time for an app to sit there - I'd recommend using a DB, if you want to ensure that you don't ever lose data.
Answer: They're alive until they're garbage collected -- so if you leave your application running for the next hundred years, and the properties remain within the scope of your applications usage, the values will persist indefinitely.  However, if you're planning on long term storage, a database would probably be a smarter idea, as your values will be removed, for instance, if the object persisting the values is removed/deconstructed, application is stopped, errors out, or computer reset, etc.
Keep in mind, a database can be anything that persists your values, whether it's a flat file, hierarchical, or relational database.
Answer: A thread is a path of execution, not an object.  Objects have properties that can store data.  Objects (and their properties) don't really live in a thread, though a thread can act on them.  Threads can come and go in the course of an application's execution.  Objects get deleted by the garbage collector after they are no longer being referred to.  Code like this...
Object o = new Object();

... does two things 1) create an object, 2) create a reference to that object (o).  If you set o = null;, you've removed the only reference to that object and the garbage collector will clean it up soon.  None of the threads or objects in your application will live longer than the application itself; they will all be wiped away when your program ends its execution and the process space is destroyed.  Any data that needs to outlive the process should be stored to a file or a database table, etc.  Data can easily outlive a thread by being in an object that is referenced outside the function that the thread executes, but it won't outlive the process.

how long property is alive


How to Find Appid in Developer Account for IOS App Before Publication

Question: My app has not yet been accepted by Apple and is not yet public although it has been uploaded to the the app store for approval.  I would like to get the appid in advance of publication for various purposes such as preparing for advertising and people have also requested it.  According to this Apple Doc, the form of the url is like
https://itunes.apple.com/us/app/keynote/id361285480?mt=8
Where the numericalpart is the appid.
How or where can I find the appid for my app in the developer account?
The appid in profiles has a prefix and the bundle-identifier and looks nothing like one of these numbers.
I also can't find an appid in the app part of developer.apple.com
Answer: You can see it in the URL when you view your app record on App Store Connect, and it's also listed in the body of the App Information.


Will solo matchmaking match you solo players from the main queue?

Question: In Dota 2, solo matchmaking will look up only players who aren't in a party. Will it match this condition only with other players in the solo matchmaking queue, or will it get people from the common queue too?
I'm just afraid that this queue mode is not using the common queue. If not, I'll send a suggestion to the dev team.
Comment: @Decency may you don't get it..  Solo matchmaking would be really faster if it look up in the common queue too for **players that aren't in party but are in the common queue anyway**
Comment: @Decency Why not? Solo matchmaking would be really faster if it look up in the common queue too..
Comment: If you can solo queue and match with parties, there's no reason to have a separate solo queue, since you can just join the regular queue by yourself. There's a tradeoff in matchmaking between speed of search and quality of game. I think you should try to reword your question.
Comment: Only solo queue. Otherwise there wouldn't be a point...
Comment: I don't know if this is answerable by anyone who's not from valve...
Answer: I strongly believe that Normal queue and Solo queue do not share the same player pool. If you queue in Solo queue you are going to be matched only with people that queued in the Solo queue aswell.
Answer: I'm not sure how it was before making solo an option, but at least now it definitely includes the people queueing for both. I tried asking around in games to see if anyone didn't pick "solo only", and I found very few people who actually had.
Answer: I don't have exact proof, but based on statistics it's very probable that it uses the common queue.
I come to this conclusion because I've played against a few teams made up primarily of people with the same tag before their name.  Coincidences or people changing their names during the game? maybe, but highly unlikely for every time I've seen it.
I'll try to look through some of my games to see if I can screenshot a few for reference later
Comment: Why would people with the same tag be more likely to come from the common queue if they're soloing?
Comment: what? if they have the same tag, as in they're with friends, then it means they joined together. thus not soloing
Comment: So then you're saying that it not only matches you with solo players from the common pool, but also with non-solo players from the common pool? Isn't it not doing that the entire point of having a solo queue?
Answer: I played solo a few days ago, and I can definitely say that I had a four friends premade team on the opponents side. I chatted with them, and they said so too.
So, that's evidence that the solo matchmaking gets players out of the common queue too.
(Maybe there is first a checkup, and only if there are not enough people in the solo queue the common queue will be added to your pool, but you can definitely say that there is the possibility to get common queue members in solo matchmaking!!!)
Comment: So, if there was a premade team in the solo queue, then the solo queue is just a blatant lie? The whole point of it is to not encounter premades.
Comment: Agreed. It seems to take **very** much longer to find a match in this queue for others reasons like the common queue being used only at a certain search range and, obviously, for a bunch of in-party-players excluded from the main queue.
Comment: @Ullallulloo:

I wouldn't say it is a whole lie, but they have to balance it if there are not enough ppl within the solo matchmaking to start games reliable and steady. (Could be one of much reasons I think!)
Comment: @Knorke: [I don't see any other claims of that though.](http://www.google.com/search?q=solo+queue+only+premade+dota+2+matchmaking&tbs=cdr:1%2Ccd_min%3A5%2F9%2F2013) [PCGamesN says, "The new queue will only be populated by solo players; cutting out the chance of going head to head against pre made teams."](http://www.pcgamesn.com/dota/dota-2-update-adds-solo-matchmaking-and-all-custom-uis), and up until recently, there were a lot of complaints about really long wait times in the solo queue, so that wouldn't have even been doing much good. Are you sure they couldn't have just been making a joke?
Comment: @Ullallulloo: I only know, that I played in solo matchmaking against ppl with the same clan tag and they confirmed that they are friends.

A friend of mine (whose playing dota since 13 years) told me that the new matchmaking only proofs the team points (lvl's) and adjust them until both teams match.

So if there are for example 230 lvl points in your team, the opponents team will have the same amount, but you don't know how much lvl's any player has.There is the possibility to get 1 player on lvl 226 and 4 players on lvl 1.
Comment: @Ullallullo: Often it's better mixed than that....but the possibility is existing.


Samsung Galaxy Tab 3: It opens with a media player

Question: I just wanna ask how to open the default folder again of my Samsung Galaxy Tab 3.
This is what happened:

First, I connected the USB Plug.
The tab says: "connected as a media device", but it opens with Rythmbox. I want to open it on the exact folder like "Playlists" "Pictures" "Videos", but when I plug the USB, the Rythmbox quickly appears.

How do I do it again? I'm not really familiar with Ubuntu because I got used on Windows.
Answer:
On your Samsung phone, before to connect it to your PC, go to Menu → Settings → Wireless and network → USB utilities.
Tap on Connect Storage to PC.
Connect the USB cable to your PC.
Tap on Connect USB storage.
Use Nautilus - the default file manager in Ubuntu - to view/copy/paste files from your phone.
Once finished, tap on Disconnect storage from PC to disconnect and unmount drive from Ubuntu.

Source: http://www.tuxtrix.com/2011/07/how-to-access-samsung-galaxy-s-ii-usb.html


Understanding Global Lower and Upper Bounds for branch and Bound

Question: I am teaching myself branch and bound and keep coming across the term optimality gap. So I am looking at an example (shown in the image below) and would like to know if my analysis is correct. I think the arrows drawn in the example are misleading me but I have found a way for it to make sense to me and I would like to confirm that I am correct. Note the top value in the node circles are the local upper bound and the bottom value is the local lower bound.

So based on the image above, the following is my analysis:

Starting at N1, no upper bound has been determined and the global lb at the root node is -13/2 (not shown on the diagram).

After branching on the root node, the global ub remains unchanged but the now the global lb is given as the min(-13/3, -16/3) = -16/3. Min is used as this is a minimization problem.

Ignoring the blue arrow and branching on N2, the global ub now becomes -3 due to a feasible optimal solution being found. Furthermore, since N5 is infeasible and no solution exists, the global lb is now given by the min(-3, -16/3) i.e. a comparison between the local lb of N4 and N3. Hence a global lb of -16/3.

Now branching on N3, we get N6 and N7, however there is no solution associated with N7 as it is infeasible and the global lb is now -22/5 as this is the only active node left. Also the global ub remains as -3 as no new feasible solution is found.

Lastly branching on N6, we get N8 and N9, the new global lb is given as the min(-4, -3) = -4. Since both are feasible solutions, the nodes are fathomed and the global ub is updated as a better feasible optimal solution is found.
Answer: Yes, this analysis is essentially correct, although you are conflating branching and processing a node.  Branching creates two children but does not necessarily process them right away.  Processing means solving the LP relaxation at that node.
You are processing the nodes as a breadth first search (BFS).  The paper mentions DFS, which is depth first search, but that must be a typo because the global bounds instead match your BFS.


Discretisation of Euler's method

Question: I don't quite understand the discretisation error of Euler's method
$$L(t,h)=\frac{x(t+h)-x(t)}{h}-f(t,x(t))$$
What I don't understand is: $\frac{x(t+h)-x(t)}{h}$ is the "gradient" and $f(t,x(t)$ is the value of the function. How can we get the error by subtracting the former by the latter?
Thanks.
Answer: You assume that $x(t)$ is an exact solution to $\dot x = f(t,x)$ and then apply Taylor formulas.

Discretisation of Euler's method


Everytime I load my php form page it gives an entry to the databse

Question: I am making a form which will input details into a mysql database.
I have one problem.
I have used the "required" attribute in my html form, but still everytime I load the page it gives an entry into the database (even though the fields are empty).
This is the code (php):
<!DOCTYPE html>
<?php
        $cnn = mysqli_connect("localhost", "root", "abc123", "usercake");

// Check connection
        if (mysqli_connect_errno($cnn)) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }

$firstname = $_POST['firstname'];
$surname = $_POST['surname'];

        $qry = "INSERT INTO usercake.huffaz (country) VALUES ('$_POST[country]')";
        mysqli_query($cnn, $qry)
?>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>

        <form action="huffaz.php" method="post" >
            <fieldset>
                <legend>
                    Your Personal Details
                </legend>
                First Name:
                <input type="text" name="firstname" required />
                Surname:
                <input type="text" name="surname" required />
                Age at 1st Ramadhan:
                <input type="number" name="age" min="15" required />
            </fieldset>
            <fieldset>
                <legend>
                    Your Contact Details
                </legend>
                City:
                <input type="text" name="city" required/>
                County/State:
                <input type="text" name="state" required/>
                Country:
                <input type="text" name="country" required/>
            </fieldset>
            <fieldset>
                <legend>
                    Your Qualifications
                </legend>
                <input type=""/>
            </fieldset>
            <input type="submit" />
        </form>

Comment: Wrap your database insertion code with `if(isset($_POST)) { ... }`
Comment: Hi, I have no idea what you are talking about. Can you add more detail? Which "required" attribute are you referring to?
Comment: Can you show us some code please.  There is no way you will get help with out it
Comment: can you explain the question a little bit more with some code snippets
Comment: show your code, check what @enenen has said.
Comment: Yes, I think that is what I am after, I'll try it.
Answer: You are not checking if there is any post set/fired.
Chenge like this:
if(isset($_POST)){
    $cnn = mysqli_connect("localhost", "root", "abc123", "usercake");
    // Check connection
    if (mysqli_connect_errno($cnn)) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    $firstname = $_POST['firstname'];
    $surname = $_POST['surname'];
    $qry = "INSERT INTO usercake.huffaz (country) VALUES ('$_POST[country]')";
    mysqli_query($cnn, $qry)
}

Comment: Thanks. like your code better as it does not even connect if $_POST is empty.
Comment: Thanks. like your code better as it does not even connect if $_POST is empty. I'll paste my script here (it is working but i'll use your method):  .


Ubuntu 13.04 unable to set keyboard layout

Question: I recently installed Ubuntu 13.04. When I try to add another keyboard layout (clicking the 'Layout Settings' link in System Settings -> Keyboard -> Typing Tab) the system doesn't respond. Is there another way to add a keyboard layout?
Comment: open the terminal, type `gnome-control-center` then go in **Keyboard Layout** and click on the small "+" icon in the bottom left. Go back to the terminal and past here any error you read on screen.
Comment: I had the following error:
*** BUG ***
In pixman_region32_init_rect: Invalid rectangle passed
Set a breakpoint on '_pixman_log_error' to debug

(gnome-control-center:15298): GLib-GIO-ERROR **: Settings schema 'com.canonical.indicator.keyboard' is not installed
Comment: If by another layout you mean another language's layout then this might help. I've had issues with chinese keyboard. What i did is go to settings, Language Support, and click install/remove languages button, which brings up menu for desired language. Click apply changes, wait till it all loads, and reboot. As for other suggestions, you could try couple configuration managers, which can be downloaded in Software Center. Just search for keyboard or text input
Answer: It seems you have a corrupted configuration file. I'd start by reinstalling the gnome control center, that may fix the problem automatically
sudo apt-get install --reinstall gnome-control-center

If that doesn't work try also to reinstall the desktop schemas
sudo apt-get install --reinstall gsettings-desktop-schemas

Comment: Thanks for the reply. Done it. Still have the same error.
Answer: You can use the following cammand in terminal
sudo dpkg-reconfigure keyboard-configuration

It will bring out an interactive process where you can select your desired preferences.
Comment: It helped, but the change isn't permanent. When I restart my computer I have to configure again. Also there is no notification which language I am using. I can only switch with Alt+Shift between languages. Thanks


What is the sum of the cube of the roots of $ x^3 + x^2 - 2x + 1=0$?

Question: I know there are roots, because if we assume the equation as a function and give -3 and 1 as $x$:
$$
(-3)^3 + (-3)^2 - 2(-3) + 1 <0
$$
$$
1^3 + 1^2 - 2(1) + 1 > 0
$$
It must have a root between $[-3,1]$. However, the root is very hard and it appeared on a high school test. How can I solve it simply?
The given options were -10, -5, 0 , 5 and 10. Note: we didn't even learn the cube root formula. The test had just logic problems and I didn't use any calculus or complicated stuff. So there must be an easier way without using cube root concepts or formulas.
Comment: Lol 3 answers exactly same
Comment: Are you sure you have to *find the sum of the cube of the roots*?
Comment: A quick search provided some useful information I think: http://math.stackexchange.com/questions/30491/sum-of-cubed-roots
Comment: A [hint](https://en.wikipedia.org/wiki/Newton%27s_identities#Application_to_the_characteristic_polynomial_of_a_matrix)
Answer: You know,
$a^3+b^3+c^3-3abc=(a+b+c)(a^2+b^2+c^2+ab+bc+ca)$
$a^3+b^3+c^3=(a+b+c)[(a+b+c)^2-3(ab+bc+ca)]+3abc$
Now I hope you know the relation between roots.
Answer: Suppose $a,b,c\in\mathbb{C}$ are the roots to your equation. There is this algebraic identity you should know:
$$a^3+b^3+c^3-3abc=(a+b+c)(a^2+b^2+c^2-ab-bc-ca)$$
Do some manipulations to get this form:
$$a^3+b^3+c^3=3abc+(a+b+c)\left((a+b+c)^2-3(ab+bc+ca)\right)$$

Vieta's formulas are formulas that relate the coefficients of a polynomial to sums and products of its roots.
Comment: I'm curious: is there any relationship with $ (x-1)^2 $ ?
Comment: @Lucas maybe. i don't see one
Comment: Take a look at the note.
Comment: @LucasHenrique this is the easiest way I can think of. It does *not* involve any calculus. The algebraic identity seems simple enough and as for Vieta's formulas, I am confident that someone your age can understand that stuff.
Answer: using the information in the equation
$$
\sum_{i=1}^3 r_i^3 = -\sum_{i=1}^3 (r_i^2 - 2r_i + 1) \\
= -5 -\sum_{i=1}^3 r_i^2
$$
also, from the well-known expressions giving the elementary symmetric functions of the roots in terms of the coefficients,
$$
\sum_{i=1}^3 r_i^2 = (\sum_{i=1}^3 r_i)^2 - 2(r_1r_2+r_2r_3+r_3r_1) \\
= 5
$$
so the sum of cubes of the roots is $-10$
Comment: if $r$ is a root, then $r^3 = -r^2+2r-1$. a cubic has three roots (in an algebraically closed field), so we can sum this relation over the roots $r_1,r_2,r_3$. the constant term $-1$ gives $-3$. the sum of the roots is minus the coefficient of $x^2$ divided by the coefficient of $x^3$, so the $2r$ term gives a sum of $-2$. the $r^2$ term is obtained by the method shown,  where the sum of the products of the roots in pairs is the ratio of the coefficient of $x$ to that of $x^3$. check out one of the references in other answers to "relations between roots" etc.
Comment: David, can you explain step by step?
Comment: Perfect! You did it.
Answer: Hint: use Newton's formulas and Vieta's formulas
https://brilliant.org/wiki/newtons-identities/
Comment: I think the link is to newton
Comment: Thnx its ok now


Uniform boundedness imply uniform convergence?

Question: If ${f_n}$ is a uniformly bounded sequence of holomorphic functions in $\Omega$ such that ${f_n(z)}$ converges for every $z \in \Omega$, is the convergence is uniform on every compact subset of $\Omega$?
I'm trying to prove using Dominated Convergence Theorem with Cauchy's Integral Formula. For any compact $K \subset \Omega$, let $\gamma = \partial K$. Then for any $z \in K$, by the CIF,
$$|f_n(z) - f_m(z)| \leq \frac{1}{2\pi i}\int_{\gamma}\left|\frac{f_n(w)-f_m(w)}{w-z}\right|\:dz.$$
Now since we are talking in compact sets, $|f_n(z)| \leq B \in L^1$, so by applying Dominated Convergence Theorem, and by taking the limit as $m \to \infty$,
$$|f_n(z)-f(z)| \leq \frac{1}{2\pi i}\int_{\gamma}\left|\frac{f_n(w)-f(w)}{w-z}\right|\:dz.$$
But by the pointwise convergence, I am trying to claim that RHS can be made sufficiently small for large enough $n$. Am I on the right track?
Comment: Can you use something like Ascoli's theorem? I am wondering if you can prove the equicontinuity of $\{f_n\}$ by Cauchy's formula.
Comment: I did run across Arzela-Ascoli's Theorem, but we haven't technically proven it yet, so I can't use it. But I assume I can mimic the proof of the A-A Theorem.
Answer: Here is a powerful convergence theorem.
Comment: Wow that is an intense convergence theorem!
Comment: I still believe you can solve your problem more easily. But powerful theorems are often useful.
Comment: You were right on the money with Ascoli's theorem. [Montel's theorem](http://en.wikipedia.org/wiki/Montel's_theorem) (stated in a somewhat cryptic fashion on Wikipedia) can be proved using Arzelà-Ascoli. This is done e.g. in Ahlfors.
Comment: What was theorem in the link ?


How can I redirect after toastr notification

Question: I'm trying to redirect after toastr notification finishes displaying. I currently have ajax request as
 $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('value')
            },
            type: $(form).attr('method'),
            url: $(form).attr('action'),
            data: $(form).serialize(),
            dataType: 'json',
            success: function (data) {
                toastr.success('Hello','Your fun',{timeOut: 2000,preventDuplicates: true, positionClass:'toast-top-center'});

                     return window.location.href = '/';

            },
            error: function (data) {
                    var html = '
Email/Password is invalid
';
                    $('#loginMsg').html(html);
            }

The problem is it shows the notification but redirects to quickly to actual read the notification. How can I redirect only after toastr notification hides?
Comment: If you're redirecting anyway, the idea of making an AJAX request and showing the notification seems completely redundant.
Comment: Why would this be redundant. A person logins and before it redirects to homepage its shows a notification of a successful login. I've seen this on plenty of sites. But even if redundant that's not really the purpose of my question.
Comment: Ok, first to answer the question, use the `onHidden` callback. See the 'callbacks' section of the documentation: https://github.com/CodeSeven/toastr. Secondly, making an AJAX request then showing a notification is redundant if you're going to redirect anyway. Instead of making a single request you've made two and held up your user while they waited for the notification to go away. The fact that the page changes when you successfully provide your credentials is clue enough to the user that they have logged in.
Comment: Thanks for the info makes since but I'm testing toastr right now and I might not use it for login. Just testing, but you make a good point.\
Answer: toastr gives the callback options
toastr.options.onShown = function() { console.log('hello'); } toastr.options.onHidden = function() { console.log('goodbye'); } toastr.options.onclick = function() { console.log('clicked'); } toastr.options.onCloseClick = function() { console.log('close button clicked'); }
inside the function you can use redirect URL
it depends on the plugin which your using check here
Answer: I hope this helps

$.ajax({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="_token"]').attr('value')
        },
        type: $(form).attr('method'),
        url: $(form).attr('action'),
        data: $(form).serialize(),
        dataType: 'json',
        success: function(data) {
            toastr.success('Hello', 'Your fun', {
                timeOut: 2000,
                preventDuplicates: true,
                positionClass: 'toast-top-center',
                // Redirect
                onHidden: function() {
                    window.location.href = '/';
                }
            });
        },
        error: function(data) {
            var html = '
Email/Password is invalid
';
            $('#loginMsg').html(html);
        }
    });
Comment: Please explain how it's help
Answer:

//Before calling the toastr method, define the callback function to reload page or redirect to onother url

toastr.options.onHidden = function(){
  window.location.reload();
}

//Call de toast
toastr.error('Your massage here');


Applying stopping compound on plywood

Question: I'm in the process of building the storage area under the stair case. Since I'm already having 15 sheets of 18mm full size plywood each 4'×8' in size, I'm framing the entire project using only this material. Only the door rail and it's suspension race are of the aluminium.
Since I want to have wall-like finish with all screws are invisible, I'm thinking if it is possible to skim the plywood surface with stopping compound.
Is this a good idea? Will it stick or flake off after sometime? I'm living in Malaysia and here the climate is constant thru the year. Thus wood expansion and contraction will not be the problem.
Comment: I'm having trouble invisioning an area under the stairs that requires 15 4x8 foot boards to enclose.  That's a pretty big room.  Why not use drywall?
Comment: "I'm framing the entire project using only this material"... please tell us that you are using some dimensional lumber or other structural framing members?
Comment: Not all 15 sheets will be used on this project. But no other lumber will be used except plywood.
Comment: @JimmyFix-it Dimensional lumber are created using glued strips cut from the plywood. The aluminium rail is 3cm in thickness and will be sandwiched between plywood walls. Thus I will need dimensional lumbers of 3cm thickness to maintain eveness.  As such, i decided to create my own out of the plywood sheets.
Answer: Yes, you can skim coat the plywood.  Use an oil based primer first, then instead of topping compound use setting type compound aka "hot mud", the type of compound that uses plaster of paris.  This type of mud is stronger and adheres better than premixed topping compound.  You will mix it a bit watery, like thick paint, and can put it on with a roller, then use a squeegee to level it off.  I did this over wooden paneling, and it worked pretty well.  It will probably take a couple of coats to level out everything, especially at the joints.
Comment: Why must apply oil based primer  first? Won't it seal the wood fibres and cause the Plaster to lose grip?

Applying stopping compound on plywood


How to program multiple Teensy's in platformIO simultaneously on Ubuntu?

Question: The issue here is that Teensy's constantly change what kind of device they are, so sometimes after programming them, either the Serial Monitor won't open, requiring them to be unplugged and replugged in.
This cause more issues, as it's possible they reconnect in a different order, so platformIO may flash to the wrong board based on undefined conditions.
How can I program them in a way that leaves no guesswork, and also consistently access the Serial Monitor?
Answer: Below info aggregated from this thread:
PJRC forum
Install tycmd command from instructions here: tytools
figure out which boards you have with
tycmd list
returns:
add 9665090-Teensy Teensy 3.6 (USB Serial)
add 10253260-Teensy Teensy 3.6 (USB Serial)

Where those numbers are serial numbers.
in platformio.ini, add
upload_command = tycmd upload -B $UPLOAD_PORT $SOURCE
upload_port = 9665090-Teensy

where upload port is the one from above you want to program to. $SOURCE is defined by platformIO.
To get the serial monitor for one of them, type
tycmd reset -B 10253260 #reset if it won't open
tycmd monitor -B 10253260

The inbuilt platformIO serial monitor will no longer be used, but the above command will open a different Serial Monitor program which is better because you can reliable specify which Teensy to use.


No POST/create form in DRF Browsable API?

Question: I am using Django Rest Framework (Django version=4.0.4, I know I need to upgrade, but I'm still learning the ropes and djangorestframework~=3.14.0) and Viewsets for an API, but I can't get the Browsable API POST form to show up on the list page. I can see the list of ParameterKeys (so I think urls.py and serializers.py are correct) and I'm using a superuser account so I don't think it's a permissions thing. What's wrong with my setup? I did notice that the Brave browser Agent request has 'text/html' and some 'application/xml', but no 'application/json'...not sure if that's it?
Here is the relevant portion of the model:
class ParameterKey(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=200)
    owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='parameter_keys')

    def __str__(self):
        return self.name

Here is the relevant portion of urls.py:
from django.urls import path, include
from rest_framework import routers
from . import api_views

router = routers.DefaultRouter()
router.register(r'', api_views.ParameterViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

Here is the relevant portion of api_views.py:
from rest_framework import viewsets, parsers
from .models import ParameterValue, ParameterKey
from .serializers import ParameterValueSerializer, ParameterKeySerializer
from parameters.permissions import IsOwnerOrPublic
# from django.http import JsonResponse
# from django.views.decorators.csrf import csrf_exempt
from rest_framework.permissions import AllowAny

class ParameterKeyViewSet(viewsets.ModelViewSet):
    permission_classes = [AllowAny]
    queryset = ParameterKey.objects.all()
    serializer_class = ParameterKeySerializer

Here is the main project urls.py:
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from datasets.views import DatasetListView, DatasetDetailView
from datasets.api_views import DatasetViewSet
from parameters.api_views import ParameterViewSet
from rest_framework import routers
from files import views
from files.views import upload_file

router = routers.DefaultRouter()
# router.register(r'datasets', DatasetViewSet, basename='dataset')
router.register(r'datasets', DatasetViewSet, basename='dataset')
router.register(r'parameterkeys', ParameterViewSet, basename='parameterkey')  # Add this line

urlpatterns = [
    # Django admin
    path("anything-but-admin/", admin.site.urls),
    # User management
    path("accounts/", include("allauth.urls")),
    # Include URLs from the datasets app
    path("api/v1/datasets/", include("datasets.api_urls")),
    # Include URLs from the parameters app
    path("api/v1/parameters/", include("parameters.urls")),
    # Non-API view
    path("", include("datasets.urls")),
    # API views
    path("api/v1/", include(router.urls)),
    # API authentication
    path("api-auth/", include("rest_framework.urls")),
    path("api/v1/dj-rest-auth/", include("dj_rest_auth.urls")),
    path("api/v1/dj-rest-auth/registration/", include("dj_rest_auth.registration.urls")),
    path('upload/', upload_file, name='upload_file'),
] + static(
    settings.MEDIA_URL, document_root=settings.MEDIA_ROOT
)

if settings.DEBUG:
    import debug_toolbar

    urlpatterns = [
        path("__debug__/", include(debug_toolbar.urls)),
    ] + urlpatterns

Here is the relevant portion of serializers.py:
from rest_framework import serializers
from .models import ParameterValue, ParameterKey

class ParameterKeySerializer(serializers.ModelSerializer):
    class Meta:
        model = ParameterKey
        fields = '__all__'

I didn't post my settings.py because SO flagged this as spam. Here are the installed apps:
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "whitenoise.runserver_nostatic",  # new
    "django.contrib.staticfiles",
    "django.contrib.sites",
    # Third-party
    "rest_framework",
    "crispy_forms",
    "crispy_bootstrap5",
    "allauth",
    "allauth.account",
    "debug_toolbar",
    "corsheaders",
    "rest_framework.authtoken",
    "dj_rest_auth",
    "storages",
    # Local
    "accounts.apps.AccountsConfig",
    'datasets',
    'parameters',
    'files',
]

MIDDLEWARE = [
    "django.middleware.cache.UpdateCacheMiddleware",
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",  # new
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "debug_toolbar.middleware.DebugToolbarMiddleware",
    "django.middleware.cache.FetchFromCacheMiddleware",
]

And here is the REST_FRAMEWORK settings:
REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES": [
        "rest_framework.permissions.IsAuthenticatedOrReadOnly",  # new
    ],
    "DEFAULT_AUTHENTICATION_CLASSES": [  # new
        "rest_framework.authentication.SessionAuthentication",
        "rest_framework.authentication.TokenAuthentication",
    ],
        'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ],
}

I've tried changing permissions and different browsers, and I tried temporarily disabling corsheaders. I believe the problem is in a setting somewhere because I don't get the POST form in the Browsable API for any of my apps. I did have the correct form on a different app when I wrote my own view (ie before I switched to viewsets).
Answer: Update: I figured it out. It was a permission thing. I removed the permission_classes= statement and the form now appears.


transform list of data frames to obtain means for df names and yearly means

Question: I'm analyzing river streamflow data with R language and I have a list of data frames. Each data frame represents a subbasin (910, 950, 1012 and 1087) and has the exact same structure and number of variables and contains a value of IHA indicators (IHA1, IHA2) per Year (2004:2007)
Flowtest <- list("910" = tibble(Year = c(2004:2007), IHA1=c(123, 170, 187, 245), IHA2=c(679, 870, 789, 233)),
                 "950" = tibble(Year = c(2004:2007), IHA1=c(570, 450, 780, 650), IHA2=c(230, 470, 687, 321)),
                 "1012" = tibble(Year = c(2004:2007), IHA1=c(160, 170, 670, 780), IHA2=c(350, 840, 701, 353)),
                 "1087" = tibble(Year = c(2004:2007), IHA1=c(120, 780, 820, 580), IHA2=c(870, 870, 763, 291)))

I'd like to obtain 3 data frames as a result, shown in the picture below:

calculate means for each IHA (without splitting into subbasins or years)
calculate means for each IHA (with splitting into years but without splitting into subbasins)
calculate means for each IHA (with splitting into subbasins but without splitting into years)

In reality, my list contains a lot more subbasins and IHA indicators

For 1. I managed to create this:
    test <- Flowtest %>%
      reduce(bind_rows) %>%
      summarise_all(mean) %>%
      select(-Year)

I would like to create a similar code to the one above to obtain results as shown in 2. and 3. (like in the picture). How can I do that?
Answer: Hi Joanna a possible solution would be this:
library(plyr)
library(dplyr)

# bind list to a tibble and make list names to a column
Flowtest_df <- plyr::ldply(Flowtest, data.frame) %>%
  dplyr::rename(RCH = 1)

# mean
Flowtest_df %>%
  dplyr::summarise(IHA1_mean = mean(IHA1),
                   IHA2_mean = mean(IHA2))
# year mean
Flowtest_df %>%
  dplyr::group_by(Year) %>%
  dplyr::summarise(IHA1_mean = mean(IHA1),
                   IHA2_mean = mean(IHA2))
# RCH mean
Flowtest_df %>%
  dplyr::group_by(RCH) %>%
  dplyr::summarise(IHA1_mean = mean(IHA1),
                   IHA2_mean = mean(IHA2))

Answer: You could also do:
map(list(NULL,'Year','subbasin'), ~bind_rows(Flowtest, .id = "subbasin") %>%
      group_by(.dots = .x)%>%summarise(across(starts_with("IHA"), mean),.groups='drop'))
[[1]]
# A tibble: 1 x 2
   IHA1  IHA2
  <dbl> <dbl>
1  453.  582.

[[2]]
# A tibble: 4 x 3
   Year  IHA1  IHA2
  <int> <dbl> <dbl>
1  2004  243.  532.
2  2005  392.  762.
3  2006  614.  735
4  2007  564.  300.

[[3]]
# A tibble: 4 x 3
  subbasin  IHA1  IHA2
  <chr>    <dbl> <dbl>
1 1012      445   561
2 1087      575   698.
3 910       181.  643.
4 950       612.  427


How to do checking before importing the csv file by php?

Question: How to do checking before importing a CSV file in PHP?
I have a CSV file which contains the information with the columns id, name, telephone, email and have the database with the same columns. I have the PHP file which can import the CSV file into the database.
Now, I want to update the information by batch, how can I match the id, name between CSV file and database so as to avoid wrong data input (suppose the data in the database is correct but that in the CSV it is wrong).
At the end, the PHP can show the message that your CSV data is incorrect! Thanks! Anyone can help?
Comment: What have you tried so far? Where did you get stuck? Show us the code and we will gladly help you.
Comment: Hi sreejith, welcome to SO.
Comment: Show us what you have for now?
Answer: You can do this as follows:

Read your CSV using fread() and filesize()
explode() the data, probably using linebreak (\n)
Loop through each line of data with foreach
Explode each line, probably using comma (,)
Test each index of that array with preg_match() and a regex pattern to make sure it meets your requirements
Query your database with something like this (in PHP, untested)
$query = "UPDATE yourtable SET name='".$name."' WHERE id='".$id."'";

Make sure your query is santized using PDO or similar, to avoid SQL injection at all times.
That last bullet point is the key to your question, I think.  You'll need to read about UPDATE and INSERT SQL queries - here's a question that may help: Mysql function: Insert if not exist or updated
You haven't included any code or a starting point in your original question, so I can't help you with the specifics, but I'm sure you can research this yourself.  I'd say it's easy-intermediate difficulty.


meego cannot play mp3 file

Question: I tried to implement SoundEffect from QtMobilityKit in QML to play music file in Meego Harmattan.
I found that it can only play .wav file.
is there any possible way to play .mp3 file in meego?
This one can play
SoundEffect{
    id: sound
    source : "/sound.wav"
}

and this one cannot
SoundEffect{
    id: sound
    source : "/sound.mp3"
}

Answer: I haven't tested this, as my N9 hasn't arrived yet, but I think the following should work:
Audio {
    id: sound
    source: "/sound.mp3"
    // Start playback as soon as clip is loaded
    onStatusChanged: if (Audio.Loaded == status) play()
}

Note that you may see a slightly longer delay in starting playback of the MP3 compared with the WAV, as the encoded clip requires some more parts of the native multimedia framework to be initialized before it can be decoded and played.
Comment: negative . no result. looks like there's codec error or something :(

meego cannot play mp3 file


Combining CheckBoxColumn and TextColumn into one column

Question: Is it possible to combine a DataGridTextColumn and DataGridCheckBoxColumn into one column?
I have this class where I combine two columns values into one result:
public class ViewQuoteItemList
{
    public string Supplier { get; set; }
    public bool TrueFalse { get; set; }

    public string CheckBoxColumn
    {
        get { return string.Format("{0} {1}", Supplier, TrueFalse); }
    }
}

Then I bind one of the columns like this:
DataGridTextColumn columnFeedbackSupplier = new DataGridTextColumn();
columnFeedbackSupplier.Binding = new Binding("CheckBoxColumn");

I do not know how to bind/join a DataGridCheckBoxColumn with a DataGridTextColumn to display both the text and a checkbox in one column
Comment: Have you look into DataGridTemplateColumn??
Comment: Yes I have but I could not find any information on how I could combine both types into one column
Comment: you could define a CellTemplate for the same using DataGridTemplateColumn
Comment: Could you please explain in a bit more detail? 0_o
Comment: Also, how can I then bind that `DataGridTemplateColumn` in code behind? I know it's a bit more difficult than a normal TextColumn
Answer: DataGridTemplateColumn you can define Template for the same.
<DataGridTemplateColumn Header="ViewQuote">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Supplier}"/>
                <CheckBox IsChecked="{Binding TrueFalse}"/>
            </StackPanel>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Comment: Great stuff! Thank you very much Abhinav! Also is there a way to bind a Tempelate column the same as you did in XAML, but do it in C# code?
Comment: [this](http://stackoverflow.com/questions/1754608/what-is-the-code-behind-for-datagridtemplatecolumn-and-how-to-use-it) and [this](http://stackoverflow.com/questions/8779893/create-datagridtemplatecolumn-through-c-sharp-code) are some links to get you started.
Comment: Also please don`t forget to mark it as answer.Thanks


Convert System.Windows.Forms.Shortcut into KeyData / KeyCode

Question: Is there an easy way to get the corresponding keydata (keycode combination) for some value in that enum?
I cannot find one, and creating a switch statement for all those is a bit overkill...
The integer values of the enum elements are not keycodes, but some 'unknown' big numbers, so simply casting to int won't work.
Answer: System.Windows.Forms.Shortcut and System.Windows.Forms.Keys can be cast directly (their integer values match).
Keys keys = (Keys) Shortcut.CtrlL;

Comment: @Denis: I appreciate the effort of adding an example to my answer, but the "probably" twice does not suit me, sorry. You could instead provide your own answer, or add a comment.
Answer: The lower 4 bytes are the key and the upper 4 bytes are a mask for Shift, Ctrl and Alt-Key, So you can get the KeyCode with something like this:
Shortcut shortcut = Shortcut.ShiftDel;
Debug.Print((((int)shortcut) & 0xFFFF).ToString());

Will output 46 which is the code for del key.