Q:

use stringbuilder to show asp chart control

I want to create dynamic chart in my webpage.I use stringbuilder but i can not see a chart on the page.Can you please help how to do it?
StringBuilder builderchart = new StringBuilder();

builderchart.Append("
");
builderchart.Append("
");
builderchart.Append("");
builderchart.Append("
");
builderchart.Append("<asp:Chart ID=Chart1 runat=server><Series><asp:Series Name=Series1></asp:Series></Series><ChartAreas><asp:ChartArea Name=ChartArea1></asp:ChartArea></ChartAreas></asp:Chart>");
builder.Append("
");
builderchart.Append("
");
Literal2.Text = builderchart.ToString();

A:

You cannot use StringBuilder to instantiate a control.
You can download some Chart Control samples from the following link: http://archive.msdn.microsoft.com/mschart


Q:

Contacting another website via program?

I know the title isn't very elaborate, but I have tried this multiple times (to figure out how) but I could never find out how to do so. I want to do stuff like upload a "paste" to pastebin.com, upload a picture to twitpic.com, upload a file to rapidshare.com, etcetera.
How would I do so? Thanks!
(Visual Basic 2010 Express | Windows 7 Ultimate)

A:

I conscious that Visual Basic 2010 express will have some way to interact with the server side.
If you couldn't find you need to change the language.
To post in twitpic you need to use their API givne in the following URL.
http://twitpic.com/api.do
let's say

  <form action="http://twitpic.com/api/uploadAndPost">
<input name="media"></input>
<input name="username"></input>
<input name="password"></input>
<input name="message"></input>
</form>


Q:

Should I periodically air out the vapor barrier in my crawlspace?

I have a vapor barrier in my crawlspace which is made of multiple sheets of 6-mil plastic.
One contractor suggested that in the dry months I should pull back the sheets of plastic and allow the dirt beneath to breathe and dry out.
A second contractor said that the first contractor was repeating an urban legend, and that I should not pull back the vapor barrier.
Should I periodically pull back the vapor barrier in my crawlspace?

A:

"allow the dirt to breathe" doesn't even sound like an urban legend. Just sounds plain pointless. The entire point of the vapor barrier is to keep the moisture out of the crawlspace--so leave the barrier there. The dirt will be OK.


Q:

Python tkinter grid_forget()

I want to make a label appear and disappear, but I am having a problem with grid_forget().  This is part of the code:
def creabackuno():
    showinfo( "Wait..","I am creating the backup, please wait...")
    vsl=Label(gui,text="Working, please wait...",font=("arial",16)).grid(row=20,rowspan=1,column=0,columnspan=1,padx=10,sticky=N)
    try:
        copytree(path,r"backup\dirbackup1\.minecraft")
        showinfo( "OK!","Backup (1) created!")
        vsl.grid_forget()
    except OSError:
        showerror( "Nope!","There is already a backup to restore")
        vsl.grid_forget()

And this is the error of the console:
AttributeError: 'NoneType' object has no attribute 'grid_forget'

A:

You currently have vsl equal to the return value of the grid method of Label.  Furthermore, this method always returns None (hence, the NoneType in your error).  Make your code like this:
vsl=Label(gui,text="Working, please wait...",font=("arial",16))
vsl.grid(row=20,rowspan=1,column=0,columnspan=1,padx=10,sticky=N)

Now vsl points to the label, not the return value of the grid method, which is None.


Q:

How to use redis with gearman for persistence

How can I use Gearman with redis for persistent queue?
I am trying to run it for centos7.
I have Gearman working.
On running
gearmand -h

I can see support for
libsqlite3,
Postgres,
libtokyocabinet and
MySQL.
I've installed hiredis using yum as per various forums although i cant figure out how to run it through terminal.
I downloaded tar file for gearman and tried running this command inside the gearman folder to no avail.
./configure --enable-FEATURE sql

A:

To build gearmand with hiredis persistence queue you have to install libhiredis-devel on CentOS or libhiredis-dev on Debian/Ubuntu package.
Insure ./configure  --enable-hiredis output contains
checking hiredis/hiredis.h usability... yes
checking hiredis/hiredis.h presence... yes
checking for hiredis/hiredis.h... yes
checking for main in -lhiredis... yes

To run gearmand with redis as queue type, run:
gearmand --verbose DEBUG --queue-type redis


Q:

MySQL, 'WHERE NOT IN' slow

I'm having issues with MySQL query running extremely slow. It takes more than 10 min for each one. I've tried to rewrite it using LEFT JOINT, but "joints" are not my best expertise ))
I hope someone will be able to help me.
    select subscriberId
    from segments
    where (segmentId = 29)
    and subscriberId not in
    (select subscriberId from que where (campaignId = 31 or campaignId = 32))
    order by rand()
    limit 20000

All indexes are in place. Thanks a lot in advance.

A:

I think, your problem is in
order by rand()

try to delete this and look time.
UPDATE

add index:
alter table que add index (subscriberId)
try this:
select segments.subscriberId from segments
left join que on que.subscriberId = segments.subscriberId and ( que.campaignId = 31 or que.campaignId = 32 )
where segments.segmentId = 29 and que.id is null
limit 20000

I see 0.08 sec and 0.13 with order by rand().
Don't use phpmyadmin to check, because of it have more time to render result. I'm using console mysql client
20000 rows in set (0.13 sec)
mysql> select segments.subscriberId from segments  left join que on que.subscriberId = segments.subscriberId and ( que.campaignId = 31 or que.campaignId = 32 ) where segments.segmentId = 29 and que.id is null order by rand() limit 20000 ;


Q:

How expensive are multiple requires on the same file on the same instance of Node JS?

My understanding of require (so far) is that it performs a traversal up the directory structure, looking for the module you're trying to import. Well, that's not exactly correct, but let's assume the directory traversal cost is negligible.
I have a module called BigModule. It has a lot of stuff in it, so there's some cost associated with loading it up with a require statement. Is importing it a hundred times a hundred times more expensive than importing it once, or is there some sort of caching mechanism which causes these scripts to share one BigModule instance? This is all happening on a single Node instance.

A:

require() caches calls by resolved filepath; require()ing the same file twice (even via symlink or different relative path) will not rerun the code.


Q:

pip3 does not install the target module version

Using Python 3.6.9 and pip 9.0.1 on Ubuntu Studio 18.04, I was trying to downgrade the PyQt5 module from version 5.10.1 to 5.9.2.
The installation seems to complete without a problem, but pip3 confirms that 5.10.1 was installed successfully:
pip3 install --no-cache-dir 'PyQt5==5.9.2'

Output:
Collecting PyQt5==5.9.2
  Downloading https://files.pythonhosted.org/packages/3a/c6/26270f5550f00920045c2f0b222a7d03d7a64382825c68bf0bb1a51d854c/PyQt5-5.9.2-5.9.3-cp35.cp36.cp37-abi3-manylinux1_x86_64.whl (105.3MB)
    100% |████████████████████████████████| 105.3MB 11.0MB/s
Collecting sip<4.20,>=4.19.4 (from PyQt5==5.9.2)
  Downloading https://files.pythonhosted.org/packages/8a/ea/d317ce5696dda4df7c156cd60447cda22833b38106c98250eae1451f03ec/sip-4.19.8-cp36-cp36m-manylinux1_x86_64.whl (66kB)
    100% |████████████████████████████████| 71kB 4.2MB/s
Installing collected packages: sip, PyQt5
Successfully installed PyQt5-5.10.1 sip-4.19.8

Checking the current version:
pip3 show PyQt5

Output:
Name: PyQt5
Version: 5.10.1
Summary: Python bindings for the Qt cross platform UI and application toolkit
Home-page: https://www.riverbankcomputing.com/software/pyqt/
Author: Riverbank Computing Limited
Author-email: info@riverbankcomputing.com
License: GPL v3
Location: /home/stragu/.local/lib/python3.6/site-packages
Requires: sip

I also tried uninstalling and installing it again, but I end up with version 5.10 (i.e. not 5.10.1) installed. It's like it forces version 5.10 as a minimum.
However, when I do the following in a Python3 kernel:
from PyQt5.Qt import PYQT_VERSION_STR
print("PyQt version:", PYQT_VERSION_STR)

I find out it is apparently using version 5.9.2!
Any idea what might be going on here?

A:

It seems it is a problem with the default version of pip3 on this installation, version 9.0.1, which always reports (at the end of the install, or when listing the module versions with pip3 list) the module's highest version ever installed.
I upgraded pip3 with:
python3 -m pip install --upgrade pip

And it now works as expected, reporting the right module version number the user asked for (which matches whatever is retrieved when looking for the relevant module's version number from a Python3 kernel).


Q:

jquery Ajax loading Content animated?

Trying out atm something with Ajax loaded Content...
Iam done so far with loading it into the div but it looks like BOOM here is it when i change it ..
So my Question is how can i animate it that its slide out the Div then it shows the Content... (this Step is easy..) but then when i click on next NavbarButton its changing the Content in the Div is changing animated or something in this way...
Here My Code so far
function getPage(id) {
 $("#output").slideToggle("slow");

var mykey = '<?php echo $_SESSION['xxxxxx']; ?>';
    $('#output').html('');
    jQuery.ajax({
        url: "./ajax/engine.php",
        data:'action='+id+"&userkey="+mykey,
        type: "POST",
        success:function(data){$('#output').html(data);}
    });
}

And here the HTML

.

A:

do it like this
jQuery.ajax({
    url: "./ajax/engine.php",
    data:'action='+id+"&userkey="+mykey,
    type: "POST",
    success:function(data){
     $("#output").fadeOut('slow');
     $('#output').html(data);
     $("#output").fadeIn('slow');
   }
});

you may try advanced animation techniques other than fadeIn fadeOut using jquery animate


Q:

Disable automatic scrolling while allowing typing in cells without macros (Excel)

I am using Excel 2016. When I type into cells at the bottom of the screen and press Enter, Excel moves the view down so that I can see what I just typed. Is it possible to disable this 'feature'? I am making a system where users type commands into cells (e.g you type in foo, then onto the cell below that you type bar, then far, then boo, etc.) and my view keeps moving away from the data that I want to see at the top of the page, to instead focus on the commands (which there can be hundreds of).
I've found other ways of restricting scrolling, but those all also stop users from typing in cells outside of the area (which means the commands can't be entered). I don't want anything fancy (for example, I don't mind if you can still scroll away manually); just to stop auto-scrolling.
TL;DR I want the screen to stay focused on the same table, wherever the cursor/selected cell is.
I'd preferably like to do this without macros/VB code as my system administrator is not very happy about people using them, but if it is very necessary that is fine.
Thanks.

A:

You can keep rows visible by freezing them.
https://support.office.com/en-us/article/freeze-panes-to-lock-rows-and-columns-dab2ffc9-020d-4026-8121-67dd25f2508f


Q:

Data type for holding different values C++

I'm wondering how to load a number of images in a function and assign it to one variable so i can call on them and also hold information for those images.
For example :
src = tile1.png
x = 10
y = 11

What kind of data type would i need ?
My goal is to loop through lines in a text file, load each image with its relevant information so the images are pre-loaded and ready to be displayed on the screen. I just a little stuck on how it would be done.

A:

A struct.
example:
#include <iostream>
#include <string>
using namespace std;

struct a_new_datatype{

    string name;
    int age;
    char gender;

};

int main(){

    a_new_datatype my_own_datatype;

    my_own_datatype.name = "Christopher";
    my_own_datatype.age = 34;
    my_own_datatype.gender = 'M';

    cout << "Name: " << my_own_datatype.name << endl;
    cout << "Age: " << my_own_datatype.age << endl;
    cout << "Gender: " << my_own_datatype.gender << endl;

    return 0;
}


Q:

How can I build a Visual Studio 2017 .NET Core .exe file on a developer machine?

Please see Solution section below for the TLDR.
I used the Visual Studio 2015 Community edition and upgraded to Visual Studio 2017. I am developing a .NET Core console application. I am talking here only about my local development machine, which has Visual Studio installed and it has .NET Core runtimes and SDKs installed.
In Visual Studio 2015, project.json files were used, and by default the build process produced a DLL file in the bin/Debug/netcoreapp1.1, that one could run using the dotnet run command. But there was an option to make a minor tweak in the project.json file:
...
"Microsoft.NETCore.App": {
  "version": "1.0.1",
  "type": "platform"
},
...

->
...
"Microsoft.NETCore.App": {
  "version": "1.0.1"
},
...

And adding a runtimes section, such as
"runtimes": {
  "win10-x64": {}
}

And if you did this and built your project, an EXE file was created that you could run directly, without using dotnet run.
Now the question is, is the same possible in Visual Studio 2017 using .csproj XML files? And more specifically, is it possible without the heavy self-contained deployments? I do want it without the full SDD publish because I use these executables for just local testing during the development. Once the project is to be released, I do the SDD publish, but that is very inconvenient during the development process.
The project was converted to Visual Studio 2017, but it only generates DLL files again. So, I tried to create a completely new and empty Hello, World! program and try to get EXE file from it. The Hello, World! csproj file looks like this:
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>
</Project>

This only generates a DLL file that you can run with dotnet run. It is possible to make a change to this:
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>netcoreapp1.1;net46</TargetFrameworks>
  </PropertyGroup>
</Project>

which is very close to what I want - generating an EXE file. However, this creates EXE file that runs .NET Framework 4.6, not .NET Core. So, it does not solve the problem. What I really want is .NET Core executable without having to do self-contained deployment. Is it possible?
Solution
I just found out that this is indeed possible. I just don't know how to do it in the IDE. What currently happens if I hit Ctrl + Alt + F7 in the IDE produces the same result as the command:
dotnet build --configuration Debug

And what I want can be produced by command:
dotnet build --configuration Debug --runtime win10-x64

So what I really want now is modify the default IDE build command to replicate this behavior with --runtime win10-x64 parameter.

A:

In .NET Core, if you want an .exe produced during dotnet build, you need to supply the runtime that you want the executable built for.
In project.json, you did it as you describe above by removing type: platform and adding a runtimes section.
In .csproj, you do it by specifying the MSBuild property named RuntimeIdentifier. On the command-line, when you say dotnet build --runtime win10-x64, the --runtime value gets passed into MSBuild has the RuntimeIdentifier property.
One option is you can purely set the RuntimeIdentifier in your .csproj:
<PropertyGroup>
  <RuntimeIdentifier>win10-x64</RuntimeIdentifier>
</PropertyGroup>

Now when you build in Visual Studio, it will produce an .exe in the build output folder.
Alternatively
I'm not sure if you are interested in this or not, but it sounds like you just want a way to run your application without calling dotnet run. If this is true, you don't need to set a runtime at all. By default your application gets built into bin\Debug\netcoreapp1.1\AppName.dll. You can run your application by saying dotnet bin\Debug\netcoreapp1.1\AppName.dll, which is basically what dotnet run does under the covers.


Q:

Execute a string in C# 4.0

I want to execute dynamically created string in C#. I know VB and JScript.Net can do it, and there is even a way to use its assembly in C# as a workaround. I also found this article describing how to do it.
I read today about C# 4.0 features which bring it closer to the dynamic languages that have this as one of the main features. So, does anybody know does C# 4.0 includes some built in features that allows for string execution, or any other way to do whats described in the article above.

A:

This is dead easy to do. I built the following convenience wrappers. They are structured so that you can construct an assembly from fragments of source code defining methods or expressions and invoke them by name using the helper methods of DynamicCodeManager.
The code is compiled on demand in response to invocation. Adding more methods will cause automatic recompilation on next invocation.
You provide only a method body. If you don't want to return a value then return null and don't bother to use the object returned by InvokeMethod.
If you use this in commercial code do me a favour and credit my work. The real jewel in this library is the invocation support. Getting the code to compile isn't the problem, it's invocation. It's quite tricky to get reflection to correctly match the method signature when you have a variable length parameter list. This is the reason for the existence of DynamicBase: the compiler resolves method binding to this explicitly declared base class giving us access to the right VMT. From there on in it all comes out in the wash.
I should also point out that this capability makes your desktop application vulnerable to script injection attacks. You should either take great care to vet the origin of script or reduce the trust level under which the generated assembly runs.
DynamicBase.cs
using System.Reflection;

namespace Dynamo
{
  public abstract class DynamicBase
  {
    public bool EvaluateCondition(string methodName, params object[] p)
    {
      methodName = string.Format("__dm_{0}", methodName);
      BindingFlags flags = BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic;
      return (bool)GetType().InvokeMember(methodName, flags, null, this, p);
    }
    public object InvokeMethod(string methodName, params object[] p)
    {
      BindingFlags flags = BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic;
      return GetType().InvokeMember(methodName, flags, null, this, p);
    }
    public double Transform(string functionName, params object[] p)
    {
      functionName = string.Format("__dm_{0}", functionName);
      BindingFlags flags = BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic;
      return (double)GetType().InvokeMember(functionName, flags, null, this, p);
    }
  }
}

DynamicCodeManager.cs
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using Microsoft.CSharp;

namespace Dynamo
{
  public static class DynamicCodeManager
  {
    #region internal statics and constants
    static Dictionary<string, string> _conditionSnippet = new Dictionary<string, string>();
    static Dictionary<string, string> _methodSnippet = new Dictionary<string, string>();
    static string CodeStart = "using System;\r\nusing System.Collections.Generic;\r\n//using System.Linq;\r\nusing System.Text;\r\nusing System.Data;\r\nusing System.Reflection;\r\nusing System.CodeDom.Compiler;\r\nusing Microsoft.CSharp;\r\nnamespace Dynamo\r\n{\r\n  public class Dynamic : DynamicBase\r\n  {\r\n";
    static string DynamicConditionPrefix = "__dm_";
    static string ConditionTemplate = "    bool {0}{1}(params object[] p) {{ return {2}; }}\r\n";
    static string MethodTemplate = "    object {0}(params object[] p) {{\r\n{1}\r\n    }}\r\n";
    static string CodeEnd = "  }\r\n}";
    static List<string> _references = new List<string>("System.dll,System.dll,System.Data.dll,System.Xml.dll,mscorlib.dll,System.Windows.Forms.dll".Split(new char[] { ',' }));
    static Assembly _assembly = null;
    #endregion

    public static Assembly Assembly { get { return DynamicCodeManager._assembly; } }

    #region manage snippets
    public static void Clear()
    {
      _methodSnippet.Clear();
      _conditionSnippet.Clear();
      _assembly = null;
    }
    public static void Clear(string name)
    {
      if (_conditionSnippet.ContainsKey(name))
      {
        _assembly = null;
        _conditionSnippet.Remove(name);
      }
      else if (_methodSnippet.ContainsKey(name))
      {
        _assembly = null;
        _methodSnippet.Remove(name);
      }
    }

    public static void AddCondition(string conditionName, string booleanExpression)
    {
      if (_conditionSnippet.ContainsKey(conditionName))
        throw new InvalidOperationException(string.Format("There is already a condition called '{0}'", conditionName));
      StringBuilder src = new StringBuilder(CodeStart);
      src.AppendFormat(ConditionTemplate, DynamicConditionPrefix, conditionName, booleanExpression);
      src.Append(CodeEnd);
      Compile(src.ToString()); //if the condition is invalid an exception will occur here
      _conditionSnippet[conditionName] = booleanExpression;
      _assembly = null;
    }

    public static void AddMethod(string methodName, string methodSource)
    {
      if (_methodSnippet.ContainsKey(methodName))
        throw new InvalidOperationException(string.Format("There is already a method called '{0}'", methodName));
      if (methodName.StartsWith(DynamicConditionPrefix))
        throw new InvalidOperationException(string.Format("'{0}' is not a valid method name because the '{1}' prefix is reserved for internal use with conditions", methodName, DynamicConditionPrefix));
      StringBuilder src = new StringBuilder(CodeStart);
      src.AppendFormat(MethodTemplate, methodName, methodSource);
      src.Append(CodeEnd);
      Trace.TraceError("SOURCE\r\n{0}", src);
      Compile(src.ToString()); //if the condition is invalid an exception will occur here
      _methodSnippet[methodName] = methodSource;
      _assembly = null;
    }
    #endregion

    #region use snippets
    public static object InvokeMethod(string methodName, params object[] p)
    {
      DynamicBase _dynamicMethod = null;
      if (_assembly == null)
      {
        Compile();
        _dynamicMethod = _assembly.CreateInstance("Dynamo.Dynamic") as DynamicBase;
      }
      return _dynamicMethod.InvokeMethod(methodName, p);
    }

    public static bool Evaluate(string conditionName, params object[] p)
    {
      DynamicBase _dynamicCondition = null;
      if (_assembly == null)
      {
        Compile();
        _dynamicCondition = _assembly.CreateInstance("Dynamo.Dynamic") as DynamicBase;
      }
      return _dynamicCondition.EvaluateCondition(conditionName, p);
    }

    public static double Transform(string functionName, params object[] p)
    {
      DynamicBase _dynamicCondition = null;
      if (_assembly == null)
      {
        Compile();
        _dynamicCondition = _assembly.CreateInstance("Dynamo.Dynamic") as DynamicBase;
      }
      return _dynamicCondition.Transform(functionName, p);
    }
    #endregion

    #region support routines
    public static string ProduceConditionName(Guid conditionId)
    {
      StringBuilder cn = new StringBuilder();
      foreach (char c in conditionId.ToString().ToCharArray()) if (char.IsLetterOrDigit(c)) cn.Append(c);
      string conditionName = cn.ToString();
      return string.Format("_dm_{0}",cn);
    }
    private static void Compile()
    {
      if (_assembly == null)
      {
        StringBuilder src = new StringBuilder(CodeStart);
        foreach (KeyValuePair<string, string> kvp in _conditionSnippet)
          src.AppendFormat(ConditionTemplate, DynamicConditionPrefix, kvp.Key, kvp.Value);
        foreach (KeyValuePair<string, string> kvp in _methodSnippet)
          src.AppendFormat(MethodTemplate, kvp.Key, kvp.Value);
        src.Append(CodeEnd);
        Trace.TraceError("SOURCE\r\n{0}", src);
        _assembly = Compile(src.ToString());
      }
    }
    private static Assembly Compile(string sourceCode)
    {
      CompilerParameters cp = new CompilerParameters();
      cp.ReferencedAssemblies.AddRange(_references.ToArray());
      cp.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);
      cp.CompilerOptions = "/target:library /optimize";
      cp.GenerateExecutable = false;
      cp.GenerateInMemory = true;
      CompilerResults cr = (new CSharpCodeProvider()).CompileAssemblyFromSource(cp, sourceCode);
      if (cr.Errors.Count > 0) throw new CompilerException(cr.Errors);
      return cr.CompiledAssembly;
    }
    #endregion

    public static bool HasItem(string methodName)
    {
      return _conditionSnippet.ContainsKey(methodName) || _methodSnippet.ContainsKey(methodName);
    }
  }
}

A:

There's no other way of executing arbitrary C# source code other than compiling it into assembly and then executing it. Anders Hejlsberg (architect of C#) announced plans to expose the C# compiler as a service (basically a set of CLR classes), so this might be of some help when this happens.
"Compiler as a Service" basically means that you can compile an arbitrary piece of code into Expression or, better yet, into an AST and generally get hold of internal compiler workings.

A:

At the moment, the CSharpCodeProvider (in the article you cite) is the only way in the MS .NET implementation. The "compiler as a service" is one of the .NET vFuture features, and provides exactly what you ask for. Mono 2.x already has something comparable, IIRC (as discussed here).


Q:

Error Code 34 twitter_oauth 4.9 Gem

We had to update the twitter_oauth gem to v.0.4.9 to support Twitter's new 1.1 API. However, Favoriting posts and Following users doesn't work. I'm getting a return error when trying to follow a user or favorite a post as follows:
{"errors"=>[{"message"=>"Sorry, that page does not exist", "code"=>34}]}

I have an api_client model with the following:
def follow(id)
  client.friend(id)
end

My controller code:
def update
status = if params[:follow]
  client.follow(params[:id])
elsif params[:follow] == 'false'
  client.follow(params[:id])
end

respond_to do |format|
  format.json do
    if status['screen_name'] == params[:screen_name]
      success = true
      notice = if params[:follow] == 'true'
        "You are now following #{status['screen_name']}"
      else
        "You are no longer following #{status['screen_name']}"
      end
    else
      success = false
      notice = 'Something went wrong. Try again in a couple of seconds.'
    end
    render :json => {:success => success, :message => notice}.to_json
  end
end
end

Has anyone else experienced this problem or can help me figure out what's going on?

A:

I figured out that the issue was the gem itself. The current 0.4.9 version of the gem is a work in progress and some of the post paths were not reflective of the new API. I have forked the repo and submitted my changes to the author for review. The changes I needed were to the favorites.rb and friendships.rb files in the gem. Here are the four changes I made to the gem:
favorites.rb
def favorite(id)
-  post("/favorites/create/#{id}.json")
+  post("/favorites/create.json?id=#{id}")
end

def unfavorite(id)
-  post("/favorites/destroy/#{id}.json")
+  post("/favorites/destroy.json?id=#{id}")
end

friendships.rb
def friend(id)
-  post("/friendships/create/#{id}.json")
+  post("/friendships/create.json?user_id=#{id}&follow=true")
end

def unfriend(id)
-  post("/friendships/destroy/#{id}.json")
+  post("/friendships/destroy.json?user_id=#{id}")
end


Q:

Property 'min' does not exist on type 'typeof Validators'

I'm creating a reactive form where I used validators to validate my input. below is my code and my angular is in version 4.1.3 as well as @angular/form.
createForm() {
this.trainee = new Trainee(null,null,null,null,null,null,null);
this.traineeForm = this.fb.group({
  firstRow: this.fb.group({
    name: ['', Validators.required],
    gender: ['',Validators.required]
  }),
  secondRow: this.fb.group({
    cgpa: ['', [Validators.required, Validators.min(3)]],
    university: ['', Validators.required]
  }),
  thirdRow: this.fb.group({
    course_division: [this.trainee.course_division, Validators.required],
    course: [this.trainee.course, Validators.required]
  }),
  forthRow: this.fb.group({
    batch: [this.trainee.batch, Validators.required]
  })
})}

However, I can't use the Validators.min(3) as the error shows:

Property 'min' does not exist on type 'typeof Validators'.
  I don't really know why I cannot use it. Please help.

A:

There is no such method in Validators in the old version of Angular you're using. Implement it yourself or, much better, upgrade. The current stable version is 6.0.7.
Note that min() validates if a number has a minimum value, and you're initializing your control with '', which is not a number. Maybe you want minLength. But anyway, you should upgrade.


Q:

PHP, OOP and Databases - performance question

I have a question regarding performance when using OOP in PHP together with databases. I'll ask my question by example, suppose a class foo represents a row from some table. Now suppose I need to use foo at 5 different pages on my web app.
The catch is that on each of the 5 pages I will use data from different columns. (i.e. the first page will use column1 and column2 while the second page uses column3 and column 4, etc..)
The OOP approach (as far as I can see) would suggest that when I initialize foo on some particular row I would connect and fetch all the columns of that row and build my object. I could then proceed with my logic and use whatever data that I might need.
The issue I have with this is that with the procedural approach (which I'm more used to when it comes to web) would not waste resources to download columns that I do not need since the query would be specifically tailored to the needs of the particular page.(i.e. If im on the first page I would only download column1 and column2 since that's what I need.)
Am i going about the OOP approach wrong or is the extra overhead so insignificant that developers in general download data which they do not need?
Thanks and sorry if this has already been covered, I thought it would be an interesting topic! :)
Erik
further clarification:
The class is like:
class foo
{
  $column1;
  $column2;
  $column3;
  $column4;

