text
stringlengths
64
89.7k
meta
dict
Q: Cheatsheet/summary of financial laws and regulations I wonder whether there are or we can collect cheat-sheets for the various international regulations of the financial markets. There is e.g. the Dodd-Frank act for the US. Can we gather cheat sheets for all the other international regulations such as: Basel II/III (with the directives), Solvency II, EMIR, and all those out there? Being a (quantitative) risk manager it is hard for me to follow all of them and soemtimes speaking with customers it looks good to know the basic facts about these regulations - apart from the advantage of knowing them for oneself. Maybe we can gather blog series as well. Then it is easier to stay up-to-date and collect the entries in appropriate software and make it searchable and so on. An example in the Basel world is this blog. EMIR: This is one of the best summaries of the Collateral requirements under EMIR . Thierry Roncalli wrote lecture notes on risk management and financial regulation. They cover many things (more or less "everything") on more than 700 pages. The lecture notes will not be updated for the next year as then a book will be published. A: Here's a few. The categories are not mutually exclusive (e.g. since most investment advisors are obviously affected by tax and short-selling). Investment advisors Investment Advisers Act of 1940 Investment Company Act of 1940 SIPA of 1970 ERISA of 1974 JOBS Act of 2012 Europe Criminal Justice Act 1993 Financial Services Act 1986 Financial Services Act 2012 FSMA 2000 AIFMD EMIR MiFID I/II Solvency I/II ESMA MAD I/II and MAR Commodities Commodities Exchange Act of 1936 CFMA of 2000 AML BSA of 1970 FCPA of 1977 PATRIOT Act of 2001 Taxation FIRPTA of 1980 Taxpayer Relief Act 1997 Sarbanes-Oxley Act of 2002 Broker-dealers and securities exchanges Securities Exchange Act of 1934 Basel I/II/III Dodd-Frank FRB Reg D Reserve requirements FRB Reg M Short selling rules FRB Reg S Reimbursement for providing financial records FRB Reg SHO Short selling practices FRB Reg T Margin requirements
{ "pile_set_name": "StackExchange" }
Q: Insert into where column count is different In SQL Server 2005, I have a temp table #Table1 which holds data from a dynamic pivot based on day of month. The table will have 28,29,30 or 31 columns depending on month/year. I then want to create another temp table #Table2 with a static 31 columns (to add some data for report formatting) and append #Table1 into it with nulls in the extra columns. I tried: Select * into #Table2 from #Table1 but this does not work, it tells me that #Table2 already exists in the database. I know it does, I put it there!! Or, is there a way to add column 29,30 and 31 to #Table 1 if I run the pivot in February or 31 if I run it in June/September? I hope this explains my dilemma and there is an easy solution. I'm not too smart at this!! A: You can add 29,30 and 31 as column names just like other dates in your pivot statement like: SELECT 1,2,...,28,29,30,31 FROM table PIVOT(SUM(aggregate column) FOR spreading column IN(1,2,...,28,29,30,31)) AS P; and then you shouldn't use Select * into clause as it creates a new table. You should use following clause: insert into #Table2 select * from #Table1 Hope this helps!!!
{ "pile_set_name": "StackExchange" }
Q: What does the double colon before println mean in kotlin What does the double colon before println mean in the Kotlin code below? class InitOrderDemo(name: String) { val firstProperty = "First property: $name".also(::println) } The code prints: First property: hello A: From Kotlin documentation :: means: creates a member reference or a class reference. In your example it's about member reference, so you can pass a function as a parameter to another function (aka First-class function). As shown in the output you can see that also invoked println with the string value, so the also function may check for some condition or doing some computation before calling println. You can rewrite your example using lambda expression (you will get the same output): class InitOrderDemo(name: String) { val firstProperty = "First property: $name".also{value -> println(value)} } You can also write your own function to accept another function as an argument: class InitOrderDemo(name: String) { val firstProperty = "First property: $name".also(::println) fun andAlso (block : (String) -> Int): Int{ return block(firstProperty) } } fun main(args : Array<String>) { InitOrderDemo("hello").andAlso(String::length).also(::println) } Will print: First property: hello 21
{ "pile_set_name": "StackExchange" }
Q: When to use activities or fragments My App (minimum API 14) uses an ActionBar with 3 tabs. The tabs are: i. enter data (approx 10 fragments) ii. manage data (15 fragments) iii. view data (8 fragments). Each tab has a default fragment, but then has multiple fragments depending on user choices. I would like the user to be able to swipe between the 3 tabs (by swiping the content) hence I need to use ViewPager and the compatibility library v4. The advice I have picked up (after much research) is to use a MainActivity which hosts the ActionBar and tabs with fragments for the tab contents. But I'm worried about the number of fragments. Also some of the fragments need to use date and time pickers which means DialogFragments coming out of fragments. It's starting to get very complicated. Does anyone see any problem with my using Activities instead of fragments for the tab contents? A: Fragments act on the UI side just like activities except you can combine multiple together. So you don't need to create a different fragment based on user choices, you just need to change the fragment just like how you would change an activity dynamically. Also if you want to use ViewPager, you are basically forced into using fragments. The nice thing about fragments is that they are reusable, so most likely you only need a few fragments and then you can combine them in different ways for the different use cases. This also makes your tablet UI a lot easier to create. For reference: http://developer.android.com/guide/components/fragments.html
{ "pile_set_name": "StackExchange" }
Q: What access does an anonymous function have in Javascript (Node) I'm trying to get the text from the response body to a request into a global variable. var Request = require('request'); var result = "Not set"; var foodrequest = Request({ uri: url }, function (error, response, body) { result = body; }); console.log(result); the "result" variable however is not set correctly. How can I achieve this? A: That's because the callback for Request is called asynchronously, while whatever is found after the invokation of the function named Request is executed (let me say) synchronously. That means that the console.log statement has no chance to be executed after the callback. So, when you reach the console.log statement, the above mentioned function has not been invoked yet.
{ "pile_set_name": "StackExchange" }
Q: Ускоряется ли загрузка страницы если объединять в CSS все селекторы и классы с одинаковыми стилями через запятую? Есть следующая конструкция, у многих классов - стили одинаковые: .oneclass { display: block; background: #f1f1f1; border-radius: 6px; margin: 10px 20px; padding: 15px; width: 50% } .twoclass { display: block; background: #000; color: #fff; border-radius: 6px; margin: 10px 20px; padding: 15px; width: 40% } .threeclass { display: block; background: #b50000; border-radius: 6px; margin: 10px 20px; padding: 15px; width: 30% } <div class="oneclass">Блок 1 </div> <div class="twoclass">Блок 2 </div> <div class="threeclass">Блок 3 </div> Есть ли смысл объединять классы через запятую и указывать одинаковый для данной группы стиль. Пример: .oneclass, .twoclass, .threeclass { display: block; border-radius: 6px; margin: 10px 20px; padding: 15px; } .oneclass { width: 50%; background: #f1f1f1; } .twoclass { background: #000; width: 40%; color: #fff; } .threeclass { background: #b50000; width: 30% } <div class="oneclass">Блок 1 </div> <div class="twoclass">Блок 2 </div> <div class="threeclass">Блок 3 </div> Ускорит ли это загрузку страницы? Или наоборот если через запятую будут указаны к примеру: блок из 50 классов имеющих одинаковый стиль, затем следующий блок из 30 классов с другим стилем и т.д. для браузера это будет более затратная по времени процедура построения страницы? Стоит ли в этом ключе оптимизировать CSS или мощность современных компьютеров нивелирует все эти усилия по оптимизации? Хочется понять, есть ли браузеру разница как построить страницу взять определенный класс и применить к нему все стили записанные подряд или если же стили будут разбросанные по всему CSS но сгруппированы классы к которым нужно применить тот или иной стиль ? Если да и так оптимизировать нужно, есть ли инструменты по автоматизации этих процессов, чтобы не просто в одну строку оптимизировать финишный вариант CSS, а вычленять из всего CSS все классы и селекторы с одинаковым стилем, записывать их через запятую, прописывать им определенный стиль, затем туже операцию делать с следующим стилем, а в конце записывать все классы и стили для них которые повторяются только один раз в CSS. (Если такие инструменты есть, то возможно есть и инструменты которые позволят произвести обратную сборку после оптимизации, найти определенный класс, найти все стили которые к нему применяются и собрать CSS в привычном образе для отладки и редактирования?) Надеюсь вопрос сформулировал понятно, благодарю за ответ! A: Вообще, CSS движок браузеров очень быстрый, разница при построении CSS Object Model перечисленных вами методов очень маленькая. Здесь гораздо больше будет влиять размер файла и время его загрузки. В этом случае обьединение классов полезно, размер файла уменьшается. Но это не всегда хорошая практика с точки зрения поддержки кода.
{ "pile_set_name": "StackExchange" }
Q: noisy gradient in p5.js The Goal An often seen effect in illustrations and other graphic works is a gradient between two colors, which is provided with a grain/noise and thus gets a very special effect. (especially example 3.) My research has shown many solutions how to achieve this effect in software like Illustrator, but I would like to recreate it with p5js or the vanilla js canvas. (source: https://medium.com/@stefanhrlemann/how-to-create-noisy-risograph-style-gradients-and-textures-in-photoshop-in-3-ways-394d6012a93a) My attempt I have already tried to create a gradient and set a random noise with a specific color using the pixel array on top of it. Which only partially leads to the desired effect: function draw() { setGradient(0, 0, width, height, color(0, 0, 0), color(255, 255 ,255)); setNoise(); } function setNoise() { loadPixels(); for (let x = 0; x < width; x++ ) { for (let y = 0; y < height; y++ ) { if (random(1) > 0.9) { const index = (x + y * width) * 4; pixels[index] = 255; pixels[index + 1] = 255; pixels[index + 2] = 255; pixels[index + 3] = 255; } } } updatePixels(); } function setGradient(x, y, w, h, c1, c2) { noFill(); for (let i = y; i <= y + h; i++) { let inter = map(i, y, y + h, 0, 1); let c = lerpColor(c1, c2, inter); stroke(c); line(x, i, x + w, i); } } what do you think? is this the right approach or is there a better / simpler solution? A: You need to blend your noise with the gradient. You can't blend directly an ImageData, you need to first transform it to a bitmap (putting it on a canvas can do). So instead of the overlay blending your tutorial talked about, you may prefer the hard-light one, which will invert the order of our layers. const w = 300; const h = 300; const canvas = document.getElementById( 'canvas' ); const ctx = canvas.getContext( '2d' ); // some colored noise const data = Uint32Array.from( {length: w*h }, () => Math.random() * 0xFFFFFFFF ); const img = new ImageData( new Uint8ClampedArray( data.buffer ), w, h ); ctx.putImageData( img, 0, 0 ); // first pass to convert our noise to black and transparent ctx.globalCompositeOperation = "color"; ctx.fillRect( 0, 0, w, h ); ctx.globalCompositeOperation = "hard-light"; ctx.fillStyle = ctx.createLinearGradient( 0, 0, 0, h ); ctx.fillStyle.addColorStop( 0.1, 'white' ); ctx.fillStyle.addColorStop( 0.9, 'black' ); ctx.fillRect( 0, 0, w, h ); canvas { background: lime; } <canvas id="canvas" height="300"></canvas> But blending requires you have an opaque scene. If you want to have transparency, then you'd have to use compositing too: const w = 300; const h = 300; const canvas = document.getElementById( 'canvas' ); const ctx = canvas.getContext( '2d' ); // some black and transparent noise const data = Uint32Array.from( {length: w*h }, () => Math.random() > 0.5 ? 0xFF000000 : 0 ); const img = new ImageData( new Uint8ClampedArray( data.buffer ), w, h ); ctx.putImageData( img, 0, 0 ); ctx.fillStyle = ctx.createLinearGradient( 0, 0, 0, h ); ctx.fillStyle.addColorStop( 0.1, 'transparent' ); ctx.fillStyle.addColorStop( 0.9, 'black' ); // apply transparency gradient on noise (dim top) ctx.globalCompositeOperation = "destination-in"; ctx.fillRect( 0, 0, w, h ); // apply black of the gradient on noise (darken bottom) ctx.globalCompositeOperation = "multiply"; ctx.fillRect( 0, 0, w, h ); // optionally change the color of the noise ctx.globalCompositeOperation = "source-atop"; ctx.fillStyle = "red"; ctx.fillRect( 0, 0, w, h ); canvas { background: lime; } <canvas id="canvas" height="300"></canvas>
{ "pile_set_name": "StackExchange" }
Q: Is there a way of replacing the default 7-Zip icons? I like 7-Zip a lot - it's my compression utility of choice on Windows. I have just one problem with it: it's butt ugly. I'm really kind of reluctant to install it on my fresh Windows 7 system because of its eye-bleeding qualities. Sad, I know, but the designer in me is just too anal to cope with it. Does anyone know of an easy, simple way to replace all of its default icons with something more attractive? A: Use 7Zip Theme Manager . You can change the file type look and feel as well the toolbar. A: You have two options: Changing the icon associated with zip files in the registry Replacing the icon referenced in the registry For the first option, you can edit the registry. The icon should be associated in HKEY_CLASSES_ROOT\zipfile\DefaultIcon. The entry is a string with the full path to the file (most probably the 7-Zip executable), and optionally a 1-based index of the icon number to use, seperated from the path by a coma. I know a tool that is helpful if you don't wand to fiddle with the registry manually: WAssociate For the second option, I recommend ResourceHacker. The easier way in my opinion is option 1, I recommend to go that way. You need elevated permissions for changes in HKCR, though. A: I use these sets of icons, created by superweapons on deviantart pros: Fits well to the Win7 design You don't have to install another program to skin 7zip cons: Every new version of 7zip has to be 'patched' again manually (it is not that bad, 7zip does not get updates very often)
{ "pile_set_name": "StackExchange" }
Q: Using yield from a block duplicates the view I have a model with a method where the goal is to output something if it exists, otherwise yield the code in the block. Pretty straightforward, but it's easier to grok with an example: In my partial I have the following: <%= @item.output do %> Default output <% end %> And my model: def output return "Override the default" if override? yield end If override? is true, this shows "Override the default" in the view the way I want it to. However, if it's false, the entire partial gets duplicated and inserted where "Default output" text should be! That's what happens if I use <%= %>. However, if I use <%- %> instead, when override? is true it outputs nothing, but when it's false it shows "Default output" as it should. The result I want is for the code in the partial to execute the code in the block (in this case, "Default output") when override? is false, and execute the code in the block when it's true. In standard Ruby, it works as it should: irb(main):001:0> def test(bool) irb(main):002:1> return "Method" if bool irb(main):003:1> yield irb(main):004:1> end => :test irb(main):005:0> irb(main):006:0> test(true) { "Block" } => "Method" irb(main):007:0> test(false) { "Block" } => "Block" But Rails is apparently doing some ^%$# with yield and views so it's not working out how I want it to whether I use - or = in my partial to render the code. Any help is appreciated. A: It turns out that simply changing yield to puts yield makes things work as intended. I guess Rails yields the yield. Wat.
{ "pile_set_name": "StackExchange" }
Q: "Новые" ES6 классы. "Старые" дескрипторы свойств Вопрос по синтаксису ES6. Нотация ES6 классов предусматривает элегантное создание статических методов, геттеров/сеттеров, в блочной инструкции также удобно описывать все методы для экземпляров класса. А что насчет установки "флагов"(writable, configurable, etc) для свойств порождаемых объектов? Так ли это, что все еще необходимы дополнительные обертки? 'use strict'; function User(name, age) { class User { constructor() { this.name = name; } } let user = new User(name); Object.defineProperties(user, { gender: { value: 'male' }, age: { get: function() { return age; }, set: function(value) { alert('Молодость не вернешь!'); return false; } } }); return user; } const user = new User('Vasya', 23); user.age = 16; console.log(user.age); A: В созданном Вами примере - new не несет никакого смысла. Т.к. возвращается не экземпляр внешнего класса User. "use strict"; class User { constructor(name, age) { this.name = name; Object.defineProperty(this, 'age', { value: age, writable: false }); } }; var user = new User('a', 123); alert('user has age ' + user.age); try { user.age = 12; //тут выбросится исключение, возраст не изменится } catch(e){ alert('Ошибка при изменении возраста'); } alert('after trying change, age = ' + user.age); В данном случае, из коробки возможность сделать alert у Вас нет, но свойство получается как раз только для чтения. Если хотите, подобным же образом можно опередить геттер, сеттер. Вообще, судя по всему, в ES2015 нет возможности красиво объявить поле класса, как readonly. Однако, в ES2016 появятся декораторы, которые позволят это сделать достаточно лаконично.
{ "pile_set_name": "StackExchange" }
Q: Listing files from resource directory in sbt 1.2.8 I have a scala application which processes binary files from some directory in resources. I would like to get this directory as java.io.File and list all the contents. In the newest sbt I am unable to do it the straight way. I have created minimal repo with my issue: https://github.com/mat646/sbt-resource-bug The issue does not occur with sbt 0.13.18 and lower. So after some research I've found out that since sbt 1.0 the design has changed and such issue has been already addressed here: https://github.com/sbt/sbt/issues/3963 So the offered solutions were: 1. downgrade to sbt 0.13 (which I would like to avoid) 2. extracting project jar itself (which I found pretty nagging, as I still haven't solved it yet - the https://github.com/sbt/io contains gunzip method but for me it still fails to extract my directory from jar, but here I might be misunderstanding how to extract nested file from project jar) (so as the sbt 1.0+ works on build jar for reading files getResourceAsStream works perfectly but fails for my issue) Thanks for any help and tips for solving it! A: run task seems to have been rewired in Forward run task to bgRun #3477 and one side-effect was to use packaged jars on classpaths instead of class directories, so that getClass.getResource("/my-dir") returns jar:file:/var/folders/84/hm7trc012j19rbgtn2h4fg6c0000gp/T/sbt_1397efb8/job-1/target/43a04671/sbt-resource-bug_2.12-0.1.jar!/my-dir instead of file:/Users/amani/IdeaProjects/sbt-resource-bug/target/scala-2.12/classes/my-dir Workaround 1 : Redefine run to the old behaviour As a workaround, we could try reverting the rewiring in our build.sbt like so: run := Defaults.runTask(fullClasspath in Runtime, mainClass in run in Compile, runner in run).evaluated Now File.listFiles should work, for example, new File(getClass.getResource("/my-dir").getFile).listFiles().foreach(println) should output sbt:sbt-resource-bug> run [info] Running Main /Users/mario/IdeaProjects/sbt-resource-bug/target/scala-2.12/classes/my-dir/file2.txt /Users/mario/IdeaProjects/sbt-resource-bug/target/scala-2.12/classes/my-dir/file1.txt  Workaround 2: Use JarFile to work with JARs directly Alternatively, if we wish to keep the current rewiring, JarFile can be used to list the contents of JAR files. For example, given object ListFileNamesInJarDirectory { def apply(dir: String): List[String] = { import scala.collection.JavaConverters.enumerationAsScalaIteratorConverter val jar = new File(getClass.getProtectionDomain().getCodeSource().getLocation().getPath()) (new JarFile(jar)) .entries() .asScala .toList .filter(!_.isDirectory) .filter(entry => entry.getRealName.contains(dir)) .map(_.getName) } } then ListFileNamesInJarDirectory("my-dir").foreach(println) should output my-dir/file1.txt my-dir/file2.txt Afterwards, getResourceAsStream can be used to get at the actual files in the jar. Note how we get File to represent the jar file: val jar = new File(getClass.getProtectionDomain().getCodeSource().getLocation().getPath())
{ "pile_set_name": "StackExchange" }
Q: If the ISS had an emergency, how long would it take to get a rocket to it? If there was an urgent need to launch a rocket to the ISS, how long would it take to have a rocket ready to launch? I am trying to understand what factors take up the time to prepare for a rocket launch. Updated: Here are some clarifications to limit scope. I am curious how long it takes to prep an emergency launch from a rocketry perspective. Assume there was an urgent need to deliver a small, lightweight package with something vital such as medicine or a replacement circuit board that is available. Assume we CAN use an existing rocket. Assume the rocket is NOT sitting ready on a launchpad. Assume travel to the ISS is within the capabilities of the rocket. A: A brand new rocket to be launched will have to be assembled, and that's a long process, though I do not know how long. But if it's for an emergency, you may find ready rockets. After the Columbia disaster, space shuttle missions all had a contingency mission in case they found issues with the orbiter before reentry. The planning and training processes for a rescue flight would allow NASA to launch the mission within a period of 40 days of its being called up. During that time the damaged (or disabled) shuttle's crew would have to take refuge on the International Space Station. You even had two shuttles on pad at the same time for a Hubble servicing mission, as the crew wouldn't be able to reach the space station for a safe haven, and would need to be rescued before the three weeks of consumables on board were exhausted. The rescue mission would have been launched only three days after call-up. That said the space shuttle isn't operating anymore, and until Spacex' Crew Dragon or Boeing's Starliner are operational (probably sometime soon), the Russian Soyuz is the only option to send people, and it seems to launch a new crew to the ISS roughly every 6 months (if there are no emergencies). For the last flight of the space shuttle, the was no contingency mission prepared, but instead the mission had only 4 astronauts, and in the case that Atlantis couldn't make the reentry, the astronauts would stay on board the ISS and come back to earth in Soyuz capsules over the following year. If your emergency doesn't require people to go to the ISS to help, but specific, unplanned cargo is still needed, a spacecraft (cargo or not) goes to the ISS every month or so, so if your emergency can wait between a week and a bit more than a month or so (to account for weather delays, mounting time of the payload and orbit maneuvers) you can just sneak it in one of those resupply missions, or replace some less vital cargo. If your emergency can't wait at all, and you absolutely need to send something to the ISS on short notice, and there are no upcoming resupply missions, you may be able to hijack another vehicle with sufficient authority. For March alone there are 10 planned rocket launches from the US, ESA or Roscosmos, so you could probably get emergency cargo to the ISS in around a bit more than a week (this is a guess, assuming the orbital maneuvers take around 3 days, and mounting the payload and waiting for a launch window take a few days too). Note that if you don't have a proper cargo spacecraft to put the cargo into, maneuvering up to the ISS might prove to be difficult, and the cargo will not be able to mate with the ISS, so astronauts may have to perform an EVA to secure the cargo outside. A: The ISS does not have emergency's that require a rocket to bring supplies. It can have an urgent need of something. Either everyone stays on the ISS or some/all crew leave. It is downhill all the way to Earth, and the crew can leave anytime. Worst case the crew abandons the ISS and it burns up on re-entry. There are a couple of good answers on this question, that talk about some of the challenges. But in the end the answer is "It depends, how much do you want to spend?" There are also a couple of good posts that talk about real emergencies. Would all crew leave the ISS if one had a medical emergency? How long can a 2 person crew survive on ISS totally cut from Earth? A: It depends on readiness of a rocket. Rocket assembly is rather long process. If you compare the dates of rocket delivery to launch facility and the launch you'll find that usually it takes about month or more. So if some rocket is ready to launch to ISS in coming days it's rather easy - just throw out some of less significant things and replace it by the emergency cargo. Well, maybe the cargo should be qualified for spaceflight (e.g. toxicity, srtength for 5-g accelerations, weightlessness behaviour, radiofrequency interference, etc), but for high emergency some of qualifications could be lifted, I think. But if no any rocket is planned to launch to ISS in next month or two - there is a big problem, and I would say it'll be close to impossible to accelerate the launch so much. Most of the time is spent on tests and checks of rocket and launchpad, so theoretically most of them could be skipped, but... List of rocket disasters tells us why the checks are so rigorous. Also, modern rockets (Falcon, Atlas V, Soyuz-2, H-IIB) make automatic self-checks before launch, and the countdown will be stopped by the rocket itself if something wrong found. Maybe the self-checks can be swithed off, too, but it's already a management nightmare without guarantee of success. All the lauch personnel was teached to follow the rules, and now they should skip most of them but make the thing flying... It's hard for me to imagine a scenario where emergency delivery to ISS can't wait at least a month. ISS have a lot of spares for this case. The crew can be evacuated if they can't stay. So the danger should be for the whole of ISS structure. Maybe some thermal regulation problem that can result in major overheat or freezing, so most of the equipment and interiors will be irreparable. In such improbable case the risky launch acceleration can be justified - try to fly now or there'll be nothing to save. Disclaimer: I'm not a space technology specialist, so take my post with grain of salt.
{ "pile_set_name": "StackExchange" }
Q: Xcode blocked at “Attaching to (app name)” when I launch my app in the simulator I know there's a lot of posts with the same that problem. I just spent at least 2 hours to read them and I tried everything I saw in the responses but it still doesn't work. I don't know what to do anymore. Can someone help me? I use Xcode 4.2.1 A: This problem occurs regularly for me, and the solution was always to kill the process named SimulatorBridge. And to simplify the solution you can add a custom 'behavior' in Xcode to do the task by following these steps: Make a shell script file with this command: #!/bin/sh killall SimulatorBridge Save it in ~/Library/Developer/Xcode/UserData/Behaviors/ as KillSimulatorBridge.sh. Open Xcode > Preferences > Behaviors, and add a new behavior to run the shell script: Now, you can run this behavior whenever Xcode hangs while trying to attach to your app, and you can even have a keyboard shortcut to run it. Hope this helps someone.
{ "pile_set_name": "StackExchange" }
Q: How to load an image server-side in ASP.NET? I'm trying to load an image that is in the root dir of my project: Dim b As Bitmap = New Bitmap("img.bmp") but it doesn't seem to find the file. I've tried various combinations like ~img.gif, /img.gif, \img.gif, ~/img.gif etc, but none seems to work. How to access the "current directory on server" in ASP.NET? Thanks A: Have you tried: Dim b As Bitmap = New Bitmap(HttpContext.Current.Server.MapPath("~/img.bmp"))
{ "pile_set_name": "StackExchange" }
Q: PHPUnit 4.8 Mock mysql database interface Good afternoon, I have a bunch of legacy code that uses the old mysql library (mysql_query($sql) for example) and am trying to test it with PHPUnit (4.8 is the latest that will run on the server for various reasons). Does anyone know how to mock this database connection so that it can return predetermined results when predetermined queries are run? I have tried using getConnection() (as per the docs here: http://devdocs.io/phpunit~4/database) to no avail. For example I have this class: class Raffle { ... public static function loadAll($filter=""){ //$filter = mysql_real_escape_string($filter); // protect against SQL injection $raffles = []; // the array to return $sql = "SELECT * FROM raffles $filter;"; // include the user filter in the query $query = mysql_query($sql); //echo mysql_error(); while($row = mysql_fetch_assoc($query)){ $raffles[] = Raffle::loadFromRow($row); // generate the raffe instance and add it to the array } return $raffles; // return the array } ... } (The mysql_connect() call is done in a file called db.php which is loaded on every page that it is needed and not in the class file itself.) Thanks in advance. A: For anyone else stuck in this situation I found that building a mock for PDO that contains a fallback to the functional api allowed me to migrate the code to a Testable OO based model while still using the old mysql library under the hood. For example: // the basic interfaces (function names taken from PDO interface DBConnAdapter { public function query($sql); } // since PDO splits connections and statements the adapter should do the same interface DBQueryAdapter { public function num_rows(); public function fetch_assoc(); } ... class DBAdapter implements DBConnAdapter { public function query($sql){ $query = mysql_query($sql); // run the query using the legacy api return $query ? new QueryAdapter($query) : false; // return a new query adapter or false. } } ... // an example of a basic mock object to test sql queries being sent to the server (inspired by mockjax :-) ) class DBMock implements DBConnAdapter { public $queries = []; // array of queries already executed public $results = []; // array of precomputed results. (key is SQL and value is the returned result (nested array)) public function query($sql) { if($this->results[$sql]){ $query = new DBQueryMock($sql, $this->results[$sql]); // a mock of PDOStatement that takes the sql it ran and the results to return $queries[] = $query; // add the query to the array return $query; // return the query } return false; // we do not know the statement so lets pretend it failed } // add a result to the list public function add_single_result($sql, $result){ // check if the index was set, if not make an array there if(!isset($this->results[$sql])) $this->results[$sql] = []; // add the result to the end of the array $this->results[$sql][] = $result; // return its index return count($this->results[$sql]) - 1; } } Admittedly this is not an ideal solution as it requires modifying the code to support the adapter objects and removes some functionality (such as mysql_real_escape_string), but it worked.... If you have a better solution please share :-) Thanks!
{ "pile_set_name": "StackExchange" }
Q: Restrict Oracle DB Login based on SQL Client being used We have an application in our organization that is based on Oracle Forms 11g (on Oracle Fusion Middleware/WLS). Users have access to the application through accounts created at the database (i.e. they exist in dba_users). Each user is assigned a specific role based on their area of work and they use the user id to log on to the application. The user may have read/write access to certain functionality in the application and for this their roles have the following permissions- EXECUTE ANY LIBRARY SELECT ANY SEQUENCE EXECUTE ANY TYPE EXECUTE ANY PROCEDURE UPDATE ANY TABLE SELECT ANY TABLE DELETE ANY TABLE EXECUTE ANY INDEXTYPE INSERT ANY TABLE Now we have some users requesting for SQL Client access (i.e. TNS settings) so that they can connect to the DB and perform queries for their research. These business users are ofcourse knowledgeable in SQL but we want to restrict their access based on the type of client they use to log on to the database. Any client other than the application itself, should restrict them to "read only". Is there a way to achieve this? A: You can check it with a database trigger, for example: CREATE ROLE ROLE_POWER_USER NOT IDENTIFIED; CREATE OR REPLACE TRIGGER LOG_T_LOGON AFTER LOGON ON DATABASE DECLARE osUser VARCHAR2(30); machine VARCHAR2(100); prog VARCHAR2(100) ip VARCHAR2(15); BEGIN IF ora_login_user IS NULL THEN RETURN; END IF; SELECT OSUSER, MACHINE, PROGRAM, ora_client_ip_address INTO osUser, machine, prog, ip FROM V$SESSION WHERE SID = SYS_CONTEXT('USERENV', 'SID'); IF NOT DBMS_SESSION.IS_ROLE_ENABLED('ROLE_POWER_USER') THEN IF LOWER(prog) <> 'your_application_name.exe' THEN RAISE_APPLICATION_ERROR(-20000, 'Logon denied: You must use only the official client application'); END IF; ELSE IF LOWER(prog) NOT IN ('sqlplus.exe', 'toad.exe') THEN RAISE_APPLICATION_ERROR(-20000, 'Logon denied: You must use only SQL*Plus or TOAD for you private queries'); END IF; END IF; -- Successful login, continue as normal END; / You can also check other conditions like IP-Address or the machine name. SELECT privileges on tables and views you have to grant to the user or ROLE in the "classic" way. This trigger only prevents to logon to the database with certain tools. Note, a user with System Privilege ADMINISTER DATABASE TRIGGER (for example DBA role, or SYS of course) never get the exception, i.e. they can logon to the database in any case and you cannot block this by the trigger. Another note: This trigger is not 100% secure. For example you can simply make a copy of your local sqlplus.exe and name it your_application_name.exe. Then this trigger would allow to use it.
{ "pile_set_name": "StackExchange" }
Q: How to get feature importance of the best model from cross validator in sparklyr? I'm able to train random forest cross validator in sparklyr but cannot find a way to get feature importance for the best model. If I train a simple random forest model, I can use: fit <- ml_random_forest(...) feature_imp <- ml_tree_feature_importance(fit) However, if I do the same thing to the best model from cross validator, I will get error: > cv_model <- ml_fit(cv, df_training) > feature_imp <- ml_tree_feature_importance(cv_model$best_model) Error in UseMethod("ml_feature_importances") : no applicable method for 'ml_feature_importances' applied to an object of class "c('ml_pipeline_model', 'ml_transformer', 'ml_pipeline_stage')" Is there a way to get feature importance for the best model from cross validator? The key to this question is, what is the difference between the output of model_fit and the output of ml_random_forest? What functions can be applied on one and what can be applied on the other? Can they be converted to each other? A: I looked closely into the structure of best model in a cross validator. For a tree based model (I checked GBT and RF), in the algorithm stage there is a component called feature_importances that contains the values for all real variables (different from the variable names given by the feature assembler stage where one hot variables are not expanded). It's sad that this feature_importances vector is not named, and I have to figure out corresponding variable name for each value. My thought is, from feature assembler we can get a simplified vector of column names where one hot encoded variables are not expanded, and for each one hot encoded variables we just need to replace it with a set of variable names with levels to eventually come up with the full column name vector -- I assume the order of variables is the same as that given by the feature assembler. To get levels of one hot variables, we can go back to stages with uid containing one_hot_encoder_ to first get one hot encoded variables, then go back to stages with uid containing string_indexer_ to get levels (stored in a sublist named labels) for each one hot encoded variable. Note that since this is in essence dummy encoding, one of the level is used as reference level that will not show up as a separate variable, and I assume the first level encountered and recorded in labels is the reference level, and the order of real variables for a particular one hot encoded variable is the same as that given in labels. Under these 3 assumptions, I'm able to reconstruct the column name vector and attach it to the feature importance vector to form a feature importance table like what I get from applying ml_feature_importances() on a GBT or RF model trained without cross validator.
{ "pile_set_name": "StackExchange" }
Q: How to tell if a buzzer is passive or active? I see a lot of buzzers (like this one) that are sold online and don't advertise whether they are active (a DC power signal produces noise) or passive (to make noise they require both the DC power signal and an additional signal). How can I tell if a buzzer is passive or active if its not immediately advertised by the distributor/website? A: Passive Piezo Buzzers run on AC only, no DC required. They're also often not called 'Buzzers', but rather 'Transducers', 'Elements' or similar. Active Piezo Buzzers run on DC, and usually the frequency they produce is specified. The one you link to is, without a doubt, an active buzzer, whereas this one is a passive transducer.
{ "pile_set_name": "StackExchange" }
Q: How to change background resource of an image button to implement on/off switch I have two power button images, one red and the other is green. I want to create a button set its background resource to red power button initially. I want its resource to be changed to green when it is pressed & after another click, i want it to turn back into red again. Please Help... A: Do this: <ToggleButton android:id="@+id/toggle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/check" //check.xml android:layout_margin="10dp" android:textOn="" android:textOff="" android:focusable="false" android:focusableInTouchMode="false" android:layout_centerVertical="true"/> create check.xml in drawable folder <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- When selected, use grey --> <item android:drawable="@drawable/selected_image" android:state_checked="true" /> <!-- When not selected, use white--> <item android:drawable="@drawable/unselected_image" android:state_checked="false"/> </selector> This works perfectly fine.
{ "pile_set_name": "StackExchange" }
Q: Is the Quaternion ring infinte? Of course by the definition of Quaternions, it is a finite set and made of 8 elements namely: $Q_8=\{\pm1, \pm i, \pm j, \pm k\}$ (with the known operations). It also can be seen that it is a division ring, but not a field simply because for example: $i\cdot j =-j\cdot i$. However by Wedderburn's theorem, every finite division ring has to be a field. Therefore it pushes $Q_8$ as a division ring to be infinite (since it is not commutative), while as I said it has only 8 elements. I am sure I am making a silly mistake, but I cannot find it. I would be appreciated if someone could point it out to me. A: That set of eight elements is a group, but not a (division) ring. It has only one binary operation, multiplication. You can't do $1+i$. – Gerry Myerson 10 mins ago You are confusing the quaternion group with the quaternion algebra; the former is a finite group with $8$ elements, and the latter is a $4$-dimensional real division algebra with uncountably many elements. – Qiaochu Yuan 9 mins ago
{ "pile_set_name": "StackExchange" }
Q: condition on model on class macros It's possible to put conditions on models like: class MyPeppers < ActiveRecord::Base acts_as_a_ferret() if Rails.env.production? end It's valid ruby code but I wonder if that should work? A: Yes, it will work because it is a perfectly valid Ruby code.
{ "pile_set_name": "StackExchange" }
Q: Firestore Query/Performance I am new to firestore, I am.confused with the pricing/shallow structure. Would like to know the better way of querying a set of data I have. I have the data structure as follow: (a) collection [productList ]- main collection (b) document [storeId ]- multiple documents in the range of 100's (c) collection [itemList ]- sub collection (d) document [Items ]- multiple documents in the range of 35 k to 45k My query will be usually getting data from (d) collection using 'where' clause. would it be better to remove the subcollections and have all it in the (b) documents and keep an extra ref parameter for querying. Keeping like it will increase the (b) document into 100k's of values. does the pricing vary if I change to that data structure,which would be better for pricing and performance. does the pricing(read) depend on the whole set of 100k's or only on the 20 or 30 values returned after the where clause query. A: You are only charged for the documents that are returned from a query or get operation, or documents that are skipped when using an offset (see under "managing large result sets"). Your queries are not charged extra for having lots of additional documents in a collection that are unread. But you are charged for that overall storage over time. If you are trying to minimize your costs, you should minimize both the total number of document reads and overall storage. The database structure that satisfies this may not be the most effective one for your application, however. You may have to trade off between cost for queries, cost of overall storage, speed, and your own convenience. Only you are able to estimate these costs, unless you share the entire contents of your database with someone who can help you make that estimate.
{ "pile_set_name": "StackExchange" }
Q: Pointer to array object in c++ I'm sort of new to C++ (coming from Java) and I want to declare an array object in a class, but it requires an integer value in its template parameters. I figured I'd have to make a pointer to an array class, but it does not work.. I want to make something like: class foo{ private: array *myArray; public: foo(int size){ //This line may be terribly wrong, but you see what I mean myArray = new array<int,5>(); } ~foo(){ free(myArray); } } Though, the correct initialization of an array object is: array<int,5> but this way does not let me choose length in runtime. A: I highly recommend that you pick up a good introductory C++ book, and forget about Java. Seriously, thinking in Java is counterproductive when learning C++. They may have similar syntax but they have very, very different semantics. The issues you're having is related to fundamental concepts of the language. You have to learn the fundamentals from a good C++ introductory book before moving on. std::array (if that's what you're using) is not the correct class to use for this particular application, because of the fact that you want to choose the length at runtime. The size of the std::array is fixed at compile-time. You should use std::vector instead, which allows you to specify (and change) the size at runtime. The standard containers such as std::vector manages the memory for you; you don't need to new or delete the standard containers. The standard containers exist because so you don't have to manually deal with memory yourself. #include <vector> class foo { private: std::vector<int> myArray; public: foo(int size) : myArray(size) // Sets the size of the array { } ~foo() { // You don't need to delete anything; the vector takes care of itself. } }; Notice that I didn't use pointers, new, delete, malloc(), or free() anywhere here. You often don't need pointers for many, many cases in C++. Contrary to popular belief, there's very little manual memory management that you actually have to do when using modern C++ techniques. In fact, if you're using delete or free() in your C++ code, you're probably doing it very wrong. I would like to stress again the importance of a good introductory C++ book in assisting you with the language. Any good intro C++ book will cover std::vector and how to use it to your advantage. Other resources such as a std::vector reference can also be of assistance. Familiarize yourself with them.
{ "pile_set_name": "StackExchange" }
Q: Why is there no reanimated Uchiha fighting in fourth shinobi war? Why didn't Kabuto reanimate any person from Uchiha clan like Sasuke's parents and all other that Itachi killed or any Uchiha that has lived in Konoha? Did he not have any one's dna or whatever it takes to reanimate? Is there any mention about this in manga or anime? Thanks. A: Both of your notions are correct: It is the dead person's DNA that is needed for the reanimation (alias Edo Tensei).[1] There is good reason to assume Kabuto did not reincarnate most of the Uchiha clan members, because he was unable to obtain their DNAs: "Kabuto mentions his desire to reincarnate certain shinobi [including] Shisui Uchiha";[2] and his ally in the Fourth Shinobi World War, Tobi (­SPOILER: alias Obito Uchiha, ), was in possession of their DNA,[3] but – being forced by Kabuto into this alliance in the first place[4] – did not let him use it.[3] Controlling more Uchiha shinobi could have made Kabuto too powerful with respect to the possibility of him turning against Tobi. However, Kabuto did summon Itachi Uchiha, Madara Uchiha, as well as (only in the anime) Inabi Uchiha[5] and used them in his war efforts.[6] As @AyaseEri points out, we can not exclude the possibility that Kabuto has managed to reincarnate the other Uchihas after all and it was just not shown. But definitely also factor in @ElPsyKongroo's answer below  on why that's very unlikely! References [1] Before this technique can be performed, the user must first acquire some of the DNA of the person they intend to reincarnate. —http://naruto.wikia.com/wiki/Summoning:_Impure_World_Reincarnation#Usage [2] —http://naruto.wikia.com/wiki/Summoning:_Impure_World_Reincarnation#cite_ref-Fivetwenty_1-5 [3] Kabuto could not find [Shisui Uchiha's] body. He suggested that one of Shisui's eyes that was crushed by Danzō Shimura, whose corpse was in Tobi's possession, would be sufficient. […] Tobi threatened him not to push his luck. —http://naruto.wikia.com/wiki/Summoning:_Impure_World_Reincarnation#cite_ref-Fivetwenty_1-5 [4] Kabuto [uses] the Impure World Reincarnation to revive five deceased Akatsuki members, which he offers to use to help Tobi in the approaching war. […] When Tobi contemplates refusing, Kabuto summons the real Madara Uchiha, forcing Tobi to agree. —http://naruto.wikia.com/wiki/Kabuto_Yakushi#Fourth_Shinobi_World_War:_Countdown [5] —http://naruto.wikia.com/wiki/Summoning:_Impure_World_Reincarnation#Kabuto_Yakushi [6] —http://naruto.wikia.com/wiki/Fourth_Shinobi_World_War Search the page for the (indeed numerous) occurrences of "Uchiha". A: Aside from the exceptional answer given by accolade, I think there might be another reason. Note that after the Uchiha clan was slaughtered, most of the cleaning up was done by the Anbu under Danzo. And given how careful he is, I'm sure he would have made sure that the bodies are not discoverable, and so, Kabuto could not have been able to obtain any DNA.
{ "pile_set_name": "StackExchange" }
Q: Delete, drop, kill ALL factor levels from Dataframe Lets take mtcars as example and create a new variable: mtcars$name <- rownames(mtcars) mtcars[,] <- lapply(mtcars, factor) mtcars[,] <- lapply(mtcars, as.numeric) Now the names are converted into numerics which i definitely dont want > mtcars mpg cyl disp hp drat wt qsec vs am gear carb name Mazda RX4 16 2 13 11 16 9 6 1 2 2 4 18 Mazda RX4 Wag 16 2 13 11 16 12 10 1 2 2 4 19 Datsun 710 19 1 6 6 15 7 22 2 2 2 1 5 Hornet 4 Drive 17 2 16 11 5 16 24 2 1 1 1 13 Hornet Sportabout 13 3 23 15 6 18 10 1 1 1 2 14 Valiant 12 2 15 9 1 19 29 2 1 1 1 31 Duster 360 3 3 23 20 7 21 5 1 1 1 4 7 Merc 240D 20 1 12 2 11 15 27 2 1 2 2 21 How can i convert factors back into the right formats.(char,log,num ...) ? A: It is possible that type.convert would suit your needs. It coerces its input to the most basic data type that can represent it. Thus, it would turn a character column that contains numbers that can be represented as integer into an integer column. mtcars$name <- rownames(mtcars) str(mtcars) # 'data.frame': 32 obs. of 12 variables: # $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ... # $ cyl : num 6 6 4 6 8 6 8 4 4 6 ... # $ disp: num 160 160 108 258 360 ... # $ hp : num 110 110 93 110 175 105 245 62 95 123 ... # $ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ... # $ wt : num 2.62 2.88 2.32 3.21 3.44 ... # $ qsec: num 16.5 17 18.6 19.4 17 ... # $ vs : num 0 0 1 1 0 1 0 1 1 1 ... # $ am : num 1 1 1 0 0 0 0 0 0 0 ... # $ gear: num 4 4 4 3 3 3 3 4 4 4 ... # $ carb: num 4 4 1 1 2 1 4 2 2 4 ... # $ name: chr "Mazda RX4" "Mazda RX4 Wag" "Datsun 710" "Hornet 4 Drive" ... mtcars[,] <- lapply(mtcars, factor) str(mtcars) # 'data.frame': 32 obs. of 12 variables: # $ mpg : Factor w/ 25 levels "10.4","13.3",..: 16 16 19 17 13 12 3 20 19 14 ... # $ cyl : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ... # $ disp: Factor w/ 27 levels "71.1","75.7",..: 13 13 6 16 23 15 23 12 10 14 ... # $ hp : Factor w/ 22 levels "52","62","65",..: 11 11 6 11 15 9 20 2 7 13 ... # $ drat: Factor w/ 22 levels "2.76","2.93",..: 16 16 15 5 6 1 7 11 17 17 ... # $ wt : Factor w/ 29 levels "1.513","1.615",..: 9 12 7 16 18 19 21 15 13 18 ... # $ qsec: Factor w/ 30 levels "14.5","14.6",..: 6 10 22 24 10 29 5 27 30 19 ... # $ vs : Factor w/ 2 levels "0","1": 1 1 2 2 1 2 1 2 2 2 ... # $ am : Factor w/ 2 levels "0","1": 2 2 2 1 1 1 1 1 1 1 ... # $ gear: Factor w/ 3 levels "3","4","5": 2 2 2 1 1 1 1 2 2 2 ... # $ carb: Factor w/ 6 levels "1","2","3","4",..: 4 4 1 1 2 1 4 2 2 4 ... # $ name: Factor w/ 32 levels "AMC Javelin",..: 18 19 5 13 14 31 7 21 20 22 ... mtcars[,] <- lapply(mtcars, function(x) type.convert(as.character(x), as.is = TRUE)) str(mtcars) #'data.frame': 32 obs. of 12 variables: #$ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ... #$ cyl : int 6 6 4 6 8 6 8 4 4 6 ... #$ disp: num 160 160 108 258 360 ... #$ hp : int 110 110 93 110 175 105 245 62 95 123 ... #$ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ... #$ wt : num 2.62 2.88 2.32 3.21 3.44 ... #$ qsec: num 16.5 17 18.6 19.4 17 ... #$ vs : int 0 0 1 1 0 1 0 1 1 1 ... #$ am : int 1 1 1 0 0 0 0 0 0 0 ... #$ gear: int 4 4 4 3 3 3 3 4 4 4 ... #$ carb: int 4 4 1 1 2 1 4 2 2 4 ... #$ name: chr "Mazda RX4" "Mazda RX4 Wag" "Datsun 710" "Hornet 4 Drive" ... If you don't store the original column classes before you turn the columns into factors, there is no way to restore this information completely. However, that shouldn't be necessary anyway.
{ "pile_set_name": "StackExchange" }
Q: Приведение дат к общему виду в запросе Есть таблица с полем типа "дата": +---------------------+ | DATE_IN | +---------------------+ | 17.02.2014 18:56:14 | | 22.12.2015 | | (null) | | 14.06.2015 17:48:12 | +---------------------+ Как в запросе привести значения к виду DD.MM.YYYY HH.mm.SS, чтобы там, где часов, минут и секунд нет, стало 00:00:00. A: Типа данных "дата" не бывает. Или date или char. Так как в вопросе вывод поля date_in имеет различный формат, со временем и без него, то тип данных этого поля символьный. Функция to_char() приведёт сначала к неявному преобразованию в тип date, что совершенно излишне и может вызвать ошибку. Правильный ответ будет: to_date (date_in, 'dd.mm.yy hh24:mi:ss') Воспроизводимый пример: select to_date (date_in, 'dd.mm.yy hh24:mi:ss') date_in from ( select trim (column_value) date_in from XmlTable ( '"17.02.2014 18:56:14", "22.12.2015 "')); DATE_IN ------------------- 2014-02-17 18:56:14 2015-12-22 00:00:00
{ "pile_set_name": "StackExchange" }
Q: Querying two datatables In vb.net I have two datatables, dt1 and dt2. Both have only one column. Now I need another table dt3 which should have the rows of dt1 that are not present in dt2. I tried to do with LINQ: Dim results = From table1 In dt1 Join table2 In dt2 On table1(0) Equals table2(0) Select table1(0) But this returns only that are matching. But I need the opposite (rows not there in dt2). Is it possible doing without LINQ? A: As far as I understand, you don't need a join (as you are selecting only rows from the first table). You can use a LINQ query like From table1 In dt1 _ Where Not (From table2 In dt2 Where table2(0) = table1(0)).Any() _ Select table1(0)
{ "pile_set_name": "StackExchange" }
Q: Use Polymer elements in Chrome extension At the moment I'm writing a Chrome extension and in the popup.html I want to use some Polymer elements, but my problem is that none of them are rendered in the popup. My popup.html looks like this: <!doctype html> <html> <head> <title>Getting Started Extension's Popup</title> <script src="js/popup.js"></script> </head> <body> <paper-tabs id="tabBar" class="bottom fit" selected="{{selected}}"> <paper-tab>TAB 1</paper-tab> <paper-tab>TAB 2</paper-tab> <paper-tab>TAB 3</paper-tab> </paper-tabs> </body> </html> This is my popup.js window.onload = function() { chrome.tabs.query({active: true, currentWindow: true}); } And here is my content script: function loadRes(res) { return new Promise( function(resolve, reject) { var link = document.createElement('link'); link.setAttribute('rel', 'import'); link.setAttribute('href', res); link.onload = function() { resolve(res); }; document.head.appendChild(link); }); } chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { loadRes(chrome.extension.getURL("polymer/webcomponentsjs/webcomponents-lite.js")) .then(loadRes(chrome.extension.getURL("polymer/paper-tabs/paper-tabs.html"))) }); This code comes from this answer and it should work, so do you have any ideas what is wrong with my code or have I misunderstood something? I thought that the code from popup.js is executed when the popup is loading and and referenced polymer files are injected into the popup.html file. Isn't that right? I also added all polymer files to web_accessible_resources and my content_scripts runs at document_start. A: You are trying to apply a solution that injects Polymer into a regular webpage (through content scripts) to your own UI page. Extensions' own pages never run any content scripts, and you don't need any complicated steps to include Polymer. You can just do it the regular way - you can add <link> elements to your markup and there is no need to call getURL. Update: due to Chrome Extensions' CSP, an additional step is needed (vulcanize or polybuild) to get rid of inline code. All the complication happens when you're trying to do that to a third-party page you have no direct control over. This is not the case with extension's own pages. For the record, you're most certainly misusing tabs.query - it does not send any messages in any case, it gives you information about open tabs in a callback (that you don't have).
{ "pile_set_name": "StackExchange" }
Q: How to properly handle a null variable perspective in kotlin? My old java version method looks like: @Override public void closeSimpleAlertDialog() { if (mAlertDialog != null && mAlertDialog.isShowing()) { mAlertDialog.dismiss(); } } As you can tell it is checked whether the null reference link to a dialog mAlertDialog and if not null check call method isShowing(), and only then caused a method of close - dismiss(). Very simple I faced a problem - how is still in "Kotlin-style" to perform the same operation? My first version looks here: if (mAlertDialog != null && mAlertDialog?.isShowing) { mAlertDialog?.dismiss() } Next step change mAlertDialog != null && mAlertDialog?.isShowing to mAlertDialog?.isShowing ?: false and last version looks like: if (mAlertDialog?.isShowing ?: false) mAlertDialog?.dismiss() But I don't understand. Why do I need "?" if the null checking already happened before (here: mAlertDialog?.)? A: Because another thread might make the property null after the null check, and before the call to dismiss. It won't happen if you use a local variable, or let. BTW, if you omit the question mark and hover on the red squiggly, IntelliJ tells you Smart cast to Dialog is impossible, because mAlertDialog is a mutable property that could have been changed by this time The canonical way (AFAIK) to do that with Kotlin would be fun close() { mAlertDialog?.let { if (it.isShowing) { it.dismiss() } } } A: mAlertDialog?.isShowing ?: false This line is providing a fallback value (false) in case the dialog or the property is null. What you are probably looking for is: alertDialog?.let { if (it.isShowing()) it.dismiss() } Where "it" is the property before the question mark null-checked. If alertDialog is null, the let will not be called and note that if you call it without the question mark it will enter even if it's null.
{ "pile_set_name": "StackExchange" }
Q: Looking for pattern to combine partial classes from different assembly's I am having the following problem. I have a main project, and some extra projects that have similar functionality. For example: I have an MVC website, then a class library project "A" with a "SettingsHelper". This just defines static wrappers for configuration settings so they can be used as propertys. Then I have another class library project "B", which also contains a "SettingsHelper class". How can I merge these SettingsHelpers in my main project, so I can use: SettingsHelper.Property from both modular extra projects. I would like to be able to plug extra class libraries into one project. A: Sounds pretty much like Dependency Injection. Normally you would expose SettingsHelper as an interface (your contract), and program against that. Then a DI container, such as Ninject, StructureMap, or Windsor would plug an implementation of that interface into the relevant parts of your code based on configuration. This would allow you to code against a known contract and provide different libraries depending on the circumstances, the DI framework could then use that library to get the concrete implementation of the interface. Would you need both instances at the same time? Note that you cannot utilise the partial keyword across different assemblies, only within an assembly. Update: based on your comment it sounds like you want to do something like Composition. Have a class that takes both classes from either library and combines them into one class that can be used by your application. Whether you then configure it to do something special or load the types when the libraries are present, it can all be encapsulated in this new class. Update 2: alternatively, look into MEF: http://msdn.microsoft.com/en-us/library/dd460648.aspx
{ "pile_set_name": "StackExchange" }
Q: how to use confirm in jalert plugin does anyone know how to use jalert confirm plugin here is documentation: http://flwebsites.biz/jAlert/ why i want to use that, i don't want to prevent multiple pop, which is default behaviour of chrome var name = prompt('please enter your name'); alert(name); i'm not getting any clear picture how to use it!! A: From this issue#5: $.fn.jAlert.defaults.confirmQuestion = 'Do you want to add this?'; confirm( function(e, btn){ //onConfirm e.preventDefault(); //do something here btn.parents('.jAlert').closeAlert(); return false; }, function(e,btn){ //onDeny e.preventDefault(); //do something here btn.parents('.jAlert').closeAlert(); return false; } ); or $.jAlert({ 'type': 'confirm', 'confirmQuestion': 'Do you want to add this?', 'onConfirm': function(e, btn){ e.preventDefault(); //do something here btn.parents('.jAlert').closeAlert(); return false; }, 'onDeny': function(e, btn){ e.preventDefault(); //do something here btn.parents('.jAlert').closeAlert(); return false; } }); Created this small jsfiddle to replicate a confirm modal/prompt. Hope this helps! Edit: If you're not forced to use jAlert, may I also suggest SweetAlert, which has a simpler interface/initialisation (and a prettier UI imo). It's also served over a CDN <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> Now it's available under a global swal variable A simple confirm prompt would look like this: swal("Are you sure you want to do this?", { buttons: ["Oh noez!", "Aww yiss!"], }); See it in action here
{ "pile_set_name": "StackExchange" }
Q: How to assign ruby variable to javascript I have a select list and its javascript function in my views. <select class="sel_list_size" id="product", onchange="build_url('dynamic_div')"> <%= options_for_select(get_product) %> </select> function build_url(div_var) { var selected_index = product.selectedIndex; var selected_value = product.options[product.selectedIndex].text; var selSpan = document.createElement('span'); $.ajax({ url: '/welcome/get_inner_dirs', type: 'GET', data: { value: selected_value } }); } and this is my controller method. def get_inner_dirs cmd = `curl #{@url}/#{params[:value]}/` result = JSON.parse(cmd) @inner_dirs = [] result.map { |e| @inner_dirs.append(e['name']) } @inner_dirs end So my aim is to create a dynamic select list using the data from @inner_dirs. Is there any way to do it? Thanks in advance. A: I am answering my own question since i found the solution. I modified my controller method to return the json response. def get_inner_dirs @inner_dirs = [] cmd = `curl #{@url}/#{params[:value]}/` result = JSON.parse(cmd) result.map { |e| @inner_dirs.append(e['name']) } render :json => @inner_dirs end Any my javascript to render dynamic select list is (Gave comments inside the code on how i achieved that) function build_url(div_var) { var selected_value = product.options[product.selectedIndex].text; var selSpan = document.createElement('span'); var MyTestData = ''; // call the controller method using ajax. When the call succeeded // assign the JSON response to a javascript variable (MyTestData) function ajax() { return $.ajax({ url: '/welcome/get_inner_dirs', type: 'GET', data: { value: selected_value }, success: function(data){ MyTestData = data } }); } // Ajax call will be done here. ajax().done(function() { // Temp variable to build a select list var selectHTML = ''; selectHTML = "<select>"; selectHTML += '<option></option>' // Use the Ajax response to add options inside the select list for (i = 0; i < MyTestData.length; i = i + 1) { selectHTML += '<option>' + MyTestData[i] + "</option>" } selectHTML += "</select>"; // Creating HTML for select list is completed now we need to // insert the HTML inside a div or span selSpan.innerHTML = selectHTML; // So this div_var will be a HTML Element id where we need to // push the select list document.getElementById(div_var).appendChild(selSpan); }).fail(function(){ alert('Ajax call Failed') }); } So here is how i used the javascript in my HTML <select class="sel_list_size" id="product" onchange="build_url('dynamic_div')"> <%= options_for_select(get_product) %> </select> <div id='dynamic_div'></div> I have an empty div below the select list in which the dynamic select list will be pushed when we select some value using the first select list
{ "pile_set_name": "StackExchange" }
Q: How do I get news feeds? Just like News and Weather app I'm trying to know how to implement the news feed retrieval, just like how it is on the News and Weather app: In the app (News and Weather), you have the option of writing the name, then the app retrieves the news based upon it. (Menu -> Settings -> News Settings -> Select news topics) For example, if I say "Android", it'll fetch me news relating to "Android". Is this based on RSS? How does it work and how can I implement it in my app? Thanks! A: I am saying as i understand: u want to make news search box* : user type any word and find latest news about written topic: i think u have to store ur RSS feed in db and then fire query on db and display news...
{ "pile_set_name": "StackExchange" }
Q: .msi file launched with java closes after a few seconds. I am trying to launch MySql server installer which is in my resources folder but it terminates after a few seconds. However if I launch it manually it runs okay until the end. Below is my code. Thread t = new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { ClassLoader classloader = Thread.currentThread().getContextClassLoader(); String fileUrl = classloader.getResource("mysql.msi").getFile(); Runtime rf = Runtime.getRuntime(); Process pf = rf.exec("msiexec /i \"\\" + fileUrl + "\""); } catch (Exception e) { // System.out.println(e.toString()); // not necessary e.printStackTrace(); } } }); t.start(); A: Okay, it was just an advice, lets come to your case, Windows OS has certain set of security restrictions which allows only administrator to install or remove any application. That is why, we see a promt window asking for Administrator password (or Admin's permission as YES/NO type, in case user has logged in as admin), and the promt screen is the heart of it's security, as it don't allow ANY OTHER APPLICATION TO HAVE CONTROL ON IT. If you do a remote desktop via third party, you will never see the client machines promt screen (this is because of security constraints), so in your case, your java application is third party app which don't have enough permission to continue the operation further. Hence it closes after few seconds. How ever, you can start and stop already installed services by allowing permission once in your windows service control. So I was suggesting you to play with service only.
{ "pile_set_name": "StackExchange" }
Q: Difference between "Descendant User Objects" and just "User Objects" i am trying to delegate permissions on a cetain OU to a certain group. All i find is "Descendatn User Objects" and not just "User Objects" ; we have those available in other domain; please do let me know what is the difference and how does it effect? A: DUO's are in 2008, UO's are in 2003. I don't think there is a difference in functionality, probably just a clarification in 2008 in regards to the wording.
{ "pile_set_name": "StackExchange" }
Q: PHP BBCode regex replacement How can I replace: <tag attr="z"> <tag attr="y"> <tag attr="x"></tag> </tag> </tag> to: <tag attr="z"> [tag=y] <tag attr="x"></tag> [/tag] </tag> Without using extensions? I unsuccessfully tried: preg_replace("#<tag attr=\"y\">(.+?)</tag>#i", "[tag=y]\\1[/tag]", $text); A: Well, PHP's regex implementation supports PCRE's recursive patterns. However, I'd hesitate to use such a feature because of its cryptic nature. However, since you asked: Without using extensions? here it is: <?php $html = '<tag attr="z"> <tag attr="y"> <tag> <tag attr="more" stuff="here"> <tag attr="x"></tag> </tag> </tag> </tag> </tag> '; $attr_regex = "(?:\s+\w+\s*=\s*(?:'[^']*'|\"[^\"]*\"))"; $recursive_regex = "@ <tag\s+attr=\"y\"> # match opening tag with attribute 'y' ( # start match group 1 \s* # match zero or more white-space chars <(\w+)$attr_regex*\\s*> # match an opening tag and store the name in group 2 ( # start match group 3 [^<]+ # match one or more chars other than '<' | # OR (?1) # match whatever the pattern from match group 1 matches (recursive call!) )* # end match group 3 </\\2> # match the closing tag with the same name stored in group 2 \s* # match zero or more white-space chars ) # end match group 1 </tag> # match closing tag @x"; echo preg_replace($recursive_regex, "[tag=y]$1[/tag]", $html); ?> which will print the following: <tag attr="z"> [tag=y] <tag> <tag attr="more" stuff="here"> <tag attr="x"></tag> </tag> </tag> [/tag] </tag>
{ "pile_set_name": "StackExchange" }
Q: Is there an open-source javascript calendar that supports built-in event detail popup? In this google calendar, when you click on a date which has an event, it will popup the event details. http://examples.tripod.com/calendar.html This is what I need (though its size is much larger than I need), but after searching on google, I realize there is a big limitation with google calendar. There is no easy way to customize its style using css because embedded google calendar is provided inside an iframe. There are solutions such as RESTYLEgc , but I don't really want to go for it. Now I am looking for an open-source javascript calendar that supports built-in event detail popup. It can be an extremely simple one, as long as it allows year/month navigation and it can highlight the date that has an event on it, and of course the built-in event pop up feature. It will be great if it's built on jQuery since I already have the jQuery library included on the website. I have only very few important events to set on the calendar, I expect I will be using codes like these: var event1Html='<div class="event-details">Some event details here</div>'; calendar.setEvent('2012-1-25',event1Html); var event2Html='<div class="event-details">Some other event details here</div>'; calendar.setEvent('2012-1-31',event2Html); Is there such a javascript calendar that you know of? A: I would look in to the fullcalendar script. From the looks of it, it can bring in google calendars, but also has an eventClick event that you can bind to and use (possibly) jQuery-UI to show a dialog of further information. For a demo, do the following: Visit that fullcalendar site and download the latest version (looks to be 1.5.2) Extract the fullcalendar-1.5.2\fullcalendar-1.5.2\fullcalendar folder to your desktop. Create a "calendardemo.html" file on your desktop and paste the following in to it: <html> <head> <title>Calendar Demo</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.0/themes/base/jquery-ui.css" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.15/jquery-ui.min.js"></script> <link rel='stylesheet' type='text/css' href='fullcalendar/fullcalendar.css' /> <link rel='stylesheet' type='text/css' href='fullcalendar/fullcalendar.print.css' media='print' /> <script type='text/javascript' src='fullcalendar/fullcalendar.min.js'></script> <style type="text/css"> body { margin-top: 40px; text-align: center; font-size: 14px; font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif; } #calendar { width: 640px; margin: 0 auto; } </style> </head> <body> <div id="calendar"></div> <div class="ui-helper-hidden" id="calendar-details" title="Event Details"> <p>Event details</p> </div> <script type="text/javascript"> $(function(){ var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); var $dialog = $('#calendar-details').dialog({ autoOpen: false, model: true, height: 300, width: 350 }); $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, editable: true, events: [ { title: 'All Day Event', start: new Date(y, m, 1) }, { title: 'Long Event', start: new Date(y, m, d-5), end: new Date(y, m, d-2) }, { id: 999, title: 'Repeating Event', start: new Date(y, m, d-3, 16, 0), allDay: false }, { id: 999, title: 'Repeating Event', start: new Date(y, m, d+4, 16, 0), allDay: false }, { title: 'Meeting', start: new Date(y, m, d, 10, 30), allDay: false }, { title: 'Lunch', start: new Date(y, m, d, 12, 0), end: new Date(y, m, d, 14, 0), allDay: false }, { title: 'Birthday Party', start: new Date(y, m, d+1, 19, 0), end: new Date(y, m, d+1, 22, 30), allDay: false }, { title: 'Click for Google', start: new Date(y, m, 28), end: new Date(y, m, 29), url: 'http://google.com/' } ], eventClick: function(event,jsEvent,view){ console.log(event); $dialog.dialog({title:event.title}); $('p',$dialog).empty().append( $('<p />').text(event.allDay ? 'All day event' : 'Scheduled: ' + event.start + '-' + event.end) ); $dialog.dialog('open'); } }); }); </script> </body> </html> Now click on an event. Unpolished, yes, but shows a pretty simple way of achieving what you're going for.
{ "pile_set_name": "StackExchange" }
Q: Toggling Google Chrome extension popout I have made a Google Chrome extension which mimics the Internet Explorer favorites drop-down. However, the thing that's bugging me is that I click the icon and the popout is displayed, but if I click the icon again it reloads my popout instead of closing like I want it to. How can I set the extension popout to toggle being opened and closed on the icon click instead of always being opened? A: You can't control this as it is handled by Chrome. I recall hearing that some platforms (maybe windows) would close the popup when the browserAction button is clicked so it may be something you can open an issue on http://crbug.com to have it be consistant.
{ "pile_set_name": "StackExchange" }
Q: Using a function to create an instance of a class based on the type passed through I have this method: internal static void AssignNewArrayItem(ref Xml.CLASSNAME[] Items, Xml.CLASSNAME Item) { if (Items != null) { Array.Resize(ref Items, Items.Length + 1); Items[Items.Length - 1] = Item; } else Items = new Xml.CLASSNAME[] { Item }; } At the moment I have about 10 overloaded versions where CLASSNAME is different but they all do the exact same thing. Is there any way I can have CLASSNAME as a generic object and cast the vars to achieve the same result? I am open to other suggestions to acheive the same result if I am going about this in the wrong way as well. A: internal static void AssignNewArrayItem<T>(ref T[] Items, T Item) { if (Items != null) { Array.Resize(ref Items, Items.Length + 1); Items[Items.Length - 1] = Item; } else Items = new T[] { Item }; }
{ "pile_set_name": "StackExchange" }
Q: SQL Server - Merge multiple query results into one result set I have three queries which return one columns each. SELECT Name FROM Tenant SELECT Name FROM Space SELECT ID FROM Contracts The table definitions are: Tenant (ID, Name) Space (ID, Name, TenantID) Contracts (ID, TenantID) The information that I have in these tables is: +----+---------+ | id | name | +----+---------+ | 1 | Tenant1 | | 2 | Tenant2 | | 3 | Tenant3 | +----+---------+ +----+------+----------+ | id | name | tenantID | +----+------+----------+ | 1 | S1 | 1 | | 2 | S2 | 1 | | 3 | S3 | 2 | | 4 | S4 | 3 | | 5 | S5 | 3 | +----+------+----------+ +----+----------+ | id | tenantID | +----+----------+ | 1 | 1 | | 2 | 1 | | 3 | 2 | | 4 | 2 | | 5 | 2 | | 6 | 3 | +----+----------+ How can I write a query to achieve the below structure? +----------+-------+----------+ | tenant | space | contract | +----------+-------+----------+ | tenant 1 | S1 | 1 | | | S2 | 2 | | tenant 2 | S3 | 3 | | | | 4 | | | | 5 | | tenant 3 | S4 | 6 | | | S5 | | +----------+-------+----------+ I have links between Tenant and Contracts table, but I don't want them to take into account the spaces between tenants and I don't want the values in any of the columns to be duplicate. I've tried using joins, but they obviously duplicate the values in the columns if matches exist between them. SELECT T.NAME 'Tname', S.NAME 'Sname', C.ID FROM Tenant T LEFT JOIN Space S ON T.ID = S.TenantID LEFT JOIN Contracts C ON T.ID = C.TenantID I've also tried correlating this into a subquery and using ROW_NUMBER() and combining with some CASE statements to achieve the desired format, but wasn't very successful. Here is a SQLFiddle with some sample data. Any suggestions/comments or links that could help are very much appreciated. A: WITH SpaceRow AS ( SELECT tenantid ,name ,ROW_NUMBER() OVER (PARTITION BY tenantid ORDER BY id) AS RowNumber FROM Space ) ,ContractRow AS ( SELECT tenantid ,id ,ROW_NUMBER() OVER (PARTITION BY tenantid ORDER BY id) AS RowNumber FROM Contracts ) ,SpaceContracts AS ( SELECT COALESCE(SpaceRow.tenantid, ContractRow.tenantid) AS tenantid ,COALESCE(SpaceRow.RowNumber, ContractRow.RowNumber) AS RowNumber ,SpaceRow.name AS SpaceName ,ContractRow.id AS ContractId FROM SpaceRow FULL OUTER JOIN ContractRow ON SpaceRow.tenantid = ContractRow.tenantid AND SpaceRow.RowNumber = ContractRow.RowNumber ) SELECT CASE WHEN SpaceContracts.RowNumber IS NULL OR SpaceContracts.RowNumber = 1 THEN Tenant.name ELSE NULL END AS TenantName ,SpaceContracts.SpaceName ,SpaceContracts.ContractId FROM Tenant LEFT JOIN SpaceContracts ON SpaceContracts.tenantid = Tenant.id ORDER BY Tenant.id ,SpaceContracts.RowNumber
{ "pile_set_name": "StackExchange" }
Q: Could my enterprise proxy know the content of an https request? Like for instance login into my bank account or knowing what information do I submit via HTTPs? I'm not sure what proxy server do we have. A: Absolutely. Several enterprise-level proxies support re-encrypting the connections your browser makes using a corporate certification authority. Essentially the administration team can push out a certificate to your workstation via group policies, and add it to the list of trusted authorities. The proxy then has the private key corresponding to that certificate and generates a certificate for each hostname on the fly. Then when your browser connects the proxy uses HTTPS to connect to the destination, but then encrypts the actual tunnel to your browser using the aforementioned certificate and private key. There's also open source and free proxies capable of this interception (which is just an MITM attack made easy by the administrators having access to the trusted certificate list on each workstation). Edit: You can detect this by inspecting who has signed the certificate for each HTTPS site, but the name can even match existing certificates so you'd have to compare the fingerprint to a known good one of each certificate authority.
{ "pile_set_name": "StackExchange" }
Q: SSRS display top n but have SUM include all values I currently have a tabllix in SSRS with multiple rows, but I wish to only display the top 5 rows, yet have the total column at the bottom include the values for however many rows are in the table. Example: NameID / Sales / % of Total 1 / 100 / 4 / 70 / 3 / 65 / 2 / 50 / 7 / 35 / DO NOT DISPLAY THESE RECORDS: 6 / 25 / 5 / 10 / TOTAL SALES: 355 (inclusive of all 7 records) I need this total sales number to be accurate so that I can then use it for the % of Total column. I don't believe a filter for top n on the dataset will work because that will not include the lower records in the dataset. The only thing I can think to do is to make the row visibility so it only displays the first 5 rows, except I do not know how to do this. Thanks A: Add a rownumber column to your query (SQL) ROW_NUMBER() OVER (partition BY FIeldName1 ORDER BY FieldName1 Asc) AS rownum On the Report: Right click on any Tablix column and select Tablix Properties Click on Filters Expression: rownum Operator: < Value: 6
{ "pile_set_name": "StackExchange" }
Q: Jquery Validator and Laravel 4 ajax issue i´m trying to validate a form in laravel 4 with Jquery Validator, the only thing i can´t perform it´s a remote validation for the email. I tried with my browser the following http://example.com/validacion/email/[email protected] and i get the result (in json) that i want. //Routes.php Route::get('validacion/email/{email}', 'ValidatorController@getValidacionEmail'); //In my JS the rule of email is email: { required: true, email: true, remote: { url: "/validacion/email/", type: "get", data: { email: "[email protected]" }, complete: function(data) { if (data.responseText !== "true") { alert(data.respuesta); } } } And when i use Firebug I get this location http://example.com/validacion/email/?email=akatcheroff%40gmail.com and a 301 code and after that a 500 and this error {"error":{"type":"Symfony\Component\HttpKernel\Exception\NotFoundHttpException","message":"","file":"C:\Users\Usuario\Dropbox\Public\sitios\futbol\vendor\laravel\framework\src\Illuminate\Routing\Router.php","line":1429}} Does anybody knows if there is a way to send my mail parameter in a way that the route recognize it? Thanks! A: Problem The route you have specified validacion/email/{email} will handle routes such as: (1) http://mysite.com/validacion/email/[email protected] (Just like you tried in Firefox.) When your ajax runs you end up (just as firebug dumped) with urls such as: (2) http://mysite.com/validacion/email/[email protected] Now notice the difference between url 1 and 2. The first one have the email value as a segment of the url. The second have the email value as part of the query string. The error Laravel throws is saying that the router couldn't find a matching handler for the url. Solutions You can solve this by either changing your javascript: remote: { url: "/validacion/email/" + "[email protected]", type: "get" } Remove the email from the query string and add it to the path. Or, you can solve it by changing your PHP route: Route::get('validacion/email', 'ValidatorController@getValidacionEmail'); Then in getValidacionEmail you can get the email from the query string using: $email = Input::get('email');
{ "pile_set_name": "StackExchange" }
Q: Retrieve WiFi password How to get saved WiFi password from my android 5.1.1 without rooting? I checked the path /data/misc/wifi/ using adb pull from terminal, but it's empty A: You can't get the passwords without root access because shell (adb) is not privileged to access the file containing those passwords. As you would know, the file wpa_supplicant.conf contains all the saved Wi-Fi passwords. In order to even ascertain the existence of that file, you must have read or executable permission until wifi directory. It just happened that the permissions on that directory is drwxrwx---, is owned by user wifi and group wifi. Executing id tells us that shell is not part of wifi group, so it ultimately would be considered others. As you can see, the permissions for others are blank --- i.e. no read/write/execute permission is available, hence, you can't enter that directory, let alone copy a particular file residing inside it. Root the device if you want that file badly. Related reading: File permissions and attributes
{ "pile_set_name": "StackExchange" }
Q: Set of values of $a$ satisfying an inverse trigonometric equation. Find the set of values of a so that the equation $(\arcsin x)^3+ (\arccos x)^3= a\pi^3$ has a solution. Attempt: Let $y = \arcsin x$ (just for convenience to avoid typing/ writing $\arcsin$ over and over again ) Note that $y + \arccos x = \pi /2$ We have $(y+\arccos x)(y^2 + (\frac\pi 2-y)^2 - y (\frac \pi2 - y)= a\pi^3$ $\implies (\sqrt 3y- \dfrac{\sqrt3}{4}\pi)^2+\dfrac{\pi^2}{16}= 2a\pi^2$ $-\frac \pi 2\le y \le \frac\pi 2$ $\implies -\dfrac{\sqrt 3 \pi}{2} - \sqrt{3}\pi/ 4\le \sqrt 3 y - \frac{\sqrt {3}}{4}\pi \le \dfrac{\sqrt 3 \pi}{2}-\sqrt{3}\pi/ 4\\ \implies 0\le 2a\pi^2- \dfrac{\pi^2}{16}\le \dfrac{3}{16}\pi^2 \implies a\in [\dfrac{1}{32}, \dfrac{1}{16}]$ I get the right lower limit of $a$ but the upper limit given in the answer is $7/8$. I'll be grateful if someone could point out my error and if that has been done, provide alternative, easier ways to solve this problem. A: The question is equivalent to finding the range of the function $$x\mapsto \frac{(\arcsin x)^3+ (\arccos x)^3}{\pi^3}$$ defined on $[-1,1]$. You can do that by studying the variations of the function via its derivative, and the data of extremal values in $x=-1$ and $x=1$. Edit The problem is here: $ -\dfrac{\sqrt 3 \pi}{2} - \sqrt{3}\pi/ 4\le \sqrt 3 y - \frac{\sqrt {3}}{4}\pi \le \dfrac{\sqrt 3 \pi}{2}-\sqrt{3}\pi/ 4$ from here, the largest value for the square will come from squaring the LHS, not the RHS.
{ "pile_set_name": "StackExchange" }
Q: Reading foreign characters I have a database containing the names of Premiership footballers which I am reading into R (3.02), but am encountering difficulties when it comes to players with foreign characters in their names (umlauts, accents etc.). The code below illustrates this: PlayerData<-read.table("C:\\Users\\Documents\\Players.csv",quote=NULL, dec = ".",,sep=",", stringsAsFactors=F,header=T,fill=T,blank.lines.skip = TRUE) Test<-PlayerData[c(33655:33656),] #names of the players here are "Cazorla" "Özil" Test[Test$Player=="Cazorla",] #Outputs correct details Test[Test$Player=="Ozil",] # Can not find data '0 rows> (or 0-length row.names)' < #Example of how the foreign character is treated: substr("Özil",1,1) [1] "Ã" substr("Özil",1,2) [1] "Ö" substr("Özil",2,2) [1] " substr("Özil",2,3) [1] "z I have tried replacing the characters, as described here: R: Replacing foreign characters in a string, but as the accented characters in my example appear to be read as two seperate characters I do not think it works. I would be grateful for any suggestions or workarounds. The file is available for download here. A: EDIT: It seems that the file you provided uses a different encoding than your system's native one. An (experimental) encoding detection done by the stri_enc_detect function from the stringi package gives: library('stringi') PlayerDataRaw <- stri_read_raw('~/Desktop/PLAYERS.csv') stri_enc_detect(PlayerDataRaw) ## [[1]] ## [[1]]$Encoding ## [1] "ISO-8859-1" "ISO-8859-2" "ISO-8859-9" "IBM424_rtl" ## ## [[1]]$Language ## [1] "en" "ro" "tr" "he" ## ## [[1]]$Confidence ## [1] 0.25 0.14 0.09 0.02 So most likely the file is in ISO-8859-1 a.k.a. latin1. Luckily, R does not have to re-encode the input while reading this file - it may just set a different than default (== native) encoding marking. You can load the file with: PlayerData<-read.table('~/Desktop/PLAYERS.csv', quote=NULL, dec = ".", sep=",", stringsAsFactors=FALSE, header=TRUE, fill=TRUE, blank.lines.skip=TRUE, encoding='latin1') Now you may access individual characters correctly, e.g. with the stri_sub function: Test<-PlayerData[c(33655:33656),] Test ## T Away H.A Home Player Year ## 33655 33654 CrystalPalace 1 Arsenal Cazorla 2013 ## 33656 33655 CrystalPalace 1 Arsenal Özil 2013 stri_sub(Test$Player, 1, length=1) ## [1] "C" "Ö" stri_sub(Test$Player, 2, length=1) ## [1] "a" "z" As per comparing strings, here are the results for a test for equality of strings, with accent characters "flattened": stri_cmp_eq("Özil", "Ozil", stri_opts_collator(strength=1)) ## [1] TRUE You may also get rid of accent characters by using iconv's transliterator (I am not sure whether it is available on Windows, though). iconv(Test$Player, 'latin1', 'ASCII//TRANSLIT') ## [1] "Cazorla" "Ozil" Or with a very powerful transliterator from the stringi package (stringi version >= 0.2-2): stri_trans_general(Test$Player, 'Latin-ASCII') ## [1] "Cazorla" "Ozil"
{ "pile_set_name": "StackExchange" }
Q: Color points in scatter plot of Bokeh I have the following simple pandas.DataFrame: df = pd.DataFrame( { "journey": ['ch1', 'ch2', 'ch2', 'ch1'], "cat": ['a', 'b', 'a', 'c'], "kpi1": [1,2,3,4], "kpi2": [4,3,2,1] } ) Which I plot as follows: import bokeh.plotting as bpl import bokeh.models as bmo bpl.output_notebook() source = bpl.ColumnDataSource.from_df(df) hover = bmo.HoverTool( tooltips=[ ("index", "@index"), ('journey', '@journey'), ("Cat", '@cat') ] ) p = bpl.figure(tools=[hover]) p.scatter( 'kpi1', 'kpi2', source=source) bpl.show(p) # open a browser I am failing to color code the dots according to the cat. Ultimately, I want to have the first and third point in the same color, and the second and fourth in two more different colors. How can I achieve this using Bokeh? A: Here's a way that avoids manual mapping to some extent. I recently stumbled on bokeh.palettes at this github issue, as well as CategoricalColorMapper in this issue. This approach combines them. See the full list of available palettes here and the CategoricalColorMapper details here. I had issues getting this to work directly on a pd.DataFrame, and also found it didn't work using your from_df() call. The docs show passing a DataFrame directly, and that worked for me. import pandas as pd import bokeh.plotting as bpl import bokeh.models as bmo from bokeh.palettes import d3 bpl.output_notebook() df = pd.DataFrame( { "journey": ['ch1', 'ch2', 'ch2', 'ch1'], "cat": ['a', 'b', 'a', 'c'], "kpi1": [1,2,3,4], "kpi2": [4,3,2,1] } ) source = bpl.ColumnDataSource(df) # use whatever palette you want... palette = d3['Category10'][len(df['cat'].unique())] color_map = bmo.CategoricalColorMapper(factors=df['cat'].unique(), palette=palette) # create figure and plot p = bpl.figure() p.scatter(x='kpi1', y='kpi2', color={'field': 'cat', 'transform': color_map}, legend='cat', source=source) bpl.show(p)
{ "pile_set_name": "StackExchange" }
Q: simultaneously reading 100 telnet connections c++ I want to write a progam in c++ which creates 100+ connections to telnet server and read their datastreams (parse and interpret them). Should i use one thread for every connection? Or is there another method to handle so many connections without hundreds of threads? A: In the simplest form, you can use one thread per connection. But that won't scale to much more than your hundreds of connections, and the multithreading may make your code and logic more complex (it very well may make it simpler too. It depends very much on what your application is trying to do.) A little better than that is to use select. It's a function call that most (all?) socket libraries and operating systems support. Basically, you put all your sockets in a set and you give the set to select and tell it to wait for any event on any of these sockets (an event is something like new data arriving on a socket or a connection error or a write completing or stuff like that.) If any events occur on any of these sockets, the select call will return and tell you what has happened on which socket(s). Then you process those events (read the incoming data, write more data, handle the errors, etc.) and then loop back and wait for more events. There are many good tutorials around about select and event-driven programming in general. Also, there are more efficient (albeit platform-specific) system calls and facilities, e.g. poll, epoll, kqueue, inotify, etc. There are of course many excellent libraries that use the most efficient platform-specific method and give you a (mostly) simple interface to work with. Libraries such as libev, libevent and libuv. If you don't need Windows portability, I suggest libev. libevent is a little older and larger, but with many more features. If you do need to support Windows, use libuv. But handling the connections and their events is just part of the solution. As mentioned by comments on your question and other answer(s), after you receive an event on a connection, one common (not to mention sensible and scalable) solution is to hand off the actual processing of data and activities like that to other threads. What is usually done is having a pool of worker threads. In your main thread, you get notified of an even on a connection (by select, etc.) but instead of doing all the work in the main thread, you give the work item to one of the worker threads to process and generate the result for and send the result back. One crucial issue here will be the communication between the main thread (the select thread) and the worker threads. Sometimes, some form of thread-safe shared queue is used. The main thread puts works items (events, requests, whatever) in this queue, and all the worker threads try to grab an item from this queue whenever they are not busy. Note that everything you read above is simplified to the bare minimum. In the real world, writing low-latency and scalable systems of this kind is a challenging and complicated task, so you might want to do (a lot) more research if you really need performance and/or you are dealing with huge amounts of data and many clients. A: yzt's answer is already good, but here's another, "hybrid" approach. Instead of using a separate thread for each connection, only use a thread from a thread pool for actually handling traffic. In your central loop, where you poll select(), you dispatch work to the next free thread. If there are no more threads available, you either simply wait for one to become available, or spawn more threads to handle the additional traffic. This provides better latencies because the next socket doesn't have to wait unless the thread pool is exhausted and you don't want to spawn more threads.
{ "pile_set_name": "StackExchange" }
Q: List & Label web report designer cross browser compatibility I'm planning to use list & label as a reporting tool for my MVC Web Application, I downloaded the trial version and the sample code was really helpful. I'm almost settled on using this as my app's reporting tool but I'm thinking twice on their web app report designer tool, because I needed to install the chrome extension before I can use it. I'm using version LL v.20 So my questions are: Is the chrome extension really needed for the designer to work? I'm thinking that if my app goes live, will I require my clients to install this plugin first? Will the designer have issues on other browser? So far I haven't seen extensions/plugins for IE (only Fireforx, Safari, Opera, Chrome). PS. If all else fail, can you suggest an alternative for this? The reporting tool that I need is web-based and allows end-users to edit the reports. Thanks! A: 1) Yes, you need to install the plugin on the client side. 2) For IE, there's a Designer ActiveX. Simply open your existing app in IE, you should be offered to install the OCX right away. As to your general concerns: We plan to replace the plugins with a client-side application that can be one-time installed with a couple of clicks in LL21. The reasoning is the step-by-step deprecation of plugins by most browser vendors. Changing between the plugins and the new designer app will be quite easy. The new designer will also support previewing at design time. Depending on when you plan to ship your application it may well be worth the wait till October.
{ "pile_set_name": "StackExchange" }
Q: ok to have high average EC2 CPU load on AWS instance? We've recently downgraded a batch processing instance in AWS to reduce costs. The CPU now is averaging about 70%. However it still seems to be coping with the load. Is there any issue with running an instance continuously at high average CPU load? Is there any kind of fair use policy that would come into play. The instance type is in the r5 class, so CPU credits aren't an issue. A: There is no issue with doing this, if your performance is adequate. You are paying for exclusive use of the CPU and memory allocated to the virtual machine. CPU resources are not shared across VMs on any class of EC2 instance -- except possibly to some not-fully-documented extent on the burstable "t"-class instances -- and even those do not restrict your usage by either technology or policy if you have available CPU credits or you use the t2/t3-unlimited feature.
{ "pile_set_name": "StackExchange" }
Q: VBA - Loop, Catch error, assign variable and continue looping? I have this email automation program. I essentially want to create a error catch for RecpName. When RecpName is passed into Lotus Notes and returns an error (due to spelling errors), I want to capture that into a error catch. I still want the loop to keep going and continue down the list, but tell the user which names it couldn't send emails to. Here's my code: Sub Send_HTML_Email() Const ENC_IDENTITY_8BIT = 1729 'Send Lotus Notes email containing links to files on local computer Dim NSession As Object 'NotesSession Dim NDatabase As Object 'NotesDatabase Dim NStream As Object 'NotesStream Dim NDoc As Object 'NotesDocument Dim NMIMEBody As Object 'NotesMIMEEntity Dim SendTo As String Dim subject As String Dim HTML As String, HTMLbody As String Dim wb As Workbook Dim ws As Worksheet Dim lstrow As Long, j As Long Dim RecpName As String, candiName As String Dim a As Hyperlink Set wb = ThisWorkbook Set ws = wb.Worksheets("Detail") ' Instantiate the Lotus Notes COM's Objects. lstrow = ws.Range("B" & Rows.Count).End(xlUp).Row Set NSession = CreateObject("Notes.NotesSession") 'using Lotus Notes Automation Classes (OLE) Set NDatabase = NSession.GetDatabase("", "") If Not NDatabase.IsOpen Then NDatabase.OPENMAIL For j = 3 To lstrow RecpName = ws.Cells(j, 2).Text candiName = ws.Cells(j, 1).Text SendTo = RecpName subject = wb.Worksheets("Email Settings").Range("B1").Text Debug.Print subject Set NStream = NSession.CreateStream HTMLbody = "<p>" & "Hi " & ws.Cells(j, 2).Text & "," & "</p>" & _ vbCrLf & _ "<p>" & Sheets("Email Settings").Cells(2, 2).Text & vbCrLf & _ Sheets("Detail").Cells(j, 1).Text & "</p>" & vbCrLf & _ "<p>" & Sheets("Email Settings").Cells(3, 2).Text & _ "<br>" & Sheets("Email Settings").Cells(4, 2).Text & _ "<br>" & Sheets("Email Settings").Cells(5, 2).Text & _ "<br>" & Sheets("Email Settings").Cells(6, 2).Text & "</p>" & _ "<p>" & Sheets("Email Settings").Cells(9, 2).Text & _ "<br>" & Sheets("Email Settings").Cells(10, 2).Text & _ "<br>" & Sheets("Email Settings").Cells(11, 2).Text & _ "<br>" & Sheets("Email Settings").Cells(12, 2).Text & _ "<br>" & Sheets("Email Settings").Cells(13, 2).Text & _ "<br>" & Sheets("Email Settings").Cells(14, 2).Text & _ "<br>" & Sheets("Email Settings").Cells(15, 2).Text & "</p>" HTML = "<html>" & vbLf & _ "<head>" & vbLf & _ "<meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8""/>" & vbLf & _ "</head>" & vbLf & _ "<body>" & vbLf & _ HTMLbody & _ "</body>" & vbLf & _ "</html>" NSession.ConvertMime = False 'Don't convert MIME to rich text Set NDoc = NDatabase.CreateDocument() With NDoc .Form = "Memo" .subject = subject .SendTo = Split(SendTo, ",") Set NMIMEBody = .CreateMIMEEntity NStream.WriteText HTML NMIMEBody.SetContentFromText NStream, "text/html; charset=UTF-8", ENC_IDENTITY_8BIT .Send False .Save True, False, False End With NSession.ConvertMime = True 'Restore conversion Next j Set NDoc = Nothing Set NSession = Nothing MsgBox "The e-mail has successfully been created and distributed", vbInformation End Sub A: Maybe this code can help you: Sub Send_HTML_Email() Dim cnt_err As Integer: cnt_err = 1 On Error GoTo ErrorHandler Const ENC_IDENTITY_8BIT = 1729 ' Insert the rest of the code here MsgBox "The e-mail has successfully been created and distributed", vbInformation Exit Sub ErrorHandler: ' Insert code to handle the error, e.g. wb.Worksheets("SheetToSaveMailsNotSent").Range("A" & cnt) = RecpName cnt = cnt + 1 ' The next instruction will continue the subroutine execution Resume Next End Sub For more help you can go to this link. HTH ;)
{ "pile_set_name": "StackExchange" }
Q: How can we have a duplicate of an unclear question? This situation is very fishy: Catholic restricted from Communion has been closed as a duplicate of Catholic baptized in another church which itself has been closed as an unclear question. It's true that the OP has had two goes at asking the same question. The second iteration is far more clear and is certainly clear enough now for it not to be closed for that reason. In what world does it make sense to close this one as a duplicate of the first one rather than the other way around? I personally would think that we should never have duplicate pointers to unclear questions - what say you all? A: I agree with your logic; it doesn't make sense to close a question as a duplicate when the target is closed as "unclear what you are asking." That said... This particular situation arose because a new user apparently wasn't familiar with the capability to edit his question. He was kind enough to provide more details in response to the petitions, but he didn't include that information in the original question. And now that both questions have answers of different types, things are a bit messy. I can't really blame close voters here, because the newer question is clearly just a fleshed out version of the original question, and closing the newer question might encourage the user to edit the original one. Now that both have answers, though, we need to reevaluate. The key difference between the two is that the newer question is actually answerable, whereas the original one wasn't. Thus, if anything were to be closed as a duplicate, it should have been the older question, not the newer one (there's no rule saying that the older question is never the duplicate; if the newer question is better in some way, or has better answers, it can take precedence). Thus the best path forward seems to be to open the newer question containing more details, and either 1) leave the older one closed as unclear and leave a comment pointing to the newer question or 2) reopen it and then immediately close it as a duplicate of the newer question. I don't see much practical difference between these two options, except that option #1 is slightly less disruptive. So I've done exactly what I've described. If someone else has a better solution, feel free to suggest it. And as lessons for the future, we can be sure to encourage new users to use the "edit" link to modify their posts, and we can encourage close voters to remember that sometimes it makes sense for older questions to be closed as duplicates of newer questions.
{ "pile_set_name": "StackExchange" }
Q: How to select multiple values in a listbox inside of a gridview editItemTemplate? If I have a dropdownlist I know I can.. SelectedValue='<%#Bind("AgencyID")%>' I want to do the same with a listbox but select multiple values. I was trying to use gridview.FindControl("listbox") but it always is null. Can someone guide me in the right direction? Thanks! EDIT: I am not sure whether I should edit someone else's question or not. But i have the same problem and need a good solution as soon as possible. I have already taken 2 days searching for a good solution for the same. Please see my question I have gone through some of the following links but didn't get much help and still trying to get the solution. Links I have gone through http://www.gutgames.com/post/Using-a-ListBox-Using-SelectionMode-Multiple-with-a-GridView.aspx http://forums.asp.net/t/1003876.aspx/1 A: Problem solved... I just set the selected values when the listbox is being databound.
{ "pile_set_name": "StackExchange" }
Q: Is file /etc/hostname ever used for host name resolution? When setting up a local Wi-Fi network in a small place from an ISP, such as Verizon, using a router and modem, the machines in the network are assigned private IP addresses. In such a local Wi-Fi network, I can use ssh name@<hostname> to access an SSH server on another computer <hostname>, where <hostname> is the output of command hostname. Is the output of hostname resolved to a private IP address, by some DNS server (possibly on the router?)? But I heard that the output of hostname is unrelated to host name resolution by DNS. Then why can I successfully run ssh name@<hostname>, where <hostname> is the output of command hostname? A: There are a couple of mechanisms that could be at work here. Firstly, a system will often include its locally-configured hostname as a DHCP Client Identifier, and the router (which is also the DHCP and DNS server) will dynamically add a DNS record for that client ID matching the IP it gave out for that request. The other likely case is that the system is advertizing it's locally-configured hostname using Multicast DNS Service Discovery (via Bonjour services on macOS, or the avahi daemon on Linux), and many modern distros include mDNS in their NSS lookup chain by default. A: Linux systems using nss-myhostname will resolve the currently configured local hostname (which on some systems comes from /etc/hostname), when you use getaddrinfo/gethostbyname. Systems without nss-myhostname usually have the local hostname listed in /etc/hosts, and resolve the local hostname that way. If you specifically do dns lookups (e.g. with nslookup or dig), that bypasses nss and only uses dns, so nss-myhostname doesn't get a chance to influence the result. If you want ssh@<hostname> to work from other devices, make sure hostname resolves in dns, or is listed in /etc/hosts on those devices.
{ "pile_set_name": "StackExchange" }
Q: How to show check mark in checkbox when using an Alert Let's say I have this: <!DOCTYPE html> <html> <body> <p>Display an alert when checkbox is checked:</p> Checkbox: <input type="checkbox" id="myCheck" onclick="myFunction()"> <p id="text" style="display:none">Checkbox is CHECKED!</p> <script> function myFunction() { var checkBox = document.getElementById("myCheck"); var text = document.getElementById("text"); if (checkBox.checked == true){ alert("check"); } else { alert("not check"); } } </script> </body> </html> The problem is as soon as I click the checkbox, it will show the alert message BUT it doesn't give it a chance to also show the check mark in the checkbox. I DO want it to be an alert and I DO want it to do that as soon as user selects a checkbox but I ALSO want to see the checkmark in chekcbox. I does work in IE 11 but it does not work in Chrome. A: You can fix this with a short setTimeout like so: function myFunction() { var checkBox = document.getElementById("myCheck"); setTimeout(function() { alert(checkBox.checked ? "check" : "not checked"); }, 10); } <p>Display an alert when checkbox is checked:</p> Checkbox: <input type="checkbox" id="myCheck" onclick="myFunction()">
{ "pile_set_name": "StackExchange" }
Q: How to retrieve a byte array from the blobstore? I read the docs, googled around, but still cannot figure how to read a blob as a byte array. I'm able to generate PDF files and store them in the blobstore. I can also serve these blobs for download using serve(), no problems. All this is working fine. Now I want to retrieve one of these blobs, and read it as a byte array to pass it to the Mail API, for sending as Mime attachment. The Mail API accepts only byte arrays as attachment data, as I understood. I saw the read() method of the BufferedInputStream, but it proposes to fetch n bytes. I need to read the full blob at once. I don't know its length before reading it. A: Like this: byte[] myFile = blobstoreService.fetchData(blobKey, index, index + batchSize); Basically you start at index=0 and you loop through this blob until you get an array which is shorter than your batch size.
{ "pile_set_name": "StackExchange" }
Q: Python: Write a new xml file based on a xml template I want to generate a new xml file (new.xml) based on a xml template (template.xml) using xml.etree.ElementTree. The idea is to change only the value of the <name> tag from 'all' to 'New' leaving the rest of the new.xml file looking exactly as the template.xml. I can change the value of the<name> but the new.xml does not look exactly the same as template.xml Here is the template.xml: <?xml version="1.0"?> <example> <version>15.0</version> <lastchange/> <theme>black</theme> <group> <name>all</name> <description><![CDATA[All Users]]></description> <scope>system</scope> <gid>1998</gid> </group> </example> and here is the new.xml: <example> <version>15.0</version> <lastchange /> <theme>black</theme> <group> <name>New</name> <description>All Users</description> <scope>system</scope> <gid>1998</gid> </group> </example> As you can notice, in the new.xml the first line is missing and the value of the <description> tag does not have ![CDATA][] structure. This is the script I wrote and I am using: import xml.etree.ElementTree as ET def load_xml(name): ''' Takes an xml file as input. Outputs ElementTree and element''' tree = ET.parse(name) root = tree.getroot() return tree, root if __name__ == "__main__": # Change and write the new xml tree, root = load_xml('template.xml') group = root.find('group') group.find('name').text = 'New' tree.write('new.xml') Any help? Thank you A: lxml provides compatible API, so you only need to specify strip_cdata=False parameter, and use the exact same codes everywhere else : form lxml import etree as ET def load_xml(name): ''' Takes an xml file as input. Outputs ElementTree and element''' # specify parser setting parser = ET.XMLParser(strip_cdata=False) # pass parser to do the actual parsing tree = ET.parse(name, parser) root = tree.getroot() return tree, root if __name__ == "__main__": # Change and write the new xml tree, root = load_xml('template.xml') group = root.find('group') group.find('name').text = 'New' tree.write('new.xml')
{ "pile_set_name": "StackExchange" }
Q: How to find recursive parent in typescript Employee JSON object var sampleObject = [ { employeeId: 1, employeeName: 'E1', managerId: null }, { employeeId: 2, employeeName: 'E2', managerId: 1 }, { employeeId: 3, employeeName: 'E3', managerId: 1 }, { employeeId: 4, employeeName: 'E4', managerId: 3 } ] In the typescript, how to find the recursive manager id to the top most until manager is null. Suppose, here I want to find the top most Manager of the E4. How to achieve that. Please suggest. Thanks. A: const sampleObject = [ { employeeId: 1, employeeName: 'E1', managerId: null }, { employeeId: 2, employeeName: 'E2', managerId: 1 }, { employeeId: 3, employeeName: 'E3', managerId: 1 }, { employeeId: 4, employeeName: 'E4', managerId: 3 } ] function getRootManager(id: number, fined: number[] = []): number { const employee = sampleObject.find(e => e.employeeId === id); // Prevent 'Maximum call stack size exceeded' if (fined.indexOf(employee.managerId) !== -1) { return employee.employeeId; } if (employee.managerId !== null) { return getRootManager(employee.managerId, [...fined, employee.managerId]) } else { return employee.employeeId; } } console.log(getRootManager(4)) A: You could take an iterative approach with an object for the name/id relations and id/manager relations. function getTop(name) { var top, id = staff.name[name]; while (top = staff.manager[id]) id = top; return id; } var array = [{ employeeId: 1, employeeName: 'E1', managerId: null }, { employeeId: 2, employeeName: 'E2', managerId: 1 }, { employeeId: 3, employeeName: 'E3', managerId: 1 }, { employeeId: 4, employeeName: 'E4', managerId: 3 }], staff = array.reduce((r, { employeeId, employeeName, managerId }) => { r.name[employeeName] = employeeId; r.manager[employeeId] = managerId; return r; }, { manager: {}, name: {} }); console.log(getTop('E4'))
{ "pile_set_name": "StackExchange" }
Q: Which groovy does grails use when run from the command line I did not install Groovy. I have installed Grails and I am able to run my app from the command line! Where is it getting a Groovy compiler? N.B I have STS that has its own Groovy compiler. Are they sharing the STS's Groovy compiler? If that is so, is it also possible to point STS to a Groovy compiler installed by gvm ? A: Grails comes with the version of Groovy that it's compatible with, like all of the other dependencies (e.g. the various Spring jars, Hibernate jars, commons-lang, etc.) They're all in the $GRAILS_HOME/lib directory (the Grails jars and their source and javadoc jars are in the $GRAILS_HOME/dist directory). You only need to install Groovy if you want to run Groovy scripts and programs independently from Grails apps. STS and other IDEs use their own Groovy compiler, but Grails has no integrations with any IDEs other than creating project files.
{ "pile_set_name": "StackExchange" }
Q: Read Properties file in java How do I give absolute path to the properties file. autoamtion_environment_properties = new Properties(); InputStream iStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(("C:\\automation_environment.properties")); This is giving a null pointer exception. If I have this file in project root folder it works, but I need to access it from outside. Any idea what needs to be done? Thanks. A: The file has to be in the CLASSPATH for it to work. Your IDE papers over the difficulty for you, but you'll need to know what you're doing when you don't have the crutch. Include the directory where the .properties files live in your CLASSPATH. A: Why not use a FileInputStream instead of all that crazy Thread stuff? InputStream in = new FileInputStream(new File("C:\\automation_environment.properties")); http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html
{ "pile_set_name": "StackExchange" }
Q: how to disable break indent of a long for-statement? for(my_struct_t *s = users; s != NULL; s = (my_struct_t *)(s->hh.next)) { printf("%d\t%s\n", s->id, s->name); } The above code is indented to the following style by the following command. I'd like to keep the original style so that for-statement is always in the same line. Is there a way to do so in clang-format? $ clang-format -style='{IndentWidth: 8, UseTab: Always, SpaceBeforeParens: Never, IndentCaseLabels: true }' for(my_struct_t *s = users; s != NULL; s = (my_struct_t *)(s->hh.next)) { printf("%d\t%s\n", s->id, s->name); } A: If the for-statement is kept on one line, then (given your input and style options) the line extends to column 81. By default the ColumnLimit is 80. So you can do one of these: Set ColumnLimit to 81 or larger Set ColumnLimit to 0 (indicating that no lines should not be broken due to column limit) Surround the for-statement with // clang-format on and // clang-format off to disable formatting Let clang-format split the for-statement into multiple lines. See the documentation for more details about ColumnLimit.
{ "pile_set_name": "StackExchange" }
Q: Symfony 3 ManyToOne relationship empty related Collection Using Symfony 3.4, I am saving an Entity that has a ManyToOne relationship. In the database the relationship is saved properly but in the Entity the related property remains an empty Collection instead of being populated with the related entities. I need this so I can return a complete JSON object as an API response. Complete means containing also the related properties. I have also tried with fetch=EAGER but it does not change the result. User.php /** * @ORM\OneToMany(targetEntity="PGS", mappedBy="user", fetch="EAGER") */ private $pgs; public function __construct() { $this->pgs = new ArrayCollection(); } PGS.php /** * @ORM\ManyToOne(targetEntity="G", fetch="EAGER") * @ORM\JoinColumn(name="gId", referencedColumnName="id") * @ORM\Id * */ private $g; /** * @ORM\ManyToOne(targetEntity="User", inversedBy="pgs", fetch="EAGER") * @ORM\JoinColumn(name="userId", referencedColumnName="id") * @ORM\Id * */ private $user; /** * @ORM\ManyToOne(targetEntity="S", fetch="EAGER") * @ORM\JoinColumn(name="sId", referencedColumnName="id") * @ORM\Id * */ private $s; /** * @ORM\ManyToOne(targetEntity="P", fetch="EAGER") * @ORM\JoinColumn(name="pId", referencedColumnName="id") * @ORM\Id * */ private $p; To abbreviate the code immagine the 3 entities P, G, and S to have the corresponding OneToMany targeting PGS (they are anyway probably not relevant to this problem). UserManager.php // $user is a valid User entity constructed before. I want to store it. $this->entityManager->persist($user); foreach ($p in $arrayOfP) { // $g and $s are known and valid $pgs = new PGS(); $pgs->setUser($user); $pgs->setG($g); $pgs->setS($s); $pgs->setP($p); $this->entityManager->persist($pgs); } $this->entityManager->flush(); // At this point I would expect the $user object to contain the pgs // Instead I get an empty collection. dump(count($user->getPGS())) // returns 0 // in the DB both User and PGS are properly created What am I missing ? A: Do you have in the PGS entity in setUser method something like this public function setUser(UserInterface $user){ $user->addPgs($this); $this->user = $user; } I think that you have to add, and after that if you dump you should have a collection.
{ "pile_set_name": "StackExchange" }
Q: How do I write good/correct package __init__.py files My package has the following structure: mobilescouter/ __init__.py #1 mapper/ __init__.py #2 lxml/ __init__.py #3 vehiclemapper.py vehiclefeaturemapper.py vehiclefeaturesetmapper.py ... basemapper.py vehicle/ __init__.py #4 vehicle.py vehiclefeature.py vehiclefeaturemapper.py ... I'm not sure how the __init__.py files should be correctly written. The __init__.py #1 looks like: __all__ = ['mapper', 'vehicle'] import mapper import vehicle But how should for example __init__.py #2 look like? Mine is: __all__ = ['basemapper', 'lxml'] from basemaper import * import lxml When should be __all__ used? A: __all__ is very good - it helps guide import statements without automatically importing modules http://docs.python.org/tutorial/modules.html#importing-from-a-package using __all__ and import * is redundant, only __all__ is needed I think one of the most powerful reasons to use import * in an __init__.py to import packages is to be able to refactor a script that has grown into multiple scripts without breaking an existing application. But if you're designing a package from the start. I think it's best to leave __init__.py files empty. for example: foo.py - contains classes related to foo such as fooFactory, tallFoo, shortFoo then the app grows and now it's a whole folder foo/ __init__.py foofactories.py tallFoos.py shortfoos.py mediumfoos.py santaslittlehelperfoo.py superawsomefoo.py anotherfoo.py then the init script can say __all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos', 'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo'] # deprecated to keep older scripts who import this from breaking from foo.foofactories import fooFactory from foo.tallfoos import tallFoo from foo.shortfoos import shortFoo so that a script written to do the following does not break during the change: from foo import fooFactory, tallFoo, shortFoo A: My own __init__.py files are empty more often than not. In particular, I never have a from blah import * as part of __init__.py -- if "importing the package" means getting all sort of classes, functions etc defined directly as part of the package, then I would lexically copy the contents of blah.py into the package's __init__.py instead and remove blah.py (the multiplication of source files does no good here). If you do insist on supporting the import * idioms (eek), then using __all__ (with as miniscule a list of names as you can bring yourself to have in it) may help for damage control. In general, namespaces and explicit imports are good things, and I strong suggest reconsidering any approach based on systematically bypassing either or both concepts!-)
{ "pile_set_name": "StackExchange" }
Q: Duplicate emails using perl MIME::Lite with smtp I have an issue sending emails via MIME::Lite module. I have to set some header parameters (return-path and reply-to) therefore I have to use $msg->send('smtp', $SMTP_HOST); If I understand right in this case the message now sent via Net::SMTP. Unfortunately it results that if an email address is included in both to and cc fields the message is delivered twice. I'm googling for a while now, but I can't figure out what is the reason behind. Can anyone please give me a hint on this? Thank you in advance! A: Mime::Lite just extracts all the recipients from the header, no matter if there are duplicates. They then get used in the dialog to the mail server (e.g. RCTP TO) and if the server sends mails twice if a recipient is given multiple times for the same mail is up to the mail server. Apart from that, why do you include the same recipient as Cc and To anyway?
{ "pile_set_name": "StackExchange" }
Q: Disable Print screen in iOS 7 Regarding this question, it seems that print screen ( either by Home + Sleep or via Assistive Touch menu ) cannot be prevented without using iPhone Configuration Utility. But in this article, it suggests that iOS 7 ( starting from beta 4 ) has a new API to detect screenshot. I tried to look into Apple's iOS 7 documentation but it does not directly mention anything related. Is the new API available in iOS 7 ( official version ) ? A: It is possible to detect screenshot by a new method in UIApplication class, called UIApplicationUserDidTakeScreenshotNotification. Notification will be posted when user presses Home + Sleep to print screen. Available in iOS 7 or above. Reference: UIApplicationUserDidTakeScreenshotNotification docs
{ "pile_set_name": "StackExchange" }
Q: Trigonometric Indentities $\dfrac{1}{\cos x}+ \dfrac{2\cos x}{\cos 2x}$ If $x=\dfrac{\pi}{7}$ Prove that above expression is equal to $4$. I worked a few steps and reached here: $\dfrac{(4\cos^2 x -1)}{\cos x (2\cos^2 x-1)}$ Not able to proceed after this!!! A: $$F=\dfrac{\cos2x+2\cos^2x}{\cos x\cos2x}=\dfrac{3-4\sin^2x}{\cos x\cos2x}$$ If $\sin x\ne0,$ $$F=\dfrac{\sin x(3-4\sin^2x)}{\sin x\cos x\cos2x}=\frac{2\sin3x}{\sin2x\cos2x}=4\cdot\dfrac{\sin3x}{\sin4x}$$ Now $\sin4x=\sin3x$ if $4x=n\pi+(-1)^n3x$ where $n$ is any integer If $n$ is odd $=2m+1,$(say), $7x=(2n+1)\pi, x=\dfrac{(2n+1)\pi}7$ where $n\equiv0,\pm1,\pm2,\pm3\pmod7$ But $n\equiv3\pmod7\implies\sin x=0$ So, $\sin x\ne0\implies n\equiv0,\pm1,\pm2,-3\pmod7$ If $n$ is even $=2m$(say), $x=2m\pi\implies\sin x=?$
{ "pile_set_name": "StackExchange" }
Q: How to fix 'Microsoft' is not defined in Ember CLI Bing Map? In an Ember CLI project, I managed to get the old 'bing-maps-element' working as a Component, but jshint and unit tests complain that "'Microsoft' is not defined". The Microsoft object is a global loaded by a 'veapicore' script (Virtual Earth API) after after the Ember Component tries to reference it, but it actually works OK at runtime. I tried to install the 'ember-cli-bing-map' addon, thinking it might better integrate this global reference but I got a 'not a properly formatted package' error with it so had to remove it. How can I resolve these problems? A: You need to specify the global variables in .jshintrc file. Add Microsoft to the predef array in the file and your jshint errors should go away.
{ "pile_set_name": "StackExchange" }
Q: React.js How to call Axios sequentially? useEffect(() => { new Promise(resolve => { setTimeout(() => { resolve(); /* 신규 로트번호 생성을 위한 다음 auto_increment 가져오기 */ axios .get("http://localhost:8080/api/item/autoId") .then(response => { var output = response && response.data; const newLote = lote; newLote.lote = nowDate + "-" + output; setLote(newLote); }) .catch(response => { console.log(response); }); }, 600); }), new Promise(resolve => { setTimeout(() => { resolve(); //재고조회 (로트번호 검색기능) axios .get("http://localhost:8080/api/item/1") .then(response => { var output = response && response.data; const newLookup = Object.assign({}, lookup); for (var i = 0; i < output.list.length; i++) { var value = output.list[i].lote_id; newLookup.lookup[value] = value; } newLookup.lookup[lote.lote] = lote.lote; setLookup(newLookup); console.log(lookup.lookup); const newState = Object.assign({}, state); newState.columns[1].lookup = lookup.lookup; setState(newState); }) .catch(response => { console.log(response); }); }, 600); }), new Promise(resolve => { setTimeout(() => { resolve(); /* 출고 이력 불러오기 */ axios .get("http://localhost:8080/api/shipping/history/1") .then(response => { var output = response && response.data; const newState = Object.assign({}, state); newState.data = output.list; setState(newState); }) .catch(response => { console.log(response); }); }, 600); }); }, []); The useEffect () function in my function components is shown below. Below is a total of three asynchronous communication. The problem is that those asynchronous communications don't go through the same order each time. How do you proceed with asynchronous communication as shown in the code? A: If you want the outputs strictly ordered as the inputs, You can use p-queue, Promise queue with concurrency control. useEffect(() => { const myPromises = [ () => new Promise(resolve => setTimeout(() => { resolve(); console.log("First(slow)"); }, 5000) ), () => new Promise(resolve => setTimeout(() => { resolve(); console.log("Second(fast)"); }, 100) ), () => new Promise(resolve => setTimeout(() => { resolve(); console.log("Third(slower)"); }, 10000) ) ]; queue.addAll(myPromises); }, [queue]); sandbox Update your code should be something like this useEffect(() => { const myPromises = [ () => axios .get("http://localhost:8080/api/item/autoId") .then(x => console.log(x)), () => axios .get("http://localhost:8080/api/item/1") .then(x => console.log(x)), () => axios .get("http://localhost:8080/api/shipping/history/1") .then(x => console.log(x)) ]; queue.addAll(myPromises); }, [queue]);
{ "pile_set_name": "StackExchange" }
Q: GTK window capture: VPython (OpenGL) application Having read the documentation for VPython and GTK threading, it seems to me that it would be possible to embed VPython graphics within a gtk GUI. I know that it is possible with wx on Windows but I am on Linux and using PyGTK. Now, I have managed to get part of the way. I can embed a VPython window provided that it is spawned a separate process. What I would like is to embed it as a thread. The latter would make GUI events that control the OpenGL easier to implement -- via a thread instead of a socket and network calls. Edit: Apparently nobody knows anything about this... Meh. Here is the code I have. Uncomment the two commented out lines and comment a few obvious others and you can get to the process spawning code. #!/usr/bin/env python # -*- coding: utf-8 -*- import time from visual import * import threading import Queue import gtk import pygtk import re import subprocess class OPenGLThreadClass (threading.Thread): """Thread running the VPython code.""" def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue self.name = 'OpenGLThread' def run (self): gtk.threads_enter() self.scene = display.get_selected() self.scene.title = 'OpenGL test' s = sphere() gtk.threads_leave() #P = subprocess.Popen(['python', 'opengl.py']) time.sleep(2) self.queue.put(self.find_window_id()) self.queue.task_done() def find_window_id (self): """Gets the OpenGL window ID.""" pattern = re.compile('0x[0-9abcdef]{7}') P = subprocess.Popen(['xwininfo', '-name', self.scene.title], #P = subprocess.Popen(['xwininfo', '-name', 'Visual WeldHead'], stdout=subprocess.PIPE) for line in P.stdout.readlines(): match = pattern.findall(line) if len(match): ret = long(match[0], 16) print("OpenGL window id is %d (%s)" % (ret, hex(ret))) return ret class GTKWindowThreadClass (threading.Thread): """Thread running the GTK code.""" def __init__ (self, winID): threading.Thread.__init__(self) self.OpenGLWindowID = winID self.name = 'GTKThread' def run (self): """Draw the GTK GUI.""" gtk.threads_enter() window = gtk.Window() window.show() socket = gtk.Socket() socket.show() window.add(socket) window.connect("destroy", lambda w: gtk.main_quit()) print("Got winID as %d (%s)" % (self.OpenGLWindowID, hex(self.OpenGLWindowID))) socket.add_id(long(self.OpenGLWindowID)) gtk.main() gtk.threads_leave() def main (): thread = {} print("Embedding OpenGL/VPython into GTK GUI") queue = Queue.Queue() thread['OpenGL'] = OPenGLThreadClass(queue) thread['OpenGL'].start() winID = queue.get() print("Got winID as %d (%s)" % (winID, hex(winID))) gtk.gdk.threads_init() thread['GTK'] = GTKWindowThreadClass(winID) thread['GTK'].start() if __name__ == "__main__": main() A: This is the code that works in case anyone cares. #!/usr/bin/env python # -*- coding: utf-8 -*- import subprocess import sys import os import re import time from visual import * def find_window_id (title): """Gets the OpenGL window ID.""" pattern = re.compile('0x[0-9abcdef]{7}') proc = subprocess.Popen(['xwininfo', '-name', title], stdout=subprocess.PIPE, stderr=subprocess.PIPE) errors = proc.stderr.readlines() if errors: return None for line in proc.stdout.readlines(): match = pattern.findall(line) if len(match): return long(match[0], 16) return None class Setting (): """VPython/OpenGL class.""" def __init__ (self, w=256, h=256, title='OpenGL via VPython'): """Initiator.""" self.width = w self.height = h self.title = title self.scene = display.get_selected() self.scene.title = self.title self.scene.width = self.width self.scene.height = self.height self.sphere = sphere() class GTKDisplay (): def __init__ (self, winID): """Initiator: Draws the GTK GUI.""" import gtk import pygtk self.OpenGLWindowID = winID window = gtk.Window() window.show() socket = gtk.Socket() socket.show() window.add(socket) window.connect("destroy", lambda w: gtk.main_quit()) socket.add_id(long(self.OpenGLWindowID)) gtk.main() def main (): """Main entry point.""" name = 'sphere OpenGL window' child_pid = os.fork() if 0 == child_pid: sut = Setting(title=name) else: winID = None while not winID: time.sleep(.1) winID = find_window_id(name) try: gui = GTKDisplay(winID) except KeyboardInterrupt, err: print '\nAdieu monde cruel!' if __name__ == "__main__": main() Note: This does not work under Gnome but works under fvwm2. Go figure...
{ "pile_set_name": "StackExchange" }
Q: How to match the chracters with # in oracle query Incident Table I have Incident Table like below i need to match the client list in client table. How can i do that in oracle ? INCIDENT_ID |CLIENTS_LIST | ------------|-----------------| 56 |A001##A05M##A0AS | Client Table BO_NAME |COMPANYID ----------------------|--------- Test1 |A001 Test2 |A0AS Test3 |A05M Test4 |A0BT Im trying to match the companyid with clients_list but there is no result. Tried Query SELECT DISTINCT INCIDENT_ID, CLIENTS_LIST, REPLACE(CLIENTS_LIST, '##', ',') AS client_id, cl.BO_NAME, COMPANYID FROM incident ir INNER JOIN Client cl ON cl.companyid IN (REPLACE(CLIENTS_LIST, '##', ',')) Expected Output BO_NAME |COMPANYID ----------------------|--------- Test1 |A001 Test2 |A0AS Test3 |A05M A: I see a design problem there, you should always save each value in a separate column, or in a separate table with a 1-to-many relationship. Now, you aren't going to make an efficient query, or at least, as efficient as it could be. With that in mind, you could use LIKE Operator in combination with CROSS JOIN This query is very unnefficient, but it should work: SELECT * FROM incidentTable t, clientTable c WHERE t.IncidentId = 56 AND '#' || t.ClientList || '#' LIKE '%#' || c.CompanyId || '#%'
{ "pile_set_name": "StackExchange" }
Q: Is this video game piece physically playable? This is a video game track that got translated into this piano sheet, the original track was made with software I'm wondering if this middle solo is physically playable? 4/4 tempo: 152 appears to have some parts in mezzo forte, as you can see it uses crescendos and decrescendos that seems too difficult for such tempo but these are vital for the original feeling A: There's nothing impossible in the notation; sure, it's fast, and there's an unhealthy obsession with semiquavers, but I'm pretty sure that it could be played. Could I play it? No. But that's because I'm not motivated enough to practice it. Or actually talented, but that's beside the point. Could the average pianist play it? Maybe. Could a professional? Sure; see Flight of the Bumblebee. The expression is not a big problem. You'll get some of that naturally, as it follows the contour of the melody. And it's not that dramatic anyway. In short, I'm sure someone could play it. Is it you? I don't know, but you might as well give it a go. A: This doesn’t look especially on the verge of impossibility; there are, as just one example, Ligeti piano etudes that are far more difficult than this, and pianists play those. At any rate, there’s nothing problematic about the dynamics at all, it’s weird to suggest that. A: Not really an answer, but I don't have enough rep to make a comment... As the comments stated, the song is Flowering Night from the Touhou series. Yes, it is possible to play such Touhou songs on the piano. Here is someone playing this song (at 1:25 it lines up with the sheet music). He is probably playing it slower than original though. Here is another pianist playing another Touhou song - not the one you have shown, but also having quick notes. That last pianist - marasy - can play a lot of Touhou songs, even the fast ones. Though I can't find a video of him playing Flowering Night in particular, I am sure he would be able to play such a piece.
{ "pile_set_name": "StackExchange" }
Q: How to Load type from string directly into linq expression in C#? This is the definition: public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source); How to replace TResult with something like: Type.GetType("MyClass from assembly"); A: You can't. Generic arguments enforce type security at compile time while the Type.GetType uses reflection and is not known at compile time. What exactly are you trying to achieve? A: You can't do this at compile time if you don't know the type involved, but you could write your own extension method for IEnumerable: public static IEnumerable OfType(this IEnumerable source, Type t) { foreach(object o in source) { if(t.IsAssignableFrom(o.GetType())) yield return o; } }
{ "pile_set_name": "StackExchange" }
Q: Separating XML Values I am working in .Net and Oracle. I am having a XML data in my table. My data is like this.. <Goals> <Reg> <Min>75</Min> <Max>90</Max> </Reg> <Sale> <Min>75</Min> <Max>90</Max> </Sale> </Goals> also have some other columns in that table. I need to fetch this and I should bind this value in gridview. My gridview will have separate columns for these XML. like, Reg Min, Reg Max, Sale Min,Sale Max etc.. How should I separate this XML values? A: You can also do it in the DB: select t.id, xmltype(t.xmltext) .extract('//Reg/Min/text()').getstringval() reg_min, xmltype(t.xmltext) .extract('//Reg/Max/text()').getstringval() reg_max, xmltype(t.xmltext) .extract('//Sale/Min/text()').getstringval() sale_min, xmltype(t.xmltext) .extract('//Sale/Max/text()').getstringval() sale_max from table_name t I used table_name as your table name, and xmltext as the column name which holds your xml (assuming it's a string)
{ "pile_set_name": "StackExchange" }
Q: How to execute code only on test failures with python unittest2? I have some class-based unit tests running in python's unittest2 framework. We're using Selenium WebDriver, which has a convenient save_screenshot() method. I'd like to grab a screenshot in tearDown() for every test failure, to reduce the time spent debugging why a test failed. However, I can't find any way to run code on test failures only. tearDown() is called regardless of whether the test succeeds, and I don't want to clutter our filesystem with hundreds of browser screenshots for tests that succeeded. How would you approach this? A: Found a solution - I can override failureException: @property def failureException(self): class MyFailureException(AssertionError): def __init__(self_, *args, **kwargs): self.b.save_screenshot('%s.png' % self.id()) return super(MyFailureException, self_).__init__(*args, **kwargs) MyFailureException.__name__ = AssertionError.__name__ return MyFailureException This seems incredibly hacky but it seems to work so far. A: Here is similar approach to @craigds answer, but with directory support and better compatibility with Python 3: @property def failureException(self): class MyFailureException(AssertionError): def __init__(self_, *args, **kwargs): screenshot_dir = 'reports/screenshots' if not os.path.exists(screenshot_dir): os.makedirs(screenshot_dir) self.driver.save_screenshot('{0}/{1}.png'.format(screenshot_dir, self.id())) return super(MyFailureException, self_).__init__(*args, **kwargs) MyFailureException.__name__ = AssertionError.__name__ return MyFailureException This was actually found in this blog. I've extended it further more with argparse: parser.add_argument("-r", "--reports-dir", action="store", dest="dir", help="Directory to save screenshots.", default="reports") so the dir can be specified dynamically either by system variable or passed argument: screenshot_dir = os.environ.get('REPORTS_DIR', self.args.dir) + '/screenshots' This is especially useful, if you've additional wrapper to run all your scripts, like a base class.
{ "pile_set_name": "StackExchange" }
Q: Size of wchar_t* for surrogate pair (Unicode character out of BMP) on Windows I have encountered an interesting issue on Windows 8. I tested I can represent Unicode characters which are out of the BMP with wchar_t* strings. The following test code produced unexpected results for me: const wchar_t* s1 = L"a"; const wchar_t* s2 = L"\U0002008A"; // The "Han" character int i1 = sizeof(wchar_t); // i1 == 2, the size of wchar_t on Windows. int i2 = sizeof(s1); // i2 == 4, because of the terminating '\0' (I guess). int i3 = sizeof(s2); // i3 == 4, why? The U+2008A is the Han character, which is out of the Binary Multilingual Pane, so it should be represented by a surrogate pair in UTF-16. Which means - if I understand it correctly - that it should be represented by two wchar_t characters. So I expected sizeof(s2) to be 6 (4 for the two wchar_t-s of the surrogate pair and 2 for the terminating \0). So why is sizeof(s2) == 4? I tested that the s2 string has been constructed correctly, because I've rendered it with DirectWrite, and the Han character was displayed correctly. UPDATE: As Naveen pointed out, I tried to determine the size of the arrays incorrectly. The following code produces correct result: const wchar_t* s1 = L"a"; const wchar_t* s2 = L"\U0002008A"; // The "Han" character int i1 = sizeof(wchar_t); // i1 == 2, the size of wchar_t on Windows. std::wstring str1 (s1); std::wstring str2 (s2); int i2 = str1.size(); // i2 == 1. int i3 = str2.size(); // i3 == 2, because two wchar_t characters needed for the surrogate pair. A: sizeof(s2) returns the number of bytes required to store the pointer s2 or any other pointer, which is 4 bytes on your system. It has nothing to do with the character(s) stored in pointed to by s2. A: sizeof(wchar_t*) is the same as sizeof(void*), in other words the size of a pointer itself. That will always 4 on a 32-bit system, and 8 on a 64-bit system. You need to use wcslen() or lstrlenW() instead of sizeof(): const wchar_t* s1 = L"a"; const wchar_t* s2 = L"\U0002008A"; // The "Han" character int i1 = sizeof(wchar_t); // i1 == 2 int i2 = wcslen(s1); // i2 == 1 int i3 = wcslen(s2); // i3 == 2
{ "pile_set_name": "StackExchange" }
Q: Img src as a php variable What Im trying to do is write a script that grabs the url of thumbnails attached to posts in wordpress. It sounds really easy(as I'm sure the solution is) but I can't seem to get it to work, I keep getting syntax errors no matter what I try. The problem line is the second echo(Img src...). Any help would be greatly appreciated. $image_id = get_post_thumbnail_id(); $image_url = wp_get_attachment_image_src($image_id,'archive-thumb'); $image_url = $image_url[0]; echo "<li class=\"recent-img-widget-li\"><a href='".get_permalink()."'>; echo "<img src=\"".$image_url."\" width=\"120\" height=\"120\">"; echo "</a></li>"; A: Simply enough, you're not closing your first string after get_permalink(). Yo need another quote after the >. A: You never close the first string. You just need a quote before the greater than on the first line (and possibly the second?). Look at the syntax highlighting that SO has. A: A general guideline is to always look at the row above the one that is giving the error. In this case you have forgotten to end the string in the last part of the first echo statement. ...ermalink()."'>; Should be ...ermalink()."'>";
{ "pile_set_name": "StackExchange" }
Q: Does InstallShield Limited Edition Support 64 bit Installer? I just started to learn InstallShield LE because it seems the only "officially" supported installer project. But I have one simple question that I can't even get a absolute answer: does ISLE support building a 64bit installer? I am asking because I found at least two posts saying that it is impossible, like this one: Replacing VS Setup projects with Installshield Limited Edition problematic. However, I can't get a (negative or positive)confirmation from flexera's website. They don't even seem to have a forum for LE version. Anyone has the experience can confirm that? Thanks! A: InstallShield Limited Edition does not support creating 64-bit installations at this time. This is covered in the installed documentation in a topic about upgrading to other versions of InstallShield. It's also implied in the online document "Does InstallShield Limited Edition for Visual Studio 2010 Meet All Your Installation Requirements?" where it mentions "Support for 64-Bit COM Extraction" is not included in the limited edition (this is just one of many aspects of 64-bit installations).
{ "pile_set_name": "StackExchange" }
Q: Getting Facebook Like Box code to trigger again with changed href Somehow I suspect this is very simple, but I'm just looking at it all the wrong way. I am dynamically loading the page name part of the href into the FB like box HTML5 code. This is triggered by clicking a button ('fbtn) - and each button has a different page name attached to it (the buttons and page names are also created dynamically). This works fine in as much as: a) the page names are being passed to the function; and b) first time, the FB code fires correctly and generates a display. When I close the div that displays the Like Box and click a second button (or the same one again), the variable (page name) is being passed, but it seems the FB code is not being fired - so, the div displays, but nothing is in it. The FB code is included inside this function to prevent it running automatically on page load (when the buttons and page names have not been created). Is there some way to re-set the entire function so that on clicking 'close' (as below), the variable function is back in the state it was before the first click (i.e. waiting to be passed a variable page name and to run the FB code)? Thanks for any suggestions. $('#classOne').on('click','.fbtn', function() { fbid = this.value; if (!fbid) { fbid = 'Boo'}; alert('' + fbid + ''); (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=XXXXXXXXXXXXXXX"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); $('#fbLike').html('<div id =closeFB>Close</div><div id=fb-root></div><fb:like-box href=https://www.facebook.com/' + fbid + ' width=900 height=500 show_faces=true stream=true show_border=true header=true></fb:like-box>'); $('#closeFB').stop().animate({height:'20'},50); $('#fbLike').stop().animate({height:'500'},500); $('#closeFB').click(function() { $('#fbLike').html('').stop().animate({height:'0'},500); $('#closeFB').stop().animate({height:'0'},50); }); }); A: Well, at least one solution is to use the FB iframe code. Dynamically altering the href in the iframe src works fine and the Like Box re-loads each time with a different src depending on which button is clicked. While this solves the problem, I'd still be interested in a javascript solution if anyone has one, if only for educational purposes. Thanks!
{ "pile_set_name": "StackExchange" }
Q: Describe all the one dimensional complex representation of the cyclic group $C_n$ . Describe all the one dimensional complex representation of the cyclic group $C_n$ . Which ones are inequivalent? attempt: Any 1 dimensional representation is irreducible. Every complex representation of $C_n$ can be expressed as a direct sum of irreducible reprentations. And by the fundamental theorem of finite abelian groups, $C_n$ is isomorphic to a direct sum of cyclic groups. Can someone please help me? I dont really know what I have to show for the inequivalent part. Any feedback would be really helpful. Thanks A: The irreducible complex representations of $C_n$ are exactly the $1$-dimensional. Each one of them is specified by the requirement that a generator $c\in C_n$ acts (upon the elements of the $1d$ complex vector space) through multiplication by an $n$-th root of unity. Thus, if $\rho:C_n\rightarrow Aut V$ is the representation, then $$\rho(c)\cdot v=e^{2\pi i\frac{k}{n}}v, \ \ \ k=1,2,...,n$$ for a generator $c\in C_n$ and for any $v\in V$. In this way, each $n$-th root of unity provides an irreducible, complex representation of $C_n$ on $V$. These representations are mutually inequivalent. Thus, there are exactly $n$ inequivalent, irreducible, complex representations.
{ "pile_set_name": "StackExchange" }
Q: image of "tab" that is not browser's function I heard a expression "keep tabs". I could find the meaning by dictionary and also found a meaning of "tab": a small flap or strip of material attached to or projecting from something, used to hold, fasten, or manipulate it, or for identification and information. To my mind comes up with the description only vague image, so I want to see the image itself. But I couldn't find the image of a "tab", because all google image search result are tabs that is related to computers. Does anyone know where to find the images of "tabs" in internet? A: These are tabs: They're the little parts of the file folders that are sticking out at the bottom: Sometimes they are removable and can be filled with slips of paper with what the content is: And this is what they look like when they're on the folders:
{ "pile_set_name": "StackExchange" }
Q: How would you connect an iPod library asset to an Audio Queue Service and process with an Audio Unit? I need to process audio that comes from the iPod library. The only way to read an asset for the iPod library is AVAssetReader. To process audio with an Audio Unit it needs to be in stereo format so I have values for the left and right channels. But when I use AVAssetReader to read an asset from the iPod library it does not allow me to get it out in stereo format. It comes out in interleaved format which I do not know how to break into left and right audio channels. To get to where I need to go I would need to do one of the following: Get AVAssetReader to give me an AudioBufferList in stereo format Convert the interleaved data to non-interleaved to get the stereo output I need Send it through Audio Queue Services to get what I need with automatic buffering I seem to be limited by what the existing public API can do and what AVAssetReader supports when reading an iPod library asset. What would you do? How can I get what I need to process with an Audio Unit? Another limitation that I have is that I cannot read an entire song at a time as it would fill up memory and crash the app. This is the reason I want to use the Audio Queue Services. If I can treat the asset from the iPod library as a stream in stereo format then all my requirements would be addressed. Can this even be done? Are there any docs, blogs or articles anywhere that would explain how this could be done? A: Sounds like you have a couple questions stacked in there. When you setups an AVAssetReader you can pass in a dictionary of settings. Here is how I create my AVAssetReaders... AVAssetReader* CreateAssetReaderFromSong(AVURLAsset* songURL) { if([songURL.tracks count] <= 0) return NULL; AVAssetTrack* songTrack = [songURL.tracks objectAtIndex:0]; NSDictionary* outputSettingsDict = [[NSDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithInt:kAudioFormatLinearPCM],AVFormatIDKey, // [NSNumber numberWithInt:AUDIO_SAMPLE_RATE],AVSampleRateKey, /*Not Supported*/ // [NSNumber numberWithInt: 2],AVNumberOfChannelsKey, /*Not Supported*/ [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey, [NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey, [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey, [NSNumber numberWithBool:NO],AVLinearPCMIsNonInterleaved, nil]; NSError* error = nil; AVAssetReader* reader = [[AVAssetReader alloc] initWithAsset:songURL error:&error]; { AVAssetReaderTrackOutput* output = [[AVAssetReaderTrackOutput alloc] initWithTrack:songTrack outputSettings:outputSettingsDict]; [reader addOutput:output]; [output release]; } return reader; } So as far as splitting the Left and Right channel, you can loop over the data based on your 'AVLinearPCMBitDepthKey'. So something like this for 16 bit... for (j=0; j<tBufCopy; j++, pAD+=2) { // Fill the buffers... mProcessingBuffer.Left[(tBlockUsed+j)] = ((sint32)pAD[0]); mProcessingBuffer.Right[(tBlockUsed+j)] = ((sint32)pAD[1]); } Now I assume you need this for your processing. But having the data in interleaved format is really quite nice. You can generally take the straight interleaved format and pass it right back to the AudioQueue or Remote I/O callback and it will play correctly. In order to get the audio playing using the AudioQueue framework the data should follow this flow: AVAssetReader -> NSData Buffer -> AudioQueueBuffer Then in the AudioQueue callback where it asks for more data simply pass the AudioQueueBuffer. Something like... - (void) audioQueueCallback:(AudioQueueRef)aq buffer:(AudioQueueBufferRef)buffer { memcpy(buffer->mAudioData, srcData, mBufferByteSize); //Setup buffer->mAudioDataSize //... AudioQueueEnqueueBuffer(mQueue, buffer, 0 /*CBR*/, 0 /*non compressed*/); }
{ "pile_set_name": "StackExchange" }
Q: Boundary removal of images in Matlab I'm trying to remove boundary from my image in Matlab. I've tried this clc,clear,clf Im=im2double(imread('Im.png')); imshow(Im);title('Original Image') pause(.5) imshow(edge(Im));title('after Sobel') pause(.5) imshow(Im-edge(Im));title('Im-edge(Im)') and the result is but there is two clear problem: The output of the edge by default Sobel contain some inner part of shape. Subtract binary image from gray scale one!(output of edge is binary) any help would be appreciated. Download original image. A: One way I can think of doing this is threshold the image so that you have a solid white object, shrink the object by a little bit. Then, use the slightly decreased object to index into the main object mask and remove this area. Also, increase the area of the intermediate result by a little bit to ensure that you remove the outer edge of the boundary. This will ultimately produce a hollowed out mask which is designed to remove the boundaries of your object within some tolerance while leaving the rest of the image intact. Any values that are true in this mask can be used to remove the boundaries. For reproducibility, I've uploaded your image to Stack Imgur so that we don't have to rely on a third party website to download your image: This "little bit" for shrinking and growing you will have to play around with. I chose 5 pixels as this seems to work. To do the shrinking and growing, use an erosion and dilation respectively with imerode and imdilate respectively and I used a structuring element of a 5 x 5 pixel square. % Read from Stack Imgur directly im = imread('https://i.stack.imgur.com/UJcKA.png'); % Perform Sobel Edge detection sim = edge(im, 'sobel'); % Find the mask of the object mask = im > 5; % Shrink the object se = strel('square', 5); mask_s = imerode(mask, se); % Remove the inner boundary of the object mask(mask_s) = false; % Slightly enlarge now to ensure outer boundary is removed mask = imdilate(mask, se); % Create new image by removing the boundaries of the % edge image sim(mask) = false; % Show the result figure; imshow(sim); We now get this image: You'll have to play around with the Sobel threshold because I actually don't know what you used to get the desired image you want. Suffice it to say that the default threshold does not give what your expected results show.
{ "pile_set_name": "StackExchange" }
Q: NumPy is missing, but fixing the environment variable removed my printer settings? I recently installed regular Python on my workstation in addition to ArcGIS 10.2. Based on various things I found online, it seemed like the consensus was to install the full Python, because there are some libraries that ArcGIS's version of Python can't access. I am a Python noob so am trying to learn as I go. I've surely messed something up, but I don't know how to fix it! I have been getting variations of this error in ArcMap: >>> import numpy Runtime error Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\program files (x86)\arcgis\desktop10.1\arcpy\arcpy\__init__.py", line 24, in <module> from arcpy.toolbox import * File "c:\program files (x86)\arcgis\desktop10.1\arcpy\arcpy\toolbox.py", line 342, in <module> from management import Graph, GraphTemplate File "c:\program files (x86)\arcgis\desktop10.1\arcpy\arcpy\management.py", line 22, in <module> import _management File "c:\program files (x86)\arcgis\desktop10.1\arcpy\arcpy\_management.py", line 14, in <module> import _graph File "c:\program files (x86)\arcgis\desktop10.1\arcpy\arcpy\_graph.py", line 27, in <module> import numpy ImportError: No module named numpy` I followed the directions at this link to set the path variable for Python to the specified library folder in Windows. It worked and I was able to use the tool that I needed. When I opened the .mxd that I'm currently working on, which is an Arch E size, the layout board was letter-sized with the data frame being the Arch E size. When I checked under the print settings, the only page size shown for the plotter was letter size. When I removed the environment variable, my map document was "fixed" and my paper sizes were back. I don't have any other Python folders in the location that the article mentions, C:\Python27\ArcGIS10.2\Lib\site-packages. I'd like to be able to use the full install of Python, but if I have to, I can uninstall it. I didn't have this NumPy error before installing Python, so my guess is that I overwrote something I shouldn't have. How should I go about trying to fix this? A: Based off this in Stack Overflow... You need to find out where your python console is pointing. I am guessing it is pointing to another python.exe that doesn't have the arcpy, numpy or other modules. Open your python console and type this: import sys sys.executable >> directory where your python.exe is..e.g. mine is 'C:\\Python27\\ArcGIS10.3\\python.exe' Here you can tell if you installed another python that modified your path variable away from the ESRI modules. You can go back in and edit it back to the ArcGIS instance if necessary. Hopefully you didn't delete the modules in there to save from installing again. After doing this... edit your question to reflect the new info. The rest below is more information to review and not entirely a solution to your problem. As for your environment variables. You need to always pay close attention when editing these. My suggestion (without going through and re-doing every variable) is to check through your list there and make sure the delimiter ; is in there where it needs to be. I find it easier to select the whole string, copy it, and paste it into Notepad to get a better look at it. Each of those values needs to be separated by a ; and they need to point to a directory. You might find you removed one or did something else that affected other ones in the string. Word of advice, if you are new to those, you should always keep a copy of the original string to revert back to if issues arise. One of the easier things to do if you want to combine these things is install something like Pip or Easy_Install to the ArcGIS python directly. That way when you use them to install stuff like NumPy, it will install to that directory. You may find this post beneficial to your needs, too. I found I wanted to be able to use different python installs together in the command prompt. It can give you an idea of ways to do things differently.
{ "pile_set_name": "StackExchange" }
Q: Learn the sum of two numbers in Tensorflow I'm trying to train a neural network to predict the sum of two numbers. But I don't understand what's wrong with my model. Model consists of 2 inputs, 2 hidden and 1 output layers. Every 1000 iteration I print test execution, but the result is getting smaller and smaller. import numpy as np import tensorflow as tf input_size = 2 hidden_size = 3 out_size = 1 def generate_test_data(): inp = 0.5*np.random.rand(10, 2) oup = np.zeros((10, 1)) for idx, val in enumerate(inp): oup[idx] = np.array([val[0] + val[1]]) return inp, oup def create_network(): x = tf.placeholder(tf.float32, [None, input_size]) w01 = tf.Variable(tf.truncated_normal([input_size, hidden_size], stddev=0.1)) y1 = tf.sigmoid(tf.matmul(tf.sigmoid(x), w01)) w12 = tf.Variable(tf.truncated_normal([hidden_size, out_size], stddev=0.1)) y2 = tf.sigmoid(tf.matmul(y1, w12)) y_ = tf.placeholder(tf.float32, [None, out_size]) return x, y_, y2 def train(x, y_, y2): cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y2) ) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) sess = tf.InteractiveSession() tf.global_variables_initializer().run() # Train for i in range(100000): batch_xs, batch_ys = generate_test_data() sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # Test if i % 1000 == 0: out_batch = sess.run(y2, {x: batch_xs}) inx = 0 print(batch_xs[inx][0], " + ", batch_xs[inx][1], " = ", out_batch[inx][0]) (x, y_, y2) = create_network() train(x, y_, y2) Output every 1000 iteration: 0.37301352864927173 + 0.28949461772342683 = 0.49111518 0.050899466843458474 + 0.006174158992116541 = 0.0025260744 0.3974852369427063 + 0.22402098418952499 = 0.00090828544 0.15735921047969498 + 0.39645077887600294 = 0.0005903727 0.23560825884336228 + 0.29010766384718145 = 0.0004317883 0.4250063393420791 + 0.24181166029062096 = 0.00031525563 = smaller and smaller A: Cross-entropy loss is used for classification problems, while your task is clearly a regression. The computed cross_entropy value doesn't make sense, hence the result. Change your loss to: cross_entropy = tf.reduce_mean( tf.nn.l2_loss(y_ - y2) ) ... and you'll see much more sensible results.
{ "pile_set_name": "StackExchange" }
Q: Taps vs formulas The official site says: A tap is homebrew-speak for a git repository containing extra formulae. But: Why are taps kept separately from regular formulae? Why use the distinction at all? What are the implications of installing software from taps versus regular formulae? I presume brew uses the distinction for a reason, and since they warn the user about it, I would like to know why. A: Why are taps kept separately from regular formulae? Why use the distinction at all? Taps are repositories that contain formulae. All formulae, even 'regular formulae' are stored in a tap. The default tap is mxcl/master. However, 'taps' usually refer to third-party taps. Third-party taps contain formulae that are managed by a third-party, and therefore aren't included in the default since they can be updated at any time by the author. Technically, there is no distinction between regular formulae and taps since regular formulae are in a tap, but that tap is pre-added. What are the implications of installing software from taps versus regular formulae? The formulae in taps aren't verified by Homebrew, and could contain anything. Always exercise caution and verify that the tap is from a legitimate source. In essence, core non-tap formulae are installed on a wider user base and have not only eyes from the maintainers of homebrew watching over them, but crowd sourced eyes which make compromised code less likely to be installed from formulae.
{ "pile_set_name": "StackExchange" }
Q: Store last login timestamp I have a Java application that connects with a MySQL database. I want to add reporting to this application. The first thing i want to track is when are people logging in. For this I have create a lastlogin column in my table. When the user successfully logs in i update it update mytable set lastlogin=Now() where userid='xxxx' 1) Is there a better way to do it? There are many people login into the app. 2) Can MySQL automatically update the timestamp everytime a row is accessed? 3) Is there Reporting library that i can use instead that will do most of the work? A: http://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html The TIMESTAMP data type offers automatic initialization and updating to the current date and time (that is, the current timestamp)
{ "pile_set_name": "StackExchange" }
Q: How to set the colour of my 1st row in my JTable to yellow(or any colour)? I am able to set one column to yellow but I am unable to set a row to yellow. The following code does it for the column: TableColumn col = mytable.getColumnModel().getColumn(0); col.setCellRenderer(new MyTableCellRenderer()); How do I do it for a row please? I have tried the tutorials and examples on the net but it always paints the whole table yellow rather than just one row. Thanks A: what you need to do is generate a custom TableCellRenderer. see this tutorial for detail. your renderer will need to test the row index that is passed in and determine whether it is row 0 or not. public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (row == 0) { setBackground(myBGColor) } ....
{ "pile_set_name": "StackExchange" }
Q: CoreData preparing for eventual migration I have an ipad application that has a simple core data model with two entities. Eventually, I'll be adding a third entity in a update to the app. Is there anything I need to do with the current version of the data model to prepare for eventual migration? A: Not really. In order for migration to work, you'll need to have both versions of the model inside the model at that point. (A model can contain multiple versions, one will be the current).
{ "pile_set_name": "StackExchange" }
Q: Handling physical keyboard's Enter key in SearchView I've implemented a SearchView in my application which is working properly when I hit the search button while I'm using the soft keyboard (using the QueryTextListener): viewHolder.mTextSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { new SearchForEquipmentTask(false, viewHolder.mTextSearch.getQuery().toString()).execute(); return true; } @Override public boolean onQueryTextChange(String newText) { //Log.d(TAG, "Query: " + newText); return false; } }); Now I'm planning to use a physical keyboard for my users to be able to work with the app, but I can't figure out how to fire the search event from the physical keyboard (onQueryTextChange is not getting invoked with that key). Same thing happens when I'm running the emulator in Android Studio. I've tried: viewHolder.mTextSearch.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View view, int i, KeyEvent keyEvent) { Log.d(TAG, "Query: " + keyEvent); return false; } }); But the SearchView seems to ignore the listener for any key... It seems that QueryTextListener is the only way to handle searches, but how to deal with special characters? Should I switch it to EditText which is more flexible? Any idea? A: That's how I've handled it: //Grab de EditText from the SearchView EditText editText = (EditText) viewHolder.mTextSearch .findViewById(android.support.v7.appcompat.R.id.search_src_text); editText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int keyAction, KeyEvent keyEvent) { if ( //Soft keyboard search keyAction == EditorInfo.IME_ACTION_SEARCH || //Physical keyboard enter key (keyEvent != null && KeyEvent.KEYCODE_ENTER == keyEvent.getKeyCode() && keyEvent.getAction() == KeyEvent.ACTION_DOWN)) { new SearchForEquipmentTask(false, viewHolder.mTextSearch .getQuery().toString()).execute(); return true; } return false; } }); Thanks for your help! See also: Grab the EditText element from a SearchView Android: how to make keyboard enter button say "Search" and handle its click?
{ "pile_set_name": "StackExchange" }
Q: How to model natural gas forward price? I'm looking to learn about gas price modeling, in particular models of forward prices. I've studied "classical" mathematical finance, fixed income theory etc. What are good references for stylized facts about gas modeling, successful models and mathematical finance in gas pricing. I am also interested in the estimation part. In all cases particular, but not restricted to forward price modeling. A: Though not exactly spelling out models for natural gas. For natural gas trading I like the book as it explains a lot about how the industry works, and might help you develop models: Trading Natural Gas: Cash, Futures, Options and Swaps Hardcover – January 1, 1997 by Fletcher J. Sturm
{ "pile_set_name": "StackExchange" }
Q: What is the explanation for the basis of Buddhislamic faith in Dune Universe? As a follow-up to a previous Dune question, Buddhislamic religion always struck me as a somewhat strange concept. From my limited (but greater than a random westerner) understanding of both, they seem to be two highly incompatible belief systems, both theologically and philosophically. Is there an in-Universe explanation of how the contradictions between the two source religions are resolved to form Buddhislamism? An alternate valid answer would be a proper analysis (on here or as a link to external source) showing that my limited understanding of both is completely wrong and they are in fact compatible enough that the notion of Buddhislamism is not that strange of a concept. A: Let me think of scenarios through which Buddhism and Islam may merge. In today's world, Islam and Buddhism show a lot of variation, but not enough to seem similar. So let's say that whenever colonization takes place, there is a colony that is populated by Buddhists(majority) and Muslims(minority), being ruled in some form by Muslims. Now a particular ruler wants greater cooperation between the two sides, so he starts making some changes. He orders a "definitive" translation of the Quran in the local language, which conveniently glosses over some aspects of Islam. Buddhism meanwhile has evolved into one of it's forms that recognises gods. Several centuries later, the new Islam has completely rooted out the second. Then along comes a man preaching revolution, who wants to put power into the hands of the people, or so he says. He has a magnetic personality, and people flock to his hill. To unify his sheep, he reveals that Buddhism and Islam are actually the offshoot of the same religion (just look at how similar they are, how can it be otherwise?). And so is born Buddhislam. NOTE : 'Akbar' is the inspiration for the first ruler, mainly because he was in the situation I described, and he was very concerned about religious divisions and intolerance. (He also started his own religion). 'Gandhi' is mainly the inspiration for the second, mainly because he tried to make the Indian freedom movement as inclusive as possible, and thus he spearheaded several kind of religious reforms. (The cynical overtone is mainly for humorous purposes). A: I'm sure your understanding of these religions isn't wrong at all, but consider the following: Sufism is a branch of Islam that emphasizes a direct connection with God. Early Sufis emphasized spiritual practice and rejected luxury. One of their doctrines is "fana," the extinction of consciousness of the self separate from God. On the Buddhist side, Buddhism seems to reject the concept of a personal creator God, but appears to contain the concept of some kind of Godhead. The Buddha is supposed to have said, "There is, O monks, an Unborn, neither become nor created nor formed . . . Were there not, there would be no deliverance from the formed, the made, the compounded." What do you think? Closer than you thought? (All information from Huston Smith's excellent The World's Religions.) A: Been a long time since I read Dune, and I did not read the whole series, so I don't know if I making any big assumptions here. Buddhislamism, as I understand it, will be a mixture of Buddhism and Islam(or maybe Christianity, according to Dampe's comment). Anyways, Islam and Christainity are Abrahamic religions, while Buddhism would properly be called an off-shoot/sibling of Hinduism. The most major difference between the two groups of religion is that in Abrahamic religion, there is a single omnipotent (and as I understand it) kind God (with a capital G). In Hinduism, gods are secondary beings, powerful but mentally not that different from humans and in Buddhism, the existence of God is left to the imagination of the readers (Buddha is said to have declined to go into metaphysics, saying that he does not what happens after death). Islam/Christainity also have authorative books (though their content is open to interpretation) and associated with several forms of rituals, while Buddhism is not so formal. There's no authorative book and rituals associated with Buddhism (though some branches of Buddhism have moved away from this). Buddhism is more a philosophy of life, which can be paraphrased in the sentence - "Suffering is caused by desire, hence let go of it." So you could perhaps merge Buddhism and Islam/Christianity by having a god and changing the books to reflect Buddhist philosophy by adding austerity, non-violence etc. as ideals EDIT1: PS: Not being a Christian/Muslim/Buddhist, I wouldn't know how compatible the philosophies are, but it was Muller (I think) who said that "Christ must have been a Buddhist" or something similar, so I guess Buddhism and Christianity may not be as irreconcilable as people think.
{ "pile_set_name": "StackExchange" }
Q: Can I use an ESP8266 as an MQTT broker? I am making a home automation project based on star topology. What I am trying to achieve is that one of the nodemcu/ESP8266 acts as a server which is accessible for the outside world and other nodemcu/ESP8266 acts as clients which are connected to relays or sensors. Upon receiving the command from the server, the relays must be triggered accordingly and update the status back to the server. I read lots of tutorial via different methods. MQTT seems good but I don't want to use any third party broker like Adafruit. I want to host the web server either on my nodemcu or my web host. The sad part is I don't own a Raspberry Pi. Can I use one of my ESP8266 devices as an MQTT broker, or is there a suitable alternative? A: Technically speaking, yes, an ESP8266 could act as an MQTT broker. In fact, someone has already tried it! By the end of their project, they claimed to have a broker that can bridge to a cloud MQTT broker, with a web interface and a decent amount of uptime. In the comments, they say that their code is proprietary, so you won't be able to use their code exactly, but it does serve as a proof of concept if you really wanted to use an ESP8266. However, using an ESP8266 as a broker is likely to be a lot of effort. Using a Pi, as suggested by MatsK, would be far easier, and although Raspberry Pi units are a little more expensive (between £5 and £25 + postage, depending on which model you choose), you'll save a lot of time. With a Pi, you can just use an established broker like Mosquitto. On an ESP8266, there's no chance that Mosquitto would run, and you'd probably have to write your own broker or use a far less reliable one. Alternatively, you could just connect all your ESP8266s directly to a cloud service like AWS IoT. This simplifies your setup, but does mean that every request is routed through the Internet, and you cannot control devices locally. If your Internet connection breaks using this approach, you'll also have no control over the devices. A: My suggestion would be a mosquitto MQTT broker on a Raspberry Pi. There is an article here https://tech.scargill.net/a-christmas-script/ where Peter Scargill have made a script that installs all necessary components and dependencies. Take a look at Node-red. With it you can create logic to complement your project. Updates: I just found a ESP8266 MQTT broker, freely available. This I have to try.... https://www.youtube.com/watch?v=0K9q4IuB_oA https://github.com/martin-ger/esp_mqtt A: In addition to the answers and comments that recommend using a Raspberry Pi because of the ESP8266’s limited resources, it would generally make sense to use the ESP32’s, the unofficial successor to the ESP8266. Due to being dual-core + 3x more RAM, it fixes WiFi connection issues that increased when user programs increased in size. On the price range it is only a few dollars more expensive than ESP8266 and significantly cheaper than RaspberryPi’s (at least until the zero comes down in price). The other answers should have you covered on the software side.
{ "pile_set_name": "StackExchange" }
Q: How can I have a single data collection of multiple derived types in C#? I'm not sure if I phrased my question appropriately, but consider the following scenario: I have an abstract class called Card. The Card class contains many members. I have two classes that derive from Card called BlueCard and RedCard. To visualize this: public abstract class Card{ //many members } public class BlueCard : Card{ //many members } public class RedCard : Card{ //many members } Now, suppose I have a class Deck. Deck needs to contain a single array of both BlueCard and RedCard. Is there a way to go about this? A: I'm using this approach in a similar situation myself, where an ElementGroup object contains a collection of objects that are either of type Element or of a type deriving from Element. I think something like this should suit your case: public class Deck { public Deck() { _cardArray = new Card[52]; } private Card[] _cardArray; public void DrawCard(int cardNumber) { var card = _cardArray[cardNumber]; if (card.GetType() == typeof(Card)) { // Do something } else if (card.GetType() == typeof(BlueCard)) { // Do something } else if (card.GetType() == typeof(RedCard)) { // Do something } } }
{ "pile_set_name": "StackExchange" }
Q: PM2 and babel always "Port is in use" I has been using PM2 to run and monit node process for awhile and it works fine until I try to use babel. I'm not sure what is the real problem, but when I starting a project with babel, it can't stop showing Port 3000 is already in use. This project is a copy of another one. They are almost the same except the scripts in package.json. "scripts": { "start": "npm run babel | node ./bin/www", "babel": "./node_modules/.bin/babel server -d lib" } and the original is much simpler "scripts": { "start": "node ./bin/www" } I use start the process by run process.json, and add "exec_interpreter": "babel-node" in the project with babel. I also installed some new packages to the copy project including babel, babel-core, babel-loader, react, react-dom, react-hot-loader, webpack and webpack-dev-server. And I changed the code from ES5 to ES6 like that's why I use babel.(yes, I'm trying to use react and transfer to ES6 based on a normal express project) When I reboot my mac and run the original project without babel, everything is fine. Then I stop the process and go on to start the project with babel, it keep throwing Port 3000 is already in use. COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Google 394 brick 14u IPv6 0x432e592f22d3b26b 0t0 TCP localhost:52261->localhost:hbci (CLOSE_WAIT) Google 394 brick 16u IPv6 0x432e592f22d397ab 0t0 TCP localhost:52262->localhost:hbci (CLOSE_WAIT) Google 394 brick 213u IPv6 0x432e592f246f87ab 0t0 TCP localhost:52264->localhost:hbci (CLOSE_WAIT) node 1210 brick 13u IPv6 0x432e592f22d377ab 0t0 TCP *:hbci (LISTEN) I use lsof -i:3000 in shell, it shows there's a node process and 2-3 named Google processes(I'm using chrome) is using the port. Even I killed the process, it reappears(with different pid). I have no idea what's the problem. A: Solved this in GitHub. It is indeed the come case babel thing. One of the workarounds is to use babel's require hook in the entry file. Can read more discussion here: https://github.com/Unitech/pm2/issues/1643
{ "pile_set_name": "StackExchange" }
Q: When and how should code-only answers copied directly from external sites be flagged? Earlier today a question was answered with a code-dump and no explanation or exposition. The code had been copied directly from an external site, without any comment or attribution. The answerer had posted a comment under the main question with a link to the code, which is how I found that the answer had been copied. I flagged the question with a custom moderator flag: This answer is not only a simple code dump, but it is copied and pasted directly from a solution posted on an external site without attribution. I also posted a comment under the answer about this being a code-dump without explanation or attribution, and that it was not the answerer's code, but had been copied from an external site. The answerer responded quickly, saying that it was in fact their code, and that the link was to the answerer's blog. I was in the process of writing a comment to apologize for suggesting that they had posted someone else's code, when the answer (which had 5 downvotes) was removed. Shortly after that, the question was also removed. I was considering retracting the flag, but the answer was removed too quickly, and the flag still seemed to apply given that the answer provided no attribution or context for the copied code. My flag was declined, with the reason: That blog is by the same author. It was not at all obvious, to me at least, that the blog belonged to the answerer until they stated this in the comments. But even granting that the answerer was posting their own code, I thought that posting any content copied from an external site without attribution is cause for a flag, and in this case since there was no context, but only the copied code, it seemed like an obvious flag. Answers which are obvious plagiarism should be flagged. But should answers which consist solely of code copied from an external site be flagged? I was under the impression that there is an unwritten rule that any material copied from any external site must be attributed. Did I flag incorrectly, or was I wrong altogether in flagging this question? A: I don't think this particular declined flag is an indication of wrong action, but rather acknowledgement that this was resolved in opposite way than flag suggested. I would also flag such answer, the only extra step possibly I'd consider is to check author's profile for blog link. Even than I'd expect clear "you can find more details in my blog at ...". Note that according to big meta's link found by abccd: What to do when plagiarism is discovered editing post with link's source would be preferred action.
{ "pile_set_name": "StackExchange" }
Q: Blend 5 Visual State Manager This question relates to VS2012 and Blend 5. What are the rules governing whether or not the visual state manager is available in Blend? I've always been able to access the visual state manager in blend when developing Windows Store Apps in C#/XAML. I'm trying to do the same in Javascript/HTML5 and the visual state manager isn't there. I can actually open C# and Javascript apps in Blend side-by-side and see that the states tab in not available in JS. A: The concept of Visual States is not available when building Store apps with HTML and JavaScript. The "states" pane is only available when building XAML apps (WPF, Silverlight or Windows Store XAML). In the same way the Styles, HTML property and CSS property panes are only available when working on Windows Store HTML apps. You can use Blend to set the CSS classes for different states. You can set the current view orientation on the Device pane. Using the css media queries you can set different properties on a similar class that is used in html. You can do this the same way as you would changing other CSS properties. I hope this screenshot explains it a little further. In this example I set a green color to the filled state and a red one to the snapped state. The media query causes one to be picked over the other. update: I decided to write a tutorial about the subject that goes into a bit more detail.
{ "pile_set_name": "StackExchange" }
Q: Protect file in web root but give access from php I have a situation where I want to protect a file from public access, but enable read and write from php. The file contains sensitive information like passwords. The problem is that I cannot put the file outside the web root (server security restriction on access from php) I would like to avoid mysql database. Also I would try to avoid .htacess files. So if I make a folder, say private, in the web root, and do chmod 700 private Then, if the file to protect is private/data, I do chmod 700 private/file will this be a safe setup? So now I can read and write to the file from php but it is not accessible for the public? Is this a safe setup? A: PHP runs as the same user as the webserver so if PHP can read it, so can your webserver (and vice versa). If you don't want to use .htaccess there is another trick: save the file as a .php file. Even if someone accesses the file from the web they can't see the source, they might just get a white page or maybe an error depending on what exactly is in the file.
{ "pile_set_name": "StackExchange" }
Q: Linking MS Access and database server without installing any additional drivers on our company-website, we have an html-form, where an e-mail is generated via php for consulting reasons - which works fine. My superiors want me to save the information of the html-form into an MS Access-database. I couldn't come up with a solution that directly writes from php into MS Access - so I convinced them to go with MySQL via phpMyAdmin - linking the tables via ODBC in Access. The connection between php and MySQL was easy, and the connection between MS Access and MySQL would've also been: To do that, an ODBC-MySQL-Provider is required for each Client to open the Database, which the IT-department doesn't want to install. We also use an MS SQL Server on an Windows Server - I could also connect php to SQL Server - but in this case we need to install the ODBC SQL Server Provider when linking the tables or the SQL Server Native Clients if we go with Ado. - IT guys: no installation of providers on all clients. My question is: Is there any possible solution for accessing MySQL/SQL Server from MS Access without the installation of ODBC-Providers at all? I have really high pressure on this and can't find anything that could satisfy user-needs and expectations. Thanks in advance Baris Edit: the working php/MySQL-Code - based on mysqli $servername = "----------.de"; $username = "-------"; $password = "--------"; $dbName = "---------"; $port = "-------"; $con= mysqli_connect($servername, $username, $password, $dbName, $port ); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } The following connection-string works for connecting to a server-side ms sqlserver from MS Access with the integrated SQLSRV32.dll-provider. Thanks to GordThompson cs = "Driver={SQL Server};" cs = cs & "Server=ip-adress,port-number;" cs = cs & "Database=database-name;" con.Open cs, "username", "password" Since there is a possiblity to connect to the SQL Server without additional provider, I am going for the PDO/SQLServer-combination, and loading the data based on the connection-string above. A: Since the overriding concern is to avoid installing additional drivers on the client machines and you have a Microsoft SQL Server available to you then you can Have your PHP script write the required information to the SQL Server, and then Create an Access process that retrieves the information from the SQL Server using the "SQL Server" ODBC driver that is installed with every copy of Windows.
{ "pile_set_name": "StackExchange" }
Q: Unable to find the .lit file reader app clit I have some lit files I want to convert from Microsoft reader files to something my other devices can read. My friend says I should have clit, in $ which clit /usr/bin/clit but I cannot find it. I tried locate clit but the results are unrelated. So then I tried sudo apt-get install clit but it says package not found. Is clit a standard package? where can I find it? A: Download Calibre - this will read your LIT format files, and also be able to convert them to other formats. OR you can install the clit program by sudo apt-get install convlit A: The general solution to the question “Which package provides file X?” is to use the in-packages search feature of the official site's Ubuntu Packages Search page. Scroll down to Search the contents of packages (the second search form on the page — using the first is an easy mistake and will give frustrating results). Enter your desired filename in the search field and hit Search, and there it is:
{ "pile_set_name": "StackExchange" }
Q: LINK : fatal error LNK1181:cannot open input file 'C:\OpenSSL-Win64\lib\libeay32.lib' I have windows 7 - 64 bit with Visual studio 2013 ultimate. I am running npm install command and getting below errors: npm info it worked if it ends with ok npm info using [email protected] npm info using [email protected] npm info attempt registry request try #1 at 10:01:07 AM npm http request GET http://registry.npmjs.org/fsevents npm http 304 http://registry.npmjs.org/fsevents npm info attempt registry request try #1 at 10:01:09 AM npm http request GET http://registry.npmjs.org/ursa npm http 304 http://registry.npmjs.org/ursa npm info lifecycle [email protected]~preinstall: [email protected] npm info linkStuff [email protected] npm info lifecycle [email protected]~install: [email protected] > [email protected] install C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa > node-gyp rebuild C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild ) else (node "" rebuild ) gyp info it worked if it ends with ok gyp info using [email protected] gyp info using [email protected] | win32 | x64 gyp info spawn C:\Python27\python.EXE gyp info spawn args [ 'C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\gyp\\gyp_main.py', gyp info spawn args 'binding.gyp', gyp info spawn args '-f', gyp info spawn args 'msvs', gyp info spawn args '-G', gyp info spawn args 'msvs_version=2013', gyp info spawn args '-I', gyp info spawn args 'C:\\Users\\sudhir_kumar05\\mockingbird\\node_modules\\ursa\\build\\config.gypi', gyp info spawn args '-I', gyp info spawn args 'C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\addon.gypi', gyp info spawn args '-I', gyp info spawn args 'C:\\Users\\sudhir_kumar05\\.node-gyp\\5.10.0\\include\\node\\common.gypi', gyp info spawn args '-Dlibrary=shared_library', gyp info spawn args '-Dvisibility=default', gyp info spawn args '-Dnode_root_dir=C:\\Users\\sudhir_kumar05\\.node-gyp\\5.10.0', gyp info spawn args '-Dnode_gyp_dir=C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp', gyp info spawn args '-Dnode_lib_file=node.lib', gyp info spawn args '-Dmodule_root_dir=C:\\Users\\sudhir_kumar05\\mockingbird\\node_modules\\ursa', gyp info spawn args '--depth=.', gyp info spawn args '--no-parallel', gyp info spawn args '--generator-output', gyp info spawn args 'C:\\Users\\sudhir_kumar05\\mockingbird\\node_modules\\ursa\\build', gyp info spawn args '-Goutput_dir=.' ] gyp info spawn C:\Program Files (x86)\MSBuild\12.0\bin\msbuild.exe gyp info spawn args [ 'build/binding.sln', gyp info spawn args '/clp:Verbosity=minimal', gyp info spawn args '/nologo', gyp info spawn args '/p:Configuration=Release;Platform=x64' ] Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch. ursaNative.cc ..\src\ursaNative.cc(157): warning C4244: 'argument' : conversion from 'ssize_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] ..\src\ursaNative.cc(172): warning C4244: 'argument' : conversion from 'ssize_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] ..\src\ursaNative.cc(378): warning C4267: 'initializing' : conversion from 'size_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] ..\src\ursaNative.cc(379): warning C4267: 'initializing' : conversion from 'size_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] ..\src\ursaNative.cc(686): warning C4267: 'argument' : conversion from 'size_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] ..\src\ursaNative.cc(734): warning C4267: 'argument' : conversion from 'size_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] ..\src\ursaNative.cc(779): warning C4267: 'argument' : conversion from 'size_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] ..\src\ursaNative.cc(826): warning C4267: 'argument' : conversion from 'size_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] ..\src\ursaNative.cc(945): warning C4267: 'argument' : conversion from 'size_t' to 'unsigned int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] ..\src\ursaNative.cc(1003): warning C4267: 'argument' : conversion from 'size_t' to 'unsigned int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] win_delay_load_hook.c LINK : fatal error LNK1181: cannot open input file 'C:\OpenSSL-Win64\lib\libeay32.lib' [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] gyp ERR! build error gyp ERR! stack Error: `C:\Program Files (x86)\MSBuild\12.0\bin\msbuild.exe` failed with exit code: 1 gyp ERR! stack at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\build.js:276:23) gyp ERR! stack at emitTwo (events.js:100:13) gyp ERR! stack at ChildProcess.emit (events.js:185:7) gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:204:12) gyp ERR! System Windows_NT 6.1.7601 gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" gyp ERR! cwd C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa gyp ERR! node -v v5.10.0 gyp ERR! node-gyp -v v3.3.1 gyp ERR! not ok npm info lifecycle [email protected]~install: Failed to exec install script npm WARN install:[email protected] [email protected] install: `node-gyp rebuild` npm WARN install:[email protected] Exit status 1 npm info lifecycle [email protected]~preinstall: [email protected] npm info linkStuff [email protected] npm info lifecycle [email protected]~install: [email protected] npm info lifecycle [email protected]~postinstall: [email protected] npm info lifecycle [email protected]~prepublish: [email protected] npm WARN optional Skipping failed optional dependency /chokidar/fsevents: npm WARN notsup Not compatible with your operating system or architecture: [email protected] npm WARN [email protected] requires a peer of kerberos@~0.0 but none was installed. npm info ok I tried running same project in IntelliJ ultimate trial version but getting same error. A: I've had the same trouble and the answer is to read the documentation. OpenSSL (normal, not light) in the same bitness as your Node.js installation. OpenSSL must be installed in the a specific install directory (C:\OpenSSL-Win32 or C:\OpenSSL-Win64) If you get Error: The specified module could not be found., copy libeay32.dll from the OpenSSL bin directory to this module's bin directory, or to Windows\System32. One problem with this - you need 1.0.2 (got here). Version 1.1.0 has no libea32.dll. And successively I've faced following problems installing ursa: node-gyp. Think it was not a real problem, but rebuilt was successful after this compiler. I had VS2010express and again error, but now when installing ursa MSBUILD : error MSB3428: Could not load the Visual C++ component "VCBuild.exe Tried out some recipes but only after VS2013express installation I've gor success and another error SSL. Use Open-SSL 64 1.0.2
{ "pile_set_name": "StackExchange" }