input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
How to add print(.....),println(..) to String scala <pre><code>def logic(n : Int):String = {
var rows = Math.pow(2,n).toInt;
var i = 0;
var str : String = "";
for(i<-0 until rows)
{
var j = n-1 ;
for(j<-(0 to n-1).reverse)
{
str+=(print((i/(Math.pow(2,j).toInt))%2)).toString;
}
str+=(println()).toString;
}
println(str.toString);
return str.toString;}
</code></pre>
<p>When i run println(postfix) i just see a lot of () help me to add print((i/(Math.pow(2,j).toInt))%2) into a string.Thanks</p>
| <p><code>print</code> and <code>println</code> doesn't return a <code>String</code>, it prints to the standard output. The <code>()</code> you are seeing in the console is scala <code>Unit</code> - which is a tuple of 0 elements, since <code>print</code> and <code>println</code> return <code>Unit</code> (which is similar in terms of semantics to javas <code>void</code>). To append the evaluated String value of your calculation simply do this</p>
<pre><code>str += ((1 / (Math.pow(2, 1).toInt)) % 2).toString
</code></pre>
<p>Then use <code>print</code> or <code>println</code> to output it to the standard out:</p>
<pre><code>println(str)
</code></pre>
<p>However, to make your code more idiomatic, I would look at </p>
<ul>
<li><code>mkString</code> on collections (<a href="http://alvinalexander.com/scala/scala-convert-array-to-string-mkstring" rel="nofollow">random resource</a>)</li>
<li>string interpolation (<a href="http://docs.scala-lang.org/overviews/core/string-interpolation.html" rel="nofollow">docs</a>)</li>
</ul>
<p>Looking at those a bit more concise solution:</p>
<pre><code>def truthtable(n: Int) = (0 until Math.pow(2, n).toInt).map { i =>
(0 to n - 1).reverse.map(j => (i / (Math.pow(2, j).toInt)) % 2).mkString("")
}.mkString("\n")
</code></pre>
<p>This returns the truthtable as a String then all you have to do is print it:</p>
<pre><code>println(truthtable(5))
</code></pre>
<p>Note that I didn't check if your algorithm is correct, just refactored what you already have.</p>
|
add unicode link in site map or farsi characters? <p>i have a shop moudle in my site that it cant be inclouded in website sitemap builder , because the sitemap builder doesnt incloude it in site map.
so im making a site map for it separately my self!
there is the main problem! links in main sitemap has perisan characters as you see below:
[Ø³Ø§ÛØª Ù
Ù¾ اÙÚ©ØªØ±ÙØ±Ø§Ù
][1]
but when in copy links from browser for making a handmade site map it will be like:
[Ø³Ø§ÛØª Ù
Ù¾ ÙØ±Ùشگا٠اÙÚ©ØªØ±ÙØ§Ø±Ù
][2]
here is the question!, which one is better? unicode or farsi characters? if farsi, how can i copy links with out braking it in unicodes?
(deleted because i paste samples here):</p>
<p>first form(farsi into some codes!):</p>
<pre><code><url><loc>http://electroeram.ir/shop/product/5/%D8%A8%D8%A7%D8%B3-%D8%A8%D8%A7%D8%B1-160-%D8%A2%D9%85%D9%BE%D8%B1-%D8%B3%D9%87-%D9%81%D8%A7%D8%B2-15-%D8%AE%D8%A7%D9%86%D9%87-%DA%A9%D8%A7%D9%86%D8%A7%D9%84-%D9%BE%D9%84%D8%A7%D8%B3%D8%AA-%D9%85%D8%AF%D9%84-cpd480/</loc><lastmod>2016-10-14</lastmod><priority>0.6</priority></url>
</code></pre>
<p>second form (farsi in regular character):</p>
<pre><code><url><loc>http://electroeram.ir/main/5-تØÙÛÙ-Ù
ØÙ
ÙÙÙ-Û-Ø¬Ø¯ÛØ¯-اÙÚ©ØªØ±ÙØ§Ø±Ù
-از-Ú©Ø§ÙØ§Ù-Ù¾ÙØ§Ø³Øª-Ø§ÛØªØ§ÙÛØ§.html</loc><lastmod>2016-10-16</lastmod><priority>0.6</priority></url>
</code></pre>
| <p>ok as long as there are many big sites like mihandownload that has url encoded urls in site map, there is no need to change the urls into regular ones for sitemaps.
but if you want it, just use this in fire fox:
tyoe about:config
search for network.standard-url and make the scape one, false </p>
|
Could not load file or assembly 'Microsoft.ReportViewer' <p>I understand how this issue is occuring, and I'm confident it's another dll, that needs an older version of 'Microsoft.ReportViewer.WebForms', and I'm guessing the 'Microsoft.ReportViewer.Common' as well.</p>
<p>Before this is marked as a duplicate, answers to this type of question just say to find the offending dll and "dealing with it".</p>
<p>What exactly do I do to allow the offending dll to use the old assembly, while keeping the existing one in my project?</p>
<p>The exact error was:</p>
<pre><code>Could not load file or assembly 'Microsoft.ReportViewer.WebForms,
Version=8.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a'
or one of its dependencies.
The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
</code></pre>
| <p>You can't use 2 versions of the same DLL in a project. It's possible that you are referencing version A of the DLL directly in your project, but that another reference <em>itself</em> makes reference to version B of the DLL. In that case, you have no choice but to either remove the reference with the reference (nested reference), or bring in the version that the nested reference wants to use and use <em>it</em>.</p>
<p>One thing that I find helps in general is that for the properties of my project references, I set "Specific Version" to <code>true</code>. This will help alleviate the application going to the GAC and getting a newer version of the DLL than you want it to.</p>
|
FormIt troubles <p>I have a FormIt form which forks in one website, but it doesn't work at another at all (same as all forms which I have created or copypasted from the manual). If it's on the top level, it works, if it's in the some sublevel menu it doesn't.
The only thing I have found - after I try to send email the wronk url is loaded - instead of:</p>
<pre><code>http://example.com/main-menu/how-to-help-us/informations/test
</code></pre>
<p>I get:</p>
<pre><code>http://example.com/main-menu/how-to-help-us/informations/main-menu/how-to-help-us/informations/test
</code></pre>
<p>My FormIt call is follwing:</p>
<pre><code>[[!FormIt?
&hooks=`FormItSaveForm, email`
&successMessage=`Message sent`
&formName=`cbd_form`
&validate=`name:required,company:required,phone:required,email:email:required`
&emailTpl=`cbdReport`
&emailSubject=`Subject`
&emailTo=`myemail@gmail.com`
]]
</code></pre>
<p>Here is the full code: <a href="http://pastebin.com/8hJTfCX2" rel="nofollow">http://pastebin.com/8hJTfCX2</a></p>
<p>Any ideas what to check?</p>
<p>It's the latest REVO installed. MODX Revolution 2.4.3-pl</p>
| <p>Do you forget to add <code><base href="[[++site_url]]"></code> tag to head of your template?</p>
|
Mock Chef::ReservedNames::Win32::Version.new in Chef unit/rspec test? [continued] <p>Assuming, I have the following recipe:</p>
<p><strong>install_iis:</strong>
</p>
<pre><code>require 'chef/win32/version'
windows_version = Chef::ReservedNames::Win32::Version.new
node.set['iis']['components'] = [
'IIS-HttpErrors',
'IIS-HttpRedirect',
'IIS-HttpLogging',
'IIS-LoggingLibraries',
'IIS-RequestMonitor',
'WAS-WindowsActivationService',
'WAS-ProcessModel',
'IIS-StaticContent',
'IIS-DefaultDocument',
'IIS-DirectoryBrowsing'
]
include_recipe 'iis::default'
include_recipe 'iis::mod_aspnet'
include_recipe 'iis::mod_auth_basic'
include_recipe 'iis::mod_auth_windows'
include_recipe 'iis::mod_compress_static'
include_recipe 'iis::mod_security'
include_recipe 'iis::mod_management'
if windows_version.windows_server_2012_r2?
include_recipe 'iis::mod_aspnet45'
include_recipe 'iis::mod_tracing'
include_recipe 'iis::mod_application_initialization'
end
</code></pre>
<p>I want to be able to test, using chefspec, if the <code>include_recipe</code> methods are running (everything in the <code>if</code> block).</p>
<hr>
<p><strong>After reading:</strong></p>
<blockquote>
<p>Standard RSpec applies so <code>allow(Chef::ReservedNames::Win32::Version).to receive(:new).and_return(double('fake version'))</code> or similar.</p>
<p><strong>Source:</strong> <a href="http://stackoverflow.com/questions/34931987/mock-chefreservednameswin32version-new-in-chef-unit-rspec-test/34936359#34936359">Mock Chef::ReservedNames::Win32::Version.new in Chef unit/rspec test?</a></p>
</blockquote>
<p>I've attempted to modified my <code>install_iis_spec</code> to mock the <code>Chef::ReservedNames::Win32::Version</code>. My spec file now looks like the following:</p>
<p><strong>install_iis_spec:</strong>
</p>
<pre><code>recipes_2012 = [
'iis::mod_aspnet45',
'iis::mod_tracing',
'iis::mod_application_initialization'
]
context 'when on "Windows Server 2012 R2"' do
before do
allow(Chef::ReservedNames::Win32::Version).to receive(:new).and_return(double('6.3'))
end
let(:chef_run) do
runner = ChefSpec::SoloRunner.new(platform: 'windows', version: '2012R2')
runner.converge(described_recipe)
end
should_include_recipe(recipes_2012)
it 'converges successfully' do
expect { chef_run }.to_not raise_error
end
end
</code></pre>
<p><strong>Note<sub>1</sub>:</strong> Assume that the <code>should_include_recipe</code> method works as intended.</p>
<p><strong>Note<sub>2</sub>:</strong> After seeing <code>double('fake version')</code>, I assume I should be putting the value <a href="https://github.com/chef/chef/blob/271d3e4f91e3d158c9112512ac75d0ca51fc928d/lib/chef/win32/version.rb#L54" rel="nofollow"><code>'6.3'</code></a>.</p>
<p>Although, when I run <code>chef exec rspec spec/unit/recipes/install_iis_spec.rb</code> I get the following error:</p>
<p><strong>Console Error:</strong></p>
<pre><code>my_recipe::install_iis when on "Windows Server 2012 R2" runs the 'iis::mod_aspnet45' recipe
Failure/Error: runner.converge(described_recipe)
#<Double "6.3"> received unexpected message :windows_server_2008? with (no args)
# C:/Users/me/AppData/Local/Temp/d20161018-26632-iyzn4f/cookbooks/iis/libraries/helper.rb:44:in `older_than_windows2008r2?'
# C:\Users\me\AppData\Local\Temp\d20161018-26632-iyzn4f\cookbooks\iis\recipes\default.rb:22:in `from_file'
# C:\Users\me\AppData\Local\Temp\d20161018-26632-iyzn4f\cookbooks\my_recipe\recipes\install_iis.rb:23:in `from_file'
# ./spec/unit/recipes/install_iis_spec.rb:61:in `block (3 levels) in <top (required)>'
# ./spec/spec_helper.rb:7:in `block (2 levels) in should_include_recipe'
</code></pre>
<p><strong>Ref:</strong> <a href="https://github.com/chef-cookbooks/iis/blob/b4b503d0721c3f367410901acd5f28453dadeee9/libraries/helper.rb#L44" rel="nofollow">cookbooks/iis/libraries/helper.rb:44:in 'older_than_windows2008r2?'</a>.</p>
<hr>
<p>What value do I have to put, in <code>double('fake version')</code>, in order to target <code>Windows Server 2012R2</code>?</p>
<p>Is there a list of supported versions?</p>
| <p>The <code>'6.3'</code> is just a label for the fake version object. You need to tell it how to respond to methods. In this, it's pretty easy: <code>double('fake version', :windows_server_2008? => false)</code> (or <code>true</code> if you want to pretend to be true). Normally you would do this in a <code>before</code> block, like this:</p>
<pre><code>before do
allow(Chef::ReservedNames::Win32::Version).to receive(:new).and_return(double('fake version', :windows_server_2008? => false))
end
</code></pre>
<p>You can find more info on how to use RSpec in the RSpec documentation or in any of several thousand tutorials I'm sure are available via Google.</p>
|
Create questionnaire with multiple results based on answers <p>I want to create a questionnaire in which I will ask the user 5 questions (maybe more in the future). These questions will have always 2 options and then I would like to show the results based on the different combinations.</p>
<p>Example:</p>
<p>A A B A B = Result A</p>
<p>B A B A B = Result B</p>
<p>A B A B A = Result C</p>
<p>...etc</p>
<p>My idea is to create an array with the different answers and then create a switch per case.</p>
<p>Am I in the good way or do you think there are better solutions? I'm not very advanced programmer but I need to do that using HTML and Javascript.</p>
<p>Thanks in advance for your help!
I.</p>
| <p>This can be done with radio buttons inside of a form. Use Javascript to get the value of the radio buttons and output the result. Here is an example of how you could do one of the questions:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<h3>What do you choose?</h3>
<form action="">
<input type="radio" name="inputs" value="A" id="A" /> A<br>
<input type="radio" name="inputs" value="B" id="B" /> B
</form>
<h3 id="out"></h3>
<button onclick="checkForm()">Submit</button>
<script>
function checkForm() {
if ((document.getElementById("A")).checked) {
(document.getElementById("out")).innerHTML = "Value is A";
}
else {
(document.getElementById("out")).innerHTML = "Value is B";
}
}
</script>
</html></code></pre>
</div>
</div>
</p>
|
LUA : Scene not being created. What is wrong? <p>I'm building a game where I have a start screen and clicking the start button it should take me to the FIRST level. Some stuff happens and then I will be taken to the SECOND level. </p>
<p>However I'm running into problems and can't seem to find a solution.
When I click the start button it seems to get stuck in the create function because i prints out something. I was told you don't have to place anything in the create function and just put everything in the SHOW FUNCTION. Was i mislead?</p>
<p>START SCENE </p>
<pre><code>local composer = require("composer")
local widget = require("widget")
local options = {effect = "fade", time = 800}
local startBtn;
local function start(event)
-- load first scene
composer.gotoScene( "level1", options);
startBtn:removeSelf();
print("Start Game")
end
startBtn = widget.newButton(
{
left = 75,
top = 100,
id = "startBtn",
label = "Start",
onEvent = start
}
)
</code></pre>
<p>When I click the START button it should take me to the FIRST LEVEL which is here
and is where i'm running into problems.</p>
<pre><code>local composer = require( "composer" );
local scene = composer.newScene();
local widget = require ("widget");
function scene:create( event )
local sceneGroup = self.view;
end
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
local params = event.params;
print(params);
if (phase == "will") then
print("Will")
elseif (phase == "did") then
print("Did")
local bg = display.newImage ("bg.png",
display.contentCenterX, display.contentCenterY);
------- ALEX KIDD ---------------------------------
local options =
{
frames = {
{ x = 1, y = 2, width = 16, height = 25}, --frame 1
{ x = 18, y = 2, width = 16, height = 25}, --frame 2
{ x = 35, y = 2, width = 16, height = 25}, --frame 3
{ x = 52, y = 2, width = 16, height = 25}, --frame 4
{ x = 1, y = 54, width = 16, height = 24}, --ready1
{ x = 19, y = 54, width = 16, height = 24}, --ready2
{ x = 37, y = 54, width = 29, height = 24}, -- rock
{ x = 67, y = 54, width = 33, height = 24}, -- scissor
{ x = 101, y = 54, width = 33, height = 24}, -- paper
}
};
local sheet = graphics.newImageSheet( "kidd.png", options );
-- Create animation sequence for animation
local seqData = {
{name = "normal", start=1 , count = 4, time = 800},
{name = "faster", frames={1,2,3,4}, time = 400},
{name = "shake", frames={5,6}, time = 500},
{name = "rock", frames={7}},
{name = "paper", frames={9}},
{name = "scissor", frames={8}},
}
local alex = display.newSprite (sheet, seqData);
alex.x = display.contentCenterX-100;
alex.y = display.contentCenterY+83;
alex.anchorX = 1;
alex.anchorY = 1;
---------- JANKEN ---------------------------------
local jankenOpt =
{
frames = {
{x= 154, y= 13, width= 39, height= 48 }, -- shake1
{x= 195, y= 13, width= 39, height= 48 }, -- shake2
{x= 236, y= 13, width= 32, height= 48 }, -- set
{x= 270, y= 13, width= 16, height= 48 }, --r/p/s
{x= 287, y= 13, width= 16, height= 48 }, --r/p/s
{x= 305, y= 13, width= 15, height= 48 }, --r/p/s
{x= 69, y= 13, width= 41, height= 48 }, --flap1
{x= 110, y= 13, width= 40, height= 48 }, --flap2
}
};
local jankenSheet = graphics.newImageSheet( "chars.png", jankenOpt );
-- Create animation sequence janken
local seqDataJanken = {
{name = "flap", frames={7,8}, time = 500},
{name = "shake", frames={1,2}, time = 500},
{name = "set", frames={3}, time = 10, loopCount=1},
}
local janken = display.newSprite (jankenSheet, seqDataJanken);
janken.x = display.contentCenterX+100;
janken.y = display.contentCenterY+83;
janken.anchorX = 1;
janken.anchorY = 1;
-------------- button setup
local btnOpt =
{
frames = {
{ x = 3, y = 2, width=70, height = 22}, --frame 1
{ x = 78, y = 2, width=70, height = 22}, --frame 2
}
};
local buttonSheet = graphics.newImageSheet( "button.png", btnOpt );
local function foo (wow)
alex:play();
janken:play();
end
local function bar (wow)
alex:pause();
janken:pause();
--alex:setFrame(2); --keep it at this frame
-- NEXT: generate more buttons
end
-- Function to handle button event
local function go( event )
-- event.target is the button widget
print (event.phase, event.target.id)
transition.to(alex, {time=2000, x=170, onStart = foo, onComplete = bar})
end
local btnGo = widget.newButton(
{
x = 200,
y = 20,
id = "btnGo",
label = "Go!",
labelColor = { default={ 0, 0, 0 }, over={ 0, 0, 0 } },
sheet = buttonSheet,
defaultFrame = 1,
overFrame = 2,
onPress = go,
}
);
-------------- play buttons
local function shoot (buttonID)
local randomHand = math.random(4,6);
-- position Janken and draw his hands
janken:setSequence("set");
hand = display.newImage (jankenSheet, randomHand, display.contentCenterX+61, display.contentCenterY+60);
if (buttonID == "btnRock") then
alex:setSequence("rock"); -- just show rock for now
elseif (buttonID == "btnScissor") then
alex:setSequence("scissor"); -- just show rock for now
else
alex:setSequence("paper"); -- just show rock for now
end
end
local function play (event)
if (event.phase == "ended") then
alex:setSequence ("shake");
alex:play();
janken:setSequence("shake");
janken:play();
local t = timer.performWithDelay (1500, function() shoot(event.target.id) end, 1);
print (event.target.id); -- which button was it?
end
end
local btnRock = widget.newButton(
{
x = 80,
y = 20,
id = "btnRock",
label = "Rock",
labelColor = { default={ 0, 0, 0 }, over={ 0, 0, 0 } },
sheet = buttonSheet,
defaultFrame = 1,
overFrame = 2,
onEvent = play,
}
);
local btnPaper = widget.newButton(
{
x = 80,
y = 50,
id = "btnPaper",
label = "Paper",
labelColor = { default={ 0, 0, 0 }, over={ 0, 0, 0 } },
sheet = buttonSheet,
defaultFrame = 1,
overFrame = 2,
onEvent = play,
}
);
local btnScissor = widget.newButton(
{
x = 80,
y = 80,
id = "btnScissor",
label = "Scissor",
labelColor = { default={ 0, 0, 0 }, over={ 0, 0, 0 } },
sheet = buttonSheet,
defaultFrame = 1,
overFrame = 2,
onEvent = play,
}
);
local scoreAlex = display.newText ( {text="Alex: 0", x=230, y=60, fontSize=20});
scoreAlex:setFillColor (0,0,0);
scoreAlex.anchorX = 1;
end
end
function scene:hide( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == "will" ) then
transition.cancel(enemy);
elseif ( phase == "did" ) then
end
end
scene:addEventListener( "create", scene )
scene:addEventListener( "enter", scene )
scene:addEventListener( "hide", scene )
return scene
</code></pre>
| <p>Well, you are adding a listener <code>scene:addEventListener( "enter", scene )</code> which should be <code>scene:addEventListener( "show", scene )</code> (Change enter to show)</p>
<p>Your listener is not even being fired, because it was not added with the correct name.</p>
<p>Composer uses the following events: <a href="https://docs.coronalabs.com/api/event/scene/index.html" rel="nofollow">create, destroy, show, hide</a>.</p>
|
Running echo command without ending ";" <p>I am freaking out because I have always known that every line in PHP should end with "<code>;</code>". My question is simple: Is it possible to run the command <code>echo</code> without ending the line with "<code>;</code>"?</p>
<p>I am sorry if this is a dumb question but I am running this code with multiple <code>echo</code> commands without ending them and everything works just perfectly fine! I just don't understand how is this possible or should it be?</p>
<pre><code> <input name="of_instores[]" id="check<?php echo $row['st_id'] ?>" type="checkbox" value="<?php echo $row['st_id'] ?>">
<label for="check<?php echo $row['st_id'] ?>"><strong><?php echo $row['st_title'] ?></strong> | <?php echo $row['st_city'] ?></label>
</code></pre>
| <p>When this:</p>
<pre><code><?php echo "Hello" ?>
</code></pre>
<p>is executed, the script <strong>ends</strong> at the <code>?></code> or simply <em>implies</em> a <strong>semi-colon</strong>. So you don't need to put a semi-colon for that.</p>
|
Listening datagram socket with any ip and any port number android <p>Hi Am sending broadcast using DatagramSocket with specific port number. Its successfully send message. But when i listening for receive message with open ip address and any port number it throwing sockettimeoutexception. But am connected with the same network.</p>
<p>//manifest</p>
<pre><code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code></pre>
<p>//defined port number globally</p>
<pre><code>int PORT=2739;
</code></pre>
<p>// starting async task</p>
<pre><code>new MyClientTask().execute();
</code></pre>
<p>///async task</p>
<pre><code>public class MyClientTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
new PacketSender().run();
new PacketReceiver().run();
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
</code></pre>
<p>This is my sending request</p>
<pre><code>public class PacketSender implements Runnable {
@Override
public void run() {
DatagramSocket sendSoc = null;
try {
sendSoc = new DatagramSocket();
sendSoc.setBroadcast(true);
sendSoc.setSoTimeout(5000);
sendSoc.setReuseAddress(true);
byte[] ip = prop.ToBuffer();
DatagramPacket packet = new DatagramPacket(ip,
ip.length, getBroadcastIp(), PORT);
Log.d("Sending", packet.getAddress().getHostAddress() + " " + packet.getPort());
sendSoc.send(packet);
sendSoc.close();
} catch (IOException e) {
Log.d("Send", "IOException");
e.printStackTrace();
if (sendSoc != null)
sendSoc.close();
}
}
}
</code></pre>
<p>This is my listening request</p>
<pre><code>public class PacketReceiver implements Runnable {
@Override
public void run() {
DatagramSocket receiveSoc = null;
try {
//here 0 represent any port number including system reserved port number
receiveSoc = new DatagramSocket(0, InetAddress.getByName("0.0.0.0"));
receiveSoc.setBroadcast(false); //also tried with true
receiveSoc.setSoTimeout(5000); //alse tried with removing timeout value
int i = 0;
while (true) {
Log.d("data value", " " + i);
i++;
byte buf[] = new byte[1024];
DatagramPacket pack = new DatagramPacket(buf, buf.length);
try {
receiveSoc.receive(pack);
String message = new String(pack.getData()).trim();
Log.i("test", message + " server ip : " + pack.getAddress().getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
} catch (SocketTimeoutException e) {
Log.d("Main", "SocketTimeoutException");
e.printStackTrace();
receiveSoc.close();
new PacketReceiver().run();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("Response", "IOException");
e.printStackTrace();
}
}
}
</code></pre>
<p>//getting broadcast ip</p>
<pre><code>public InetAddress getBroadcastIp() throws IOException {
DhcpInfo dhcp = myWifiManager.getDhcpInfo();
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);
}
</code></pre>
<p>It can able to receive broadcast message from all host in LAN except the hardware which i want to communicate. I can send broadcast to it.But i cant able to receive broadcast from this particular device. </p>
<p><a href="https://i.stack.imgur.com/x7Hvo.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/x7Hvo.jpg" alt="enter image description here"></a></p>
| <p>Make these changes to your code:</p>
<pre class="lang-java prettyprint-override"><code>public class PacketSender implements Runnable {
@Override
public void run() {
// ...
DatagramPacket packet = new DatagramPacket(ip,
ip.length, InetAddress.getByName("255.255.255.255"), PORT);
// ...
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>public class PacketReceiver implements Runnable {
@Override
public void run() {
// ...
receiveSoc = new DatagramSocket(PORT, InetAddress.getByName("0.0.0.0"));
// ...
}
}
</code></pre>
<p><strong>UPDATE</strong></p>
<p>The <code>MyClientTask</code> code doesn't work because it calls the sender and the receiver sequentially. The sender will send to no one and the receiver will wait forever for no message. You have to call the sender while the receiver is already listening to datagrams.</p>
<p>So, instead of</p>
<pre class="lang-java prettyprint-override"><code>new MyClientTask().execute();
</code></pre>
<p>You'll want something like</p>
<pre class="lang-java prettyprint-override"><code>new Thread(new PacketReceiver()).start();
// Just to make sure that the receiver has started up.
// You'll want to do a different kind of synchronization.
SystemClock.sleep(50);
new Thread(new PacketSender()).start();
</code></pre>
|
create unique file name in sas using guids <p>I am currently trying something along those lines in SAS:</p>
<pre><code>%let PartialString = %sysfunc(uuidgen());
%let OUTFILE = /SomeFolder/FileName_%SYMGET(&PartialString.).csv;
</code></pre>
<p>The second line throws errors.</p>
| <p>You don't need %SYMGET.</p>
<pre><code>50 %let OUTFILE = /SomeFolder/FileName_&PartialString..csv;
51 %put &=outfile;
OUTFILE=/SomeFolder/FileName_077e90fb-4877-67c7-9e86-b1e2779cf868.csv
</code></pre>
|
Converting Returned PHP Data into JavaScript Object <p>I have a dataset that needs to be in the same format as a JavaScript variable like below:</p>
<pre><code>var theData = {
datasets: [
{
label: "My First dataset",
backgroundColor: "rgba(179,181,198,0.2)",
borderColor: "rgba(179,181,198,1)",
data: [65, 59, 90, 81, 56, 55, 40]
},
{
label: "My Second dataset",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
data: [28, 48, 40, 19, 96, 27, 100]
}
],
labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"]
};
</code></pre>
<p>The data is being built in PHP but I can't get it quite like that. </p>
<p>Here is what I have in PHP (sample data, but same method of filling it):</p>
<pre><code>$data = array();
$data['datasets'][1]['label'] = "First Data Set";
$data['datasets'][1]['borderColor'] = "rgba(30, 87, 153, .9)";
$data['datasets'][1]['backgroundColor'] = "rgba(30, 87, 153, .5)";
$data['datasets'][2]['label'] = "Afternoon";
$data['datasets'][2]['borderColor'] = "rgba(41, 137, 216, .9)";
$data['datasets'][2]['backgroundColor'] = "rgba(41, 137, 216, .5)";
// Loop through some foreachs and fill the $data
// Not the actual loop I use but same principle
foreach ($theData as $data)
{
$data['datasets'][1]['data'][] = data;
}
foreach ($otherData as $data)
{
$data['datasets'][2]['data'][] = data;
}
</code></pre>
<p>This is returned back to JavaScript using a <code>json_encode();</code> when I do <code>console.log(JSON.stringify(theData))</code> I get this:</p>
<pre><code>{
"datasets":{
"1":{
"label":"Morning",
"borderColor":"rgba(125, 185, 232, .9)",
"backgroundColor":"rgba(125, 185, 232, .5)",
"borderWidth":1,
"data":[
"24",
0,
0,
"30",
"24",
"36",
"36"
]
},
"2":{
"label":"Afternoon",
"borderColor":"rgba(41, 137, 216, .9)",
"backgroundColor":"rgba(41, 137, 216, .5)",
"borderWidth":1,
"data":[
"24",
0,
0,
"24",
"24",
"30",
"36"
]
}
},
"labels":[
"Sun Aug 14",
"Mon Aug 15",
"Tue Aug 16",
"Wed Aug 17",
"Thu Aug 18",
"Fri Aug 19",
"Sat Aug 20"
]
}
</code></pre>
<p>This is for Chart.js 2.3. The sample data up top is directly from Chart.js sample data. The JSON above is my results. Because they are not identical, the chart is not working. I can I change my PHP to make it more like the sample at the very top?</p>
| <p>Let's start from the top</p>
<ul>
<li><code>theData</code> is an <code>object</code></li>
<li><code>datasets</code> is an <code>array</code> of <code>objects</code></li>
<li><code>labels</code> is an <code>array</code></li>
</ul>
<p>So let's set about building this</p>
<pre><code>$data = array();
$data['datasets'] = array();
$data['datasets'][] = array("label" => "First Data Set",
"borderColor" => "rgba(30, 87, 153, .9)",
"backgroundColor" => "rgba(30, 87, 153, .5)"
);
$data['datasets'][] = array("label" => "Second Data Set",
"borderColor" => "rgba(41, 137, 216, .9)",
"backgroundColor" => "rgba(41, 137, 216, .9)"
);
$data['labels'] = array("Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running");
echo json_encode($data);
</code></pre>
<p>As mentioned, <code>json_encode</code> does all the work for you here once you build the array</p>
<pre><code>{
"datasets": [
{
"label": "First Data Set",
"borderColor": "rgba(30, 87, 153, .9)",
"backgroundColor": "rgba(30, 87, 153, .5)"
},
{
"label": "Second Data Set",
"borderColor": "rgba(41, 137, 216, .9)",
"backgroundColor": "rgba(41, 137, 216, .9)"
}
],
"labels": [
"Eating",
"Drinking",
"Sleeping",
"Designing",
"Coding",
"Cycling",
"Running"
]
}
</code></pre>
|
getJSON allways goes to fail, MVC .NET <p>I'm trying to get a JSON from my controller in ASP.Net MVC. The <code>$.getJSON</code> always goes to the <code>fail</code> function. My controller is working right. The object arrives with the correct data, and builds the JSON ok, with no incorrect data.</p>
<pre><code>public JsonResult Rentabilidad(ObtenerRentabilidadViewModel data)
{
var JsonChart = Json(RentabilidadManager.Rentabilidad(data.DTInicio, data.DTFinal), JsonRequestBehavior.AllowGet);
return JsonChart;
}
</code></pre>
<p>After the request to my controller the JSON jumps directly to the <code>fail</code> part.</p>
<pre><code>$.getJSON('@Url.Action("Rentabilidad")', {
Inicio: fechaInicio,
Final: fechaFinal
}, function (data) {
console.log(data);
}).fail(function (jq,msg,error) {
console.log(jq);
console.log(msg);
console.log(error);
$("#chartdiv").html('<div class="alert alert-danger col-md-12" id="alert">Error! Vuelva a intentarlo. </div>');
Desvanecer3segundos("#alert");
});
</code></pre>
<p>And the console shows:</p>
<pre><code>Object {readyState: 4, responseText: "[{"Ingresos":0,"Egresos":1334,"Proyecto":"proy1","â¦2,"Rentabilidad":Infinity,"BulletSize":Infinity}]", status: 200, statusText: "OK"}
Index:114 parsererror
Index:115 SyntaxError: Unexpected token N in JSON at position 172(â¦)
</code></pre>
<p>Thanks!</p>
| <p>You have some invalid JSON getting parsed:</p>
<p>"Proyecto":"proy1","â¦2,"Rentabilidad"</p>
<p>Notice that the <code>...2</code> has a double quote before it, but no double quote after it. Also, it doesn't have a property name affiliated with it.</p>
|
displaying products from database using php <p>This is a php code for displaying 3 products (from database). It displays products in a raw, but their is a fault that the first product that should appears in the very next raw is missing.</p>
<pre><code><html>
<head>
</head>
<body>
<?php
$connect = mysqli_connect("localhost", "root", "", "shopping") or
die("Please, check your server connection.");
$query = "SELECT item_code, item_name, description, imagename, price FROM
products";
$results = mysqli_query($connect, $query) or die(mysql_error());
echo "<table border=\"0\">";
$x = 1;
echo "<tr>";
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
if ($x <= 3) {
$x = $x + 1;
extract($row);
echo "<td style=\"padding-right:15px;\">";
echo "<a href=itemdetails.php?itemcode=$item_code>";
echo '<img src=' . $imagename . ' style="max-width:220px;max-height:240px;
width:auto;height:auto;"></img><br/>';
echo $item_name . '<br/>';
echo "</a>";
echo '$' . $price . '<br/>';
echo "</td>";
}
else {
$x = 1;
echo "</tr><tr>";
}
}
echo "</table>";
?>
</body>
</html>
</code></pre>
| <p>Assign <code>$x</code> to zero. <code>$x=0;</code> </p>
<p>Complete code:- </p>
<pre><code><html>
<head>
</head>
<body>
<?php
$connect = mysqli_connect("localhost", "root", "", "shopping") or
die("Please, check your server connection.");
$query = "SELECT item_code, item_name, description, imagename, price FROM products";
$results = mysqli_query($connect, $query) or die(mysqli_error());
echo "<table border=\"0\">";
$x=0;
echo "<tr>";
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
if ($x <= 3)
{
$x = $x + 1;
extract($row);
echo "<td style=\"padding-right:15px;\">";
echo "<a href=itemdetails.php?itemcode=$item_code>";
echo '<img src=' . $imagename . ' style="max-width:220px;max-height:240px; width:auto;height:auto;"></img><br/>';
echo $item_name .'<br/>';
echo "</a>";
echo '$'.$price .'<br/>';
echo "</td>";
}
else
{
$x=1;
echo "</tr><tr>";
}
}
echo "</table>";
?>
</body>
</html>
</code></pre>
|
Navigation Drawer - Fragments crashing <p>My app crash everytime I click on fragment (Huawai Nexus 6P, iPhone SE...) What should go wrong? Error is pasted below the picture<a href="https://i.stack.imgur.com/tPUwh.png" rel="nofollow"><img src="https://i.stack.imgur.com/tPUwh.png" alt="enter image description here"></a></p>
<p>I debugged the app, and I got these errors: </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>E/AndroidRuntime: FATAL EXCEPTION: main
Process: sl.povhe.platinet, PID: 3756
java.lang.RuntimeException: sl.povhe.platinet.MainActivity@100ff0c must implement OnFragmentInteractionListener
at sl.povhe.platinet.Nexus6P_Fragment.onAttach(Nexus6P_Fragment.java:83)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1043)
at android.support.v4.app.BackStackRecord.setLastIn(BackStackRecord.java:838)
at android.support.v4.app.BackStackRecord.calculateFragments(BackStackRecord.java:878)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:719)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1677)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:536)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)</code></pre>
</div>
</div>
</p>
<p>What my code looks like:
MainActivity.java:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>package sl.povhe.platinet;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.security.PublicKey;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nexus_6p) {
//Zamenaj fragment
Nexus6P_Fragment fragment = new Nexus6P_Fragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_main, fragment, fragment.getTag()).commit();
} else if (id == R.id.iphone_se) {
//Zamenaj fragment
iPhoneSE fragment = new iPhoneSE();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_main, fragment);
fragmentTransaction.commit();
} else if (id == R.id.sam_a5) {
} else if (id == R.id.sam_core2) {
} else if (id == R.id.nad_2000) {
} else if (id == R.id.pod_2000) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}</code></pre>
</div>
</div>
Nexus6P_Fragment.java:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>package sl.povhe.platinet;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link Nexus6P_Fragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link Nexus6P_Fragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class Nexus6P_Fragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public Nexus6P_Fragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Nexus6P_Fragment.
*/
// TODO: Rename and change types and number of parameters
public static Nexus6P_Fragment newInstance(String param1, String param2) {
Nexus6P_Fragment fragment = new Nexus6P_Fragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_nexus6p, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}</code></pre>
</div>
</div>
</p>
| <p>Implement your activity to OnFragmentInteractionListener. That's why, you check your context in <code>onAttact(Context context)</code> with <code>OnFragmentInteractionListener</code> . But you send activity to <code>onAttach</code> method. </p>
|
Spark transform RDD <p>I have csv file like this on imput:</p>
<pre><code>time,col1,col2,col3
0,5,8,9
1,6,65,3
2,5,8,465,4
3,85,45,8
</code></pre>
<p>number of columns is unknown
and I expect result RDD in format:</p>
<pre><code>(constant,column,time,value)
</code></pre>
<p>that means:
((car1,col1,0,5),(car1,col2,1,8)..)</p>
<p>I have RDDs time, rows and header</p>
<pre><code>class SimpleCSVHeader(header:Array[String]) extends Serializable {
val index = header.zipWithIndex.toMap
def apply(array:Array[String], key:String):String = array(index(key))
}
val constant = "car1"
val csv = sc.textFile("C:\\file.csv")
val data = csv.map(line => line.split(",").map(elem => elem.trim))
val header = new SimpleCSVHeader(data.take(1)(0)) // we build our header with the first line
val rows = data.filter(line => header(line,"time") != "time") // filter the header out
val time = rows.map(row => header(row,"time"))
</code></pre>
<p>but I'm not sure how to create result RDD from that</p>
| <p>My suggetion is to use DataFrame rather than RDD for your scenario. But I tired to give you working solution which is subjected to volume of data. </p>
<pre><code> val lines = Array("time,col1,col2,col3", "0,5,8,9", "1,6,65,3", "2,5,8,465,4")
val sc = prepareConfig()
val baseRDD = sc.parallelize(lines)
val columList = baseRDD.take(1)
//Prepare column list. this code can be avoided if you use DataFrames
val map = scala.collection.mutable.Map[Int, String]()
columList.foreach { x =>
{
var index: Int = 0
x.split(",").foreach { x =>
{
index += 1
map += (index -> x)
}
}
}
}
val mapRDD = baseRDD.flatMap { line =>
{
val splits = line.split(",")
//Replace Tuples with your case classes
Array(("car1", map(2), splits(0), splits(1)), ("car1", map(3), splits(0), splits(2)), ("car1", map(4), splits(0), splits(3)))
}
}
mapRDD.collect().foreach(f => println(f))
</code></pre>
<p>Result:</p>
<blockquote>
<p>(car1,col1,0,5) (car1,col2,0,8) (car1,col3,0,9) (car1,col1,1,6)
(car1,col2,1,65) (car1,col3,1,3) (car1,col1,2,5) (car1,col2,2,8)
(car1,col3,2,465)</p>
</blockquote>
|
Optimized way to find Padovan numbers <p>What is the most optimized way to find <a href="https://en.wikipedia.org/wiki/Padovan_sequence" rel="nofollow">Padovan number</a>?
This is what I have currently.
Even though it returns correct result, I want to know what is the quickest method possible.</p>
<pre><code> long Sum = 0;
public long Get(int number)
{
Sum = 0;
if (number == 0 || number == 1 || number == 2)
return 1;
return GetPadovanAlt(number);
}
public long GetPadovanAlt(int n)
{
if(n == 0 || n == 1 || n == 2)
return 1;
return GetPadovanAlt(n - 2) + GetPadovanAlt(n - 3);
}
</code></pre>
| <p>You are doing more work than you need by using recursion. When you calculate <code>GetPadovan(42)</code> you fire off a binary tree of recursions, which will include sub-calls like <code>GetPadovan(12)</code>. That <code>GetPadovan(12)</code> will be called many times on many branches of the recursion tree. Put in something like <code>if (n == 12) then print("*");</code> to see how many.</p>
<p>When you calculate a specific Padovan number, store it and retrieve the stored number for second and subsequent calls. Alternatively switch to a non-recursive calculation: start from Padovan(3) and work up, keeping track of four numbers: P(n), P(n-1), P(n-2) and P(n-3) as you proceed.</p>
<p>ETA: running a quick program, <code>GetPadovan(42)</code> calls <code>GetPadovan(12)</code> 1897 times. Recursion is definitely not the fastest way to go.</p>
|
How to select all dates without data using JOIN SQLs in MySQL? <p>I have 3 tables, users, sites, and site_traffic, respectively. The users table contains the name of the user and other details about the user. Each user has 1 or more sites which is stored in the sites table. Now every site has its own traffic data.</p>
<p>What I am trying to accomplish to select all the dates that has no traffic data for each site for all users. This should display all the user's names, the site_ids of each user and the date that has no data for each of those sites.</p>
<p>As of this query I am able to get the dates that have no data just for 1 specific user. How do I modify this query to list all the users and their sites and the dates that have no data for each site.</p>
<p>Here's my query:</p>
<pre><code>SELECT b.dates_without_data
FROM (
SELECT a.dates AS dates_without_data
FROM (
SELECT CURDATE() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as dates
FROM (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) as a
CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) as b
CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) as c
) a
WHERE a.dates >= DATE_SUB(DATE_SUB(NOW(),INTERVAL 1 DAY), INTERVAL 35 DAY)
) b
WHERE b.dates_without_data NOT IN (
SELECT recorded_on
FROM site_traffic, sites, users
WHERE site_traffic.site_id = sites.site_id
AND sites.user_id = users.user_id
AND users.user_id = 1
)
AND b.dates_without_data < DATE_SUB(NOW(),INTERVAL 1 DAY)
ORDER BY b.dates_without_data ASC
</code></pre>
<p>Thanks for your help guys.</p>
| <p>I would use an anti-join pattern.</p>
<p>First, do a cross join operation between the generated list of possible dates and all sites. That gives us rows for every site, for every day. Then go ahead and do the join to the users table.</p>
<p>The trick is the anti-join. We take that set of all sites and all days, and then "match" to rows in site_traffic. We just want to return the rows that don't have a match. We can do that with an outer join, and then add a condition in the WHERE clause that excludes a row if it found a match. Leaving only rows that didn't have a match.</p>
<p>Something like this:</p>
<pre><code> SELECT s.site_id
, u.user_id
, d.dt AS date_without_data
FROM (
SELECT DATE(NOW()) - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY AS dt
FROM (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) as a
CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) as b
CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) as c
HAVING dt >= DATE(NOW()) + INTERVAL -1-35 DAY
AND dt < DATE(NOW()) + INTERVAL -1 DAY
) d
CROSS
JOIN site s
JOIN users u
ON u.user_id = s.user_id
LEFT
JOIN site_traffic t
ON t.site_id = s.site_id
ON t.recorded_on >= d.dt
AND t.recorded_on < d.dt + INTERVAL 1 DAY
WHERE t.site_id IS NULL
ORDER BY s.site_id, u.user_id
</code></pre>
<p>The trick there is the condition in the WHERE clause. Any rows that found matching rows in <code>site_traffic</code> will have a non-NULL value for <code>site_id</code>. (The equality comparison to <code>site_id</code> in the join condition guarantees us that.) So if we exclude all rows that have non-NULL values, we are left with the rows that didn't have a match.</p>
<p>(I assumed that recorded_on was a datetime, so I used a range comparison... to match any value of <code>recorded_on</code> within the given date. If <code>recorded_on</code> is actually a <code>date</code> (with no time) then we could just do a simpler equality comparison.)</p>
<p>Add to the SELECT list whatever expressions you need, from the <code>u</code> and <code>s</code> tables.</p>
<p>Some people suggest that the inline view <code>d</code> (to generate a list of "all dates") looks kind of messy. But I'm fine with it.</p>
<p>It would be nice if MySQL provided a table valued function, or some other "prettier" mechanism for generating a series of integer values.</p>
<p>I would include all of the conditions on date within the view query itself, get it done inside the view, and not have to muck with the outer query.</p>
|
Checkbox positioning center instead of left <p>I am creating a sign in form and I added a remember me checkbox. For some reason I cannot get the checkbox to align left. It is centering in the middle of the form. Does anyone see what I am doing wrong?</p>
<p>Also, side note...why is my submit button not the same size as my other input text boxes?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#sign-in-form {
width: 400px;
height: auto;
padding: 50px 30px;
margin: auto;
border-radius: 3px;
background: rgba(115,155,175,0.2);
}
#sign-in-form input {
width: 100%;
padding: 8px 6px;
margin: 22px auto;
display: block;
font-size: 1.4em;
border-radius: 3px;
border: none;
}
#sign-in-form input[type="checkbox"] {
padding: 7px;
text-align: left;
}
#sign-in-form input[type="submit"] {
background: #4FCBFE;
color: #FFF;
border: none;
border-radius: 3px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="sign-in-form">
<input type="text" name="username" placeholder="User Name" autocomplete="on" required>
<input type="password" name="password" placeholder="Password" autocomplete="off" required>
<label><input type="checkbox" name="remember" id="remember">Remember me</label>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input type="submit" value="Sign In">
</div></code></pre>
</div>
</div>
</p>
| <p>You should set the <code>width</code> to <code>auto</code> and add <code>margin-left: 0</code></p>
<pre><code>#sign-in-form input[type="checkbox"] {
padding: 7px;
text-align: left;
width: auto;
margin-left: 0;
}
</code></pre>
<p>Here is the working snippet.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#sign-in-form {
width: 400px;
height: auto;
padding: 50px 30px;
margin: auto;
border-radius: 3px;
background: rgba(115,155,175,0.2);
}
#sign-in-form input {
width: 100%;
padding: 8px 6px;
margin: 22px auto;
display: block;
font-size: 1.4em;
border-radius: 3px;
border: none;
}
#sign-in-form input[type="checkbox"] {
padding: 7px;
text-align: left;
width: auto;
margin-left: 0;
}
#sign-in-form input[type="submit"] {
background: #4FCBFE;
color: #FFF;
border: none;
border-radius: 3px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="sign-in-form">
<input type="text" name="username" placeholder="User Name" autocomplete="on" required>
<input type="password" name="password" placeholder="Password" autocomplete="off" required>
<label><input type="checkbox" name="remember" id="remember">Remember me</label>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input type="submit" value="Sign In">
</div></code></pre>
</div>
</div>
</p>
<p>I think this is the result you are looking for:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#sign-in-form {
width: 400px;
height: auto;
padding: 50px 30px;
margin: auto;
border-radius: 3px;
background: rgba(115,155,175,0.2);
}
#sign-in-form input {
width: 100%;
padding: 8px 6px;
margin: 22px auto;
display: block;
font-size: 1.4em;
border-radius: 3px;
border: none;
}
#sign-in-form input[type="checkbox"] {
padding: 7px;
text-align: left;
width: auto;
display: inline-block;
margin: 5px 5px 0 0;
}
#sign-in-form input[type="submit"] {
background: #4FCBFE;
color: #FFF;
border: none;
border-radius: 3px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="sign-in-form">
<input type="text" name="username" placeholder="User Name" autocomplete="on" required>
<input type="password" name="password" placeholder="Password" autocomplete="off" required>
<label><input type="checkbox" name="remember" id="remember">Remember me</label>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input type="submit" value="Sign In">
</div></code></pre>
</div>
</div>
</p>
|
Aurelia compose element view model, configureRouter not being called <p>I have a parent view with routing (view):</p>
<pre><code><div class="render-body ${nav.hide === true?'hide':''}">
<router-view class="router-view flex"></router-view>
<div class="right-flyout ${rightFlyout.show?'show':''}">
<i click.delegate="rightFlyoutCloseClick()" class="fa fa-close right- flyout-close"></i>
<compose class="add-widget-container flex" view-model="../add- widget/add-widget"></compose>
</div><!-- right-flyout -->
</div><!-- render-body -->
</code></pre>
<p>parent (view model):</p>
<pre><code>configureRouter(config, router){
this.router = router;
config.title = "NexLP Dashboard";
config.map([
{ route:['', 'insights'], moduleId:'../insights/insights', nav: true, title: 'insights' },
{ route:'investigate', moduleId:'../investigate/investigate', nav: true, title: 'investigate' },
{ route:'research', moduleId:'../research/research', nav: true, title: 'research' }
]);
}//configureRouter()
</code></pre>
<p>then in my view model for my compose element (add-widget module) the configureRouter is never being called but it is loading the module because the html is rendering to the page:</p>
<pre><code>export class AddWidget{
configureRouter(config, router){
console.log('in configureRouter in add-widget');
console.log(router);
this.router = router;
router.title = 'add widget';
config = config;
config.map([
{ route:['', 'chart'], moduleId:'./chart', nav: true, title: 'chart', name: 'chart' },
{ route:'gecko', moduleId:'./gecko', nav: true, title: 'gecko', name: 'gecko' },
{ route:'list', moduleId:'./list', nav: true, title: 'list', name: 'list' }
]);
}//configureRouter()
constructor(){
console.log('add widget ctor');
}//constructor()
}//class AddWidget
</code></pre>
<p>view:</p>
<pre><code> <template>
add template
<ul class="add-widget-nav flex">
<li repeat.for="route of router.navigation">
${route.title}
</li>
</ul>
</code></pre>
<p></p>
<p>the two console.log()'s never get called. So I have surmised that the consfigureRouter() is never getting called. Why would this be?</p>
| <p>Custom Elements don't support child routers, only pages.</p>
<p>Also, you are misusing the <code>compose</code> element here. You have a statically determined view and viewmodel, so there is no need to use the <code>compose</code> element.</p>
|
Find missing data indices using python <p>What is the optimum way to return indices where 1-d array has missing data. The missing data is represented by zeros. The data may be genuinely zero but not missing. We only want to return indices where data is zero for more than or equal to 3 places at a time. For example for array [1,2,3,4,0,1,2,3,0,0,0,1,2,3] the function should only return indices for second segment where there are zeros and not the first instance.</p>
<p>This is actually an interview question :) challenge is to do most effeciently in one line</p>
| <p>Keep track of the count of zeros in the current run. Then if a run finishes that has at least three zeros calculate the indexes.</p>
<pre><code>def find_dx_of_missing(a):
runsize = 3 # 3 or more, change to 4 if your need "more than 3"
zcount = 0
for i, n in enumerate(a):
if n == 0:
zcount += 1
else:
if zcount >= runsize:
for j in range(i - zcount, i):
yield j
zcount = 0
if zcount >= runsize: # needed if sequence ends with missing
i += 1
for j in range(i - zcount, i):
yield j
</code></pre>
<p>Examples:</p>
<pre><code>>>> a = [1,2,3,4,0,1,2,3,0,0,0,1,2,3]
>>> list(find_dx_of_missing(a))
[8, 9, 10]
>>> a = [0,0,0,3,0,5,0,0,0,0,10,0,0,0,0,0]
>>> list(find_dx_of_missing(a))
[0, 1, 2, 6, 7, 8, 9, 11, 12, 13, 14, 15]
</code></pre>
<p><strong>Edit:</strong> Since you need a one liner here are two candidates assuming <code>a</code> is your list and <code>n</code> is the smallest run of zeros that count as missing data:</p>
<pre><code>[v for vals in (list(vals) for iszeros, vals in itertools.groupby(xrange(len(a)), lambda dx, a=a: a[dx]==0) if iszeros) for v in vals if len(vals) >= n]
</code></pre>
<p>Or</p>
<pre><code>sorted({dx for i in xrange(len(a)-n+1) for dx in xrange(i, i+n) if set(a[i:i+n]) == {0}})
</code></pre>
|
post file from HDFS using Curl <p>How can I post a file from HDFS using Curl ?</p>
<pre><code>curl --data-binary @/user/file.txt 'http://127.0.0.1/update'
</code></pre>
<p>this works but now I have put my file in HDFS are they any way to use curl to post the file in hdfs</p>
| <p>You can use HDFS REST APIs to do this. Refer <a href="http://hadoop.apache.org/docs/r2.7.2/hadoop-project-dist/hadoop-hdfs/WebHDFS.html#Create_and_Write_to_a_File" rel="nofollow">this</a>.</p>
|
Updating specific columns not all model entities <p>Zend 1.8 Geeks!</p>
<p>I always use model_mapper to update insert and fetch data from the db by this example :</p>
<pre><code> $a=somthin;
$y=qwe;
$dataMapper = new model_mapper_data();
$dataModel = new model_data();
$dataEntity=$dataModel->AA=$a ;
=> $dataMapper->update($dataEntity,'x'=$y);
</code></pre>
<p>Now on the last line the Mapper generates a query to update all table row columns AA and rest stored in the data-model where 'x'=$y.</p>
<p>isn't there a way to force the Mapper to update specific columns only?</p>
| <p>Well all what you need is to not give the update method the model entity Since the model initialize objects for all of the columns .</p>
<p>Just give it an array of the columns names you would like to modify and Pair them to their values like below :</p>
<pre><code>Mapper->update('column_name'=>value);
</code></pre>
|
Solving normal equation gives different coefficients from using `lm`? <p>I wanted to compute a simple regression using the <code>lm</code> and plain matrix algebra. However, my regression coefficients obtained from matrix algebra are only half of those obtained from using the <code>lm</code> and I have no clue why.</p>
<p>Here's the code</p>
<pre><code>boot_example <- data.frame(
x1 = c(1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L),
x2 = c(0L, 0L, 0L, 1L, 1L, 1L, 0L, 0L, 0L),
x3 = c(1L, 0L, 0L, 1L, 0L, 0L, 1L, 0L, 0L),
x4 = c(0L, 1L, 0L, 0L, 1L, 0L, 0L, 1L, 0L),
x5 = c(1L, 0L, 0L, 0L, 0L, 1L, 0L, 1L, 0L),
x6 = c(0L, 1L, 0L, 1L, 0L, 0L, 0L, 0L, 1L),
preference_rating = c(9L, 7L, 5L, 6L, 5L, 6L, 5L, 7L, 6L)
)
dummy_regression <- lm("preference_rating ~ x1+x2+x3+x4+x5+x6", data = boot_example)
dummy_regression
Call:
lm(formula = "preference_rating ~ x1+x2+x3+x4+x5+x6", data = boot_example)
Coefficients:
(Intercept) x1 x2 x3 x4 x5 x6
4.2222 1.0000 -0.3333 1.0000 0.6667 2.3333 1.3333
###The same by matrix algebra
X <- matrix(c(
c(1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L), #upper var
c(0L, 0L, 0L, 1L, 1L, 1L, 0L, 0L, 0L), #upper var
c(1L, 0L, 0L, 1L, 0L, 0L, 1L, 0L, 0L), #country var
c(0L, 1L, 0L, 0L, 1L, 0L, 0L, 1L, 0L), #country var
c(1L, 0L, 0L, 0L, 0L, 1L, 0L, 1L, 0L), #price var
c(0L, 1L, 0L, 1L, 0L, 0L, 0L, 0L, 1L) #price var
),
nrow = 9, ncol=6)
Y <- c(9L, 7L, 5L, 6L, 5L, 6L, 5L, 7L, 6L)
#Using standardized (mean=0, std=1) "z" -transformation Z = (X-mean(X))/sd(X) for all predictors
X_std <- apply(X, MARGIN = 2, FUN = function(x){(x-mean(x))/sd(x)})
##If constant shall be computed as well, uncomment next line
#X_std <- cbind(c(rep(1,9)),X_std)
#using matrix algebra formula
solve(t(X_std) %*% X_std) %*% (t(X_std) %*% Y)
[,1]
[1,] 0.5000000
[2,] -0.1666667
[3,] 0.5000000
[4,] 0.3333333
[5,] 1.1666667
[6,] 0.6666667
</code></pre>
<p>Does anyone see the error in my matrix computation?</p>
<p>Thank you in advance!</p>
| <p><code>lm</code> is not performing standardization. If you want to obtain the same result by <code>lm</code>, you need:</p>
<pre><code>X1 <- cbind(1, X) ## include intercept
solve(crossprod(X1), crossprod(X1,Y))
# [,1]
#[1,] 4.2222222
#[2,] 1.0000000
#[3,] -0.3333333
#[4,] 1.0000000
#[5,] 0.6666667
#[6,] 2.3333333
#[7,] 1.3333333
</code></pre>
<p>I don't want to repeat that we should use <code>crossprod</code>. See the "follow-up" part of <a href="http://stackoverflow.com/a/39864889/4891738">Ridge regression with <code>glmnet</code> gives different coefficients than what I compute by âtextbook definitionâ?</a></p>
|
Select2 not displayed when added dynamically for the first time <p>I am working with Jquery and I have a use case to add some elements dynamically on a button click.</p>
<p>While adding the 'select' dynamically, the select2 is not displayed when the add button is clicked for the first time, instead, a simple 'select' is displayed, and when we click on add button again, all the previous 'select' get formatted to select2.</p>
<p>I needed that when we click the add button, the first generated selects should also get the select2.</p>
<p>Following is the script:</p>
<pre><code>var container = $(document.createElement('div')).css({
padding: '5px', margin: '20px', width: '400px', border: '1px solid',
borderTopColor: '#999', float: 'left', borderBottomColor: '#999',
borderLeftColor: '#999', borderRightColor: '#999'
});
var iCnt = 0;
function add()
{
if (iCnt <= 19) {
iCnt = iCnt + 1;
$(container).append($("<select class ='selinput' id=tb" + iCnt + " " + "value='Text Element " + iCnt + "' style='float : left; margin-right:70px;'>"));
//Add Property Selector
$(container).append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
$(container).append($("<select class ='selinput2" + iCnt + "'' id=tb2" + iCnt + " " + "value='Text Element " + iCnt + " ' ><option value='equalto'>A</option><option value='notequalto'>B</option></select>"));
$(container).append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
// ADD TEXTBOX.
$('select').select2({width : '20%'});
$(container).append('<input type=text class="input" id=tbtext' + iCnt + ' ' +
'placeholder="Value ' + iCnt + '" style="float : center;" /><br><br>');
// SHOW SUBMIT BUTTON IF ATLEAST "1" ELEMENT HAS BEEN CREATED.
if (iCnt == 1) {
var divSubmit = $(document.createElement('div'));
$(divSubmit).append('<input type=button class="bt"' +
'onclick="GetTextValue()"' +
'id=btSubmit value=Submit />');
}
// ADD BOTH THE DIV ELEMENTS TO THE "main" CONTAINER.
$('#main').after(container, divSubmit);
}
// AFTER REACHING THE SPECIFIED LIMIT, DISABLE THE "ADD" BUTTON.
// (20 IS THE LIMIT WE HAVE SET)
else {
$(container).append('<label>Reached the limit</label>');
$('#btAdd').attr('class', 'bt-disable');
$('#btAdd').attr('disabled', 'disabled');
}
}
</code></pre>
<p>Following is the link to js fiddle: </p>
<p><a href="https://jsfiddle.net/hns0qk2b/43/" rel="nofollow">https://jsfiddle.net/hns0qk2b/43/</a> </p>
<p>Please advise.</p>
| <p>Select2 doesn't work on Dom fragment because it needs to bind on document object to work.You are creating a dynamic div <code>container</code> and populating it with more dynamic html and selects when you call <code>select2</code> on selects your dynamic div is still hasn't been yet attached to document.You need to move the initialization code ie this line</p>
<pre><code> $('select').select2({width : '20%'});
</code></pre>
<p>and paste it after you have attached dynamic div to the document ie after this line</p>
<pre><code> $('#main').after(container, divSubmit);
</code></pre>
|
Bootstrap modal - Prevent shift AND background scroll <p>I was having trouble to prevent background shifting when bootstrap modal opened. I added the following classes to my css:</p>
<pre><code>.modal {
overflow-y: auto !important;
}
.modal-open {
overflow: auto !important;
}
</code></pre>
<p>It worked, but now background can scroll up and down. How do I fix both problems? Thanks!</p>
| <p>Solved it using the css like this:</p>
<pre><code>body.modal-open {
overflow-y: scroll !important;
margin: 0 !important;
}
.modal {
overflow: auto !important;
}
</code></pre>
|
What's best MVC to use with react? <p>Like we all know React is just a V in MVC.So If I wanna use the complete MVC with react,what is the best possible technology that I can consider?</p>
| <p>You may want to explore <a href="https://facebook.github.io/flux/docs/overview.html" rel="nofollow">Flux</a> and <a href="https://github.com/reactjs/redux" rel="nofollow">Redux</a> if you're looking for a pattern or framework to design and structure your application.</p>
|
Visual Studio 2013 Conditional Breakpoint fails to evaluate <p>Visual Studio 2013 conditional breakpoint fails to evaluate. </p>
<blockquote>
<p>The condition for a breakpoint failed to execute. .... Evaluation of native methods in this content is not supported.</p>
</blockquote>
<p>Yet the Quick Watch will evaluate just fine.</p>
<p>Is there a way around this?
<a href="https://i.stack.imgur.com/k22jG.png" rel="nofollow"><img src="https://i.stack.imgur.com/k22jG.png" alt="enter image description here"></a></p>
| <p>Right click your project in the solution explorer and select <code>Clean</code> command then rebuild the project with break point</p>
<p>Also make sure both project and solution is in debug mode</p>
|
transfer click event from one page to another in javascript <p>I am trying to transfer click event from a page to another page using javascript. I have a div with a click event on page A and this is the div</p>
<p><strong>HTML:</strong></p>
<pre><code><div class="play">Play Sound</div>
<div class="pause">Stop Sound</div>
</code></pre>
<p>Then on page <code>B</code> I have a script file intended to receive the click of the div from page <code>A</code>. Is there a way how can I make it in such a way that if I click the div on page <code>A</code> let the script event on page <code>B</code> be called within the same application</p>
<p><strong>Javascript:</strong></p>
<pre><code>$(document).ready(function() {
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'audio.mp3');
audioElement.setAttribute('autoplay', 'autoplay');
// audioElement.load()
$.get();
audioElement.addEventListener("load", function() {
audioElement.play();
}, true);
$('.play').click(function() {
audioElement.play();
});
$('.pause').click(function() {
audioElement.pause();
});
});
</code></pre>
| <p>you can use socket or local storage. local storage fires an event when other tabs makes changes. check this answer <a href="http://stackoverflow.com/questions/2236828/javascript-communication-between-tabs-windows-with-same-origin/12514384#12514384">Javascript; communication between tabs/windows with same origin</a></p>
|
How would I go about inserting values that affect multiple tables? <p>My schema is this:</p>
<pre><code>Tables:
Titles -> ID | TitleID | TitleName | ArtistNameFull | Length
Artists-> ID | ArtistNameRoot
ArtistRelation-> ID | TitleID | ArtistID | Relationship
</code></pre>
<p>ArtistNameFull is artist name including: "feat, with, including, featuring, presents, etc."</p>
<p>ArtistNameRoot is just the artist without "feat, with including, featuring, etc."</p>
<p>The relationship between them in ArtistRelation is in another table which has indexes 1-15 and their corresponding "suffix" essentially. As in, index 3 would be "featuring" and index 7 would be "with".</p>
<p>I have about 1000 rows of data that I need to insert into my tables, which is just values of (Title, Artist, length).</p>
<p>Methods so far:
My methods so far have been to place all this data that I need inserted into a temporary table itself and then call sql functions that select unique values between the Title table and the temporary table and then insert them, which works if I'm inserting into just the Titles table, but I also need to insert into Artists which is a little more tricky because I need to get rid of anything but the root artist. So then I tried using php to grab data from my temporary table and using regular expressions to get just the root artist, which works wonders for getting just the root artist, but connecting all this together and figuring out how to insert both into artist relation when there could already be artists from previous insertions is hard to wrap my head around.</p>
<p>Anyway, I guess I just need words of wisdom for if I'm going about this in a really inefficient way, or this is how it is usually done and I just have to keep going.</p>
| <p>PHP is much better than SQL at manipulating strings. So keep doing that. Also using the temp table is a valid method. </p>
<p>You will need to use PHP to pull all of the data from the temp table. </p>
<p>For each result parse out the artist name and insert it into artists. </p>
<p>After each insert you want to get the last ID that was inserted (PDO and mysqli_ have methods for this) and then store that ID and the artist name in an array so that the ID can be used later.</p>
<p>Then insert the title information.</p>
<p>After each insert get the last ID that was inserted and use it and the artist ID to insert a record into the relations table.</p>
<p>Does this help?</p>
|
No Module name Yum in Ansible Error on vagrant <p>I am running Ansible on Ubuntu Vagrant machine. I have written a simple playbook named examyum.yml as follows:</p>
<pre><code>---
- hosts: local
tasks:
- name: Installing packages
yum: name=httpd state=latest
sudo: yes
</code></pre>
<p>When I run </p>
<pre><code>ansible-playbook -i ~/inventory.ini examyum.yml
</code></pre>
<p>I am getting below error:</p>
<pre><code> An exception occurred during task execution. To see the full traceback, use -vvv. The error was: ImportError: No module named yum
fatal: [localhost]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Traceback (most recent call last):\n
File \"/tmp/ansible_qeXrGO/ansible_module_yum.py\", line 25, in <module>\n import yum\nImportError: No module named yum\n", "module_stdout": "", "msg": "MODULE FAILURE"}
</code></pre>
<p>It gives some import error and module failure. I know that Yum is a core module and hence it should work properly, but it doesn't. Any help would be appreciated.</p>
| <blockquote>
<p>I am running Ansible on Ubuntu Vagrant machine.</p>
</blockquote>
<p>So why do you use <code>yum</code> and not <code>apt</code> module first of all?</p>
<p>If you still need <code>yum</code> module for some reason, ensure that <code>yum</code> python package is installed on the managed host.</p>
|
How to count local variable indexes in MethodVariableAccess? <p>According to [1], in a method frame, the local variable array contains a reference to the called instance, the parameters and, finally, any other variables used in the method's code. Also, <code>long</code> and <code>double</code> values occupies two local variables.</p>
<p>When using Byte Buddy to generate the method's code via stack manipulations, does the <code>MethodVariableAccess.OffsetLoading</code> index <code>long</code> and <code>double</code> values into a single index or is it needed, as using ASM directly, to account for these kinds of values to calculate a local var index?</p>
<p>[1] <a href="https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.6.1" rel="nofollow">https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.6.1</a></p>
| <p><code>MethodVariableAccess.OffsetLoading</code> accesses an offset which is not named index to distinguish exactly that. If a <code>long</code> or <code>double</code> type is contained in the array, this accounts to two slots. Byte Buddy uses this abstraction to interact with ASM where the same offset is required for calling the respective visitor.</p>
|
Combine content from 2 files Programming In C <p>I would like to combine contents from 2 files. but i unable to do it.</p>
<p>My output seem like </p>
<pre><code>Username: admin
Password: password123
Username: admin
Password: password456
Username: admin
Password: password789
Username: admin
Password: p@ssw0rd
Username: admin123
Password: password123
</code></pre>
<p>But i would like to do like this output</p>
<pre><code>Username: admin
Password: password123
Username: admin
Password: password456
Username: admin
Password: password789
Username: admin
Password: p@ssw0rd
Username: admin123
Password: password123
Username: admin123
Password: password456
Username: admin123
Password: password789
Username: admin123
Password: p@ssw0rd
</code></pre>
<p>The code is as follows:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fpUser, *fpPass;
char user[100], pass[100];
fpUser = fopen("username.txt","r");
fpPass = fopen("password.txt","r");
if (fpUser==NULL || fpPass==NULL)
{
printf("Username or Password File Cannot Found\n");
exit(0);
} else {
while(fgets(user , 100 , fpUser) != NULL)
{
do
{
printf("Username: %s\n", user);
printf("Password: %s\n", pass);
}
while (fgets(pass , 100 , fpPass) != NULL);
}
}
return 0;
}
</code></pre>
| <p>You need to rethink your loop. I think you want something like this:</p>
<pre><code> while((fgets(user , 100 , fpUser) != NULL) &&
(fgets(pass , 100 , fpPass) != NULL))
{
printf("Username: %s", user);
printf("Password: %s\n", pass);
}
}
return 0;
}
</code></pre>
<p>Given the files <code>username.txt</code>:</p>
<pre><code>admin
admin
admin123
admin123
user1
user2
user3
</code></pre>
<p>and <code>password.txt</code>:</p>
<pre><code>password
badmin
x_234$yz00o@
n@@dles
p1ckL3z
sandW1ch3z
</code></pre>
<p>with the new loop the program outputs:</p>
<pre><code>Username: admin
Password: password
Username: admin
Password: badmin
Username: admin123
Password: x_234$yz00o@
Username: admin123
Password: n@@dles
Username: user1
Password: p1ckL3z
Username: user2
Password: sandW1ch3z
</code></pre>
<p>Notice that I have removed the newline from the first call to <code>printf()</code>, since <code>fgets()</code> reads through the newline and keeps it. Also notice that the program simply stops when it runs out of passwords or usernames.</p>
<h1>Update:</h1>
<p>@David C. Rankin suggested that the code should handle blank lines in the input. This is a really good idea, that was vaguely in my mind before he mentioned it, but I was too lazy to really entertain the notion. Here is a modified version of the whole program that accomplishes this. I added two pointers to <code>char</code> in the declarations to receive the return values from the calls to <code>fgets()</code>.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *fpUser, *fpPass;
char *isUser, *isPass;
char user[100], pass[100];
fpUser = fopen("username.txt","r");
fpPass = fopen("password.txt","r");
if (fpUser==NULL || fpPass==NULL)
{
printf("Username or Password File Cannot Found\n");
exit(0);
} else do {
while ((isUser = fgets(user, 100, fpUser)) != NULL &&
user[0] == '\n')
continue;
while ((isPass = fgets(pass, 100, fpPass)) != NULL &&
pass[0] == '\n')
continue;
if (isUser && isPass) {
printf("Username: %s", user);
printf("Password: %s\n", pass);
}
} while (isUser && isPass);
return 0;
}
</code></pre>
<p>Here are the files <code>username.txt</code>:</p>
<pre><code>admin
admin
admin123
admin123
user1
user2
user3
</code></pre>
<p>and <code>password.txt</code>:</p>
<pre><code>password
badmin
x_234$yz00o@
n@@dles
p1ckL3z
sandW1ch3z
anotherpass
longforapass
</code></pre>
<p>You can't see it here, but the <code>password.txt</code> file started with a blank line. Here is the new output:</p>
<pre><code>Username: admin
Password: password
Username: admin
Password: badmin
Username: admin123
Password: x_234$yz00o@
Username: admin123
Password: n@@dles
Username: user1
Password: p1ckL3z
Username: user2
Password: sandW1ch3z
Username: user3
Password: anotherpass
</code></pre>
|
ExecuteReader requires an open and available Connection,The connection's current state is closed <blockquote>
<p>Server Error in '/' Application. ExecuteReader requires an open and
available Connection. The connection's current state is closed.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.</p>
<p>Exception Details: System.InvalidOperationException: ExecuteReader
requires an open and available Connection. The connection's current
state is closed.</p>
</blockquote>
<pre><code>Source Error:
Line 244:
Line 245:
Line 246: using (SqlDataReader sqlReaderNo = cmdGetStudentNo.ExecuteReader())
Line 247: {
Line 248: if (sqlReaderNo.HasRows)
Source File: d:\Portals\PortalApp\Portal-21Apr2015\Default.aspx.cs Line: 246
Stack Trace:
[InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is closed.]
System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async) +6553785
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +151
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +104
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +288
System.Data.SqlClient.SqlCommand.ExecuteReader() +302
_Default.ValidStudentNo(String username) in d:\Portals\PortalApp\Portal-21Apr2015\Default.aspx.cs:246
_Default.Button1_Click(Object sender, EventArgs e) in d:\Portals\PortalApp\Portal-21Apr2015\Default.aspx.cs:27
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +155
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3804
</code></pre>
| <p>Your connection is not open. You need to call </p>
<pre><code>cmdGetStudentNo.Open();
</code></pre>
<p>before you start using it</p>
|
Anyone tried using IgniteRDD/IgniteSQL of accessing Spark datasets using Scala? <p>We have a need to share the RDDs across multiple sessions. I see option of using Java to access Ignite RDD/Ignite SQL of accessing Spark datasets. Anyone tried using IgniteRDD/IgniteSQL of accessing Spark datasets using Scala.</p>
| <p><code>IgniteRDD</code> is a Scala class and Scala is fully supported by Ignite.</p>
|
tup SQL reset error: database is locked <p>Just installed tup on ubuntu 16.04 and got the following error: </p>
<pre><code>$ tup init
.tup repository initialized.
SQL reset error: database is locked
Statement was: commit
</code></pre>
<p>Also tup upd has error as well.</p>
<pre><code>$ tup upd
.tup/shared: No such file or directory
tup error: Unable to open lockfile.
</code></pre>
<p>Any ideas on how I can get tup to work?</p>
<p>EDIT: I downloaded the source from git (<a href="https://github.com/gittup/tup" rel="nofollow">https://github.com/gittup/tup</a>) and stepped through it and the error appears to be in src/tup/db.c:tup_db_commit() line 933</p>
<pre><code>rc = sqlite3_step(*stmt);
</code></pre>
<p>sqlite3_step function is returning SQLITE_BUSY(5).<br>
My noob guess is that I'm using a newer version of sqlite and some cleanup isn't being done correctly anymore. But it definitely seems like some sort of sqllite3 issue.</p>
| <p>according to multiple other questions/answers on stackoverflow, you are not supposed to use sqlite3 on a network drive. So by association, you should not use tup on a network drive.</p>
|
Dynamically resize drop down width when bolded <p>I have a very simple drop down list such as this:</p>
<pre><code><select>
<option selected="selected" value="MyVeryFirstLongValue">MyFirstLongestValue</option>
<option value="MyVerySecondLongValue">MySecondLongValue</option>
</select>
</code></pre>
<p>When I run this on its own the width of the dropdown is exactly as it needs to be. It auto adjusts. However, my problem now is when I make the text bold.</p>
<pre><code><select>
<option selected="selected" value="MyVeryFirstLongValue">MyFirstLongestValue</option>
<option value="MyVerySecondLongValue">MySecondLongValue</option>
</select>
select{
font-weight: bold;
}
</code></pre>
<p>Now the text gets cut off. How can I maintain the auto width based on the text and still have it bolded? The text in the drop down is dynamic so I cannot give it a fixed width.</p>
<p><a href="https://jsfiddle.net/z3enm7L8/" rel="nofollow">JS Fiddle Example</a></p>
<p><a href="https://i.stack.imgur.com/g948A.png" rel="nofollow"><img src="https://i.stack.imgur.com/g948A.png" alt="What I see on JS Fiddle"></a></p>
| <p>I can reproduce it only in chrome</p>
<p>It could be an option to have bold options also:</p>
<pre><code>select,option{
font-weight: bold;
}
</code></pre>
|
JS can't delete all images from page <p>I'm trying to delete all images from page. The page is in HTML. This is my HTML button: </p>
<pre><code><input id="clickMe" type="button" value="Delete Images" onclick="click();" />
</code></pre>
<p>And the function is:</p>
<pre><code><script type="text/javascript">
function click(){
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
images[i].Node.removeChild(images[0]);
}
}
</script>
</code></pre>
<p>All elements are tagged "img"</p>
| <p>Removing a child can only be done from the parent:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function removeImages() {
var images = [].slice.call(document.getElementsByTagName('img'), 0); // get the images as array like object, and turn it into an array using slice
images.forEach(function(img) { // iterate the images array
img.parentNode.removeChild(img); // remove the child node via the parent node
});
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="button" onclick="removeImages()">Remove Images</button>
<div>
<img src="http://static.wixstatic.com/media/60d837_94f714500a3145a1b98efd7a6fe78ce7~mv2_d_3456_3456_s_4_2.jpg_256" />
<img src="https://static-s.aa-cdn.net/img/ios/442131982/82d94c67fc3d8eb87e07d9bb568c5d4d?v=1" />
<img src="https://pbs.twimg.com/profile_images/625769159339737088/2dwpQAXA.jpg" />
</div></code></pre>
</div>
</div>
</p>
<p>You can also use <code>img.remove()</code> instead of the cumbersome <code>img.parentNode.removeChild(img)</code>, but it won't work in IE - see <a href="https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove" rel="nofollow"><code>ChildNode.remove()</code> on MDN</a>.</p>
|
Angular ng-pattern regex validation using scope data <p>I'm pretty new at Angular, so forgive me if I'm asking or looking at this the wrong way, but I'm trying to dynamically build a form from fields in a database. When the page loads, I'm pulling data from the database and assigning those values to the scope in the Controller. In the HTML, I'm looping through those scope values to populate the page. In this example, <code>fields.field.dataType.type="text"</code>, <code>{{fields.field.isRequired}}="true"</code>, and <code>{{fields.field.regEx}}="/^\d{11}$/"</code>.</p>
<pre><code><div ng-if="fields.field.dataType.type=='text'" class="form-group control-group" ng-class="{true: 'error'}[submitted && fieldsForm.$invalid]">
<div ng-repeat="fields in selectedPage.fieldValue">
<ng-form name="fieldsForm>
/*other code*/
<div class="controls"
<input type="{{fields.field.dataType.type}}"
ng-model="fields.value"
name="{{fields.field.fieldName}}"
ng-required="{{fields.field.isRequired}}"
ng-pattern="{{fields.field.regEx}}" />
</div>
<span class="help-label" ng-show="submitted && fieldsForm.$error.pattern">Please enter a valid field</span>
/*rest of code*/
</ng-form>
</div>
</code></pre>
<p>The other parameters within the input tag work perfectly, but the regex field always returns invalid. I can substitute <code>ng-pattern="{{fields.field.regEx}}"</code> with <code>ng-pattern="/^\d{11}$/"</code> and the validation works as expected.</p>
<p>Is there something different I have to do to pull in this regular expression from <code>{{fields.field.regEx}}</code>? Why would the validation work when I hard-code <code>"/^\d{11}$/"</code> in <code>ng-pattern</code> but fail when it's pulling from <code>{{fields.field.regEx}}</code> even though they contain the same data? </p>
<p>Any insight would be appreciated, thanks!</p>
| <p><code>NgPattern</code> expect it's value to be a <code>Regex</code> parseable expression.</p>
<p>According to <a href="https://docs.angularjs.org/api/ng/directive/ngPattern" rel="nofollow">angularjs ngPattern</a> docs:</p>
<blockquote>
<ul>
<li>If the expression evaluates to a RegExp object, then this is used directly.</li>
<li>If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it in <code>^</code> and <code>$</code> characters. For<br>
instance, <code>"abc"</code> will be converted to new <code>RegExp('^abc$')</code>.</li>
</ul>
</blockquote>
<p>In your case, the regex is being parsed like a string, so the problem is with the scaping of the back slash inside the string <code>"/^\d{11}$/"</code>. So, to fix it, you mustn't surround your regex with <code>/</code>, because it's not a regex, it's a string with the pattern for a regex, and you must escape your regex pattern as well (if it isn't being scaped yet), like so: <code>"^\\d{11}$"</code>.</p>
<p>Also, you don't need to use <code>{{}}</code> since your regex string comes from an object on scope you can use it like this: <code>ng-pattern="fields.field.regEx"</code>.</p>
|
Scrapy opening html in editor , not browser <p><a href="https://i.stack.imgur.com/LWxmP.png" rel="nofollow"><img src="https://i.stack.imgur.com/LWxmP.png" alt="enter image description here"></a></p>
<p>I am working on some code which returns an <code>HTML</code> string (<code>my_html</code>). I want to see how this looks in a browser using <a href="https://doc.scrapy.org/en/latest/topics/debug.html#open-in-browser" rel="nofollow">https://doc.scrapy.org/en/latest/topics/debug.html#open-in-browser</a>. I just asked a question on this (<a href="http://stackoverflow.com/questions/40109782/scrapy-how-to-load-html-string-into-open-in-browser-function">Scrapy - How to load html string into open_in_browser function</a>) and the answers have shown me how to load the string into the 'open_in_browser object'</p>
<pre><code>headers = {
'accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
'upgrade-insecure-requests': "1",
'user-agent': "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36",
'referer': "http://civilinquiry.jud.ct.gov/GetDocket.aspx",
'accept-encoding': "gzip, deflate, sdch",
'accept-language': "en-US,en;q=0.8",
'cache-control': "no-cache",
}
new_response = TextResponse('https://doc.scrapy.org/en/latest/topics/request-response.html#response-objects', headers=headers, body='<html><body>Oh yeah!</body></html>')
open_in_browser(new_response)
</code></pre>
<p>However now I'm seeing the text open up in notepad rather than the browser (on my windows system) making me think that the system thinks this is a text string not html (even though it has an outer html tag):</p>
<p>How can I get this working?</p>
<p>edit:</p>
<p>I changed the code to </p>
<pre><code>new_response = Response('https://doc.scrapy.org/en/latest/topics/request-response.html#response-objects', headers=headers, body='<html><body>Oh yeah!</body></html>')
</code></pre>
<p>Now getting:</p>
<pre><code>TypeError: Unsupported response type: Response
</code></pre>
<p>edit2:</p>
<p>I realized that in my version of scrapy (1.1) the source is:</p>
<pre><code>def open_in_browser(response, _openfunc=webbrowser.open):
"""Open the given response in a local web browser, populating the <base>
tag for external links to work
"""
from scrapy.http import HtmlResponse, TextResponse
# XXX: this implementation is a bit dirty and could be improved
body = response.body
if isinstance(response, HtmlResponse):
if b'<base' not in body:
repl = '<head><base href="%s">' % response.url
body = body.replace(b'<head>', to_bytes(repl))
ext = '.html'
elif isinstance(response, TextResponse):
ext = '.txt'
else:
raise TypeError("Unsupported response type: %s" %
response.__class__.__name__)
fd, fname = tempfile.mkstemp(ext)
os.write(fd, body)
os.close(fd)
return _openfunc("file://%s" % fname)
</code></pre>
<p>I changed Response to HTMLresponse and it started working. Thank you</p>
| <p>Look at how the <a href="https://github.com/scrapy/scrapy/blob/129421c7e31b89b9b0f9c5f7d8ae59e47df36091/scrapy/utils/response.py#L63" rel="nofollow"><code>open_in_browser()</code></a> function is defined:</p>
<pre><code>if isinstance(response, HtmlResponse):
if b'<base' not in body:
repl = '<head><base href="%s">' % response.url
body = body.replace(b'<head>', to_bytes(repl))
ext = '.html'
elif isinstance(response, TextResponse):
ext = '.txt'
else:
raise TypeError("Unsupported response type: %s" %
response.__class__.__name__)
</code></pre>
<p>It would create a <code>.txt</code> file if it is getting a <code>TextResponse</code> - that's why you see the notepad opening the file with your HTML inside. </p>
<p>Instead, you need to initialize the regular <a href="https://doc.scrapy.org/en/latest/topics/request-response.html#scrapy.http.Response" rel="nofollow"><code>scrapy.Response</code></a> object and pass it to <code>open_in_browser()</code>.</p>
<p>Or, you can create the temp HTML file with the desired contents manually and then using the <code>file://</code> protocol open it in a default browser through the <a href="https://docs.python.org/2/library/webbrowser.html#webbrowser.open" rel="nofollow"><code>webbrowser.open()</code></a>. </p>
|
How to affect the change in the original input box? <p>I have made an input box and i have cloned this input box to a div,let's name them ipbox1 and ipbox2, ipbox2 is the copy of ipbox1 now what i want to do is that when
i enter/change the value in either of them, the dom.value or $("#id").val() should return the updated the value. But now it's only functioning with the ipbox2.
What should i do?</p>
<p><a href="https://jsfiddle.net/s6td1bof/" rel="nofollow">fiddle</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$("#ghj").click(function(){
$("#abc").val("Some text");
$("#abc").clone(true).appendTo("#pastehere");
})
$("#abc").on('change',function(){
alert();
})</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type = "text" id = "abc">This is the first box
<div id = "pastehere">
</div>This is the cloned box
<br><button type = "button" id = "ghj">
Clone
</button></code></pre>
</div>
</div>
</p>
| <p>If you want to be able to read the value of either of them independently, then check out this <a href="https://jsfiddle.net/s6td1bof/2/" rel="nofollow">fiddle</a> </p>
<p>If not, then I must be offtrack. Please add more details about what you need to achieve :)</p>
<p>HTML</p>
<pre><code><input type = "text" class = "abc">This is the first box
<div id = "pastehere">
</div>This is the cloned box
<br><button type = "button" id = "ghj">
Clone
</button>
</code></pre>
<p>JS</p>
<pre><code>var initialInput = $(".abc");
$("#ghj").click(function(){
initialInput.val("Some text");
initialInput.clone(true).appendTo("#pastehere");
})
$(".abc").on('change',function(ev){
var targetInput = $(ev.target);
alert('myValueIs:' + targetInput.val())
});
</code></pre>
|
Android request often fails when app is in background <p>The request throws java.net.SocketTimeoutException: connect timed out.
I use IntentService for executing the request.
I set all the timeouts to 85 seconds. Background data is enabled on the app settings. Power saving mode is off. Data limit is off.
The request is always successful when the app is on foreground. Any ideas?</p>
<p>Here is a code:</p>
<pre><code>@Override
public List<EnterExitDeviceGeofenceResult> reportGeofenceEvent(String locationId,
LatLng latLng, boolean enter)
throws IOException {
String enterExitUrlPart = enter ? "/enter" : "/exit";
String url = getUrl("/users/me/geofences/" + locationId + enterExitUrlPart +
"?fields=command{resultingAcState,failureReason,status},deviceId", 2);
String body = generateLatLngRequestBody(latLng);
return executeCall(
deserializers.enterExitGeofenceResult(),
new Request.Builder()
.url(url)
.post(RequestBody.create(JSON, body))
.build(),
getClientBuilder()
.addInterceptor(defaultErrorInterceptor)
.connectTimeout(REPORT_GEOFENCE_EVENT_TIMEOUT,
TimeUnit.MILLISECONDS)
.readTimeout(REPORT_GEOFENCE_EVENT_TIMEOUT,
TimeUnit.MILLISECONDS)
.writeTimeout(REPORT_GEOFENCE_EVENT_TIMEOUT,
TimeUnit.MILLISECONDS)
.build()
);
}
@Nullable
private <T> T executeCall(JsonDeserializer<T> deserializer, Request request,
OkHttpClient client) throws IOException {
if (deserializer == null) {
throw new NullPointerException("deserializer == null");
}
StringReader sr = new StringReader(executeCall(request, client));
try {
return deserializer.deserialize(new JsonForwardReaderFromJsonReader(new JsonReader(sr)));
} catch(Throwable t) {
if (logsEnabled) {
LogUtil.e(TAG, "Error deserializing", t);
}
throw t;
}
}
private String executeCall(Request request, OkHttpClient client) throws IOException {
ResponseBody responseBody = null;
try {
if (logsEnabled) {
LogUtil.i(TAG, request.url().toString());
}
responseBody = client.newCall(request).execute().body();
String responseString = responseBody.string();
if (logsEnabled) {
LogUtil.i(TAG, String.format("<- %s", responseString));
}
return responseString;
} finally {
if (responseBody != null) {
responseBody.close();
}
}
}
@Override
protected void onHandleIntent(Intent intent) {
/*some code*/
restApiClient.reportGeofenceEvent(...);
}
</code></pre>
| <p>While I would say to try a proper Service instead of an IntentService, you can achieve this with the following code. Now the only drawback is that you will need to stop it manually with stopSelf at some part of your code.
Also, you can try setting the OkHttpClient builder retryOnConnectionFailure to true.</p>
<pre><code>@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent,flags,startId);
return START_STICKY;
}
</code></pre>
|
Is there an equivalent function to get index of element in an array like using index to get position within a string? <p>I was hoping the the <code>index</code> function would work since Perl makes no distinction between a number and a string of numeric characters, having used index successfully on strings, but it did not work with an array.</p>
<p>Is there a similar function for array element indices like index for a string?</p>
| <p>The <a href="http://perldoc.perl.org/functions/index.html" rel="nofollow"><code>index</code> builtin</a> takes a string, a substring and an optional position as its arguments. Passing an array won't search the array.</p>
<p>If you want to check for the first occurrence of <code>$sortedSeq[$i]</code> in each element of <code>@Seq</code>, use <code>map</code>.</p>
<pre><code>$seqIndx[$i] = map { index $_, $sortedSeq[$i] } @Seq;
</code></pre>
|
Jquery Data attribute selector not working <p>I have this element </p>
<pre><code><div class="messages selected" data-conversationId=""></div>
</code></pre>
<p>The <code>data-attribute</code> <code>conversationId</code> is set dynamically like so:</p>
<pre><code>$(".messages").data("conversationId", conversationId);
</code></pre>
<p>I am having issues using a selector to select this element by the data attribute.</p>
<pre><code>$(".messages[data-conversationId=4]")
</code></pre>
<p>Returns empty array. Interestingly: </p>
<pre><code>$(".messages").data("conversationId")
</code></pre>
<p>returns <code>4</code></p>
<p>What is wrong with my selector?</p>
| <p>If you set your dynamic attribute via jquery's .data() you will have the above problem.</p>
<p>However, if you set the dynamic attribute via jquery's .attr() method, you won't have this problem</p>
<p>Example here: <a href="https://jsfiddle.net/6dn5wjL8/8/" rel="nofollow">https://jsfiddle.net/6dn5wjL8/8/</a></p>
<p>HTML</p>
<pre><code><div id="test1" class="messages selected" data-conversationId="">testContent1</div>
<div id="test2" class="messages selected" data-conversationId="">testContent2</div>
</code></pre>
<p>JS:</p>
<pre><code>// Will work
$("#test1").attr("data-conversationId", 4)
// Will not work
$("#test2").data("conversationId", 3)
alert("With selector .messages[data-conversationId=4] I found a div with this content: "+$(".messages[data-conversationId=4]").html())
alert("With selector .messages[data-conversationId=3] I found a div with this content: "+$(".messages[data-conversationId=3]").html())
</code></pre>
|
loop optimization in c# <p>I am working on a music player for pc using c# and all seems to go fine but, i have problem in loading all the music files from the music directory because it loads very slowly and this take time when opening the app, it could take 5 min depending on the amount of music files. I think this happens because i created a loop to loop through each music file and get the metadatas and also the picture to load on different picture boxes for each music file.<br>
Please Help, i need it to be faster. Thank you.
the code is below...</p>
<pre><code> public List<MusicDetails> Music_Library()
{
List<MusicDetails> files = new List<MusicDetails>();
string[] musicfolder = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyMusic),"*mp3", SearchOption.AllDirectories);
for (int i = 0; i <musicfolder.Length; i++)
{
try {
files.Add(new MusicDetails
{
title = TagLib.File.Create(musicfolder[i]).Tag.Title,
genre = TagLib.File.Create(musicfolder[i]).Tag.FirstGenre,
artist = TagLib.File.Create(musicfolder[i]).Tag.FirstPerformer,
path = musicfolder[i],
CoverArt = OrganiseAlbums.SingleAlbumImage(musicfolder[i],true)
});
}catch(Exception)
{
// OMIT FILE
}
}
return files;
}
</code></pre>
| <p>You could try replacing your loop with a parallel foreach loop using background threads - add each item to the UI as it is processed, and let .Net determine the most efficient way to process everything. If you do it right, your UI will remain responsive, and your users will start out with "enough to look at..." Here is a link to get you started:</p>
<p><a href="https://msdn.microsoft.com/en-us/library/dd460720(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1" rel="nofollow">https://msdn.microsoft.com/en-us/library/dd460720(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1</a></p>
<p>If you have a ton of music files, though, you may not want to load them all into memory at once. I would look into some sort of a list control or layout control that allows virtualization so that you instantiate and display only the visible ones at any given time. Use a tutorial to see how to bind to your collection so that it is virtualized.</p>
<p>If you post a more specific question with examples of what you have tried, you will get more specific answers...</p>
|
UWP C# Scroll to the bottom of TextBox <p>How do you scroll to the bottom of a TextBox for a UWP app?</p>
<p>With my transition to UWP, this has been one of the questions that hasn't been straight-forward.</p>
<p>I used to be able to use this:</p>
<pre><code>textBox.SelectionStart = textBox.TextLength;
textBox.ScrollToCaret();
</code></pre>
<p>But, this doesn't work for UWP apps</p>
| <p>If anyone needs to scroll to the bottom of a TextBox in UWP apps:</p>
<p><a href="https://code.msdn.microsoft.com/windowsapps/How-to-scroll-to-the-a8ea5867" rel="nofollow">https://code.msdn.microsoft.com/windowsapps/How-to-scroll-to-the-a8ea5867</a></p>
<pre><code>private void TextBox_TextChanged(object sender, TextChangedEventArgs e)Â
{Â
var grid = (Grid)VisualTreeHelper.GetChild(textBox1, 0);Â
for (var i = 0; i <= VisualTreeHelper.GetChildrenCount(grid) - 1; i++)Â
{Â
object obj = VisualTreeHelper.GetChild(grid, i);Â
if (!(obj is ScrollViewer)) continue;Â
((ScrollViewer)obj).ChangeView(0.0f, ((ScrollViewer)obj).ExtentHeight, 1.0f);Â
break;Â
}Â
}
}
</code></pre>
<p>where textBox1 is the TextBox you want to scroll to the bottom.</p>
|
how to set a color for check box in angularjs with css <p>here is my code. Please find a solution for this. </p>
<pre><code> <div class="list">
<ul class="items-list">
<li ng-repeat="listService in servicesList">
<input type="checkbox" ng-model="listService.selected" />
<img ng-src="{{listService.img}}" title="{{listService.name}}" alt="{{listService.name}}" />
<span>{{listService.name}}</span>
</li>
</ul>
</div>
</code></pre>
| <p>ng-class is what your looking for: </p>
<pre><code> <ANY class="ng-class: expression;"> ... </ANY>
</code></pre>
<p>And the expression can be a css class</p>
|
Basic explanation needed while using while loops and arrays <pre><code>// ConsoleApplication27.cpp : Defines the entry point for the console application.
</code></pre>
<p>//</p>
<pre><code>#include "stdafx.h"
#include "stdio.h"
#include <string.h>
void main()
{
char couples[5][50] = { "John Nora", "Paul Kathy", "Tom Claire", "Martin Mary", "Tony Teresa" };
char male[5][51];
char female[5][51];
int i;
int j = 0;
printf("Males: ");
for (i = 0; i < 5; i++)
{
while (couples[i][j] != ' ')
{
male[i][j] = couples[i][j];
j++;
}
male[i][j] = '\0';
puts(male[i]);
j = 0;
}
printf("\n");
}
</code></pre>
<p>Hello, I am essentially trying to print all the male names and then print the female names (I have yet to do that part). The code below does work however I'm just finding it difficult to understand how it is working. Like, for example I don't understand the part where it says while(couples[I][j] != ' '). If I am trying to split the string by the space mark, why is it NOT equal to space. I would appreciate any sort of help and explanation people may have! Thanks!</p>
| <p>Each row of 'couples' can be treated as a string (i.e a character array) consisting of two names - one male, one female - separated by a single space character. The 'while' loop is copying the male name of the pair into the separate array 'male', one character at a time. The intended action of the 'while' loop is to keep copying characters <em>until</em> the separating space is encountered, then put in the '\0' to mark the end of the copied male name-string. But 'while' means 'do this as long as some condition is true', so <strong>the condition you want to be true</strong> is that the space ISN'T the character being looked at right now. Execute the code in your head on the first row of 'couples', like so:</p>
<pre><code>a) i=0 and j=0 and enter the 'while' loop:
b) couples[i][j] = 'J'. Is 'J' != ' ' ? --> YES, copy 'J' to males[0][0], increment j
c) couples[i][j] = 'o'. Is 'o' != ' ' ? --> YES, copy 'o' to males[0][1], increment j
d) couples[i][j] = 'h'. Is 'h' != ' ' ? --> YES, copy 'h' to males[0][2], increment j
e) couples[i][j] = 'n'. Is 'n' != ' ' ? --> YES, copy 'n' to males[0][3], increment j
f) couples[i][j] = ' '. Is ' ' != ' ' ? --> NO, copy '\0' to males[0][4], reset j to 0
</code></pre>
|
Is it possible to commit a file to a remote base repository using JGit <p>My requirement is that I want to programmatically commit a file to a remote base repository (that resides in a central location like <code>https//:myproject.git</code>). </p>
<p>I would like to know if it is possible to commit a file to a remote base repository (master) without cloning the base repo into my local machine. I am a newbie to JGit. Please let me know.</p>
| <p>As <a href="http://stackoverflow.com/users/147356/larsks">@larsks</a> already pointed out, you need to first create a local clone of the remote base repository. Changes can only be committed to the local copy of the base repository. Finally, by pushing to the originating repository, the local changes are made available on the remote repository for others.</p>
<p>JGit has a <em>Command API</em> that is modeled after the Git command line and can be used to clone, commit, and push.</p>
<p>For example:</p>
<pre class="lang-java prettyprint-override"><code>// clone base repository into a local directory
Git git Git.cloneRepository().setURI( "https://..." ).setDirectory( new File( "/path/to/local/copy/of/repo" ) ).call();
// create, modify, delete files in the repository's working directory,
// that is located at git.getRepository().getWorkTree()
// add and new and changed files to the staging area
git.add().addFilepattern( "." ).call();
// remove deleted files from the staging area
git.rm().addFilepattern( "" ).call();
// commit changes to the local repository
git.commit().setMessage( "..." ).call();
// push new commits to the base repository
git.push().setRemote( "http://..." ).setRefspec( new Refspec( "refs/heads/*:refs/remotes/origin/*" ) ).call();
</code></pre>
<p>The <code>PushCommand</code> in the above example explicitly states which remote to push to and which branches to update. In many cases, it may be sufficient to omit the setter and let the command read suitable defaults from the repository configuration with <code>git.push().call()</code>.</p>
<p>For further information, you may want to have a look at some articles that go into more detail of <a href="http://www.codeaffine.com/2015/11/30/jgit-clone-repository/" rel="nofollow">cloning</a>, <a href="http://www.codeaffine.com/2015/12/15/getting-started-with-jgit/" rel="nofollow">making local changes</a>, and other aspects like <a href="http://www.codeaffine.com/2014/12/09/jgit-authentication/" rel="nofollow">authentication</a> and <a href="http://www.codeaffine.com/2015/12/15/getting-started-with-jgit/" rel="nofollow">setting up the development environment</a></p>
|
Querying a document in Mongo using DateTime C# <p>I have a mongo document with DateTime like this: </p>
<pre><code>"_id" : "58064346e74f22124037a607",
"DateEffective" : "2016-10-18T15:44:01.083Z",
</code></pre>
<p>In my C# code I want to query my collection for any document that it's DateEffective is before today's date, here is my Builders:</p>
<pre><code>var filterDefinition = builder.Lt("DateEffective", new BsonDateTime(DateTime.Now))
var result = collection.Find(filterDefinition).ToList()
</code></pre>
<p>my result.Count is 0</p>
<p>any ideas? </p>
| <p>As per your document "DateEffective" is not a date, it is string. In string key less than will not work. So change your "DateEffective" to date format</p>
<p>the document should in this format </p>
<pre><code>{
"_id" : ObjectId("58064346e74f22124037a607"),
"DateEffective" : ISODate("2016-10-18T15:44:01.083Z")
}
</code></pre>
<p>not in this format </p>
<pre><code>{
"_id" : "58064346e74f22124037a607",
"DateEffective" : "2016-10-18T15:44:01.083Z"
}
</code></pre>
|
Is it possible for Regex.Match() to return null? (C# .Net framework 3.5?) <p>Is it possible that regex.Match in the (much simplified) code below can ever return null? </p>
<pre><code>Regex regex = new Regex(pattern);
Match m = regex.Match(input);
</code></pre>
<p>My static analysis tool complains without a null check on m, but I'm thinking it's not actually necessary. It'd be nice to remove the null check so my code coverage is 100% for the method it's contained in.</p>
<p>Thoughts?</p>
<p>Charles.</p>
| <p><a href="https://msdn.microsoft.com/en-us/library/twcw2f1c(v=vs.110).aspx" rel="nofollow">Documentation</a> is your friend here:</p>
<blockquote>
<p><em>Return Value</em></p>
<p>Type: <a href="https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.match(v=vs.110).aspx" rel="nofollow">System.Text.RegularExpressions.Match</a></p>
<p>An object that contains information about the match.</p>
</blockquote>
<p>Microsoft is telling you that it will only return a <code>Match</code> object (not <code>null</code>), which means you can rightfully assume this to be true.</p>
<p>There is a chance, according to the docs, that it throws an exception (<a href="https://msdn.microsoft.com/en-us/library/system.argumentnullexception(v=vs.110).aspx" rel="nofollow"><code>ArgumentNullException</code></a> or <a href="https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regexmatchtimeoutexception(v=vs.110).aspx" rel="nofollow"><code>RegexMatchTimeoutException</code></a>), though.</p>
|
Using "spring-security-oauth2," can custom parameters be passed in the "Authorization Phase" of OAuth2? <p>I am implementing the <strong>Authorization Code</strong> flow + <strong>JWT</strong>.</p>
<p>I would like to know if and how it may be possible to add additional custom parameters to the <em>Authorization Phase</em> of the flow.</p>
<p>Essentially, I am looking to do the following:</p>
<ol>
<li>When redirecting the user to the /oauth/authorize endpoint I would like to
pass in an additional parameter (customPar<em>emphasized text</em>ameter) in the GET url
<a href="http://.../oauth/authorize" rel="nofollow">http://.../oauth/authorize</a>?...<em>customParameter</em>=[VALUE] such that
VALUE is dynamic</li>
<li>I will need to retrieve VALUE when creating the
<strong>JWT</strong>, populating the <strong>JWT</strong> with that VALUE</li>
</ol>
<p>Is this possible? How can I implement?</p>
<p>Thanks in advance.</p>
| <p>My idea is add your parameter during <em>AuthorizationRequest</em> in custom <em>OAuth2RequestFactory</em> at <em>createAuthorizationRequest</em> method like <a href="http://stackoverflow.com/questions/31345466/mapping-user-roles-to-oauth2-scopes-authorities">here</a>: </p>
<pre><code>@Override
public AuthorizationRequest createAuthorizationRequest(Map<String, String> authorizationParameters) {
//here
authorizationParameters.put("your", "parameter");
//
AuthorizationRequest request = super.createAuthorizationRequest(authorizationParameters);
if (securityContextAccessor.isUser()) {
request.setAuthorities(securityContextAccessor.getAuthorities());
}
return request;
}
</code></pre>
<p>You can populate request and inject Request or Session in your custom OAuth2RequestFactory and retrieve it</p>
|
Efficient way to reverse three consecutive subranges [A,B,C] -> [C,B,A] <p>I've got an array [A,B,C] consisting of three consecutive sub-arrays A, B and C. I'd like to reverse the larger array into [C,B,A]. My current attempt involves thee calls to <code>std::rotate</code>, as shown below. I wonder if there is a more straightforward/efficient way to achieve this, preferably using an std algorithm.</p>
<pre><code>Step 1: "swap" sub-array B,C
[A,B,C] -> [A|B,C] -> [A,C,B]
Step 2: "swap" sub-array A,C
[A,C,B] -> [A,C|B] -> [C,A,B]
Step 3: "swap" sub-array A,B
[C,A,B] -> [C|A,B] -> [C,B,A]
</code></pre>
<p><strong>Edit</strong></p>
<p>For example given the array <code>[1,2,3|4,5,6|7,8,9]</code> I would like to "reverse" it into <code>[7,8,9|4,5,6|1,2,3]</code></p>
<p><a href="http://rextester.com/MGUY61030" rel="nofollow">Sample implementation</a>. Please note that the sizes of the "ranges" are merely illustrative.</p>
| <p>Reverse the whole array then reverse each subarray.</p>
<pre><code>[1,2,3|4,5,6|7,8,9]
[9,8,7|6,5,4|3,2,1]
[7,8,9|4,5,6|1,2,3]
</code></pre>
<p>This will take two linear passes and is extremely CPU cache friendly.</p>
|
Initializer for conditional binding must have Optional type, not '[String]' - Xcode 8.0 Swift 3.0 <p>I am creating a function that allows me to create a array on VC1 and then I can transfer over the array using "prepare for segue" to VC2. On VC2 I can append an item to the array in VC2 and then transfer over the array back to VC1. My issue is, is that on the line <code>if let newString = receivedString</code> (VC1) and erro is comming up that states, "Initializer for conditional binding must have Optional type, not '[String]'"This is my code on VC1:</p>
<pre><code>var receivedString = [String]()
override func viewDidAppear(_ animated: Bool) {
if let newString = receivedString {
print(newString)
}
}
</code></pre>
<p>This is my code on VC2:</p>
<pre><code>let stringToPass = "Hello World"
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! ViewController
destinationVC.receivedString = [stringToPass]
destinationVC.receivedString.append("DYLAN MURPHY")
}
</code></pre>
<p>I am new to Swift so I realise that I may be completely wrong so I appreciate any help that leads me closer to this goal. </p>
| <p>It's telling you that, since <code>receivedString</code> is not an optional type, the <code>if let</code> doesn't make sense. You've created it as an array of strings and that's what it's always going to be.</p>
<p>Even if the array is empty, it will still evaluate as an array.</p>
|
Javascript HTTP client library <p>Does anybody know how to create a JavaScript command line Application that consumes a public API using a HTTP client library?</p>
<p>Which JavaScript http library should I use?</p>
| <p><a href="https://www.npmjs.com/package/request" rel="nofollow">request</a> will do the job. <a href="https://www.npmjs.com/package/xhr2" rel="nofollow">xhr2</a> also provides a nice <code>XMLHttpRequest</code> emulation for Node applications.</p>
|
Flexbox not taking the full height of the wrapper <p>I have a problem with my side flexbox, which is not taking the full height of the site. </p>
<pre><code>.aside-1 {
padding: 10px;
font-size: 18px;
flex: 1;
height: 100%;
}
</code></pre>
<p>I tried to set the height to 100% but with no effect. Here is the site in full: <a href="http://jsbin.com/yujoqaxubi/edit?output" rel="nofollow">http://jsbin.com/yujoqaxubi/edit?output</a></p>
<p>I tried also to add</p>
<pre><code>position:absolute; bottom:0
</code></pre>
<p>But it just breaks the site.</p>
<p>Thanks for any help!</p>
| <pre><code>.aside-1 {
padding: 10px;
font-size: 18px;
flex: 1;
height: auto;
}
</code></pre>
<p>will do the tricks</p>
|
Google Maps API heatmap, object array not working <p>I am trying to create a heatmap using imported data from a csv file. My csv data seems to import fine but once I try to pass the object to an array (to be used in my heatmap) something goes wrong and my heatmap is not printed to the screen.</p>
<p>Here is what I have:</p>
<pre><code><script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src='//maps.googleapis.com/maps/api/js?key=--MY_KEY--&libraries=visualization'></script>
<?php
$addy_arr = array("");
$file = fopen('mylocations.csv', 'r');
while(($line = fgetcsv($file)) !== FALSE){
$line = str_replace(" ", "+", $line);
$immmp = implode("+", $line);
array_push($addy_arr, $immmp);
}
fclose($file);
$js_array = json_encode($addy_arr);
echo "<script> var javascript_array = ". $js_array . ";\n </script>";
?>
<style>
#map_canvas {
width:1024px;
height:900px;
}
</style>
<script>
$(document).ready(function (){
var address_index = 0;
var addresses = javascript_array;
var heatcordarr = [];
buildarr();
function buildarr(){
addMapMarker();
function addMapMarker(){
var address = addresses[address_index];
if(address.length){
$.getJSON('//maps.googleapis.com/maps/api/geocode/json?address='+address, null, function (data){
if(data.results.length > 0){
var p = data.results[0].geometry.location;
var latlng = new google.maps.LatLng(p.lat, p.lng);
heatcordarr.push(latlng);
}
nextAddress();
});
} else {
nextAddress();
}
}
function nextAddress(){
address_index++;
if(address_index < addresses.length){
addMapMarker();
}
}
heatmapper();
}
function heatmapper(){
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 2,
mapTypeId: 'satellite'
});
var heatmap = new google.maps.visualization.HeatmapLayer({
data: heatcordarr
});
heatmap.setMap(map);
}
});
</script>
<div id="map_canvas"></div>
</code></pre>
| <p>You have two issues with your code.</p>
<ol>
<li>the geocoder is asynchronous, you are calling the <code>heatmapper</code> function before the responses come back from the service and the <code>heatcorarr</code> is populated.</li>
</ol>
<pre><code>function nextAddress() {
address_index++;
if (address_index < addresses.length) {
addMapMarker();
} else {
// call heatmapper function once all the addresses are geocoded, not before
heatmapper();
}
}
</code></pre>
<ol start="2">
<li>Your map is never initialized. To be initialized a map has to have both a <code>center</code> and a <code>zoom</code>. You are only setting the zoom level.</li>
</ol>
<pre><code>// either set the map center or zoom and center the map on the data
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < heatcordarr.length; i++) {
bounds.extend(heatcordarr[i]);
}
// map.fitBounds(bounds); or
map.setCenter(bounds.getCenter());
</code></pre>
<p><a href="http://jsfiddle.net/geocodezip/qocvomfr/1/" rel="nofollow">working fiddle</a></p>
<p><strong>code snippet:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var javascript_array = ["New York, NY", "Jersey City, NJ", "Teterboro, NJ", "Broadway, New York, NY", "Secaucus, NJ", "West New York, NJ", "North Bergen, NJ"];
$(document).ready(function() {
var address_index = 0;
var addresses = javascript_array;
var heatcordarr = [];
buildarr();
function buildarr() {
addMapMarker();
function addMapMarker() {
var address = addresses[address_index];
if (address.length) {
$.getJSON('//maps.googleapis.com/maps/api/geocode/json?address=' + address, null, function(data) {
if (data.results.length > 0) {
var p = data.results[0].geometry.location;
var latlng = new google.maps.LatLng(p.lat, p.lng);
heatcordarr.push(latlng);
}
nextAddress();
});
} else {
nextAddress();
}
}
function nextAddress() {
address_index++;
if (address_index < addresses.length) {
addMapMarker();
} else {
// call heatmapper function once all the addresses are geocoded, not before
heatmapper();
}
}
}
function heatmapper() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
// missing mandatory center option.
zoom: 2,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var heatmap = new google.maps.visualization.HeatmapLayer({
data: heatcordarr
});
// either set the map center or zoom and center the map on the data
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < heatcordarr.length; i++) {
bounds.extend(heatcordarr[i]);
}
// map.fitBounds(bounds); or
map.setCenter(bounds.getCenter());
heatmap.setMap(map);
}
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://maps.googleapis.com/maps/api/js?libraries=visualization"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="map_canvas"></div></code></pre>
</div>
</div>
</p>
|
set ActiveX checkbox properties with VBA word 2010 <p>I have searched high and low for this, but no luck.</p>
<p>To create a checkbox:</p>
<pre><code>Selection.InlineShapes.AddOLEControl ClassType:="Forms.CheckBox.1"
</code></pre>
<p>However, there are several properties associated with a checkbox, and I wanted to find out how to set them as well when I am creating the checkbox.</p>
<p>For example, I tried this:</p>
<pre><code>Selection.InlineShapes.AddOLEControl ClassType:="Forms.CheckBox.1", Caption:=""
</code></pre>
<p>But the code throws a "Named Argument Not Found" error while highlighting Caption:=""</p>
| <p>For anyone with the same issue</p>
<pre><code>'to place it in the table, assuming only 1 table, and in this example the checkbox is placed in the second Row, first Column
ActiveDocument.Tables(1).Cell(2, 1).Select
Set myOB = Selection.InlineShapes.AddOLEControl(ClassType:="Forms.CheckBox.1")
With myOB.OLEFormat
.Activate
Set myObj = .Object
End With
With myObj
'now you can name the field anything you want
.Name = "CB1"
.Value = False
'delete the caption, or have it say what you want
.Caption = ""
.Height = 22
.Width = 22
End With
</code></pre>
|
Bitmap from a whole Windows Form <p>In my Visual Studio 2015 Project I have a Form (tabPage) that is bigger as the screen, so one have to scroll. How can I draw the whole Form (not only visible area) into a bitmap?</p>
<pre><code>Bitmap bitmap = new Bitmap(tabPage1.Width, tabPage1.Height);
tabPage1.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
</code></pre>
<p>The code above draws only the visible part of the Form.</p>
| <p>Looks very similar to the question asked here:</p>
<p><a href="http://stackoverflow.com/questions/6001576/saving-panel-as-jpeg-only-saving-visible-areas-c-sharp">Saving Panel as JPEG, only saving visible areas c#</a></p>
<p>Here is the accepted answer from this post:</p>
<blockquote>
<p>Try following</p>
<pre><code> public void DrawControl(Control control,Bitmap bitmap)
{
control.DrawToBitmap(bitmap,control.Bounds);
foreach (Control childControl in control.Controls)
{
DrawControl(childControl,bitmap);
}
}
public void SaveBitmap()
{
Bitmap bmp = new Bitmap(this.panel1.Width, this.panel.Height);
this.panel.DrawToBitmap(bmp, new Rectangle(0, 0, this.panel.Width, this.panel.Height));
foreach (Control control in panel1.Controls)
{
DrawControl(control, bmp);
}
bmp.Save("d:\\panel.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}
</code></pre>
<p>Here is my result:</p>
<p><strong>Form ScreenShot</strong> :</p>
<p><img src="http://i.stack.imgur.com/Q2mgb.png" alt="enter image description here"></p>
<p><strong>Saved bitmap</strong> :</p>
<p><img src="http://i.stack.imgur.com/SKUSo.jpg" alt="enter image description here"></p>
<p>As you can see there is TextBox wich is not visible on form but is present in saved bitmap</p>
</blockquote>
|
Why can't I access EOF using fseek()? <pre><code>#include <stdio.h>
int main()
{
FILE * fp = fopen("Introduce.txt","rt");
fseek(fp,0,SEEK_END);
int i = feof(fp);
printf("%d",i);
fseek(fp,1,SEEK_END);
i = feof(fp);
printf("%d",i);
fseek(fp,-1,SEEK_END);
i = feof(fp);
printf("%d",i);
return 0;
}
</code></pre>
<p>I tried to access EOF positioning 'file position indicator' at the end of the file.<br>
But the result of this code is "000".
Why does this happen?</p>
| <p>The <code>feof()</code> function doesn't report that it is at EOF until you try to read some data and there is no data to read.</p>
<p>You can seek beyond the current EOF of a file that's open for writing (or that's open for reading and writing).</p>
<p>See <a href="http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong"><code>while (!feof(file))</code> is always wrong</a> for more information on why you seldom if ever need to use <code>feof()</code>. In some ways, <code>feof()</code> is a function you should forget about â most of your programs will improve if you assume it doesn't exist.</p>
|
Need Output on a Sql Queries <p>I have a Sql table:</p>
<pre><code>PLAN_CD PLAN_NM CLASS
D01501 DENTAL AA
D01501 DENTAL AB
D01501 DENTAL AC
V01501 VISION AA
V01501 VISION AB
</code></pre>
<p>Output should be:</p>
<pre><code>PLAN_CD PLAN_NM
D01501 DENTAL,AA,AB,AC
V01501 VISION,AA,AB
</code></pre>
| <p>Following 2 Questions might help you:</p>
<p><a href="http://stackoverflow.com/questions/273238/how-to-use-group-by-to-concatenate-strings-in-sql-server">How to use GROUP BY to concatenate strings in SQL Server?</a></p>
<p><a href="http://stackoverflow.com/questions/15154644/group-by-to-combine-concat-a-column">GROUP BY to combine/concat a column</a></p>
<p>Have a look.</p>
|
How to override "WebKit Built in pdf" of safari 10 with adobe pdf? <p>I want to override "webkit built in pdf" of safari 10 with adobePDFViewer.plugin, so that navigator.plugins in JavaScript could detect adobePDFViewer Plugin instead of "WebKit Built in pdf"</p>
<p>here what i am getting plugin array from navigator.plugins in console of latest safari 10.</p>
<p>platform: "MacIntel"</p>
<p>plugins: PluginArray</p>
<p>0: Plugin {0: MimeType, 1: MimeType, 2: MimeType, name: "WebKit built-in PDF", filename: "", description: "", length: 3, item: function, â¦}</p>
<p>length: 1</p>
<p>PluginArray Prototype</p>
<p>product: "Gecko"</p>
<p>productSub: "20030107"</p>
<p>userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Safari/602.1.50"</p>
<p>vendor: "Apple Computer, Inc."</p>
<p>vendorSub: ""</p>
<p>webdriver: undefined</p>
| <p>Hello Every one i found answer to this solution myself...!
As of now Safari and other latest browsers and Firefox restricts enumeration via navigator[] array of objects, which means that it does not allow plugins to content enumerating navigator.plugins[]. This change does not disable any plugins; it just hides some plugins names from enumeration.</p>
<p>In theory, all plugin names could be cloaked because web content can query navigator.plugins[] by plugin name. Unfortunately, we could not cloak all plugin names because many popular websites check for Flash or QuickTime by enumerating navigator.plugins[] and comparing plugin names one by one, instead of just asking for navigator.plugins["Shockwave Flash"] by name. These websites should be fixed. </p>
<pre><code> for (plugin of navigator.plugins) { console.log(plugin.name); }
"Shockwave Flash"
"QuickTime Plug-in 7.7.3"
"Default Browser Helper"
"Unity Player"
"Google Earth Plug-in"
"Silverlight Plug-In"
"Java Applet Plug-in"
"Adobe Acrobat NPAPI Plug-in, Version 11.0.18"
"WacomTabletPlugin"
navigator.plugins["Adobe Acrobat NPAPI Plug-in, Version 11.0.18"].name // get cloaked plugin by name
"Adobe Acrobat NPAPI Plug-in, Version 11.0.18"
</code></pre>
|
Why does Rust need to return static sizes? <p>I thought one of the big features of Rust is being a systems language comparable to C but with a garbage collector. If this is the case, why do you need to return values of a static size (or use <code>Box</code> from what I gather)?</p>
| <blockquote>
<p>Why does Rust need to return static sizes?</p>
</blockquote>
<p>Every value in every language needs to have a static size. That's how the compiler / interpreter / runtime / virtual machine / hardware knows how to access the bits that make up the value.</p>
<p>In many languages, every value is comparable to a Rust <code>Box</code>, so they all take up one or two pointer's worth of space. The statically-known size for those values allows a layer of indirection which can point to something with a runtime-determined size. </p>
<p>In Rust (and C, C++, probably other system languages), you can also directly store arbitrary values on the stack, unboxed. In these cases, you still need to know the size that the value will occupy.</p>
<p>This is a simplification, as some languages allow certain specific values to reside on the stack, while others "embed" certain value types inside of the fixed-size indirection. Tricks like these are usually for performance reasons.</p>
<blockquote>
<p>but with a garbage collector</p>
</blockquote>
<p><a href="https://www.rust-lang.org/en-US/faq.html#is-rust-garbage-collected">Rust <strong>does not</strong> have a garbage collector</a>. It does have <em>smart pointers</em> that deallocate resources when the pointer goes out of scope.</p>
<p><a href="https://doc.rust-lang.org/std/boxed/struct.Box.html"><code>Box</code></a> is the obvious smart pointer, but there's also <a href="https://doc.rust-lang.org/std/rc/struct.Rc.html"><code>Rc</code></a> and <a href="https://doc.rust-lang.org/std/sync/struct.Arc.html"><code>Arc</code></a>.</p>
|
c++ temp object created? <p>I would like to know how this code works. </p>
<pre><code>class Room
{
int sqft;
public:
Room(int k)
{
sqft = k;
}
int add(Room r)
{
return r.sqft + sqft;
}
};
int main()
{
Room living = Room(400);
Room Kitchen = Room(250);
Room Bedroom = Room(300);
int total = living.add(Kitchen.add(Bedroom)); // ***
cout << total << endl;
system("pause");
return 0;
}
</code></pre>
<p>The starred line is calling the add function within the Room class. But after Kitchen.add(Bedroom) the returned type is an int. There is not an add function that would take an int as a parameter so I expected the code to error. I thought the line would need to be:</p>
<pre><code>int total = living.add(Room(Kitchen.add(Bedroom)));
</code></pre>
<p>And this indeed works as well, I just don't understand how it works just passing the int to add as this line works as well:</p>
<pre><code>cout << living.add(10);
</code></pre>
<p>It appears as though since Room takes an int constructor c++ then knows how to implicitly cast an int to a Room. Is this true? And what is going on in C++ behind the scenes that makes this work?</p>
| <p>Yes it's true, since you declared a constructor that takes an <code>int</code> parameter, the compiler will implicitly convert an <code>int</code> to a <code>Room</code>.</p>
<p>You fix this by declaring the constructor to be explicit, then the compiler will no longer do an implicit conversion but will require you to <em>explicitly</em> call the constructor as you do in your example.</p>
<pre><code> explicit Room(int k)
//^^^^^^^^
{
sqft = k;
}
Room Bedroom = Room(300); // still works
int total = living.add(Kitchen.add(Bedroom)); // gives compile error
total = living.add(Room(Kitchen.add(Bedroom))); // works
</code></pre>
|
Is there a way to use itertools in python to clean up nested iterations? <p>Let's say I have the following code:</p>
<pre><code>a = [1,2,3]
b = [2,4,6]
c = [3,5,7]
for i in a:
for j in b:
for k in c:
print i * j * k
</code></pre>
<p>Is there a way I can consolidate an iterator in one line instead of making it nested?</p>
| <p>Use <code>itertools.product</code> within a list comprehension:</p>
<pre><code>In [1]: from itertools import product
In [5]: [i*j*k for i, j, k in product(a, b, c)]
Out[5]:
[6,
10,
14,
12,
20,
28,
18,
30,
42,
12,
20,
28,
24,
40,
56,
36,
60,
84,
18,
30,
42,
36,
60,
84,
54,
90,
126]
</code></pre>
|
Unable to set property 'src' of undefined or null reference <p>I am trying to use a button to change a picture on my webpage. When assigning a new value to the <code>src</code> attribute I have below error</p>
<blockquote>
<p>Unable to set property 'src' of undefined or null reference</p>
</blockquote>
<p>My code is below:</p>
<pre><code><nav>
<ul class="menuitem">
<li><a href="#Introduction">Introduction</a></li>
<li><a href="#Experience">Experience</a></li>
<li><a href="#Skills">Skills</a></li>
<li><a href="#Courses">Courses</a></li>
<li><a href="#Links">Links</a></li>
<li><a href="#Contact">Contact</a></li>
</ul>
<id ="navImg">
<img src="C:\Users\toffy\Desktop\Course\CMP\Web-based\Worksheets\Tools\cat-selfie.jpg" alt="CatSelfie"style="width:125px;height:75px;" />
</id>
<button type="button" onclick="imgUpdate()">Another image</button></button>
<script>
function imgUpdate(){
document.getElementById("navImg").src="C:\Users\toffy\Desktop\Course\CMP\Web-based\Worksheets\Tools\foo.jpg";
}
</script>
</nav>
</code></pre>
| <p>You can fix it by not making up your own HTML tags. <code><id></code> is not a valid html tag, period. ID is an <strong>ATTRIBUTE</strong> for a tag, it is not tag itself:</p>
<pre><code><img id="navImg" ...>
</code></pre>
<p>And even if it WAS a tag, you'd be setting the <code>src</code> of the <code><id></code> tag, not the img, and effectively have</p>
<pre><code><id =navImg src="...">
</code></pre>
|
Spring Boot @ModelAttribute include other model using string key <p>I'm a spring newbie.</p>
<p>I have a Model like below.</p>
<pre><code>User {
@Id
@GeneratedValue
private Integer id;
}
PowerUser {
@ManyToOne
private User user;
private Integer point;
}
Controller {
registerPowerUser(@ModelAttribute PowerUser powerUser) {
return ResponseEntity.status(HttpStatus.CREATED).body(powerUser);
}
}
</code></pre>
<p>I could call controller with <strong>?user=1</strong></p>
<p>But, I changed User like this.</p>
<pre><code>User {
@Id
@Column(unique = true)
private String serial_number;
}
</code></pre>
<p>This code is not work with <strong>?user=serial_number</strong></p>
<p>Failed to convert property value of type [java.lang.String] to required type [com.project.domain.User] for property 'user';...</p>
<p>Is it impossible to use auto reference using String id?</p>
| <p>The problem was repository.</p>
<pre><code>public interface UserRepository extends JpaRepository<User, Integer> {
</code></pre>
<p>to</p>
<pre><code>public interface UserRepository extends JpaRepository<User, String> {
</code></pre>
<p>works well.</p>
|
imgurpython.helpers.error.ImgurClientRateLimitError: Rate-limit exceeded <p>I have the following error:</p>
<pre><code>/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
Traceback (most recent call last):
File "download.py", line 22, in <module>
search = imgur_client.gallery_search('cat', window='all', sort='time', page=p)
File "/usr/local/lib/python2.7/dist-packages/imgurpython/client.py", line 531, in gallery_search
response = self.make_request('GET', 'gallery/search/%s/%s/%s' % (sort, window, page), data)
File "/usr/local/lib/python2.7/dist-packages/imgurpython/client.py", line 153, in make_request
raise ImgurClientRateLimitError()
imgurpython.helpers.error.ImgurClientRateLimitError: Rate-limit exceeded!
</code></pre>
<p>for this code:</p>
<pre><code> 1 from imgurpython import ImgurClient
2 import inspect
3 import random
4 import urllib2
5 import requests
6 from imgurpython.helpers.error import ImgurClientError
7
8 client_id = "ABC"
9 client_secret = "ABC"
10 access_token = "ABC"
11 refresh_token = "ABC"
12
13
14
15 image_type = ['jpg', 'jpeg']
16
17 imgur_client = ImgurClient(client_id, client_secret, access_token, refresh_token)
18
19 item_count = 0
20 for p in range(1, 10000):
21 try:
22 search = imgur_client.gallery_search('cat', window='all', sort='time', page=p)
23 for i in range(0,https://gist.github.com/monajalal/e02792e9a5cbced301a8691b7a62836f len(search)):
24 item_count +=1
25 print(search[i].comment_count)
26 if search[i].comment_count > 10 and not search[i].is_album:
27 print(search[i].type)
28 if search[i].type[6:] in image_type:
29 count = 0
30 try:
31 image_file = urllib2.urlopen(search[i].link, timeout = 5)
32 image_file_name = 'images/'+ search[i].id+'.'+search[i].type[6:]
33 output_image = open(image_file_name, 'wb')
34 output_image.write(image_file.read())
35 for post in imgur_client.gallery_item_comments(search[i].id, sort='best'):
36 if count <= 10:
37 count += 1
38 output_image.close()
39 except urllib2.URLError as e:
40 print(e)
41 continue
42 except socket.timeout as e:
43 print(e)
44 continue
45 except socket.error as e:
46 print(e)
47 continue
48 except ImgurClientError as e:
49 print(e)
50 continue
51
52 print item_count
</code></pre>
<p>Also I see this line almost very often:</p>
<pre><code>/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
</code></pre>
<p>How can I fix the error? Is there any workaround for rate limit error in Imgur? So I am creating this app for academic research use not for commercial and according to <a href="https://api.imgur.com/#limits" rel="nofollow">https://api.imgur.com/#limits</a> it should be free but I had to register my app to get client_id related stuff. How can I set my application as non-commercial so that I would not get this rate limit error or if all kind of applications get this error how should I handle it? How should I set my code so that it would make only 1250 requests per hour?</p>
<p>Also here's my credit info:</p>
<pre><code>User Limit: 500
User Remaining: 500
User Reset: 2016-10-18 14:32:41
User Client Limit: 12500
User Client Remaining: 9570
</code></pre>
<p>UPDATE: With sleep(8) as suggested in the answer I end up with this going on continuously. For different search query this happens at different pages. How can I fix the code so that it would stop executing when this happens? Here's the related code to the update: <a href="https://gist.github.com/monajalal/e02792e9a5cbced301a8691b7a62836f" rel="nofollow">https://gist.github.com/monajalal/e02792e9a5cbced301a8691b7a62836f</a></p>
<pre><code>page number is: 157
0
image/jpeg
page number is: 157
0
page number is: 157
0
page number is: 157
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
</code></pre>
| <p>The rate limit refers to how frequently you're hitting the API, not how many calls you're allowed. To prevent hammering, most APIs have a rate limit (eg: 30 requests per minute, 1 every 2 seconds). Your script is making requests as quickly possible, hundreds or even thousands of times faster than the limit.</p>
<p>To prevent your script from hammering, the simplest solution is to introduce a <a href="https://docs.python.org/2/library/time.html#time.sleep" rel="nofollow"><code>sleep</code></a> to your for loop.</p>
<pre><code>from time import sleep
for i in range(10000):
print i
sleep(2) # seconds
</code></pre>
<p>Adjust the sleep time to be at least one second greater than what the API defines as its rate limit.</p>
<p><a href="https://api.imgur.com/#limits" rel="nofollow">https://api.imgur.com/#limits</a></p>
<blockquote>
<p>The Imgur API uses a credit allocation system to ensure fair distribution of capacity. Each application can allow <strong>approximately 1,250 uploads per day or approximately 12,500 requests per day</strong>. If the daily limit is hit five times in a month, then the app will be blocked for the rest of the month. The remaining credit limit will be shown with each requests response in the <code>X-RateLimit-ClientRemaining</code> HTTP header.</p>
</blockquote>
<p>So 12500 requests / 24 hours is 520 requests per hour or ~8 per minute. That means your sleep should be about 8 seconds long.</p>
|
I am unable to break a loop that repeatedly asks for user input. Anyone know how to solve this? <p>I am trying to create a loop that will ask the user for an integer and will then print "hi" an integer number of times and then ask for input again. I then want the loop to break if the user inputs "bye". </p>
<p>my code so far: </p>
<pre><code> def hi_hi_goodbye
loop do
number = gets
(number.to_i).times do
print "hi"
end
break if
gets == "bye"
end
end
</code></pre>
<p>My code so far will not loop. It receives the integer and prints "hi" a given amount of times. However, I am unable to break the loop.</p>
| <p>Try</p>
<pre><code> break if gets.chomp == "bye"
</code></pre>
<p>This is so because your input would be something like <code>bye\n</code>, so your condition always false, because <code>gets</code> takes even the enter.</p>
|
VBA - Split and IsError Function <p>I'm struggling with VBA code. I'm working on a ID code generator program. One of the processes involves Split Company Names by words, and taking the first two words. Split has proved to be useful in this tasks, however, when in dealing with Company Names shorter than 2 words I've got a #VALUE! Error.</p>
<p>One way I tried to fix it, was using the ISERROR function, so if I get any error it replaces it with a character, say "X".</p>
<p>In summary, what I'm trying is to capture only the second Word of the Name, if there is no second Word, just display "X".</p>
<pre><code>Public Function idcode_2(text As String) As String
Dim Arr_text As Variant
Dim rz_x, rz2, code As String
Dim i As Integer
Dim c
Arr_text = Split(text, " ", 3)
rz2 = Arr_text(1)
If IsError(rz2) = True Then
rz2 = "X"
Else
rz2 = rz2 & ""
End If
idcode_2 = rz2
End Function
</code></pre>
<p>I'm using VBA in Excel - Microsoft Office Professional Plus 2013.</p>
| <p>Arr_text will be a zero-based array - UBound(Arr_text) will give you the upper bound of that array (zero if one item, one if two items, etc)</p>
<pre><code>Public Function idcode_2(text As String) As String
Dim Arr_text As Variant, rz2
Arr_text = Split(text, " ", 3)
If UBound(Arr_text ) > 0 Then
rz2 = Arr_text(1)
Else
rz2 = "x"
End If
idcode_2 = rz2
End Function
</code></pre>
|
Can't execute sql file <p>I'm trying to execute the following code using isql:</p>
<pre><code>IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'SFPTB051_ABERTURARCLH'))
BEGIN
SELECT * FROM SFPTB051_ABERTURARCLH;
END
</code></pre>
<p>The way i'm doing:</p>
<pre><code>isql -i sql_scripts/test.sql _input/mygdb.GDB -user SYSADM -pass masterkey
</code></pre>
<p>Output:</p>
<pre><code>Statement failed, SQLSTATE = 42000
Dynamic SQL Error
-SQL error code = -104
-Token unknown - line 1, column 1
-IF
At line 1 in file sql_scripts/test.sql
Expected end of statement, encountered EOF
</code></pre>
<p>Any ideias?</p>
<p>Thanks!</p>
<p>UPDATE ---</p>
<p>I'm trying the following:</p>
<pre><code>SET TERM # ;
EXECUTE BLOCK AS
BEGIN
SELECT * FROM SFPTB051_ABERTURARCLH
END#
SET TERM ; #
</code></pre>
<p>But it's returning:</p>
<pre><code>Statement failed, SQLSTATE = 42000
Dynamic SQL Error
-SQL error code = -104
-Token unknown - line 4, column 1
-END
</code></pre>
| <p>Usually, select statements within a block statement need to return their values. For example, you can return them into variables or return values, which are almost the same.</p>
<p>Furthermore, every statement within a block statement has to be terminated by a semi-colon (<code>;</code>).</p>
<p>Your block statement could look something like this:</p>
<pre><code>SET TERM # ;
EXECUTE BLOCK AS
DECLARE VARIABLE FIELD1 TYPE OF COLUMN SFPTB051_ABERTURARCLH.FIELD1;
/* declare more variables as needed */
BEGIN
FOR
SELECT FIELD1
FROM SFPTB051_ABERTURARCLH
INTO :FIELD1
DO
BEGIN
/* do something with the variables values */
END
END#
SET TERM ; #
</code></pre>
|
Converting a recursive method into a non-recursive method using loop in java <p>So I'm currently making a game where the instructions are to move left or right within an array using the integer stored at a marked index (circle in this case) until we can get the circle to the last index of the array. The last integer of the array is always 0.</p>
<p>For example,</p>
<p>[4] 1 2 3 1 0, here we start at the circle 0 (index)</p>
<p>We move 4 to the right, 4 1 2 3 [1] 0</p>
<p>Then 1 time to the right, 4 1 2 3 1 [0]. Here the game stops and we win.</p>
<p>My code is as follows for a recursive method:</p>
<pre><code>public static boolean rightWing (int circle, int[] game, List<Integer> checkerList){
int last = game.length-1;
if (circle == last){ // base case for recursion
return true;
}
if (circle < 0){ // if we go out of bounds on the left
return false;
}
if (circle > last){ // if we go out of bounds on the right
return false;
}
if (checkerList.contains(circle)){ // check for the impossible case
return false;
}
checkerList.add(circle); // adds the circle value for the last check to checkerList so we can check for the impossible case
int moveRight = circle + game[circle]; // these two integers help the game move according to the value of the int at circle
int moveLeft = circle - game[circle];
return rightWing( moveRight, game, checkerList) || rightWing(moveLeft, game,checkerList);
}
</code></pre>
<p>This works great, but the only problem is it's recursive and slow. I'm trying to redesign it using loops and stacks/queues to make it more efficient, but I'm stuck after writing this (in pseudo):</p>
<pre><code> Boolean rightWing (int circle, List<int> game, List<int> checkerList)
Int lastPlace = game.size() - 1
For int i <- 0 to game.size() - 1 do
If i equals lastPlace then // returns true when i is at the last position of the game
Return true
</code></pre>
<p>Any input on how to go forward would be appreciated! </p>
| <p>The most important bit: when debugging app for the slowness, you should <strong>collect some performance data first</strong> to identify where your app is spending the most of its time. Otherwise fixing performance is inefficient. You can use <code>jvisualvm</code> it's bundled with jdk.</p>
<h1>Data structures rule the world of performance</h1>
<p>One thing why it can be slow is because of this:</p>
<pre><code>if (checkerList.contains(circle)){ // check for the impossible case
return false;
}
</code></pre>
<p>The more items you have in the list, the slower it becomes. List has <code>linear complexity</code> for the <code>contains</code> method. You can make it <code>constant complexity</code> if you'll use <code>HashSet</code>. E.g. if you have list with 100 elements, this part will be around slower 100 times with <code>List</code> than with <code>HashSet</code>.</p>
<p>Another thing which might be taking some time is boxing/unboxing: each time you put element to the list, <code>int</code> is being wrapped into new <code>Integer</code> object - this is called boxing. You might want to use <code>IntSet</code> to avoid boxing/unboxing and save on the GC time.</p>
<h1>Converting to the iterative form</h1>
<p>I won't expect this to affect your application speed, but just for the sake of completeness of the answer.</p>
<p>Converting recursive app to iterative form is pretty simple: each of the method parameters under the cover is stored on a hidden stack on each call of your (or others function). During conversion you just create your own stack and manage it manually</p>
<pre><code>public static boolean rightWingRecursive(int circle, int[] game) {
Set<Integer> checkerList = new HashSet<Integer>();
Deque<Integer> statesToExplore = new LinkedList<>();
int last = game.length - 1;
statesToExplore.push(circle);
while (!statesToExplore.isEmpty()) {
int circleState = statesToExplore.pop();
if (circleState == last) { // base case for recursion
return true;
}
if (circleState < 0) { // if we go out of bounds on the left
continue;
}
if (circleState > last) { // if we go out of bounds on the right
continue;
}
if (checkerList.contains(circle)) { // check for the impossible case
continue;
}
checkerList.add(circle); // adds the circle value for the last check to
// checkerList so we can check for the
// impossible case
int moveRight = circle + game[circle]; // these two integers help the
// game move according to the
// value of the int at circle
int moveLeft = circle - game[circle];
statesToExplore.push(moveRight);
statesToExplore.push(moveLeft);
}
return false;
}
</code></pre>
|
get index in multidimensional array in javascript <p>This question is follow up for,
<a href="http://stackoverflow.com/questions/40111302/get-the-index-of-a-multidimensional-array-with-the-value-of-a-given-string-in-ja">Get the index of a multidimensional array with the value of a given string in javascript</a></p>
<p>I tried this answer,</p>
<pre><code>var a1 = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]],
a2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]],["S",["Sally","Sam","Sammy Davis"]]],
getStatus = (a,n) => a.find(e => e[1].indexOf(n) !== -1)[0],
getIndex = (a,n) => a.findIndex(e => e[1].indexOf(n) !== -1);
console.log(getStatus(a1,"Mary"));
console.log(getIndex(a2,"Sammy Davis"));
</code></pre>
<p>This is working, but there are issues.
What if the given string is not in the array? how to handle that?
How to get all the indexes if there are more than one index that have a value of the given string?</p>
<p>For example, In the a1,</p>
<pre><code>var a1 = ["present",["John","Josh","Jay"]],["absent",["May","Josh","Mary Jane"]]]
</code></pre>
<p>How to get 0,1? using getIndex()?</p>
| <p>I have to agree with @Rob M.'s comment yet still you might do as follows;</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var a1 = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]],
a2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]],["S",["Sally","Sam","Sammy Davis"]]],
getStatus = (a,n) => a.find(e => e[1].indexOf(n) !== -1)[0],
getIndex = (a,n) => { var x = -1;
return [a.findIndex(e => (x = e[1].indexOf(n), x !== -1)),x];
};
console.log(getIndex(a2,"May"));
console.log(getIndex(a2,"Sammy Davis"));
console.log(getIndex(a2,"Daniel"));</code></pre>
</div>
</div>
</p>
|
SOAP to Rest Service Using Adapter <p>I have a legacy project where it has SOAP webservices exposed. Now I have a requirement to convert them to rest and use it accordingly. </p>
<p>Can I have implementation like Jersey available to consume these soap services and then publish the same as REST?</p>
| <p>This is a common problem when dealing with legacy APIs. Since REST is not a protocol by definition you can implement either:</p>
<ul>
<li><p><strong>Protocol Bridging Pattern</strong>. It is a common SOA pattern that helps you transform between different protocols by using a bridging broker as intermediary. The broker holds the transformation logic. You can find <a href="http://soapatterns.org/design_patterns/protocol_bridging" rel="nofollow">more information here</a>. Such bridges are available in most ESBs and EAI middle-wares.
<a href="https://i.stack.imgur.com/hHVDP.png" rel="nofollow"><img src="https://i.stack.imgur.com/hHVDP.png" alt="Protocol Bridging Pattern"></a></p></li>
<li><p><strong>Data Format Transformation Pattern</strong>. It transforms between data formats and you can use it to transform from XML to the REST format you are using. You can implement it by putting in some internal service logic, service agents, or a dedicated transformation service. <a href="http://soapatterns.org/design_patterns/data_format_transformation" rel="nofollow">You can see more here.</a>. You can absolutely use Jersey to build a REST Facade and transform internally from XML, or build the logic inside each service.
<a href="https://i.stack.imgur.com/O1icO.png" rel="nofollow"><img src="https://i.stack.imgur.com/O1icO.png" alt="Data Format Transformation Pattern"></a></p></li>
</ul>
<p>It really depends on the size of your API and the type of solution you need. For few services I will choose the second approach - it's easier but a bit more coupled, while if I have many services I'd go for the first approach, which in my opinion abstracts transformation logic better, but it may require additional middleware and effort.</p>
|
How to add additional tick labels, formatted differently, in matplotlib <p>I'm having real problems plotting a 2nd line of tick labels on x-axis directly underneath the original ones. I'm using seaborn so I need to add these extra labels after the plot is rendered.</p>
<p>Below is <a href="http://content.screencast.com/users/cmardiros/folders/Jing/media/51a8b412-e3db-4030-81c9-cd389336f626/00000034.png" rel="nofollow">what I'm trying</a> to achieve but I'd like the gap between the 2 rows of tick labels to be a bit bigger and make the 2nd row bold and a different colour.</p>
<p><a href="https://i.stack.imgur.com/V1pGKm.png" rel="nofollow"><img src="https://i.stack.imgur.com/V1pGKm.png" alt="enter image description here"></a></p>
<p>My attempts involve hacking the existing tick labels and appending the new strings underneath separated by newline:</p>
<pre><code> # n_labels is list that has the new labels I wish to plot directly
# underneath the 1st row
locs = ax.get_xticks().tolist()
labels = [x.get_text() for x in ax.get_xticklabels()]
nl = ['\n'.join([l, n_labels[i]]) for i, l in enumerate(labels)]
ax.set_xticks(locs)
ax.set_xticklabels(nl)
</code></pre>
<p>Any ideas? Thank you!</p>
| <p>One possibility would be to create a second x-axis on top of the first, and adjust the position and xtickslabels of the second x-axis. Check <a href="http://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html" rel="nofollow">this example</a> in the documentation as a starting point.</p>
|
How to known the level of current page in Django-CMS <p>my page.html has this</p>
<pre><code>{% extends "base.html" %}
{% load cms_tags menu_tags %}
{% block title %}{% page_attribute "page_title" %}{% endblock title %}
{% block content %}
{% placeholder "content" %}
{% show_menu 2 0 0 100 %}
{% endblock content %}
</code></pre>
<p>But depend of the level of the current page I have to show different element on the page, something like this</p>
<pre><code>{% if node.menu_level == 2 %}
{% show_menu 2 0 0 100 %}
{% else %}
#do something different
{% endif %}
</code></pre>
<p>How to do that? How to know the level of the current page?</p>
| <p>I do something like this to select a relevant page title based on the ancestry of the page;</p>
<pre><code>{% if request.current_page.get_ancestors|length <= 1 %}
<h1 class="pipe-title pipe-title--inset">
{{ request.current_page.get_page_title }}
</h1>
{% else %}
{% for ance in request.current_page.get_ancestors %}
{% if ance.depth == 2 %}
<h1 class="pipe-title pipe-title--inset">{{ ance.get_page_title }}</h1>
{% endif %}
{% endfor %}
{% endif %}
</code></pre>
<p>So you could do whatever you wanted based on the page depth in the menu tree.</p>
|
Activity to Fragment on button click <p>I have navigation bar on my app. Using that has created fragments. I added regular activities to the app and I have found how to go from a Fragment page to an activity page with using the onclick method. </p>
<p>By the click of a button I want to go from an activity page to a fragment page. How do I go about that?</p>
<p>Thank you</p>
| <p>If you want to close the current activity to go back to your Fragment-container Activity you may call the finish() method or onBackPressed() method (in case you're not overriding it).</p>
<hr>
<p>If you want to bring a fragment to the current activity you must have a fragment container and attach it with:</p>
<pre><code>getSupportFragmentManager().beginTransaction.add(R.id.container, fragment, TAG).addToBackStack().commit();
</code></pre>
|
java get web content for many webpages <p>So previously I had a program that would go to a lot of websites and get part of the source code out of those websites that I wanted. However recently the websites have been updated to now load the information I want dynamically, and I no longer get it. </p>
<p>I have made another version of my program using Selenium that worked, but it took too long to be practical, is there another way of getting the content faster? One thing I noticed is that Internet Explorer version 11 still has the website content loaded the way it used to be, can I get the source specifically from there?</p>
<p>The way I was getting it before that worked was like this:</p>
<pre><code>public static void main(String[] args) throws IOException{
String example = getSource("http://www.google.com");
System.out.println(example);
}
public static String getSource(String urlToGoTo) throws IOException
{
URL url = new URL(urlToGoTo);
URLConnection connection = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
StringBuilder a = new StringBuilder();
while ((inputLine = in.readLine()) != null)
a.append(inputLine);
in.close();
return a.toString();
}
</code></pre>
<p>Any ideas are welcome, I've been trying to find a way to get this to work for way to long, given that it sounds like it shouldn't be too complicated.</p>
| <p>It seems your are trying to get the page source. There's a method for that in selenium. You may use it instead of your </p>
<pre><code>getSource("http://www.google.com");
</code></pre>
<p>Create an WebDriver instance and navigate to your url and get the page source.</p>
<p><strong>Code snippet:</strong></p>
<pre><code>WebDriver driver = new FirefoxDriver();
driver.get("your URL");
String pageSource = driver.getPageSource();
</code></pre>
|
Ajax not returning results <p>Alright so I have this code which basically finds the user inside the table users and displays it in alert, but it seems that I am doing something wrong. The log shows "Function is not set" and the alert itself displays that.</p>
<p>This is the HTML form I have for it</p>
<pre><code><center><form method='POST' >
<input id="search_fix" type="text" name="search" placeholder="Search..">
<input type="submit" name="submit_menu_search" style="display: none;">
</form></center>
</code></pre>
<p>This is the ajax processing </p>
<pre><code>$(document).ready(function() {
$("#search_fix").keyup(function() {
var search_text = $(this).val();
if(search_text != '') {
$.ajax({
url:"handler.php",
method:"POST",
data:{"function":"search_ajax", search:search_text},
dataType:"text",
success:function(data){
$('#search_result').html(data);
console.log(data);
alert(data);
}
});
}
else {
}
});
});
</code></pre>
<p>And these are my PHP functions that I used to basically search for the term</p>
<pre><code>public function search_ajax($term) {
$handler = new sql();
$sql = $handler->connect();
$sql->real_escape_string($term);
$result = $sql->query("SELECT ime FROM users WHERE ime LIKE '%".$term."%'") or die (mysql_error());
if($result->num_rows >= 1){
while($row = $result->fetch_assoc()) {
echo $row['ime'];
}
}
}
if(isset($_POST['function'])) {
switch($_POST['function']) {
case "search_ajax": {
require_once "assembly/user.php";
$user = new User();
$user->search_ajax($_POST['search']);
break;
}
default: {
echo "Unknown AJAX function handler";
break;
}
}
}
else {
echo "Function is not set";
}
</code></pre>
| <p>It sounds like you're using a version of jQuery before 1.9.0. The <code>method:</code> option didn't exist in the older versions, it was called <code>type:</code>. That's why you're seeing the parameters appended to the URL, because <code>type: "GET"</code> is the default.</p>
<p>So change</p>
<pre><code>method: "POST",
</code></pre>
<p>to:</p>
<pre><code>type: "POST",
</code></pre>
|
Displaying component with @Input in another component's router-outlet <p>I wanted to know if you guys know a way to display components that take a @Input directive inside of a router-outlet.</p>
<p>I have several components that takes in @Inputs and I would like to display these components dynamically in one component. I would like to design this one component container to be as abstract as possible, so it would be reusable and extendable in the future.</p>
<p>I'm trying to achieve something like</p>
<p>big-container.component has </p>
<pre><code><router-outlet name='container1'></router-outlet>
</code></pre>
<p>in which links to container1.component which contains</p>
<pre><code><container1 [settings]=mySettings></container1>
</code></pre>
<p>I would like to get container1.component to display in big-container.component's router-outlet with the [settings].</p>
<p>Thank you!</p>
| <p>As this <a href="http://stackoverflow.com/a/34648272/7038491">POST</a> states it is currently not possible. </p>
<p>Here is the <a href="https://github.com/angular/angular/issues/4452" rel="nofollow">linked issue</a> on Github</p>
<blockquote>
<p>Use a shared service to communicate with components added by the router. For details see <a href="https://angular.io/docs/ts/latest/cookbook/component-communication.html" rel="nofollow">https://angular.io/docs/ts/latest/cookbook/component-communication.html</a></p>
</blockquote>
|
How to add a new column or table to sqlite database pre-populated in the assets and using SQLiteAssetHelper <p>How can I add a new column or new table to the database that pre-populated (in the assets) using SQLiteAssetHelper.
I originally preload a simple table with 3 columns:</p>
<ul>
<li>id</li>
<li>question</li>
<li>answer</li>
</ul>
<p>Once installed the app, I need to add some columns that will be populated with user data, like marked as favorite, seen before, edited...
Also I need to add a new table that record the time of the study session, and last question seen.
here's my code:</p>
<pre><code>import android.content.Context;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class DatabaseOpenHelper extends SQLiteAssetHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "mydatabase.db.sqlite";
public DatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
</code></pre>
<p>and </p>
<pre><code>public class DatabaseAccess {
private SQLiteOpenHelper openHelper;
private SQLiteDatabase database;
private static DatabaseAccess instance;
</code></pre>
| <p>Hi you can use onUpgrade </p>
<pre><code>public class OpenHelper extends SQLiteOpenHelper {
private final static int DB_VERSION = 2;
public TracksDB(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
//....
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 2) {
"create table session"
" (_id integer primary key autoincrement, " +
"date text not null, " +
"question text not null);";
db.execSQL(CREATE_TBL );
}
}
}
</code></pre>
<p>You can check database Version. If database version in app old version run create or alter query query.</p>
<pre><code>SQLiteDatabase db = new Helper(context).getWritableDatabase();
if(db.getVersion()<2){
"create table session"
" (_id integer primary key autoincrement, " +
"date text not null, " +
"question text not null);";
db.execSQL(CREATE_TBL );
}
You must upgrade database version in asset folder.
</code></pre>
|
python: could not convert string to float <p>im submitting this code..</p>
<pre><code>a = float(input())
b = float(input())
c = float(input())
if abs(b - c) < a < (b + c) and abs(a - c) < b < (a + c) and abs(a - b) < c < (a + b):
print("Perimetro = " + str(a + b + c))
else:
print("Area = " + str(((a + b) * c) / 2))
</code></pre>
<p>and for me it was correct, but, as a response, i get: </p>
<pre><code>Traceback (most recent call last):
File "Main.py", line 1, in <module>
a = float(input())
ValueError: could not convert string to float: '6.0 4.0 2.0'
Command exited with non-zero status (1)
</code></pre>
<p>which i dont get it cause i converted the strings in the begginning.</p>
<p>what am i doing wrong here?</p>
<p>thanks x</p>
| <p>The issue is that you are entering all the three values at once. Add one value and then press enter. For example:</p>
<pre><code>>>> a = float(input())
6.0
>>> b = float(input())
4.0
>>> c = float(input())
2.0
>>> a, b, c
(6.0, 4.0, 2.0)
</code></pre>
<p>OR, get the single string and <code>split</code> the string to assign the value to <code>a</code>, <code>b</code> and <code>c</code>. For example:</p>
<pre><code>>>> a, b, c = [float(item) for item in input().split()]
6.0 4.0 2.0
>>> a, b, c
(6.0, 4.0, 2.0)
</code></pre>
|
How do I switch to the new color map in matplotlib 1.5? <p>I want to write a line to switch all my plots to the new color map (viridis), how do I do that?</p>
<p>There's a lot of information on the new available colors <a href="http://matplotlib.org/users/colormaps.html" rel="nofollow">http://matplotlib.org/users/colormaps.html</a>, there's information on how to pick a style with the <code>style.use("ggplot")</code> <a href="http://matplotlib.org/users/style_sheets.html" rel="nofollow">http://matplotlib.org/users/style_sheets.html</a>, and there's a page saying that the new color map is changing <a href="http://matplotlib.org/style_changes.html#" rel="nofollow">http://matplotlib.org/style_changes.html#</a>. On none of those do they say how to actually switch to a different colormap...</p>
| <p>In matplotlib, the "styles" control much, much more than just the colormap.</p>
<p>To configure one aspect of the style on the fly, use:</p>
<pre><code>import matplotlib
matplotlib.rcParams['image.cmap'] = 'viridis'
</code></pre>
<p>In the forthcoming v2.0 release of matplotlib, viridis will be the default colormap and this won't be necessary. Lots of other stylistic changes will be in place as well. You can look at those here:</p>
<p><a href="http://matplotlib.org/devdocs/gallery.html" rel="nofollow">http://matplotlib.org/devdocs/gallery.html</a></p>
<p>To look at the available styles, inspect the <code>available</code> list:</p>
<pre><code>from matplotlib import pyplot
pyplot.style.available
</code></pre>
<p>For the new default color cycle, you'd do:</p>
<pre><code>from cycler import cycler
colors = [
'#1f77b4', '#ff7f0e', '#2ca02c',
'#d62728', '#9467bd', '#8c564b',
'#e377c2', '#7f7f7f', '#bcbd22',
'#17becf'
]
matplotlib.rcParams['axes.prob_cycle'] = cycler('color', colors)
</code></pre>
|
Problems with reversing line into file <p>This code does reverse and put result in file, but not fully correct.
Like, some issues with detecting line breaker or sth. Here's an example:</p>
<p>Source:</p>
<pre><code>This is a line.
This is another line.
Quick brown fox jumps over a lazy dog!
</code></pre>
<p>Result:</p>
<pre><code>(blank line)
.enil a si sihT
.enil rehtona si sihT!god yzal a revo spmuj xof nworb kciuQ
</code></pre>
<pre><code>#include <stdio.h>
#include <string.h>
char *reverse (char *str)
{
char *begin, *end, c;
if (!str || !(*str))
return NULL;
for (begin=str, end=str+strlen(str)-1; begin<end; begin++, end--)
{
c=*begin;
*begin=*end;
*end=c;
}
begin=str+strlen(str)+1; *begin='\0'; //??
return str;
}
void main(void)
{
char line[1000];
FILE *fsrc, *frslt;
fsrc=fopen("source.txt", "r");
if (fsrc==NULL) return;
frslt=fopen("result.txt", "w");
while (!feof(fsrc))
{
fgets (line, 1000, fsrc);
fputs (reverse(line), frslt);
}
fclose(fsrc);
fclose(frslt);
}
</code></pre>
| <p>A couple of comments/nitpicks, which may or may not solve your problem :)</p>
<pre><code>if (!str || !(*str))
return NULL;
</code></pre>
<p>Don't do that. Don't return NULL on empty strings, fputs() will barf. In my experience, it's better to a) assert that the str pointer is non-null, b) return the empty string. </p>
<pre><code>begin=str+strlen(str)+1; *begin='\0'; //??
</code></pre>
<p>There should be no need to terminate the string, since it's already terminated.</p>
<pre><code>void main(void)
</code></pre>
<p>Nah, main() returns an int. </p>
<pre><code>while (!feof(fsrc))
</code></pre>
<p>This won't work. You need to do some IO before you can test for feof()/ferror(). IMHO it's better to simply loop on fgets().</p>
<pre><code>while (fgets(line, sizeof line, fsrc) {
...
}
</code></pre>
<p>It may be a good idea to drop the input and output files, and simply read from stdin and write to stdout, at least while testing. The functionality you're trying to implement is already available in a UNIX shell (man rev). Using stdin/stdout makes it easier to test and compare results with the results from rev.</p>
<p>Also, keep in mind that fgets() won't remove the \n from the string. input like "foo\n" becomes "\noof", which is probably not what you want. </p>
<p>Here's a snippet which illustrates my comments in code. It doesn't solve all problems, but should be sufficient to get you going. </p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <assert.h>
void reverse(char *str)
{
char *begin, *end, c;
size_t n;
assert(str != NULL);
n = strlen(str);
if (n == 0)
return;
for (begin = str, end = str + n - 1; begin < end; begin++, end--) {
c = *begin;
*begin = *end;
*end = c;
}
}
int main(void)
{
char line[1000];
while (fgets(line, sizeof line, stdin)) {
reverse(line);
fputs(line, stdout);
}
}
</code></pre>
<p>HTH</p>
|
How to apply a PropertyChanges on a property named "target" <p>Here's an example <code>State</code> and <code>PropertyChanges</code> from the docs:</p>
<pre><code>State {
name: "resized"; when: mouseArea.pressed
PropertyChanges { target: rect; color: "blue"; height: container.height }
}
</code></pre>
<p>The object to change is identified in the <code>target</code> property, and other properties of <code>PropertyChanges</code> map 1-to-1 to properties of the targeted object.</p>
<p>But if one wants to change a property named <code>target</code> on <code>foo</code> to <code>bar</code>, the naive thing would be <code>PropertyChanges { target: foo; target: bar }</code>, which I'm sure wouldn't work.</p>
<p>Is there a way to disambiguate the target of <code>PropertyChanges</code> from the target of its target?</p>
| <p>With a little tweak, this is no problem.
If you can't alias it at the targetobject creation yourself, do it in the states like so:</p>
<pre><code>Rectangle {
id: rect
property int target: 20
x: target
y: target
width: target
height: target
color: 'orchid'
states: State {
id: altState
name: 'alternative'
property alias mytarget: rect.target
PropertyChanges {
target: altState
mytarget: 50
}
}
MouseArea {
anchors.fill: parent
onClicked: parent.state = 'alternative'
}
}
</code></pre>
|
If statement in foreach loop char check <p>I need to only run the foreach on iterations that find a currency symbol. Currently, I have this -</p>
<pre><code>$transferid = $key;
$donation1 = $value["news"];
$donationcomma = getStringBetween($donation1,$from,$to);
$donation = str_replace(',', '', $donationcomma);
$playeridregex = preg_match("/XID=(.*)\"/", $donation1, $playerid);
$playerid1 = preg_replace("/[^A-Za-z0-9'-]/","",$playerid[1]);
</code></pre>
<p>which I can in turn get the player ID from the string</p>
<pre><code><a href = "http://www..com/.php?XID=1826888">saeed</a> donated $800,000,000 to the faction
</code></pre>
<p>However, as it stands, I need to only check strings that include the money donation, $800,000,000.</p>
<p>Included in the output can be such things as </p>
<pre><code> <a href = "http://www..com/.php?XID=2023426">French_</a> donated 1 x First Aid Kit to the faction
</code></pre>
<p>I need to not run the foreach info on strings such as this.</p>
| <p>from what i understand, you could do something like this :<br></p>
<pre><code><?php
foreach($values AS $key=>$value) {
if(preg_match('/^(\$)(.+)/', $value) == 1) {
$transferid = $key;
$donation1 = $value["news"];
$donationcomma = getStringBetween($donation1,$from,$to);
$donation = str_replace(',', '', $donationcomma);
$playeridregex = preg_match("/XID=(.*)\"/", $donation1, $playerid);
$playerid1 = preg_replace("/[^A-Za-z0-9'-]/","",$playerid[1]);
}
}
</code></pre>
<p>But still, i'm not sure what you are looking for.</p>
|
C# naming array names on the fly <p>I am trying to create a two dimensional array of random 1 and 0. These will be used to switch on or off I/O lines on an Arduino. The number of arrays (<code>height</code>) to create will come from a textbox on the UI as will the number of items (<code>width</code>) in each array. </p>
<p>This means I do not know how many arrays I will have so what I want to do is have a loop in which I name each array e.g. a0 then a1 then a2 etc. </p>
<p>I have tried to name them but as you can see below have not been able to get it right. What do I need to do?</p>
<pre><code>private int[][] build_data(int height, int width)
{
Random randNum = new Random();
int Min = 0, Max = 2;
var array_name = "a";
rch_txtbx.AppendText(height.ToString() + "\r");
rch_txtbx.AppendText(width.ToString() + "\r");
for (int j = 0; j <= height; j++) //create a0 to ax
{
array_name = "a" + j; //this creates the name I want
int[] a = new int[width]; //need to initialise each array in turn but how?
for (int i = 0; i <= width; i++) //create number of items in each array
{
a[i] = randNum.Next(Min, Max);
}
}
/* This is what I am trying to create arayys of random 0 and 1
int[] a1 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int[] a2 = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
int[] a3 = { 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0 };
int[] a4 = { 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0 };
int[] a5 = { 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0 };
int[] a6 = { 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0 };
int[] a7 = { 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0 };
int[] a8 = { 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0 };
int[] a9 = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0 };
int[] a10 = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0 };
int[] a11 = { 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0 };
int[] a12 = { 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0 };
int[] a13 = { 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0 };
int[] a14 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*/
//get data ready to send back
int[][] arr = { a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14 };
return arr;
}
</code></pre>
| <p>Instead of trying to dynamically create variables and then add them into the array just at the end of each outer loop iteration set the value of that array:</p>
<pre><code>int[][] array = new int[height][];
for (int i = 0; i < height; i++)
{
int[] innerArray = new int[width];
for (int j = 0; j < width; j++)
innerArray[j] = r.Next(min, max);
array[i] = innerArray;
}
</code></pre>
<p>You can also replace the above <code>for</code> loops with Linq:</p>
<pre><code> // Creates an enumerable with N
var array = Enumerable.Repeat(0, height) items
// For each item create an enumerable with M items
.Select(i => Enumerable.Repeat(0, width)
// Set the value of each inner item to a
// random number
.Select(j => r.Next(min,max))
// Convert to an array
.ToArray())
.ToArray();
</code></pre>
|
Profiling *every* function call? <p>You may wonder why I would want to do this. I'm trying to debug PHP performance on an embedded system. Don't have access to any kind of tools on the device.</p>
<p>I was thinking if I could just do a simple <code>microseconds</code> calculation on every call, it would work.</p>
<p>Is there a way to do it? Essentially wrap all of my functions (not built in php).</p>
<p>This wouldn't be for production of course.</p>
| <p>You can use <code>declare(ticks=1000);</code> to run an callback, like: </p>
<pre><code>// you can use this:
declare(ticks=1);
// A function called on each tick event
function tick_handler()
{
debug_backtrace();//get function name
microtime();//get time
}
</code></pre>
<p><a href="http://www.php.net/declare" rel="nofollow">http://www.php.net/declare</a></p>
<p>you only have to get the right number e.g. <code>1000</code> for your tests cycles</p>
|
API call from post trigger of DocumentDB <p>I need to make an API call from post trigger of Azure DocumentDB.
I tried calling external APIs - but found that such calls are blocked in DocumentDB. If I host an API on Azure's same account will that API is allowed to be called from the post trigger ? If not what can be the alternatives.</p>
| <p>Server-side code runs in a sandboxed environment and cannot make external calls. You can, instead, make the same call from your client after your request is acknowledged by the service (indicating your post-trigger succeeded/failed).</p>
|
Grails error handling in controllers <p>I would like to render custom JSON error messages. I created the following controller:</p>
<pre><code>class ErrorController {
static responseFormats = ['json']
def notAuthorized() {
render([error: "You are not authorized to access ${request.getRequestURL()} on this server.",
path: request.getRequestURI()] as JSON)
}
}
</code></pre>
<p>Inside the <code>UrlMappings</code> class I have the following:</p>
<pre><code>"401"(controller: 'error', action: 'notAuthorized')
</code></pre>
<p>Everything works alright, except for the fact that I <code>GET http://localhost/path</code> the following error message:</p>
<pre><code>{"error":"You are not authorized to access http://localhost:8080/error on this server.",
"path":"/error"}
</code></pre>
<p>So the URI/URL in the <code>request</code> object does not point to the URI/URL given by the request. Is there a way to obtain the correct URI/URL?</p>
| <p>I think what you want is <code>request.forwardURI</code>. That should give you the request that triggered the error.</p>
|
I am getting the error "This method must return a result of type java.lang.String" and I dont understand why. <p>I dont know why I am getting this error. If anyone can explain it to me and edit my code it would be appreciated.</p>
<pre><code>public class Exam1 {
public static void main(String[] args)
{
Exam1 e = new Exam1();
String s= e.dayName(1);
}
public static String dayName(int dayNum)
{
String day1 = "monday";
if (dayNum==1)
return day1;
}
}
</code></pre>
| <p>If you notice. You have a condition on your return. And because you have labeled that method to return a string it must return something. There is however an eventuality where it doesn't return a string. So you have to figure out what you want to do when your if is false.
public class Exam1 {</p>
<pre><code> public static void main(String[] args)
{
Exam1 e = new Exam1();
String s= e.dayName(1);
}
public static String dayName(int dayNum)
{
String day1 = "monday";
if (dayNum==1){
return day1;
}
//this is the part you are missing. a default return is your condition is
//wrong
return "";
}
}
</code></pre>
<p>That being said. I would revisit your design. If you must do what you are doing, I would use a Map. </p>
<pre><code>HashMap<Integer,String> daysOfWeek = new HashMap<>();
daysOfWeek.put(1,"Monday")
</code></pre>
<p>That way you can call </p>
<pre><code>String day = daysOfWeek.get(1);
</code></pre>
<p>and out comes your day of the week. </p>
|
Weird error using Android License server <p>So following the instruction from the official android developers website I've set up everything to create a license check, but I am having the weirdest of the errors...</p>
<p>I've created 3 activities for the 3 posible responses from the license server:</p>
<p>-EverythingOkActivity</p>
<p>-NotLicensedActivity</p>
<p>-ErrorActivity</p>
<p>Each one should be launched depending on the server's response, But...</p>
<p>When I connect my phone to debug my app, if the condition to launch the <strong>ErrorActivity</strong> is meet, then it launches the <strong>NotLicensedActivity</strong> intent and viceversa, if the condition to launch the <strong>NotLicensedActivity</strong> intent is meet, then it launches the <strong>ErrorActivity</strong> intent.</p>
<p>Plus I am never able to launch the <strong>EverythingOkActivity</strong>, I've already setup my test gmail account on the developer console and selected <strong>LICENSED</strong> at the license test response on my account, I've also uploaded the APK.</p>
<p>The debug console shows this response from the server:</p>
<pre><code>I/LicenseChecker: Received response.
I/LicenseChecker: Clearing timeout.
</code></pre>
<p>But no errors at least I have no internet, in that case is shows:</p>
<pre><code>I/LicenseChecker: Received response.
I/LicenseChecker: Clearing timeout.
W/LicenseValidator: Error contacting licensing server.
</code></pre>
<p>And then launches the intent to <strong>NotLicensedActivity</strong> instead of <strong>ErrorActivity</strong></p>
<p>I have no idea what could be wrong, Excuse me if I am Android noob.</p>
<p>Here is the code of my Main Activity:</p>
<pre><code>import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import com.google.android.vending.licensing.AESObfuscator;
import com.google.android.vending.licensing.LicenseChecker;
import com.google.android.vending.licensing.LicenseCheckerCallback;
import com.google.android.vending.licensing.ServerManagedPolicy;
public class MainActivity extends AppCompatActivity {
private static final String BASE64_PUBLIC_KEY = "MIIBIjANBgkq[...]";
private static final byte[] SALT = new byte[] {
-44, 55, 30, -128, -103, -57, 74, -64, 51, 88, -95, -45, 77, -117, -36, -113, -11, 32, -64,
89
};
private LicenseCheckerCallback mLicenseCheckerCallback;
private LicenseChecker mChecker;
private boolean keepGoing = true;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String deviceId = Settings.Secure.getString(getContentResolver(),
Settings.Secure.ANDROID_ID);
mLicenseCheckerCallback = new MyLicenseCheckerCallback();
mChecker = new LicenseChecker(this, new ServerManagedPolicy(this,
new AESObfuscator(SALT, getPackageName(), deviceId)),
BASE64_PUBLIC_KEY);
doCheck();
}
@Override
public void onResume() {
super.onResume();
if (!keepGoing) {
finish();
}
}
private void doCheck() {
mChecker.checkAccess(mLicenseCheckerCallback);
}
private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
public void allow(int policyReason) {
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
Intent intent = new Intent(MainActivity.this, EverythingOkActivity.class);
startActivity(intent);
}
public void dontAllow(int policyReason) {
if (isFinishing()) {
return;
}
keepGoing = false;
Intent intent = new Intent(MainActivity.this, NotLicensedActivity.class);
startActivity(intent);
}
public void applicationError(int errorCode) {
if (isFinishing()) {
return;
}
keepGoing = false;
Intent intent = new Intent(MainActivity.this, ErrorActivity.class);
startActivity(intent);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mChecker.onDestroy(); //Don't forget this line. Without it, your app might crash.
}
}
</code></pre>
| <p>I solved!!! The problem is the app needs to be published in the Play Store at least as an Alpha and then you need to add a list a Alpha-tester users (in this case myself) to the app. Is not enough to to upload the APK, you need to actually publish the app to get the license to work. I will let that code here as a example, since it works like a charm. Cheers (^_^)</p>
|
How can I compare items in two list that occur in the same position? <p>As the title says, I need to compare items in two list that occur in the same position.</p>
<pre><code>la=['a0', 'b1', 'a2', 'b3', 'a4', 'b5']
lb=['b0', 'a1', 'b2', 'a3', 'b4', 'b5']
</code></pre>
<p>Like <code>'a0'</code> and <code>'b0'</code> for example</p>
<p>By comparing them, I want to delete from the list the one that is strictly greater that the other.If they are the same item, I want to delete them both from the list. The result of this function would be:</p>
<pre><code>la=['a0','a2','a4']
lb=['a1','a3']
</code></pre>
<p>My problem is that I don't know how to compare each item.</p>
<p>I can use only the built-in functions from the standard Python library</p>
| <pre><code>i = 0
j = 0
while True:
try:
if la[i] > lb[j]:
del la[i]
j += 1
elif la[i] < lb[j]:
del lb[j]
i += 1
else:
del la[i]
del lb[j]
except IndexError:
break
</code></pre>
<p>This assumes both lists are the same length. If you're removing element from one list and not the other you have to keep track of the indices separately. </p>
|
How to bind a click event to a Leaflet canvas GridLayer <p>I'm trying to bind a click event to a leaflet plug-in's extension of a canvas GridLayer (using Leaflet 1.0, with <a href="https://github.com/domoritz/leaflet-maskcanvas" rel="nofollow">Leaflet.MaskCanvas</a>).</p>
<p><a href="http://leafletjs.com/reference-1.0.0.html#gridlayer-on" rel="nofollow">From the Leaflet Documentation about GridLayer</a>, I would expect that I could bind a click to <code>coverageLayer</code> using either</p>
<pre><code>// add event listener to determine when layer has been clicked
coverageLayer.on('click', function(e) {
console.log('clicked the line');
});
// second (alias) method to add event listener
coverageLayer.addEventListener('click', function(e) {
console.log('clicked the line');
});
</code></pre>
<p>but neither of the above seem to be working. </p>
<p><a href="https://jsfiddle.net/y6py47w4/" rel="nofollow">Here's a fiddle</a> where I've forked and tweaked the example code from the MaskCanvas plugin.</p>
<p><strong>Is there some other way to bind a click to a canvas layer in Leaflet?</strong></p>
<p><em>Edit: <code>.on()</code> and <code>.addEventListener()</code> are aliases.</em></p>
<p><em>Previously the question dealt with Leaflet 0.7, and TileLayer. From the <a href="http://leafletjs.com/reference.html#tilelayer-canvas" rel="nofollow">old Leaflet Documentation</a>, it appears that TileLayer did not have these events. JSFiddle code has been updated to use Leaflet 1.0.</em></p>
| <p>In Leaflet 1.0, <code>GridLayer</code>s do not handle mouse/touch/pointer events (notice their <a href="http://leafletjs.com/reference-1.0.0.html#gridlayer-event" rel="nofollow">events documentation</a> does <strong>not</strong> list pointer events, whereas some <a href="http://leafletjs.com/reference-1.0.0.html#interactive-layer" rel="nofollow">other layer types do</a>).</p>
<p>Furthermore, the DOM element containing the tiles (a <code><div class='leaflet-tile-container></code>) has a <code>pointer-events: none;</code> CSS rule. This makes the browser ignore pointer events (giving it a tiny bit of better performance).</p>
<p>You'll need to attach the events to the cells themselves (when on your custom <code>createTile()</code>) and override the <code>pointer-events</code> CSS rule.</p>
|
RxJava android chaining requests <p>I am using Retrofit with RxJAva for an app that gets Rss Feeds, but the rss doesn't contain all the informations so i use jsoup to parse every item link, to retrieve the image and the article's description. now i am using it this way:</p>
<pre><code> public Observable<Rss> getDumpData() {
System.out.println("in the getDumpData");
if (newsAppService == null) {
System.out.println("newsAppServer is null");
}
return newsAppService.getDumpData()
.flatMap(new Func1<Rss, Observable<Rss>>() {
@Override
public Observable<Rss> call(Rss rss) {
List<Item> items = new ArrayList<Item>();
for (int i = 0; i < rss.channel.items.size(); i++) {
Document document = null;
try {
document = Jsoup.connect(rss.channel.items.get(i).link).get();
Element element = document.select("div[itemprop=image] > img").first();
Element bodyElement = document.select("div[class=articlebody]").first();
System.out.println("got element " +bodyElement.toString());
rss.channel.items.get(i).image = element.attr("src");
items.add(rss.channel.items.get(i));
} catch (IOException e) {
e.printStackTrace();
}
}
rss.channel.items = items;
rss.version = "Mams :D";
return Observable.just(rss);
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
</code></pre>
<p>is it clean ? is there a better way ? </p>
| <p>Let's see...</p>
<pre><code>public Observable<Rss> getDumpData() {
System.out.println("in the getDumpData");
if (newsAppService == null) {
System.out.println("newsAppServer is null");
}
return newsAppService.getDumpData()
.flatMap(rss -> Observable
.from(rss.channel.items)
.observeOn(Schedulers.io())
.flatMap(Checked.f1(item -> Observable
.just(Jsoup.connect(item.link).get())
.map(document -> document.select("div[itemprop=image] > img").first())
.doOnNext(element -> item.image=element.attr("src"))
))
)
.ignoreElements()
.defaultIfEmpty(rss)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
</code></pre>
<p>The class checked is from rxJava-extras, but you can write one on your own easily. And yes, Java 8 really helps with Rx; the above will make all calls to the network simultaneously.</p>
|
Minimize memory overhead in sparse matrix inverse <p>As pretense, I am continuing development in Python 2.7 from a prior question: <a href="http://stackoverflow.com/questions/40050947/determining-a-sparse-matrix-quotient">Determining a sparse matrix quotient</a> </p>
<h2>My existing code:</h2>
<pre><code>import scipy.sparse as sp
k = sp.csr_matrix(([], ([],[])),shape=[R,R])
denom = sp.csc_matrix(denominator)
halfeq = sp.linalg.inv(denom)
k = numerator.dot(halfeq)
</code></pre>
<p>I was successful in calculating for the base <code>k</code> and <code>denom</code>. Python continued attempting calculation on <code>halfeq</code>. The process sat in limbo for aproximately 2 hours before returning an error </p>
<h2>Error Statement:</h2>
<pre><code>Not enough memory to perform factorization.
Traceback (most recent call last):
File "<myfilename.py>", line 111, in <module>
halfeq = sp.linalg.inv(denom)
File "/opt/anaconda/lib/python2.7/site-packages/scipy/sparse/linalg/matfuncs.py", line 61, in inv Ainv = spsolve(A, I)
File "/opt/anaconda/lib/python2.7/site-packages/scipy/sparse/linalg/dsolve/linsolve.py", line 151, in spsolve Afactsolve = factorized(A)
File "/opt/anaconda/lib/python2.7/site-packages/scipy/sparse/linalg/dsolve/linsolve.py", line 366, in factorized return splu(A).solve
File "/opt/anaconda/lib/python2.7/site-packages/scipy/sparse/linalg/dsolve/linsolve.py", line 242, in splu ilu=False, options=_options)
MemoryError
</code></pre>
<p>From the <a href="https://github.com/scipy/scipy/blob/master/scipy/sparse/linalg/dsolve/SuperLU/SRC/smemory.c" rel="nofollow">scipy/smemory.c sourcecode</a>, the initial statement from the error is found on line 256. I am unable to further analyze the memory defs to determine how to best reallocate memory usage sufficient for execution. </p>
<p>For reference, </p>
<p><code>numerator</code> has <code>shape: (552297, 552297)</code> with <code>stored elements: 301067607</code> calculated as <code>sp.csr_matrix(A.T.dot(Ap))</code></p>
<p><code>denominator</code> has <code>shape: (552297, 552297)</code> with <code>stored elements: 170837213</code> calculated as <code>sp.csr_matrix(A.T.dot(A))</code></p>
<p><strong>EDIT</strong>: I've found <a href="https://www.reddit.com/r/Python/comments/3c0m7b/what_is_the_most_precise_way_to_invert_large/" rel="nofollow">a related question on Reddit</a>, but cannot determine how I would change my equation from <code>numerator * inv(denominator) = k</code></p>
| <p>No need to 'preallocate' <code>k</code>; this isn't a compiled language. Not that this is costing anything.</p>
<pre><code>k = sp.csr_matrix(([], ([],[])),shape=[R,R])
</code></pre>
<p>I need to double check this, but I think the <code>dot/inv</code> can be replaced by one call to <code>spsolve</code>. Remember in the other question I noted that <code>inv</code> is <code>spsolve(A, I)</code>; </p>
<pre><code>denom = sp.csc_matrix(denominator)
#halfeq = sp.linalg.inv(denom)
#k = numerator.dot(halfeq)
k = sp.linalg.spsolve(denom, numerator)
</code></pre>
<p>That said, it looks like the problem is in the <code>inv</code> part, the <code>factorized(denom)</code>. While your arrays are sparse, (denom density is 0.00056), they still have a large number of values.</p>
<p>Maybe it would help to step back and look at:</p>
<pre><code>num = A.T.dot(Ap)
den = A.T.dot(A)
k = solve(den, num)
</code></pre>
<p>In other words, review the matrix algebra.</p>
<pre><code>(A'*Ap)/(A'*A)
</code></pre>
<p>I'm little rusty on this. Can we reduce this? Can we partition? </p>
<p>Just throwing great big arrays together, even if they are sparse, isn't working.</p>
<p>How about providing small <code>A</code> and <code>Ap</code> arrays that we can use for testing? I'm not interested in testing memory limits, but I'd like to experiment with different calculation methods.</p>
<p>The sparse linalg module has a number of iterative solvers. I have no idea whether their memory use is greater or less.</p>
|
How do I know where an email form is being delivered? <p>Is there a way to extract the email address an online form will send to?</p>
<p>This website for instance: <a href="http://www.extrememicro.net" rel="nofollow">http://www.extrememicro.net</a>
There is a "contact us" page where you fill out first name, last name, subject, and body of a message to this company. </p>
<p>How do I know the email address where this message will be sent to?</p>
| <p>With the <code><form action=""</code> from the source :</p>
<pre><code> <form action="/#wpcf7-f37-o1" method="post" >
</code></pre>
<p>So it's a <code>POST</code> to the page <a href="http://www.extrememicro.net/#wpcf7-f37-o1" rel="nofollow">http://www.extrememicro.net/#wpcf7-f37-o1</a></p>
|
After creating a bigger array, how do I use the new array in other functions of the same class? <p>It was asked of us to implement this class without built-in functions or Arraylist.
When needing to make the data array bigger, I created a new array and gave it a new size (which is the capacity+10). As the data array is a data member, I can access it from the other functions of the array. However, I can't access the newArray. Can I create a bigger array using the data array? If not,how can I access the new Array from the other functions of the class?</p>
<pre><code>package ADTDynamicArrays;
import java.util.*;
public class DynamicIntgerArray {
public int data[];
int size;
int capacity;
public DynamicIntgerArray(){
data = new int[5];
size = 0;
capacity = 5;
}
public DynamicIntgerArray(int ca){
size=0;
if(ca<5)
capacity=5;
else
capacity=ca;
data=new int[capacity];
}
public boolean checkIndex(int index){
if(index < 0 || index >=data.length)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
else
return true; }
public void copyOldtoNew(int [] arry1, int arry2[]){
arry2=arry1;
}
public void checkCapacity(int s){
if(capacity<= s){
capacity +=10 ;
int newArray[]=new int[capacity];
copyOldtoNew(data,newArray);
}
}
public void getElement (int index){
}
public int getlength(){
return capacity;
}
public void insertElement(int element){
}
public void replaceElement(int index, int element){
}
public void print(){
}
public void addShiftElements(int index, int element){
}
}
</code></pre>
<p>This is the code that was given to us that we have to work with that we cannot modify:</p>
<pre><code>package ADTDynamicArrays;
import java.util.*;
public class DynamicIntgerArray {
public int [] data;
public DynamicIntgerArray(){
data = new int[5];
size = 0;
capacity = 5;}
public DynamicIntgerArray(int ca){
}
public boolean checkIndex(int index){
if(index < 0 || index >=data.length)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
else
return true; }
public void copyOldtoNew(int [] arry1, int arry2[]){
}
public void checkCapacity(int s){
if(capacity<= s){
capacity +=10 ;
}
}
public void getElement (int index){
}
public int getlength(){
}
public void insetElement(int element){
checkCapacity(size+1);
}
public void replaceElement(int index, int element){
}
public void print(){
}
public void addShiftElements(int index, int element){
if(checkIndex(index)){
checkCapacity(size + 1);
}
}
}
</code></pre>
| <p>After this code:</p>
<pre><code>int newArray[]=new int[capacity];
copyOldtoNew(data,newArray);
</code></pre>
<p>you need this little piece of magic:</p>
<pre><code>data = newArray;
</code></pre>
<p><sub>well, I hope you understand it is not magic at all.</sub></p>
|
Post request saving only versionKey with Mongoose and Express <p>I am trying to save a number and a few string values to a MongoDB and even though the code makes perfect sense to me, returns no errors and creates an entry in the database, all I get is just a versionKey, something like this:</p>
<pre><code>{
"_id": {
"$oid": "58052711f319bc041c5ebdac"
},
"__v": 0
}
</code></pre>
<p>I thought I'd try just saving the number and the title first to see if they get saved, but they don't, as you can see above.
Every RESTful API and Express "post" request tutorial and answer I find seems to do it differently!</p>
<p>Also, is it supposed to show the res.json in plaintext for me to format or render somehow, or is it supposed to show the value of the property <code>message:</code>?</p>
<p>Here is the code</p>
<pre><code>// modules =======================================================
const express = require('express')
const app = express()
const mongoose = require('mongoose')
// configuration =================================================
const db = require('./config/db')
// mongoose ======================================================
mongoose.connect(db.url)
const PostSchema = new mongoose.Schema({
number:Number,
title:String,
body:String,
images:String
}, { collection: 'posts' })
const posts = mongoose.model('Post', PostSchema)
// routes ========================================================
app.post('/api/post', function(req, res) {
var post = new posts()
post.number = req.body.number
post.title = req.body.title
post.save(function(err) {
if (err) res.send(err)
res.json({ message: 'Post saved'})
})
})
</code></pre>
<p>Here is my HTML5 form</p>
<pre><code><form action="/api/post" enctype="multipart/form-data" method="post">
<label for="number">Post Number:</label>
<input type="number" name="number" size="2" placeholder="required" required /><br />
<label for="title">Title:</label>
<input type="text" name="title" placeholder="optional" /><br />
<label for="body">Text:</label><br />
<textarea name="body" cols="80" rows="20" placeholder="optional"></textarea><br />
<label for="images">Images:</label>
<input type="text" name="images" placeholder="optional" />
<span class="form-hint">Comma separated file names, e.g. image1.jpg,image2.jpg,image3.png</span><br />
<input type="submit" value="Submit" />
</form>
</code></pre>
<p>My middleware that comes just before the routes in server.js</p>
<pre><code>// middleware ====================================================
app.use(bodyParser.json()) // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })) // parse application/vnd.api+json as json
app.use(bodyParser.urlencoded({ extended: true })) // parse application/x-www-form-urlencoded
app.use(methodOverride('X-HTTP-Method-Override')) // override with the X-HTTP-Method-Override header in the request
app.use(express.static(__dirname + '/public')) // set static files location
</code></pre>
| <p>First question, the encoding must match what you have Express parsing (in this case it wasn't <code>multipart/form-data</code> but <code>application/json</code>, <code>'application/vnd.api+json'</code>, and <code>application/x-www-form-urlencoded</code>. Removing the encoding type you were specifying fixes that.</p>
<p>Second, the response will be a simple JSON object:</p>
<pre><code>{
"message": "Post saved"
}
</code></pre>
|
How can I check the color of the tab bar buttons? <p>Do you have an idea how can I change the gray color of this tab button to another color?This is basically the non-taped button, when the user taps it, it is changing to white.
<a href="https://i.stack.imgur.com/w9DTl.png" rel="nofollow"><img src="https://i.stack.imgur.com/w9DTl.png" alt="enter image description here"></a></p>
<p>I have tried that:</p>
<pre><code> UITabBar.appearance().barTintColor = UIColor.flatBlue()
UITabBar.appearance().tintColor = UIColor.flatWhite()
</code></pre>
<p>But it it not working.</p>
| <p>You need to set <code>barTintColor</code> for the whole bar and <code>tintColor</code> for the tapped button. </p>
<pre><code>self.tabBar.barTintColor = UIColor.whiteColor()
self.tabBar.tintColor = UIColor.greenColor()
</code></pre>
<p>inside Appdelegate.swift</p>
<p>Insert code somewhere in </p>
<pre><code>func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
}
</code></pre>
|
415 unsupported mediaType in POST request <p>Was reading around and a lot of the issues others were having were Spring, Gradle, or something else. It seems that Postman does not like my request that I'm giving to my <code>POST</code> method. </p>
<p>Error:</p>
<pre><code>b>description</b>
<u>The server refused this request because the request entity is in a format not supported by the requested resource for the requested method (Unsupported Media Type).</u>
</code></pre>
<p>Body from Postman: </p>
<pre><code>{
"firstName": "firstName",
"lastName": "lastName",
"dob": "12/12/2012",
"address": "123 main st."
}
</code></pre>
<p>POST in question: </p>
<pre><code>@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/createQuery")
public Response createQuery(ApplicationInfo info) throws IOException {
String queryString =createStringFromJSON(info,true);
queryMap.put(""+countId,queryString);
countId++;
ObjectMapper objectMapper = new ObjectMapper();
String json = "";
try {
json = objectMapper.writeValueAsString(queryMap);
} catch (JsonProcessingException e) {
e.printStackTrace();
} return Response.ok(json,MediaType.APPLICATION_JSON_TYPE).entity(json).build();
}
</code></pre>
<p>Incredibly complex ApplicationInfo Object: </p>
<pre><code> public class ApplicationInfo
{
String firstName;
String lastName;
String dob;
String address;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
</code></pre>
<p>Hopefully someone more experienced can pinpoint the issue. Please keep it relevant to my issue. </p>
| <p>This is a bit of a shot in the dark, but you're POSTing a string to a method which takes ApplicationInfo, and I'm not too sure JAX-RS does object mapping on the fly like Spring can do with @RequestBody.</p>
<p>Try changing your method signature to <code>public Response createQuery(String info) throws IOException</code> as your method is just trying to convert ApplicationInfo to JSON anyway.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.