  public function _construct($id)
  {
    //get column 1,2,3 and 4 from database where table_id = $id
  }
}

The issue is that if i only need column1 one one page i download column2,3 and 4 for nothing. In procedural approach you would not do that. Is my OOP model bad or is this ok?

A:

You can still incorporate the selective query inside of an OOP class by using either an array of columns to grab upon construction, or by using a public class method to handle the query grabbing.
Example of constructor:
<?php

class Foo{
    public function __construct( $column ) {

        if(is_array($column)){
             if(count($column) > 1){
                 $result = mysql_query('SELECT `'.implode('`,`', $column).'` FROM `table`;');
             }else{
                 $result = mysql_query('SELECT `'.$column[0].'` FROM `table`;');
             }
        }else{
             $result = mysql_query('SELECT `'.$column.'` FROM `table`;');
        }

        $this->result = mysql_result($result, 0);
    }
}
?>

The public function method would be identical to that, except you could return the result instead of setting $this->result.


Q:

google no captcha still shows text

I have this code in  my form:

And the validation part:
//  Re captcha part
    if (isset($_POST['g-recaptcha-response'])){
        $captcha = $_POST['g-recaptcha-response'];
    }
    if (!$captcha) {
        redirect('login', 'refresh');
    }

    $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=MY_SECRET_KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
    // t($response,1);
    if($response."success" == false) {
        redirect('login', 'refresh');
    }

It sort of works now, this is my result:

When I click the checkbox, I still need to type the text for verification.
I thought that clicking the checkbox was enough?
Am I doing something wrong here?

A:

Here's how I check "No Captcha" response and it always shows me "one click" verification box, even in localhost:
$g_recaptcha_response = filter_input(INPUT_POST, 'g-recaptcha-response');
if (isset($g_recaptcha_response)) {
    $google = 'https://www.google.com/recaptcha/api/siteverify?secret='
            . ZorAuthConfig::RC_SECRET_KEY
            . '&response=' . $g_recaptcha_response;
    $google_json = file_get_contents($google);
    $google_data = json_decode($google_json);
    // Check reCaptcha response.
    if (!$google_data->success) {
        // Do something if robot.
    } else {
       // Do something if human.
    }
}

I implemented this in small library I wrote recently, so you can check it out if you want more details: https://github.com/zoran-petrovic-87/ZorAuth
http://zoran87.blogspot.com/2014/12/zorauth-10b-complete-flexible-no.html


Q:

Structuremap PerRequest lifecycle

I want to inject an instance into structuremap on the fly (i.e. outside of a registry/configuration) that lives for the life of the request.
Currently I'm doing this in the HandleBeginRequest event of an IHttpModule:
container.Configure(x => x.For<IMyClass>()
  .LifecycleIs(Lifecycles.GetLifecycle(InstanceScope.PerRequest))
  .Use(new MyClass()));

However, if at some point in the application's life I do:
ObjectFactory.WhatDoIHave();

I see as many configured instances for IMyClass as there have been requests (or at least a significant amount).
Thinking about it, this sort of makes sense given the code I have.
Is there a better way to inject an instance into the container just for the life of the current request in a way that doesn't pollute the whole container?
Thanks

A:

Your problem is that you're registering the type in the container once per request, which is building up on the registrations. Configuring the container should ideally be made once in the application's lifecycle - typically in the Application_Start event for web applications.
Structuremap allows you to specify a creational function that is invoked upon creating the object, which will let you configure advanced object creation steps.
Instead of your current call to Configure in the Begin_Request event, stick the following in the container configuration during Application_Start.
For<IMyClass>().HttpContextScoped().Use(() => new MyClass());

Notice the lambda in the Use method. The lambda can contain any logic needed in order to create the object and it will be invoked one per lifecycle (per request in the case of HttpContext lifecycle).

A:

I went with this in the end
For<IRequestContextStorage>()
    .HybridHttpOrThreadLocalScoped()
    .Use<RequestContextStorage>();

For<MyClass>()
    .Use(c => c.GetInstance<IRequestContextStorage>().Get<MyClass>());

...

public class RequestContextStorage : IRequestContextStorage
{
    readonly IDictionary<Type, object> hash;

    public RequestContextStorage()
    {
        this.hash = new Dictionary<Type, object>();
    }

    public T Get<T>() where T : class
    {
        if(this.hash.ContainsKey(typeof(T)))
            return this.hash[typeof (T)] as T;

        return null;
    }

    public void Set<T>(T instance)
    {
        this.hash[typeof (T)] = instance;
    }
}

...

static void HandleBeginRequest(object sender, EventArgs e) {

    ObjectFactory.Get<IRequestContextStore>().Set(new MyClass());

}

A:

If you only have one container, and you have multiple requests, you will run into this problem.  I would suggest managing the per request instances yourself by storing them in HttpContext.Items.
If you want to be able to access it through the container, create a gateway class that holds no state and pulls your per request dependency out of HttpContext for you.  Register that in your container, and update dependencies on the per request object to you the gateway.
Update
I can't believe I overlooked this before, what you really want is to use HttpContextLifecycle, which will cache a given instance in the HttpContext.Items collection, where it will be available throughout your request.  You will still have multiple instances active during concurrent requests, but StructureMap can figure out which one to return based on HttpContext.Current.


Q:

What is Black Widow's service record?

During Captain America: The Winter Soldier a number of details about Black Widow are disclosed.
Firstly, that she was born in 1984, making her 30 years old during the events of CA:TWS
Secondly, that she was indeed born in Stalingrad, and worked for The KGB.
We know that Natalia/Natasha was trained as a child soldier: but if, as she states, her 'red ledger' was built whilst she was working for the KGB, she could only have been working for the Russians until she was 7 years old, 1991 being the year the KGB was disbanded.
She specifically mentions the KGB as being the organization she worked for, when she discusses her 'Clean Start'. If there were another, more malevolent organisation she served under, wouldn't she have referred to them instead? If she had continued working for the Russians, wouldn't the majority of her career have occurred under the FSB: and as such why wouldn't she have named them? Does this mean she worked for someone else?
Is it possible that Black Widow is referring only to her actions during the first 7 years of her life (which, lets face it, could only have plausibly seen a very very short period of active service)?
Does the MCU/Earth-199999 continuity provide any details on who she worked for between the fall of the KGB and SHIELD? is it possible she was recruited straight to SHIELD by Barton, at age 7?
I'm aware that the wider Marvel Universes, whilst operating different continuities, provide supportive commentary on each other to create a unified ballast across brand... do any of the other Marvel continuities make reference to Black Widow's past in a way that corroborates, or is reference by the MCU?
I don't need answers that link to the Marvel Wiki: its frequently inaccurate and constantly being updated. I'm trying to find if someone can find a precedent for this continuity in other work: whether it be Cinematic or otherwise...

A:

They had to keep some of her comic backstory relevant, or the fanboys would have cried foul.  In the comics, she was actually born in the late 20's/early 30's.  If you recall the scene in The Avengers, when she lures Banner out, she uses a very young girl and remarks something like, "I was about her age when I started."  So the MCU already has her working at an extremely young age for the KGB, and her comic backstory involves her working for the KGB, as it was initially written in the 60's.


Q:

using ice:selectOneMenu with f:ajax

I developed portlet based on Icefaces and portletfaces. I used partialsubmit for ajax, but when I saw some post they said it should use out-of-the-box JSF 2 ajax support to avoid validation firing I tried to use f:ajax but doesn't work.
I also tried to use it out of the portlet environment doesn't work, I change the ice:selectOneMenu to h:selectOneMenu then got DOM exception.
the version of Icefaces is 2.0.1

A:

I solve this problem through using old mechanism for JSF1 with immediate attribute and in the end of the change listener method I add this
FacesContext.getCurrentInstance().renderResponse();

and the validation not firing.


Q:

Use temporal class weights in many-to-one RNNs in Keras

I have a model that uses several many-to-many RNN layers, followed by a single many-to-one layer and a one-to-one decoding layer.
So the first RNN layer uses the parameter "return_sequences=True" and the second RNN layer uses "return_sequences=False".
So far this works, but it falls apart when I add sample weights. If I had a regular many-to-many network, I would simply set sample_weight_mode="temporal" in the compile() function and define the weights as a 2d matrix.
However in my many-to-one case, this doesn't work, as I get the error that temporal weights expect a time dimension in the output. I realize that this is likely due to the fact that my decoding layer is not temporal anymore (many-to-one). But I can't run the network using non-temporal weights as this would not work together with the many-to-many layers.
Is there a solution to having sample weights with mixed many-to-many and many-to-one layers?
Here's my model to hopefully clarify a bit:
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
the_input (InputLayer)       (None, 20, 249)           0
_________________________________________________________________
masking_1 (Masking)          (None, 20, 249)           0
_________________________________________________________________
time_distributed_1 (TimeDist (None, 20, 64)            16000
_________________________________________________________________
relu (Activation)            (None, 20, 64)            0
_________________________________________________________________
simple_rnn_1 (SimpleRNN)     (None, 20, 16)            1296
_________________________________________________________________
simple_rnn_2 (SimpleRNN)     (None, 16)                528
_________________________________________________________________
dense_2 (Dense)              (None, 36)                612
_________________________________________________________________
softmax (Activation)         (None, 36)                0
=================================================================

A:

TL;DR - Just set you sample_weight_mode to None

But I can't run the network using non-temporal weights as this would not work together with the many-to-many layers.

This sentence makes me think you don't actually understand what sample weighting should be doing.
From keras' docs:

sample_weight: Optional Numpy array of weights for the training samples, used for weighting the loss function

This means your sample weights will only be used on the loss function (and, on more recent versions, on the weighted metrics also). Since your loss function is a function of your output alone, I see no reason why your time dependent intermediate layers would affect anything at all.
If you have a single output per time sequence, then your sample is the entire time sequence, not each time step. Thus making your sample weights no different then the ones you would be using for a MLP, for example


Q:

The calling thread cannot access this object (rewrited but same error)

I have a MainFrame window with imageViewer control on it. Also there is my dll which calculates changes for the image all was working fine before I decided to add ProgressDialog.(( The Idea was - firstly I am loading the image via dll to main frame (this still OK). Then if user clicks button then show ProgressDialog and in worker.DoWork create new image via the same dllwrapper class (I am using "new")
All seems to be ok but when i am trying to set my currentImage property of imageviewer control (this is nothing more then setter for Image)it show me this error!
This is the code of my userButtonClickHandler from where I am launching ProgressDialog:
void OnThumbnailClick(object sender, RoutedEventArgs e)
{
    pd = new ProgressDlg();
    pd.Cancel += CancelProcess;

    int max = 1000;
    System.Windows.Threading.Dispatcher pdDispatcher = pd.Dispatcher;
    worker = new BackgroundWorker();
    worker.WorkerSupportsCancellation = true;
    LibWrap lwrap = new LibWrap();//!NEW instance for dll wrapper!

    worker.DoWork += delegate(object s, DoWorkEventArgs args)
    {
        imageViewer.CurrentImage = lwrap.engine2(BitmapFrame.Create(MyPrj.App.draggedImage));//ERROR IS HERE!!!//The calling thread cannot access this object because a different thread owns it.
        //what process??
    };

    worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
    {
        pd.Close();
    };

    worker.RunWorkerAsync();
    pd.ShowDialog();
}

There is function from the same MainFrame class for canceling (There is OK too)
void CancelProcess(object sender, EventArgs e)
{
   worker.CancelAsync();
 }

This is class for ProgressDlg (it has nothing more then progress bar and cancel button):
public partial class ProgressDlg : Window
    {
        public ProgressDlg()
        {
            InitializeComponent();
        }
        public string ProgressText
        {
            set
            {
                this.lblProgress.Content = value;
            }
        }
        public int ProgressValue
        {
            set
            {
                this.progress.Value = value;
            }
        }
        public event EventHandler Cancel = delegate { };
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            Cancel(sender, e);
        }
    }
}

I am working with this problem for (almost) two days and still couldn't find the solution. Help me please if you have an idea.
1 UPDATE
It seems to me that you was right about this threads - when I am trying to load previously loaded(initial) image (from the main thread) -it loads OK but if I am trying libWrap it fails due to processes conflict!
worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
            {
imageViewer.Width = 1000;//work!
  imageViewer.CurrentImage = MyPrj.App.draggedImage;//Work!
imageViewer.CurrentImage = lwrap.engine2(BitmapFrame.Create(MyPrj.App.draggedImage));//Fail =(!

}

2 UPDATE
I have tried this construction OnThumbnailClick
Application.Current.MainWindow.Dispatcher.BeginInvoke(new Action(() =>
                {
imaeViewer.CurrentImage = lwrap.engine2(BitmapFrame.Create(FXPhotoStudio.App.draggedImage));
}

This caused same error/ Perhaps it will be correct to pass this value in MainThread (UI)? But I have no idea how.( I couldnot use serializers - becouse it is rapidly calling operation and this images are temporary/

A:

WPF cannot alter items that were created on another thread.
So if you create an ImageViewer on one thread, you cannot alter it's properties on another thread.
Instead, use the Dispatcher, which is WPF's internal message queue for the main UI thread, to update your objects.
Or, use Henk's Answer to do your work on another thread, but return the result to the main thread so it can update your ImageViewer's properties


Q:

Sorting data from Angular http get api call

This seems like it should be a really trivial thing, but I'm really struggling to work out a neat non-hacky solution to a simple problem.
my http.get(... Angular call to my service brings back an Observable - which is a stream of T items (after I have mapped with response.json())
The Observable is a property on my component. I have a <select> element in the component template with the <option> elements created via the *ngFor="let item of myObservable | async" code in my template.
This has created a nice select element with all values that I expect showing up nicely in the browser :)
Now someone has asked me to sort the options in the select statement alphabetically.
I dont want to create a sorting pipe, as the Angular team recommend not doing that, and it seems that Observables are by their nature un-sortable.
Ive tried to convert the Observable into a simple array of results - but that seems impossible too.
So how do I achieve this simple thing? my JSON service returns 20 or so JSON objects, and I cant seem to work out how to get them sorted by one of their properties.
Thanks for any help.

A:

OK, Ive solved it (if anyone is interested;
My original code from the service was like this:
  public getAllItems(): Rx.Observable<DataItem> {
    var returnVar = this.http.get("http://localhost:8090/api/rest/dataitem")
      .map(res => {
        return res.json()
      });
    return returnVar;

But then I changed the observable to an observable of type array, and sorted it in the map
public getAllItems(): Rx.Observable<DataItem[]> {
    var returnVar = this.http.get("http://localhost:8090/api/rest/dataitem")
      .map(res => {
          var ret = <DataItem[]>res.json();
          ret.sort((a,b) => a.name < b.name ? -1 : 1);
          return ret;
      } );

I didnt realise that you could cast the response object into either a single item or the entire array.
Thanks for everyone who tried to help.


Q:

How to implement cryptographic algorithms in smart contracts?

I need to implement cryptographic algorithms such as AESCCM and elliptic curve algorithms (ECDSA, ECIES) within a smart contract. Is there any implementation of such algorithms in Solidity or Serpent?
Or is there is any way to integrate Python code (or other language) within Serpent for example (there many cryptographic libraries in Python)?
Or any other suggestions on how can I implement those algorithms?

A:

This library is a good starting point:
https://github.com/HarryR/solcrypto
As Richard points out symmetric key crypto and private key operation are rarely sensible in a smart contract as the smart contract has no privacy. However public key operations like checking signatures, proofs and hashes can be very useful and got more efficient with the addition of the elliptic curve precompiled contracts in Byzantium.


Q:

здравствуйте, не подскажете как увести текст placheolderа вверх, чтобы 23 начиналось сверху, а не по середине

[![

  .rek {
  width: 730px;
  height: 100px;
  background-color: #3c5499;
  margin: 10px 0px 50px 0px;

}

::placeholder {
  color: #FFF;
  opacity: 1;
<!doctype html>

  <meta charset="utf-8">
  <link rel="stylesheet" href="style.css">
  <title>Site</title>

    <input class="rek" type="text" placeholder="Your message">

]1]1

A:

Возможно Вам стоит использовать вместо тега <input ... /> тег <textarea></textarea>

  .rek {
  width: 730px;
  height: 100px;
  background-color: #3c5499;
  margin: 10px 0px 50px 0px;
  color: #FFF;
}
<!doctype html>

  <meta charset="utf-8">
  <link rel="stylesheet" href="style.css">
  <title>Site</title>

    <textarea class="rek">Можно использовать textarea вместо input если хотите получить многострочный текст.</textarea>


Q:

Jsoup encoding in post requests

I am having this issue when posting a POST request to the Cyrillic. I Have been using JSoup and tried something similar to this and the site uses win1251 encoding
. header ("Content-Type", "application / x-www-form-urlencoded; charset = UTF-8")
but it is not working? what could be the issue

A:

Problem solved. I have edited the source code of jsoup to make it work.


Q:

Visual Studio 2010 editions - switching from Premium (not a trial) to Ultimate trial and back again

I have installed Visual Studio 2010 Premium RTM (not a trial) and would like to run the Visual Studio 2010 Ultimate Trial for a while.
What is the fastest way to switch to Ultimate trial and back again to the Premium?
My best idea:

not uninstalling the Premium edition.
running the Microsoft Visual Studio 2010 Ultimate Trial - Web Install
testing the Ultimate trial
uninstalling the Ultimate trial
repairing the Premium installation

A:

Probably the safest way would be to run the trial in a VM under VMWare or VirtualBox. I wouldn't trust different versions or levels of the same software to run nicely together.
But I'm inherently paranoid :-)


Q:

PHPでRubyのようなキーワード引数はできますでしょうか？

Rubyでは引数の順序を気にしないで、
下記のように書くことができます。
これをキーワード引数というそうです。
def self.piyo(msg: 'hello', name: 'Yamada')
  p "#{msg}, #{name}"
end

Hoge.piyo #=>"hello, Yamada"
Hoge.piyo(msg: 'Hi', name: 'Sato') #=> "Hi, Sato"
Hoge.piyo( name: 'Sato', msg: 'Hi') #=> "Hi, Sato"

そこで質問なのですが、PHPではこの機能はありますでしょうか？
ご存知の方がいらっしゃいましたら、教えて頂けると幸いです。
コードは↓を参考にしています。
http://qiita.com/rtoya/items/33617078501776fdcad7
よろしくお願いします。

A:

PHPでは、キーワード引数を言語に加えるという提案がありますが、キーワード引数は今のまま不可能です。
しかし、配列を使えます。例えば：
function piyo($args) {
  // 初期値を足す
  $args += array(
    'msg' => 'hello',
    'name' => 'Yamada'
  );

  echo("$args[msg], $args[name]");
}

piyo(array('msg' => 'Hi', 'name' => 'Sato')); // => "Hi, Sato"
piyo(array('name' => 'Sato', 'msg' => 'Hi')); // => "Hi, Sato"

PHP5.4では、piyo(['msg' => 'Hi', 'name' => 'Sato']);というシンタックスも使えます。

補足：JavaScriptのFunction.applyのように、call_user_func_arrayも使えるようです。例えば：
function piyo($msg = 'hello', $name = 'Yamada') {
  echo("$msg, $name");
}

// => "Hi, Sato"
call_user_func_array(
  'piyo', array('msg' => 'Hi', 'name' => 'Sato')
);
// => "Hi, Sato"
call_user_func_array(
  'piyo', array('name' => 'Sato', 'msg' => 'Hi')
);

このSOの回答のように、extractも使えるようです：
function piyo($args = array(), $msg = 'hello', $name = 'Yamada') {
  extract($args);
  echo("$msg, $name");
}

piyo(array('msg' => 'Hi', 'name' => 'Sato')); // => "Hi, Sato"
piyo(array('name' => 'Sato', 'msg' => 'Hi')); // => "Hi, Sato"

A:

今のところ配列かオブジェクトで擬似的に表現するしかないかもですね。
function piyo($k) {
    echo $k['msg'] . ", " . $k['name'];
}
piyo(['msg' => 'hello', 'name' => 'Yamada']);


Q:

LibGdx game dev shooting bullets

So basically every time i shoot, a new dynamic body is created with linear impulse , after constantly shooting my bullets game starts to get slow( it's obvious because i constantly create a new object..). What should i do to avoid this problem, i tried deleting objects, bodies?
Thank you for your answers in advance.

A:

I'm still new to Java, but the way I understand it is that if anything references an object, that object won't be picked up by the recycler. Triple check all of your arrays and lists to make sure one isn't filling up with bullets. Display the sizes of your arrays while playing to see if one is acting weird.
For each bullet you probably want to see if it is off screen. If so, remove it from the list/array.


Q:

media query, browser width issue on mobile

This is my grid setup for media query. But, it shows its in 980px on my mobile.
 @import "grid/grid";

 $display_320: 'only screen and (max-width: 479px)'; $display_480:
 'only screen and (min-width: 480px) and (max-width: 767px)';
 $display_768: 'only screen and (min-width: 768px) and (max-width:
 985px)'; $display_1024: 'only screen and (min-width: 986px)';

 @media #{$display_320} {   @import "grid/grid_320"; } @media
 #{$display_480} {   @import "grid/grid_480"; } @media #{$display_768} {   @import "grid/grid_768"; } @media #{$display_1024} {   @import
 "grid/grid_1024"; }

My mobile phone is suppose to be 320px, but it says 980px. Do I have to do anything in my html?
Here is my code : http://jsfiddle.net/m38Gw/

A:

What's Going On
A lot of mobile browsers will provide fake information about their window width. This started with the iPhone because the pixel density was (is) so high compared to traditional computer monitors.
To give a more current example, the Galaxy S4 has a screen resolution of 1920x1080 pixels. That is the exact same as my 27" monitor. Media Queries, without resolution spoofing by mobile browsers, would be utterly useless here, because there is no difference in terms of real pixels.
To combat this, we have the viewport. This is the "fake" resolution of the mobile device, normally much smaller than the true resolution. Through the viewport we can retain use of media queries.
As tv4free stated, we have a tool to control the viewport, in the form of meta elements. One potential issue with his code though, is the maximum-scale. This will fix the viewport and not allow any scaling. Personally, I don't think that is an a problem is your media queries are properly designed. However, many people consider it to be a bad idea. If you leave out maximum-scale=1.0; user-scalable=0;, you will make the page load correctly each time, but allow the user to zoom in and out.
Code
Set the resolution, allow zoom:
<meta name="viewport" content="width=device-width; initial-scale=1.0;">

Set the resolution, don't allow zoom:
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"

More information:
http://www.quirksmode.org/mobile/viewports.html
http://www.quirksmode.org/mobile/viewports2.html


Q:

Remainder Question

What process do I use to show what is the remainder when 14 × 7^36 + 92 when divided by 8?
Is it the same to show the remainder of 5^2003 when divided by 7?
I tried out the problem using congruent modulo but cannot help

A:

HINT:
For the first $7^2=49\equiv1\pmod8\implies 7^{2n}\equiv1$ where $n$ is any integer $\ge0$
For the second $5^3=125\equiv-1\pmod7$ and $2003=667\cdot3+2$
$\displaystyle\implies 5^{2003}=(5^3)^{667}\cdot5^2\equiv(-1)^{667}\cdot5^2\pmod 7$


Q:

Is it possible to block thread access to 'A' while a thread is executing 'B'?

Suppose I have two classes A and B
public class A
{
    public synchronized void doSomethingA
    {
        //Do stuff
    }
}

public class B
{
    public synchronized void doSomethingB
    {
        //Do other stuff
    }
}

And i have two threads running in unison, let's call them x and y.
Since the methods are synchronized, it is not possible for y to access dosomethingA while x is in there, but it can access doSomethingA while x is doing doSomethingB.
Is there any way to block y from doing anything while x is in doSomethingA or in doSomethinB?

A:

Plenty of ways. The most direct way would be to use a ReentrantLock`.
It provides the same functionality as synchronized, but you are responsible for managing the locking yourself. You'll need to share one between the classes, so that both methods can then use it for locking.


Q:

Why can immutable variables be passed as arguments to functions that require mutable arguments?

Example code：
fn main() {
    let a = [1, 2, 3, 4, 5];
    reset(a);
}

fn reset(mut b: [u32; 5]) {
    b[0] = 5;
}

The variable a is an immutable array, and the reset function's parameter b is a mutable array; intuitively I need to modify a to a mutable array before I can call the reset method, but the compiler tells me that I don't need to do this, why is this?
fn main() {
    let mut a = [1, 2, 3, 4, 5];
    reset(a);
}

fn reset(mut b: [u32; 5]) {
    b[0] = 5;
}

warning: variable does not need to be mutable
 --> src/main.rs:2:9
  |
2 |     let mut a = [1, 2, 3, 4, 5];
  |         ----^
  |         |
  |         help: remove this `mut`
  |
  = note: #[warn(unused_mut)] on by default

A:

When you pass by value, you are transferring ownership of the value. No copies of the variable are required — first main owns it, then reset owns it, then it's gone1.
In Rust, when you have ownership of a variable, you can control the mutability of it. For example, you can do this:
let a = [1, 2, 3, 4, 5];
let mut b = a;

You could also do the same thing inside of reset, although I would not do this, preferring to use the mut in the function signature:
fn reset(b: [u32; 5]) {
    let mut c = b;
    c[0] = 5;
}

See also:

What's the idiomatic way to pass by mutable value?
What's the difference between placing "mut" before a variable name and after the ":"?

1 — In this specific case, your type is an [i32; 5], which implements the Copy trait. If you attempted to use a after giving ownership to reset, then an implicit copy would be made. The value of a would appear unchanged.


Q:

select query records if multiple type is matched

I have some mysql tables like below,
1)videos
id      name
1       test1
2       test2

2)tags
id      name
1       theme1=test1
2       theme1=test2
3       theme2=test1
4       theme2=test2
5       age=senior
6       age=children

3)tags_to_items
vid    tagid
1      1
1      5

Here in table tags_to_item you see videos.id=1 has 2 tags
1)theme1=test1 AND 2)age=senior. It means video.id=1 has 2 tags.
Now here is one conflict,
what i am doing now is, i am searching for theme's only. It means if i search where theme1=theme1 then it need to also search theme1 in theme2 and vice versa. like this
WHERE tagid=1 OR tagid=2

This is functioning proper, but now i want to search if video have multiple tag with AND condition like this
WHERE tagid=5 AND tagid IN (1,2)

It should return video.id=1
So, probably it need to search where video 1 contains tag tag age=senior AND theme1=theme1 OR  theme2=theme1. But its not working, anyone have idea how can i do like this?

A:

I think i got the answer.
I need to do join like this,
INNER JOIN tags_to_items t2      ON (v.id = t2.tagid AND t2.tagid = 5)

INNER JOIN tags_to_items t3      ON (v.id = t3.tagid AND t3.tagid in ('27' ,'69','84' ,'99' ))


Q:

Came or come from a poor family

Would you say

I came/was from a poor family
I come/am from a poor family

My family used to be poor but not anymore. Normally, you would say I am from this country because that is your native country. However for this question your origin has changed from being poor to not being one. I would use came/was from a poor family. But I heard someone say "I am from a middle class family" even though that person is rich now.

A:

I come from a poor family is a more idiomatic way of speaking than I am from a poor family although both are grammatically correct.
I am from a poor family sounds slightly more poetic or theatrical.
To say: I came from a poor family implies either that you are telling a story or that the family is now better off.
If the latter, it would be better to say clearly that your family was poor at the time that you were born.
It would be natural for a writer to use the past tense in a biography or novel that is written in this tense.
Regarding the statement you heard, it's perfectly fair to say that one comes/is from a middle class family even if the speaker has subsequently grown wealthy. It implies that the (rest of the) family is still middle class, whether financially or in its outlook and habits.


Q:

What does P_SEND_MILESTONE config do?

From what I understand it is the probability that a milestone is selected as a tip?
If this value was a bit higher, would it make the nodes sync faster?
Here are the places in code which I mean:
    conf.put(DefaultConfSettings.P_SEND_MILESTONE.name(), "0.02");

L95 &
private Hash getRandomTipPointer() throws Exception {
        Hash tip = rnd.nextDouble() < P_SEND_MILESTONE? milestone.latestMilestone: tipsViewModel.getRandomSolidTipHash();
        return tip == null ? Hash.NULL_HASH: tip;
    }

L450 Source
This relates to the development of Nelson. I am trying to find out whether relatively frequent peer switching could lead to milestone lags.
Here is an idea, which might explain some lagging behind the latest milestone:
Since the milestones are sent randomly in less than 2% of all cases, it might take time for a node to send/receive a milestone. When running Nelson, certain time is lost to connect/disconnect peers, which maybe decreases a little the probability to receive a milestone.
Now, what if this IRI config value was changed when running Nelson to 0.05, for example, instead of 0.02? The Nelson nodes would reference the milestone more often and get in sync faster?
Is it worth trying?

A:

What does P_SEND_MILESTONE config do?

P_SEND_MILESTONE is used when a neighbor requests a random tip L420, w.h.p a random tip will be sent back, but in a small probability a milestone will be sent as a response. this was added to support older IRI versions while syncing IIRC.
However, milestones are propagated in two main ways (P_SEND_MILESTONE being a third & minor way):

TipRequesterThread - which broadcasts the latest milestone to all neighbors every 5 seconds.
processReceivedData - like any new transaction, when received, it is broadcast to all the neighbors.

This relates to the development of Nelson. I am trying to find out whether relatively frequent peer switching could lead to milestone lags.
If this value was a bit higher, would it make the nodes sync faster?
  no, as milestones are re-sent every 5 sec.

to clarify, do you mean that the latestMilestone is lagging, or the latestSolidSubtangleMilestone?
if the former, then yes, this might help. but this is a rare event on normal nodes & should be investigated if so.
if the latter, then no, fast propagation of milestones doesn't promise that a subtangle would be solid - that is an issue related to fetching all the missing transactions which are referenced by a milestone, or could be an issue in recognizing that this has happen.


Q:

Can you add an .addEventListener inside another to complete a form?

I want to open a form when you press a button and then when you completed the form make another button to store the datas in an object.
I did that, but in the second addEventListener it gives me this error:

cannot read property 'addEventListener' of null

const newStudentButton = document.getElementById("addStudent");
const introducingButton = document.getElementById('introducingStudent');
newStudentButton.addEventListener("click", function () {
  let firstName;
  let lastName;
  let age;
  let eyeColor;
  let hairColor;
  let programmingSkills;

  formDiv.innerHTML += "<form>
First Name:

<input type = 'text' id = 'firstName' class = 'form_input'></form>"
  firstName = document.getElementById('firstName').value;

  formDiv.innerHTML += "<form>
Last Name:

<input type = 'text' id = 'lastName' class = 'form_input'></form>"
  lastName = document.getElementById('lastName').value;

  formDiv.innerHTML += "<form>
Age:

<input type = 'text' id = 'age' class = 'form_input'></form>"
  age = document.getElementById('age').value;

  formDiv.innerHTML += "<form>
Eye Color:

<input type = 'text' id = 'eyeColor' class = 'form_input'></form>"
  eyeColor = document.getElementById('eyeColor').value;

  formDiv.innerHTML += "<form>
Hair Color:

<input type = 'text' id = 'hairColor' class = 'form_input'></form>"
  age = document.getElementById('hairColor').value;

  formDiv.innerHTML += "<form>
Programming Skils:

<input type = 'text' id = 'programmingSkills' class = 'form_input'></form>"
  programmingSkills = document.getElementById('programmingSkills').value;

  formDiv.innerHTML += "<button type = 'button' id = 'introducingStudent'>Submit</button>"

  introducingButton.addEventListener("click", function() {
  var newStudent = {
    firstName: firstName,
    lastName: lastName,
    age: age,
    eyeColor: eyeColor,
    hairColor: hairColor,
    programmingSkills: programmingSkills
  }
  allStudents.push(newStudent)
  console.log(allStudents)
})

A:

Why are you calling document.getElementById('introducingStudent'); at first. When the page load the div with id introducingStudent is null because it is only created when newStudentButton is clicked. So document.getElementById('introducingStudent'); should be done only after the click event of newStudentButton
const newStudentButton = document.getElementById("addStudent");
newStudentButton.addEventListener("click", function () {
  let firstName;
  let lastName;
  let age;
  let eyeColor;
  let hairColor;
  let programmingSkills;

  formDiv.innerHTML += "<form>
First Name:

<input type = 'text' id = 'firstName' class = 'form_input'></form>"
  firstName = document.getElementById('firstName').value;

  formDiv.innerHTML += "<form>
Last Name:

<input type = 'text' id = 'lastName' class = 'form_input'></form>"
  lastName = document.getElementById('lastName').value;

  formDiv.innerHTML += "<form>
Age:

<input type = 'text' id = 'age' class = 'form_input'></form>"
  age = document.getElementById('age').value;

  formDiv.innerHTML += "<form>
Eye Color:

<input type = 'text' id = 'eyeColor' class = 'form_input'></form>"
  eyeColor = document.getElementById('eyeColor').value;

  formDiv.innerHTML += "<form>
Hair Color:

<input type = 'text' id = 'hairColor' class = 'form_input'></form>"
  age = document.getElementById('hairColor').value;

  formDiv.innerHTML += "<form>
Programming Skils:

<input type = 'text' id = 'programmingSkills' class = 'form_input'></form>"
  programmingSkills = document.getElementById('programmingSkills').value;

  formDiv.innerHTML += "<button type = 'button' id = 'introducingStudent'>Submit</button>"

  const introducingButton = document.getElementById('introducingStudent');
  introducingButton.addEventListener("click", function() {
  var newStudent = {
    firstName: firstName,
    lastName: lastName,
    age: age,
    eyeColor: eyeColor,
    hairColor: hairColor,
    programmingSkills: programmingSkills
  }
  allStudents.push(newStudent)
  console.log(allStudents)
})


Q:

What software is out there for domain availability in bulk for free?

I am looking for software (possibly a website) where I can check domains in bulk for availability - and a very large number of them ~ 500 000 including tlds such as .in, .it, .nl and other 2 letter domains (not just .com, .net, .org etc). Does anyone know of anything suitable?

A:

I used to use BulkRegister when I did this a few years ago.
I'm afraid I can't access the website from here to try it, so it may not be available any more!


Q:

How to get the percentage of my brute forcer?

I need help on understanding how to calculate the percentage, of my scripts progress as it takes a while depending on the [CPU, clock speed, RAM, and length of the target password_list].
Would you point me in the right direction, or show me a snippet of how to calculate this?
import itertools, math
Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") # Add or remove whatevs you think will be in the password you're cracking (example, [symbols])
counter = 1
CharLength = 1
start_range = int(raw_input("Enter start range: ") # <<< To begin brute force
end_range = int(raw_input("Enter end range: ")) # <<< To end brute force
filename = "bruteforce_%r-%r.txt" % (start_range, end_range)

This below is where the calculation would be done; unfortunately percentages just nope my brain will not let me understand em :/
# Math below don't let it bore you :)
y = len(Alphabet)
x = len(start_range)
total = math.pow(x, y)
f = open(filename, 'a')
# Math above don't let it bore you :(

The First for loop
for CharLength in range(start_range, end_range):
    passwords = (itertools.product(Alphabet, repeat = CharLength))

The Second for loop
    for i in passwords:
        counter += 1
        i = str(i)
        i = i.replace("[", "")
        i = i.replace("]", "")
        i = i.replace("'", "")
        i = i.replace(" ", "")
        i = i.replace(",", "")
        i = i.replace("(", "")
        i = i.replace(")", "")
        f.write(i)
        f.write('\n')
        print "%r:  %r" % (i, percentage) # <--- *Display percentages on second format argument
        pass

A:

Use python-progressbar. From their git repo:

The ProgressBar class manages the current progress, and the format of
  the line is given by a number of widgets. A widget is an object that
  may display differently depending on the state of the progress bar.
  There are three types of widgets:

a string, which always shows itself
a ProgressBarWidget, which may return a different value every time its    update method is called
a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it    expands to fill the remaining width of the line.

Example:
import progressbar as pb

progress = pb.ProgressBar(widgets=_widgets, maxval = 400000).start()
progvar = 0

for i in range(400000):
    # Your code here
    progress.update(progvar + 1)
    progvar += 1

Output:
Progress: |####################################################            |80%


Q:

Nested dictionary from dataframe with loop over list

complete newbie here.
I want to read data from two columns in several excel sheets in a nested dictionary. In the end, I'd like to have a dictionary looking like this:
{SheetName1:{Index1: Value1, Index2: Value2,...}, SheetName2:{Index1: Value1, Index2: Value2} ...}

So far I read in the data using pandas and figured out how to combine the two columns I need into the inner dictionary {Index: Value}, which afterwards gets assigned the name of the sheet as a key to from the outer dictionary:
#read excel sheet into dataframe
df = ExcelWorkbook.parse(sheet_name = None, header= 1, usecols= 16, skiprows= 6)

#read in the different excel sheet names in a List
    SHEETNAMES = []
    SHEETNAMES = ExcelWorkbook.sheet_names

#nested dictionary
for Sheet in SHEETNAMES:
    df[Sheet] = df[Sheet].loc[0:87,:]
    dic = dict(zip(df[Sheet].index, df[Sheet]['ColumnName']))
    dic = {Sheet: dic}

Now when I run this, it only returns the last sheet with its corresponding {Index: Value} pair:
{'LastSheetName': {Key1: Value1, Key2: Value2,...}

Now it seems to me that I've done the "harder" part but I can't seem to figure out, how to fill a new dictionary with the dictionaries generated by this loop....
Any help is greatly appreciated!
Best regards,
Jan

A:

You are assigning dic as a new variable each time you iterate through your for loop. Instead, instantiate dic as an empty list [] outside of the loop and then append the dictionaries you define inside the loop to it, such as:
#read excel sheet into dataframe
df = ExcelWorkbook.parse(sheet_name = None, header= 1, usecols= 16, skiprows= 6)

#nested dictionary
dic = []
for Sheet in ExcelWorkbook.sheet_names:
    df[Sheet] = df[Sheet].iloc[0:87,:]
    out = {Sheet: dict(zip(df[Sheet].index, df[Sheet]['ColumnName']))}
    dic.update(out)

Also, you want you to use .iloc in place of .loc considering you are specifying index locations inside of the dataframe.


Q:

how to fix /bin/sh: syntax error: unexpected "(" without changing to /bin/bash

I have this makefile:
SHELL = /bin/sh
INSTALL =/usr/bin/install
INSTALL_PROGRAM = $(INSTALL)
INSTALL_DATA = $(INSTALL) -m 644
STRIP=$(TARGET_CROSS)strip
EXEC=monApp
SRC= $(wildcard src/*.cpp)
OBJ= $(SRC:.cpp=.o)
CXX=$(TARGET_CROSS)g++
CXXFLAGS = -I./include –I$(STAGING_DIR)/include –I(STAGING_DIR)/usr/include/
LDFLAGS = -g -Wall -L$(STAGING_DIR)/lib –lEGL –lGLESv2 –lIMGegl –L$(STAGING_DIR)/usr/lib
all: $(EXEC)
$(EXEC): $(OBJ)
    $(CXX) -o $@ $^ $(LDFLAGS)
%.o: %.cpp
    @$(CXX) -o $@ -c $< $(CXXFLAGS)

.PHONY: clean
clean:
    @rm -rf src/*.o
    @rm -rf $(EXEC)
install: $(EXEC)
    mkdir -p ./package.release
    $(INSTALL_PROGRAM) $(EXEC) ./package.release/
    $(STRIP) ./package.release/$(EXEC)
uninstall:
    @rm -rf ./package.release/

How do I fix this issue without changing to /bin/bash (i do not have bash so i have to use sh)?
Thank you,

A:

Since feature requests to mark a comment as an answer remain declined, I copy the above solution from J.F. Sebastian here.
add missing $ to (STAGING_DIR) in the CXXFLAGS


Q:

Implementation of Random Forest using alglib in C++

I am a novice in C++, who is trying to implemenent Random Forest Algorithm by Leo Breimen.
I have worked with Random Forest algorithm in MATLAB with the code for
 https://code.google.com/p/randomforest-matlab/ and I am able to train and test with an accuracy of 98%
for my Phd thesis, now I need to work with RF using C++. I am trying to use alglib
g++ dataanalysis.cpp -o  analyzer

I tried compiling the dataanalysis.cpp, resulted me with the following error.
http://pastebin.com/bxmRa4pq
Any suggestions of using other multi class Random Forest algorithm (Original algorithm by Breimen)

A:

Check gcc for the path where libalglib.a is installed, for example:
gcc -lalglib -L/my/path/

Check include files, you are adding none or some?
gcc -I/my/path/alglib/include

complete it would look like this
gcc -I/my/path/alglib/include -lalglib -L/my/path/


Q:

Is there any negatives to storing JSON in MySQL?

I am building a complex ordering system and I am struggling with whether I should store some of the more detailed information in a single column as JSON or if I should create the multiple tables and logic to keep JSON out of the picture.
Since each order will have multiple required dates, ship dates, parts, kits (collections of parts), and more. It just seems easier to store this as JSON of a single 'order'row.
Are there any major down sides to doing this?

A:

JSON is geared more towards short term storage to send data from one thing to another.  It is horribly inefficient space and computationally wise for long term storage compared to a database.  You will also loose the ability to query the data directly without parsing it first (e.g "select * from table where orderdate < today").  You'll also have to develop your own tools to view the data, since if you try to view it in the database directly, everything will run together.
In short, this is almost always a really bad idea.


Q:

Maximum disjoint set: what is the actual approximation factor of the greedy algorithm?

Consider the problem of finding a maximum disjoint set - a maximum set of non-overlapping geometric shapes, from a given collection of candidates. This is an NP-complete problem, but in many cases, the following greedy algorithm yields a constant-factor approximation:

For every candidate shape x, calculate its disjoint intersection number $DIN(x)$ = the largest number of disjoint shapes that intersect x.
Select a candidate shape with a smallest DIN ($\arg \min_{x} DIN(x)$). Remove it and all the shapes it intersects.
Continue until no more candidates remain.

For example, consider the following figure from the Wikipedia page:

The green disk intersects 5 other disks, but its DIN is 3 (the 3 red disks are disjoint). The topmost and bottommost red disks intersect 2 other disks, but they themselves intersect, so their DIN is 1. The yellow disks have a DIN of 2.
The greedy algorithm thus selects the topmost or the bottommost red disk.
If the minimum DIN can be bounded by a constant, then the greedy algorithm is a polynomial constant-factor approximation.
For example, if all candidate shapes are unit disks, Marathe et al (1995) show that a disk with a DIN of at most 3 always exists: the leftmost disk (the disk with the smallest x coordinate) intersects at most 3 other disjoint disks. Therefore the greedy algorithm yields a 3-approximation because it obtains 1 disk for each (at most) 3 disks in the optimal solution.
Similarly, if all candidate shapes are disks of arbitrary size, the greedy algorithm yields a 5-approximation, because the smallest disk intersects at most 5 other disjoint disks, i.e. the minimum DIN is at most 5.
So far so good, but Are these factors of 3 and 5 tight? I am not sure.
Consider the figure above. Selecting the leftmost disk (green) will find a disjoint set of size 1, which is indeed a 3-approximation to the maximum disjoint set of size 3 (red), but, the greedy algorithm will not select the green disk - it will select the top/bottom red disk, whose DIN is 1. In this case the greedy algorithm will find the optimal solution.
I couldn't find a counter-example for general $n$, in which the greedy algorithm finds a disjoint set with $n$ unit disks while the maximum disjoint set has $3n$. Actually, I couldn't even construct a general counter-example in which the minimum DIN is indeed 3. The best I could come up with is the following, in which each unit disk intersects at most 2 other disjoint disks (i.e. the minimum DIN is 2). But even here, the greedy algorithm finds the optimal solution rather than a 2-approximation:

My questions are:

What is the actual max min DIN in collections of unit-disks? Arbitrary-sized disks?
What is the actual approximation factor of the greedy algorithm for collections of unit-disks? For arbitrary-sized disks? (this factor is at most as large as the max min DIN, but may be smaller).

UPDATE: For every k-tuple of shapes, $x_1,...,x_k$, define $DIN(x_1,...,x_k)$ = the largest number of disjoint shapes intersected by their union $x_1\cup...\cup x_k$. Define $minDIN_k$ as the minimum DIN of over all k-tuples of disjoint shapes.
For example, in Yury's answer below, $minDIN_1=3$, because every circle intersects 3 other circles. $minDIN_2=4$, because it is possible to select 2 disjoint circles, one from the outer circle and one from the inner circle, that together intersect only 4 other circles. For every $k$, $minDIN_k\leq k+2$.
I THINK that the approximation ratio of the greedy algorithm can be bounded by $\frac{minDIN_k}{k}$, because, for every $minDIN_k$ shapes in the optimal solution, we have at least $k$ shapes in the algorithm output. Is this correct?
EDIT: I am now reading the excellent book Research problems in discrete geometry. While I haven't found this exact problem, I found a problem that looks related. In section "2.5 Thin Packings with Many Neighbors", there are examples of circle packings in which each circle touchese 5 other circles. I wonder if such a packing can yield a configuration of circles with DIN = 5.

A:

What is the actual maximum minimum DIN in collections of unit-disks?

It is 3.


Q:

applying a rolling error function using rollapply

I am trying to calculate a rolling error function in R where I take the last 30 days and compute the rmse, move forward 1 day and take the last 30 days from this point and compute the new rmse.
My data looks like the following where I have a date and two values:
         dates         val1         val2
1   2010-01-01 -0.479526441 -0.294149127
2   2010-01-02 -0.860588950  0.426375720
3   2010-01-03 -0.660643894 -1.483020861
4   2010-01-04 -0.938748812 -1.631823690

Where am I going wrong in the code?
Data & attempt:
d <- data.frame(
  dates = seq(from = as.Date("2010-01-01"), to = as.Date("2012-12-31"), by = 1),
  val1 = rnorm(1096),
  val2 = rnorm(1096)
)

d %>%
  mutate(rollRMSE = rollapply(., width = 30, by = 1, FUN = Metrics::rmse(val1, val2)))

A:

EDIT : setting window size as a variable
I have sliced the steps, rollapply will result in 29 less data with a 30 window so may want to collect this in another tibble.
suppressPackageStartupMessages(library(dplyr))

d <- data.frame(
        dates = seq(from = as.Date("2010-01-01"), to = as.Date("2012-12-31"), by = 1),
        val1 = rnorm(1096),
        val2 = rnorm(1096)
)

rse <- function(x, y){sqrt((x-y)**2)}

# assign window size for moving average
window <- 30

d %>% tibble::as_tibble() %>%
        mutate(err = rse(val1, val2),
             roll = c(zoo::rollapply(err, width = window, by = 1, FUN = mean), rep(NA, window -1) )
)
#> # A tibble: 1,096 x 5
#>    dates          val1   val2   err  roll
#>    <date>        <dbl>  <dbl> <dbl> <dbl>
#>  1 2010-01-01 -0.0248   1.18  1.20   1.40
#>  2 2010-01-02 -0.684    0.603 1.29   1.38
#>  3 2010-01-03 -0.344   -1.92  1.58   1.42
#>  4 2010-01-04  0.447    0.319 0.128  1.38
#>  5 2010-01-05  0.123   -0.810 0.933  1.42
#>  6 2010-01-06  0.00384  2.29  2.29   1.43
#>  7 2010-01-07 -1.51    -1.03  0.487  1.39
#>  8 2010-01-08  0.394   -1.25  1.64   1.41
#>  9 2010-01-09 -1.30     1.61  2.92   1.42
#> 10 2010-01-10  0.394    0.117 0.278  1.33
#> # ... with 1,086 more rows


Q:

How can we use include function in html

How can I include one html file in another html file?

A:

You cannot include one HTML file in another directly in HTML. You should use a server side script (like PHP) to include, or JavaScript to load it in a div.


Q:

Can't get http to work in php

I keep getting this error:
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib64/php/modules/http.so' - /usr/lib64/php/modules/http.so: undefined symbol: php_persistent_handle_abandon in Unknown on line 0
PHP Fatal error:  Class 'HttpResponse' not found in /var/www/api/init.php on line 4
I've reinstalled http through pecl a few times, even tried installing it from the tar.gz. I'm running an EC2 instance.
I HAVE put extension=http.so in my php.ini.

A:

You probably got version 2 of pecl_http, and it has some new requirements. See the installation instructions. For me these lines worked:
extension=raphf.so
extension=propro.so
extension=http.so

Edit: Order matters, so first try the same order as I used.
I also made sure http.so is loaded after json.so and the other prerequisites.

A:

I installed pecl_http successfully with following steps on Debian

execute

sudo pecl install raphf propro pecl_http

create /etc/php5/mods-available/zhttp.ini

extension=raphf.so
extension=propro.so
extension=http.so

execute

sudo php5enmod zhttp

restart your web server


Q:

jQuery reset dialog on cancel and close before form posting

I have code that opens a dialog, validates, and posts a form when the validation is successful.
If the user clicks "Cancel," the dialog should reset until the next time it's called.
If the user clicks "OK," the dialog should close and the form should post, so if I hit the back button the dialog doesn't appear on the page.
Code is as follows:

    Test

            <form id="flagform" action="modalReceipt.asp" method="post">
      Please choose a reason for flagging this document and provide an explanation, if necessary.

      .

Reason:

    <select name="reason" id="reason" class="required">
        <option value="">-- Choose a Reason --</option>
        <option value="plagiarism">Plagiarism</option>
        <option value="submissionError">Submission Error</option>
        <option value="instructions">Student Didn't Follow Instructions</option>
        <option value="blankDocument">Blank Document</option>
        <option value="other">Other (please explain)</option>
      </select>

Explanation:
 <textarea name="explanation" rows="10" cols="35"></textarea>

<input type="hidden" id="fycuserid" name="fycuserid" value="33"/>
<input type="hidden" id="documentGUID" name="documentGUID" value="26219247-EB85-4ABD-8F74-C8448BA06472"/>

</form>

A:

If the user clicks "Cancel," the
  dialog should reset until the next
  time it's called.

edit your "Cancel" to something like this,
"Cancel": function() {
     $(this).dialog("close");
     $(this).find('form')[0].reset();
}

If the user clicks "OK," the dialog should close and the form should post, so if I hit the back button the dialog doesn't appear on the page.

I suggest you do it on server-side. When submit is successful, do a cookie or session variables. Check that variable when page is loaded and do something for the dialog to appear or not appear in the page.


Q:

WebSockets - one or many?

I'm playing around with WebSockets for fun, running Tomcat on the backend.  If I have several streams of data I'd like to share with the client, is it better to have one WebSocket per stream or to multiplex them over one shared WebSocket?
It certainly seems easier to have one WebSocket per stream.  I don't need the advanced logic on the client and server to funnel all data into one pipe, and I don't need any overhead in my data format to indicate the source/destination of each frame.
But are there any downsides to using several WebSockets (5-10) on one client page?

A:

When you want to allow a lot of multiple simultaneous users, you should minimize the numbers of connections per user, because the number of connections a TCP/IP server can have open at the same time is not unlimited. The number of simultaneous connections is limited in the webservers config, by the operating system and last but not least by the architecture of the IP protocol itself (there are only 2^16 ports).

A:

I've heard rumors (but never actually tested) that some browsers may throttle rapid creation of Websocket connections from the same tab/page. If it's true it's to discourage malicious Javascript from trying to use WebSockets to do port scanning. However, apart from that there shouldn't be any issue.
However, since WebSockets is message based (rather than raw streams), it wouldn't be that difficult to mux/demux traffic over one connection. You could add a single character to the beginning of each message to indicate which stream (or if you are sending/receiving JSON maps then just add another field to each message).


Q:

I have 2 forms on this page one, if i only have one it works fine as soon as i add the 2nd it doesnt work?

How am i able to have two form submissions on the one page?
I have 2 forms on this page one, if i only have one it works fine as soon as i add the 2nd it doesnt work?
Is it possible or do have have to link out to another page
site is http://www.vestedutility.com.au/join_vested_utility.php
 <?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $FNAME= trim($_POST["FNAME"]);
    $LNAME = trim($_POST["LNAME"]);
    $CNAME = trim($_POST["CNAME"]);

    $EMAIL= trim($_POST["EMAIL"]);
    $MMERGE4 = trim($_POST["MMERGE4"]);
    $MMERGE5 = trim($_POST["MMERGE5"]);
      $MMERGE3addr1 = trim($_POST["MMERGE3addr1"]);
      $MMERGE3city= trim($_POST["MMERGE3city"]);
      $MMERGE3state = trim($_POST["MMERGE3state"]);
      $MMERGE3zip = trim($_POST["MMERGE3zip"]);
    $MMERGE3country = trim($_POST["MMERGE3country"]);
    $ecew= trim($_POST["ecew"]);

    if ($LNAME == "" OR $EMAIL== ""OR $MMERGE4== ""OR $MMERGE4== "" OR $MMERGE6== "") {
       $error_message = "You must specify a value for name, email address, phone number, post code and message.";

    }
if (!isset($error_message)) {
    foreach( $_POST as $value ){
        if( stripos($value,'Content-Type:') !== FALSE ){
            echo "There was a problem with the information you entered.";
            exit;
        }
    }
}

    if (!isset($error_message) && $_POST["address"] != "") {
        $error_message = "Your form submission has an error.";

    }

    require_once("inc/phpmailer/class.phpmailer.php");

    $mail = new PHPMailer();

   if (!isset($error_message) && !$mail->ValidateAddress($EMAIL)){
        $error_message = "You must specify a valid email address.";

    }
if (!isset($error_message)){
    $email_body = "";
    $email_body = $email_body . "First Name: " . $FNAME . "
";
    $email_body = $email_body . "Last Name: " . $LNAME . "
";
    $email_body = $email_body . "Compnay Name: " . $CNAME . "
";

    $email_body = $email_body . "Email: " . $EMAIL . "
";
    $email_body = $email_body . "Phone: " . $MMERGE4 . "
";
    $email_body = $email_body . "Mobile: " . $MMERGE5 . "
";
    $email_body = $email_body . "Address: " . $MMERGE3addr1 . "
";
    $email_body = $email_body . "City: " . $MMERGE3city . "
";
    $email_body = $email_body . "State: " . $MMERGE3state . "
";
    $email_body = $email_body . "Post code: " . $MMERGE3zip . "
";
    $email_body = $email_body . "Country: " . $MMERGE3country . "
";
    $email_body = $email_body . "EC OR EW number: " . $ECEW;

    $mail->SetFrom($EMAIL, $FNAME, LNAME);
    $address = "james@vestedutility.com";
    $mail->AddAddress($address, "test");
    $mail->Subject    = " VESTED UTILITY JOB MAIL | " . $LNAME;
    $mail->MsgHTML($email_body);

    if($mail->Send()) {
        header("Location: $location?status=thanks");
    exit;
    } else {
      $error_message =  "There was a problem sending the email: " . $mail->ErrorInfo;
      exit;
    }

}
}
     ?>

<?php
$pageTitle = "Join Vested Utility Electricians";
$section = "join vested utility";
$slogan =   'Find Electrical work in Perth';
include('inc/header.php');
?>

Join Vested Utility<text class="r">&reg</text> to get quality

       Electrical job leads in your location

      Vested Utility<text class="r">&reg</text> was created by Electricians who have battled large scale
contractors & franchises and felt the pressure of trying to find work during
slow periods. Our solution was to create a system based lead generation
platform, providing affordable marketing to small business without dreaded
franchise obligations.

Looking for work in Perth metropolitian?

Need help booking and planning jobs?

Starting an Electrical business?

Vested Utility is here to help.

<form action="electrical_work_perth.php" method="post" class="indexform" class="elecform">

 Enquire now by entering your details below.

* indicates required

    *
    <input type="text" value="<?php if (isset($FNAME)) {echo htmlspecialchars($FNAME); } ?>" name="FNAME" class="required" id="mce-FNAME" placeholder="First Name" required>

    *
    <input type="text" value="<?php if (isset($LNAME)) {echo htmlspecialchars($LNAME); } ?>" name="LNAME" class="required" id="mce-LNAME" placeholder="Last Name" required>

    *
    <input type="text" value="<?php if (isset($CNAME)) {echo htmlspecialchars($CNAME); } ?>" name="CNAME" class="required" id="mce-CNAME" placeholder="Company Name" required>

    *
    <input type="email" value="<?php if (isset($EMAIL)) {echo htmlspecialchars($EMAIL); } ?>" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="Email Address" required>

    *
    <input type="text" name="MMERGE4" class="required" value="<?php if (isset($MMERGE4)) {echo specialcharacter($MMERGE4); } ?>" id="mce-MMERGE4" placeholder="Phone number" required>

    <input type="text" name="MMERGE5" class="" value="" id="mce-MMERGE5" placeholder="Mobile number">

    *
        <input type="text" value="" maxlength="140" name="MMERGE3addr1" id="mce-MMERGE3-addr1" class="required" placeholder="Address">

        <input type="text" value="" maxlength="40" name="MMERGE3city" id="mce-MMERGE3-city" class="required" placeholder="City">

    <input type="text" value="" maxlength="20" name="MMERGE3state" id="mce-MMERGE3-state" class="required" placeholder="State" >

        <input type="text" value="<?php if (isset($MMERGE3zip)) {echo htmlspecialchars($MMERGE3zip); } ?>" maxlength="10" name="MMERGE3zip" id="mce-MMERGE3-zip" class="required" placeholder="Post Code" >

        <select name="MMERGE3country" id="mce-MMERGE3-country" class="required"><option value="">Select a country</option><option value="Australia" selected>Australia</option></select>

    *
    <input type="text" value="<?php if (isset($ecew)) {echo htmlspecialchars($ecew); } ?>" name="ecew" class="required" id="mce-ecew" placeholder="EC or EW Number" required>

                                Address

                                <input type="text" name="address" id="address">

Humans (and frogs): please leave this field blank.

<input type="text" name="b_f07378b089dcb03e4f7d873e9_c95eea1049" tabindex="-1" value="">

<input type="submit" value="Send" name="subscribe" id="mc-embedded-subscribe" class="submit">

</form>

<link rel="stylesheet" href="js/click-popup-window/demo/css/jquery.popup.css" type="text/css">

      <?php if (isset($_GET["status"]) AND $_GET["status"] == "thanks") { ?>

                Thank you for submitting your details, please click here to start the download.

            <?php } else { ?>

 Download information PDF

<form action="join_vested_utility.php" method="post" class="indexform" class="elecform">

 Enquire now by entering your details below.

* indicates required

    *
    <input type="text" value="<?php if (isset($FNAME)) {echo htmlspecialchars($FNAME); } ?>" name="FNAME" class="required" id="mce-FNAME" placeholder="First Name" required>

    *
    <input type="text" value="<?php if (isset($LNAME)) {echo htmlspecialchars($LNAME); } ?>" name="LNAME" class="required" id="mce-LNAME" placeholder="Last Name" required>

    *
    <input type="text" value="<?php if (isset($CNAME)) {echo htmlspecialchars($CNAME); } ?>" name="CNAME" class="required" id="mce-CNAME" placeholder="Company Name" required>

    *
    <input type="email" value="<?php if (isset($EMAIL)) {echo htmlspecialchars($EMAIL); } ?>" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="Email Address" required>

    *
    <input type="text" name="MMERGE4" class="required" value="<?php if (isset($MMERGE4)) {echo specialcharacter($MMERGE4); } ?>" id="mce-MMERGE4" placeholder="Phone number" required>

    <input type="text" name="MMERGE5" class="" value="" id="mce-MMERGE5" placeholder="Mobile number">

    *
        <input type="text" value="" maxlength="140" name="MMERGE3addr1" id="mce-MMERGE3-addr1" class="required" placeholder="Address">

        <input type="text" value="" maxlength="40" name="MMERGE3city" id="mce-MMERGE3-city" class="required" placeholder="City">

    <input type="text" value="" maxlength="20" name="MMERGE3state" id="mce-MMERGE3-state" class="required" placeholder="State" >

        <input type="text" value="<?php if (isset($MMERGE3zip)) {echo htmlspecialchars($MMERGE3zip); } ?>" maxlength="10" name="MMERGE3zip" id="mce-MMERGE3-zip" class="required" placeholder="Post Code" >

        <select name="MMERGE3country" id="mce-MMERGE3-country" class="required"><option value="">Select a country</option><option value="Australia" selected>Australia</option></select>

    *
    <input type="text" value="<?php if (isset($ecew)) {echo htmlspecialchars($ecew); } ?>" name="ecew" class="required" id="mce-ecew" placeholder="EC or EW Number" required>

                                Address

                                <input type="text" name="address" id="address">

Humans (and frogs): please leave this field blank.

<input type="text" name="b_f07378b089dcb03e4f7d873e9_c95eea1049" tabindex="-1" value="">

<input type="submit" value="Send" name="subscribe" id="mc-embedded-subscribe" class="submit">

</form>

            <?php } ?>

<?php
 include('inc/footer.php');
 ?>

A:

  <form name="mailinglist" method="post">
   <input type="text" name="email" />
   <input type="submit" name="mailing-submit" value="Join Our Mailing
    List" />
  </form>
 <form name="contactus" method="post">
  <input type="text" name="email" />
  <input type="text" name="subjet" />
  <textarea name="message"></textarea>
  <input type="submit" name="contact-submit" value="Send Email" />
 </form>
<?php
  if (!empty($_POST['mailing-submit']))
   {
   //do something here;
   }

  if (!empty($_POST['contact-submit']))
   {
   //do something here;
   }
 ?>