text:
Q: Write numbers to a file instead of string for data compression? I was encoding a simple text file using LZW algorithm in python. However, i realised that i can only write a string to a .txt file using the write() function, which itself occupies almost as much space. So is it possible to somehow just write actual integers to a file (maybe in a different format),
to achieve proper compression ?
readfile = open("C:/Users/Dhruv/Desktop/read.txt", "r")
writefile = open("C:/Users/Dhruv/Desktop/write.txt", "w")
content = readfile.read()
length = len(content)

codes = []
for i in range(0, 256) :
    codes.append(str(chr(i)))

current_string = ""
for i in range(0, length) :
    temp = current_string + content[i]
    print(temp)
    if temp in codes :
        current_string += content[i]
    else :
        codes.append(current_string + content[i])
        writefile.write(str(codes.index(current_string)) + " ")
        current_string = str(content[i])
writefile.write(str(codes.index(current_string)) + " ")
readfile.close()
writefile.close();

A: If your data can be represented as Numpy array, the following function can write it as integer in a .txt file:
import numpy as np
def writer(_hd, _data):
    out_file_name = str(_hd) + '.csv'
    np.savetxt(out_file_name, _data, fmt='%i')
    return None

where _hd is the file name and _data is the numpy array.
The fmt='%i' saves the data as integer; Other options are also available here.


text:
Q: How to debug NT_STATUS_INVALID_PARAMETER when mounting cifs share? Mounting cifs share exported by one host (hostx) works ok:
[piotr@demon ~]$ sudo mount -t cifs //hostx.intranet.local/pdobrogost /home/piotr/remote/hostx/ --verbose -o credentials=/home/piotr/.config/cifs-credentials.conf,uid=piotr,gid=piotr
domain=domainx
mount.cifs kernel mount options: ip=1.2.3.4,unc=\\hostx.intranet.local\pdobrogost,uid=1000,gid=1000,user=pdobrogost,,domain=domainx,pass=********

The same does not work for cifs share exported by another host (hosty):
[piotr@demon ~]$ sudo mount -t cifs //hosty.intranet.local/pdobrogost /home/piotr/remote/hosty/ --verbose -o credentials=/home/piotr/.config/cifs-credentials.conf,uid=piotr,gid=piotr
domain=domainx
mount.cifs kernel mount options: ip=1.2.3.5,unc=\\hosty.intranet.local\pdobrogost,uid=1000,gid=1000,user=pdobrogost,,domain=domainx,pass=********
mount error(22): Invalid argument
Refer to the mount.cifs(8) manual page (e.g. man mount.cifs)

/home/piotr/.config/cifs-credentials.conf looks like this:
username=my_cifs_username
password=my_cifs_password
domain=domainx

I tried connecting to cifs share on hosty using smbclient and got this:
[piotr@demon ~]$ smbclient -d 3 -A /home/piotr/.config/cifs-credentials.conf -W domainx //hosty.intranet.local/pdobrogost
lp_load_ex: refreshing parameters
Initialising global parameters
rlimit_max: increasing rlimit_max (1024) to minimum Windows limit (16384)
params.c:pm_process() - Processing configuration file "/etc/samba/smb.conf"
Processing section "[global]"
added interface p1p1 ip=10.92.2.80 bcast=10.92.2.255 netmask=255.255.255.0
Client started (version 4.1.6).
tdb(/var/lib/samba/gencache.tdb): tdb_open_ex: could not open file /var/lib/samba/gencache.tdb: Permission denied
resolve_lmhosts: Attempting lmhosts lookup for name hosty.intranet.local<0x20>
resolve_lmhosts: Attempting lmhosts lookup for name hosty.intranet.local<0x20>
resolve_wins: WINS server resolution selected and no WINS servers listed.
resolve_hosts: Attempting host lookup for name hosty.intranet.local<0x20>
Connecting to 1.2.3.5 at port 445
Doing spnego session setup (blob length=97)
got OID=1.2.840.113554.1.2.2
got OID=1.2.840.48018.1.2.2
got OID=1.3.6.1.4.1.311.2.2.10
got principal=cifs/hosty.intranet.local@INTRANET.LOCAL
Got challenge flags:
Got NTLMSSP neg_flags=0x60898215
NTLMSSP: Set final flags:
Got NTLMSSP neg_flags=0x60088215
NTLMSSP Sign/Seal - Initialising with flags:
Got NTLMSSP neg_flags=0x60088215
SPNEGO login failed: Unexpected information received
session setup failed: NT_STATUS_INVALID_PARAMETER

local system running Fedora 20
mount.cifs version: 6.3
smbclient version: 4.1.6
hostx running Debian 6.0.10
Samba version on hostx: 2:3.5.6~dfsg-3squeeze11
hosty running Red Hat Enterprise Linux ES release 4
Samba version on hosty: samba-3.0.33-0.19.el4_8.3
In samba logs on hosty there are the following entries:
Nov 14 15:09:37 hosty smbd[28956]: [2014/11/14 15:09:37, 0] rpc_client/cli_pipe.c:cli_pipe_verify_schannel(354)
Nov 14 15:09:37 hosty smbd[28956]:   cli_pipe_verify_schannel: auth_len 56.
Nov 14 15:09:37 hosty smbd[28956]: [2014/11/14 15:09:37, 0] auth/auth_domain.c:domain_client_validate(260)
Nov 14 15:09:37 hosty smbd[28956]:   domain_client_validate: unable to validate password for user pdobrogost in domain domainx to Domain controller A.INTRANET.LOCAL. Error was NT_STATUS_INVALID_PARAMETER.

which would suggest the problem lies in authorizing my password by Active Directory domain controller.

A: Can you also run smbclient with the hostx, and share the results ?
If it works you should maybe compare the smb conf file for both hosts (from your results, it seems that it is file: /etc/samba/smb.conf).
Have you checked that SPNEGO is configured on your server ? If it's not the case, you should maybe disable it by adding this in the smb.conf settings of hosty:
[global]
client use spnego = No

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to use viewbinding in listview? I'm a newbie.I find the listview doesn't show up if i use viewbinding to control the listview.the code is
class MainActivity : AppCompatActivity() {
private val data = listOf("Apple", "Banana", "Orange", "Watermelon",
    "Pear", "Grape", "Pineapple", "Strawberry", "Cherry", "Mango")
private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)

    val listviewdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data)
    binding.listview1.adapter = listviewdapter

    }
}

and the xml is simple
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ListView
    android:id="@+id/listview1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</LinearLayout>

but if i use findViewById the listview will show up, why?
class MainActivity : AppCompatActivity() {
private val data = listOf("Apple", "Banana", "Orange", "Watermelon",
    "Pear", "Grape", "Pineapple", "Strawberry", "Cherry", "Mango")
private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)

    val listviewdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data)
    val listview1 = findViewById<ListView>(R.id.listview1)
    listview1.adapter=listviewdapter
    }
}

A: Because list items aren't inflated when the list is created.  The binding won't work for the listview at all.  It will only work for the main activity.  And in fact it couldn't work for the listview-  you're going to have multiple of each id, 1 for each on screen element (plus a few possibly).  If you want to use viewbinding inside the list view, the binding would have to be in the adapter.
Also, you probably shouldn't be using ListView anymore.  Everything moved to RecyclerView about 8 years ago now.

A: Do like this...
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <ListView
            android:id="@+id/listview1"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>
</layout>

and then you can access your view in code file
binding.listview1


text:
Q: php/mysql connection on different servers I have a local and a remote server on which I am developing a project
//local
$servername = "localhost";
$username = "bob";
$password = "fred";
$dbname = "jane";

//remote
$servername = "arthur";
$username = "Milly";
$password = "Horace";
$dbname = "Erastus";

At the moment I am commenting out the //local or //remote bit depending which way I am connecting. Of course, I regularly overwrite the connection file by mistake which is a pain.
Is there some sort of way I can detect which server I am on, and then connect automatically. I have tried googling but couldn't turn anything up maybe because i couldn't think of the right search terms.
Thanks

A: There are more than a few ways of doing this but one you could try is to detect which server you are on from the IP Address
if ($_SERVER['SERVER_ADDR'] === '127.0.0.1') {
  $servername = "localhost";
  $username = "bob";
  $password = "fred";
  $dbname = "jane";
} else {
   //remote
  $servername = "arthur";
  $username = "Milly";
  $password = "Horace";
  $dbname = "Erastus";
}

A: You can try this code:-
<?php

if ($_SERVER['SERVER_NAME'] == "localhost") {
$servername = "localhost";
$username = "bob";
$password = "fred";
$dbname = "jane";
}
elseif ($_SERVER['SERVER_NAME'] == "google.com") {
$servername = "arthur";
$username = "Milly";
$password = "Horace";
$dbname = "Erastus";
}
else {
echo "No configuration found!";
exit;
}

A: try this code :-
$conn = new mysqli($servername1, $username1, $password1);
if (! $conn->connect_error) {
$conn = new mysqli($servername2, $username2, $password2);
}

Or check :-
$_SERVER['HTTP_HOST']=="localhost"


text:
Q: How do I clear all 45 waves in Big Time Gangsta? Has anyone cleared all 45 waves in Big Time Gangsta? I'm playing the game without buying any credits (I think that model is silly) so I can only purchase items that do not require credits.
I have come up with some fighting strategies that help my to clear the first 10 waves without too much effort or loss of health but I think beyond that I'll have to stock up on equipment like health kits.
What does it take to clear all 45 waves?

A: You need smove no matter what. I got lucky with credit lottos and my threesome is 500 hp, 450 hp, and 250 hp, to beat all 45 waves you have to be completely focused with at least 20 minutes of time on your hand. To beat all 45 waves I equipped the three characters I used with 100 medium health and 70 medium damage. I used one credit weapon because honestly, without at least one credit item or thing, you're screwed. On to the battle: mow down the first three at the start of the wave then as more and more start coming take them down one at a time alternating quickly between shooters firing at one target. This will kill him a lot faster. If your health starts getting low use a health pack and use damage increases whenever you can. Around wave 40 the enemies get lower health but increased damage. That isn't too hard if you can dispatch them quickly enough. Wave 45, no matter how good you are, unless you have 100% credit weapons and the three best characters in the game you will have at least one of your thugs gunned down.  After this target the weakest enemies and hope for the best. I lost 8/11 times at the arena using this method, so don't expect it to work at first.

A: Ridiculous.
Get free cred by watching free videos, downloading free apps, etc. Don't buy a thing, don't spend a dime. Wait until you have the guins and equipment to mount a single successful assault.
Gun up with at least the Law Elite; The Oma 7 is even better. Health is the only thing that REALLY matters; I suggest at least 30 medium per character for the first few times (don't forget to use all six allowed character spaces). Back it up with your choice of damage, pillz, etc.
After yout first successful assault, subsequent times become easier and easier - you now have Gold Hammers to make it a LOT easier. I also like to load up with small med - 35 per person (they're cheap) and run it up to level 44 and quit. $42K in the bank for only about $6K.

A: 7/9
I think the arena might have gotten tougher. I tried this today with 285000$ on my account. Most went into healing and defence. At lvl 35+ i had to use like 4 medium health pr wave pr. char and 2 medium defence. Thats atleast 24k and probably more pr. wave. I had to quit at lvl 42 cuss otherwise all my guys would die. Will try again at 500k.
26/10
Okay, so i tried this again with 472.000$ on my account. My tactic was more thought out this time, so i was sure it was gonna work. One thing i did wrong last time, was never using small health power-ups. By using small health+medium, you can get to somewhere around 35-40. At lvl 42 you for sure need to switch to medium health and medium defence. I've made a list of how many enemies come pr. wave and what weapons they are using if someone is interrested. The six guys i used were Biddy Big(500hp), Smoove(500hp), Chillz(675hp), Caliente(550hp), Mikey D(250hp) and the 200hp guy. Four of them with GenX Hawk and two with MP5. At the end i had like 120.000$ left and a gold hammer in my stash. For the last four waves i had eight medium health and four medium defence on each. When the arena finished i only had two guys left standing. Wave 42-45 are 12-13 guys with Steyer and other cred weapons.


text:
Q: Rails 4 error when runnning the rails server command on console I have been working on an application and just installed the twitter bootstrap gem and installed 'therubyracer' gem using the https://github.com/hiranpeiris/therubyracer_for_windows tutorial, can anybody help with the following error I get when running 'rails server', any help here would be appreciated, I'm not sure whats gone wrong here?
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0.0/lib/action
_dispatch/routing/mapper.rb:229:in `default_controller_and_action': missing :con
troller (ArgumentError)
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0
.0/lib/action_dispatch/routing/mapper.rb:116:in `normalize_options!'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0
.0/lib/action_dispatch/routing/mapper.rb:64:in `initialize'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0
.0/lib/action_dispatch/routing/mapper.rb:1438:in `new'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0
.0/lib/action_dispatch/routing/mapper.rb:1438:in `add_route'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0
.0/lib/action_dispatch/routing/mapper.rb:1417:in `decomposed_match'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0
.0/lib/action_dispatch/routing/mapper.rb:1398:in `block in match'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0
.0/lib/action_dispatch/routing/mapper.rb:1389:in `each'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0
.0/lib/action_dispatch/routing/mapper.rb:1389:in `match'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0
.0/lib/action_dispatch/routing/mapper.rb:596:in `map_method'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0
.0/lib/action_dispatch/routing/mapper.rb:557:in `get'
        from C:/Sites/socialeyes/config/routes.rb:4:in `block in <top (required)
>'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0
.0/lib/action_dispatch/routing/route_set.rb:316:in `instance_exec'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0
.0/lib/action_dispatch/routing/route_set.rb:316:in `eval_block'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0
.0/lib/action_dispatch/routing/route_set.rb:294:in `draw'
        from C:/Sites/socialeyes/config/routes.rb:1:in `<top (required)>'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-
4.0.0/lib/active_support/dependencies.rb:222:in `load'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-
4.0.0/lib/active_support/dependencies.rb:222:in `block in load'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-
4.0.0/lib/active_support/dependencies.rb:213:in `load_dependency'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-
4.0.0/lib/active_support/dependencies.rb:222:in `load'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0
/lib/rails/application/routes_reloader.rb:40:in `block in load_paths'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0
/lib/rails/application/routes_reloader.rb:40:in `each'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0
/lib/rails/application/routes_reloader.rb:40:in `load_paths'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0
/lib/rails/application/routes_reloader.rb:16:in `reload!'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0
/lib/rails/application/routes_reloader.rb:26:in `block in updater'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-
4.0.0/lib/active_support/file_update_checker.rb:75:in `call'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-
4.0.0/lib/active_support/file_update_checker.rb:75:in `execute'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0
/lib/rails/application/routes_reloader.rb:27:in `updater'
        from C:65535:in `execute_if_updated'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0
/lib/rails/application/finisher.rb:69:in `block in <module:Finisher>'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0
/lib/rails/initializable.rb:30:in `instance_exec'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0
/lib/rails/initializable.rb:30:in `run'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0
/lib/rails/initializable.rb:55:in `block in run_initializers'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/tsort.rb:150:in `block i
n tsort_each'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/tsort.rb:183:in `block (
2 levels) in each_strongly_connected_component'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/tsort.rb:219:in `each_st
rongly_connected_component_from'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/tsort.rb:182:in `block i
n each_strongly_connected_component'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/tsort.rb:180:in `each'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/tsort.rb:180:in `each_st
rongly_connected_component'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/tsort.rb:148:in `tsort_e
ach'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0
/lib/rails/initializable.rb:54:in `run_initializers'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0
/lib/rails/application.rb:215:in `initialize!'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0
/lib/rails/railtie/configurable.rb:30:in `method_missing'
        from C:/Sites/socialeyes/config/environment.rb:5:in `<top (required)>'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-
4.0.0/lib/active_support/dependencies.rb:228:in `require'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-
4.0.0/lib/active_support/dependencies.rb:228:in `block in require'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-
4.0.0/lib/active_support/dependencies.rb:213:in `load_dependency'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-
4.0.0/lib/active_support/dependencies.rb:228:in `require'
        from C:/Sites/socialeyes/config.ru:3:in `block in <main>'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rack-1.5.2/lib
/rack/builder.rb:55:in `instance_eval'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rack-1.5.2/lib
/rack/builder.rb:55:in `initialize'
        from C:/Sites/socialeyes/config.ru:in `new'
        from C:/Sites/socialeyes/config.ru:in `<main>'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rack-1.5.2/lib
/rack/builder.rb:49:in `eval'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rack-1.5.2/lib
/rack/builder.rb:49:in `new_from_string'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rack-1.5.2/lib
/rack/builder.rb:40:in `parse_file'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rack-1.5.2/lib
/rack/server.rb:277:in `build_app_and_options_from_config'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rack-1.5.2/lib
/rack/server.rb:199:in `app'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0
/lib/rails/commands/server.rb:48:in `app'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rack-1.5.2/lib
/rack/server.rb:314:in `wrapped_app'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0
/lib/rails/commands/server.rb:75:in `start'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0
/lib/rails/commands.rb:78:in `block in <top (required)>'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0
/lib/rails/commands.rb:73:in `tap'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0
/lib/rails/commands.rb:73:in `<top (required)>'
        from bin/rails:4:in `require'
        from bin/rails:4:in `<main>'

A: You have to define a root route in your config/routes.rb file or at least one route.
Here is an exemple :
# At least a route (here for HelloController)
get '/hello' => 'hello#index'

# Or a root route
root 'hello#index'


text:
Q: 3 phase heating elements Is there a simple way of calculating the power (kW) of a 3 phase heating element?
I have 3 elements mounted in a pack and inserted into a tube and there are 12 tubes, so 36 elements in total. They are connected in delta. I have 22ohms between L1+L2, L2+L3 and L3+L1.

A:
They are connected in delta

That's a 22 ohm resistor connected to each line voltage.

I measured between L1 and L2 etc with the rest all disconnected. These are approximately 6000mm long and running 415v delta

The power for each 22 ohm resistor is \$V_{LINE}^2/R\$. This equals 7.828 kW.
The total power is therefore 3 x 7.828 kW = 23.485 kW

A: Once you have all of the resistors connected in a balanced load, you don't really need to know how they are really connected, you can assume they are wye connected. If you measure 22 ohms from terminal to terminal and apply balanced, 3-phase, 415 volts from terminal to terminal, you have the equivalent of 240 volts across each of three, 11-ohm resistors. Using the voltage squared divided by the resistance, you have 5236 watts in each of three resistors for a total of 15,708 watts.


text:
Q: Is there a function to run all possible combinations of values for multiple variables? Apologies if I'm missing an existing function that does this, but struggling to find something.
Basically I have an example like follows (keeping it generic):
function <- (var1, var2)
values_for_var1 <- c("a", "b", "c")
values_for_var2 <- c(1:5)

What I'm wondering is if there is a quick function that would enable me to 'feed' in the two vectors listed to var1 and var2 respectively, and run this for all possible pairings? Eg, run the function where var1 == "a" for var2 == 1, then var2 == 2, then var2 == 3, etc, and repeat for var1 == "b" amd var2 == c.
Could do it the 'long-way' round but this doesn't scale very well with many variables or possible values for said variables. I thought purrr may have something but unless I'm misreading the guidance it doesn't do it.
Thanks.

A: 1) expand.grid expand.grid will give all combinations of its arguments in a grid data frame g. Then we can operate over the rows of g.
Note that expand.grid will convert character inputs into factors by default unless stringsAsFactors = FALSE is specified as an argument to it.
An alternative to expand.grid is merge but it is limited to two arguments whereas expand.grid will work with any number.
# inputs
var1 <- letters[1:3]
var2 <- 1:5
f <- function(let, num) paste(10 * num, let)

# create grid
g <- expand.grid(var1, var2)

# operate on each row of grid

do.call(mapply, c("f", unname(as.list(g))))
# or
sapply(1:nrow(g), function(i) do.call("f", unname(g[i, ])))
# or
mapply(f, g[, 1], g[, 2])

These also work (or can be adapted in the case of the last one) for more than 2 vectors with functions having the same number of arguments.
2) outer For just 2 variables (as we have here) another approach is to use outer.  This produces a length(var1) by length(var2) matrix.  Note that outer only works with vectorized functions so it is common to write it like this:
outer(var1, var2, Vectorize(f))

3) Comprehensions
There are three packages on CRAN that support Python-like comprehensions with possibly modified syntax.
3a) eList
library(eList)
Chr(for(v1 in var1) for(v2 in var2) f(v1, v2))

If the result were numeric use Num in place of Chr or if it were a complex object use List.
3b) listcompr
library(listcompr)

n1 <- length(var1); n2 <- length(var2)
gen.vector.char("{ f(var1[i], var2[j]) }", i = 1:n1, j = 1:n2)

If the result were numeric use gen.vector instead of gen.vector.char and don't use the quotes or brace brackets.
3c) comprehenr
library(comprehenr)
to_vec(for (v1 in var1) for(v2 in var2) f(v1, v2))

4) Other  Some packages have alternatives to expand.grid and then we could use the facilities of that package to apply f or reproduce it natively.
4a) dplyr/tidyr
library(dplyr)
library(tidyr)
crossing(var1, var2) %>%
  rowwise %>%
  mutate(result = f(var1, var2)) %>%
  ungroup

4b) data.table
library(data.table)
outDT <- CJ(var1, var2)[, result := f(var1, var2), by = .I]

4c) sqldf
library(sqldf)
var1df <- data.frame(var1); var2df <- data.frame(var2)
sqldf("select (10 * var2) || ' ' || var1 from var1df, var2df")

A: Perhaps you can do expand.grid + Vectorize like below
with(
  expand.grid(values_for_var1, values_for_var2),
  Vectorize(func)(Var1, Var2)
)


text:
Q: Why does a Crookes tube work when connected to an induction coil? From reading the answer below (regarding the mechanics of an induction coil) and the wikipedia article, it is clear that induction coils produce AC. However, the following excerpt from the "Crookes tube" wikipedia article states that induction coils produce DC. My intuition in regards to this is that induction coils only produce low voltage pulses in one direction and high voltage pulses in the other, effectively creating high voltage pulses in one direction, and thus a quazi-DC. If this is right (if not please correct me) then WHY/HOW does a Crookes tube work with a quazi-DC (which is actually AC) when they apparently need DC.
"Crookes tubes are cold cathode tubes, meaning that they do not have a heated filament in them that releases electrons as the later electronic vacuum tubes usually do. Instead, electrons are generated by the ionization of the residual air by a high DC voltage (from a few kilovolts to about 100 kilovolts) applied between the electrodes, usually by an induction coil (a "Ruhmkorff coil")."

A: The answer is in two parts:

*

*The first parts is in response to the original question (before it
was edited), which was: "Is the output of an induction coil
AC or DC?"

*The second part is in response to the second form of the question as
of 2018-02-07 (7th Feb): "Why does a Crookes tube work when connected to an induction coil?".

Part 1, in answer to "Is the output of an induction coil AC or DC?":
Your question is relevant in the face of evidence. Firstly: what is the definition of alternating current? Quoting Wikipedia:
"Alternating current (AC) is an electric current which periodically reverses direction, in contrast to direct current (DC) which flows only in one direction."
In response to the primary coil input current i$_1$, the secondary coil has an output voltage $V_2$, with a waveform like that in the figure below (with and without a capacitor across the interrupter). Credit to Wikipedia.

By the definition above, this is clearly this is alternating current, though not having a clean wave form like the AC we normally use in our homes.
Is this a peculiarity of an induction coil, that it outputs AC instead of DC? Not really: to induce voltage in a secondary coil, the voltage in the primary coil (more exactly the magnetic field it causes) must be changing, or the secondary coil must be in motion (as in a generator). This is electromagnetic induction.
To get direct current from an induction coil or a voltage transformer (same principle), we normally employ a rectifier such as a Wheatstone bridge to effect the change as in the figure below, where the AC on the left would come out as AC on the right, were it not for the array of rectifiers shown. The rectifiers themselves do not create DC but a pulsating voltage as seen on the right. This needs to be smoothed using appropriate capacitors to become DC (illustration credit to Wikipedia):

Part 2, in answer to "Why does a Crookes tube work when connected to an induction coil?":
If a voltage is alternating (AC), but during a particular period it remains long enough with one polarity or direction (+ or -), such that the circuit to which it is applied cannot differentiate it from 'stable DC' during that period, then, as far as the circuit is concerned, the voltage is 'DC' during that period.
In the case of the Crooke's tube, the voltage induced by an induction coil attached to it needs to satisfy the following conditions:

*

*It must supply a high enough voltage to the Crooke's tube, charging the anode and cathode with high '+' and '-' polarities respectively.

*This high voltage must be maintained long enough to cause ionisation of the gas inside the Crooke's tube and produce an electrical discharge in the form of a stream of electrons (a cathode ray).

It turns out that the charge on the anode and cathode in the Crooke's tube can be reversed, and the glow of electrons in it will still be visible. Therefore a Crooke's tube will work using symmetric AC, provided again that during each half cycle, the two conditions mentioned above are met.


text:
Q: How to set default sorting order for each column in jQuery Tablesorter? I have an HTML table, tablesorter works fine on it, I am able to set the default sorting and everything else (even my own parser)... BUT: I need some of the columns to be sorted in descending order after the user first clicks on their respective headers.
By default, all the columns are being sorted in ascending order after the first click. I found a way to change this to descending order for ALL the columns. But what I need is to sort some of the columns in ascending order and some other columns in descending order after the user first clicks on them.
Example: Some columns contain strings, so I want to sort them in ascending order. Some columns contain values where bigger values are better - and it would be nice to sort them in descending order after the user first clicks on their headers.
Thank you.

A: The original tablesorter (version 2.0.5) doesn't seem to work with this code:
$('table').tablesorter({

    // default sortInitialOrder setting
    sortInitialOrder: "asc",

    // pass the headers argument and passing a object
    headers: {
        2: { sortInitialOrder: 'desc' },
        3: { sortInitialOrder: 'desc' },
        4: { sortInitialOrder: 'desc' }
    }

});

But in my fork of tablesorter, you can use the above code to set the initial sort order for each column - see this demo.
There is also an option named sortRestart which resets the sort order when when the column was previously unsorted - see this demo.


text:
Q: Why is only bandgap-energy usable? (Thermal Relaxation) I know from solar cell physics, that in a first approximation, the maximum energy from an exited electron is the energy of the bandgap, no matter how high the electron was excited by a photon in the first place. The rest of the excitation energy is given back from the electron via thermal relaxation.
So for example, if a photon with 3eV excites an electron from the valence band to the conduction band (bandgap 2eV), then the electron will relax thermally by 1eV and only 2eV can be used for generating the voltage.
But why is this?
Why is one not able to get the full excitation energy from an electron?

A: This is generally true in most cases, the electron would thermally de-excite to the bottom of the valence band in a time scale and length scale characteristic of the material, and is called the carrier drift regime. However, if the device length is shorter than the mean free path for collisions, the energy recovered is greater than the bandgap energy (Ballistic transport). The same applies if the electrons are extracted out of the system in a time shorter than the average scattering time (Hot Carrier Transport).


text:
Q: How I can add multiple textField in a single Loop? I wants add multiple UITextFields in a single loop. And  identify them  when user interact with UITextFields . So please help me.
Thanks
Currently I place UITextField Individually, like this
txt_FirstName=[[UITextField alloc]initWithFrame:CGRectMake(framex1, framey1, framex2, framey2)];
txt_FirstName.borderStyle = UITextBorderStyleRoundedRect;
txt_FirstName.font = [UIFont systemFontOfSize:15];
txt_FirstName.placeholder = @"First Name";
txt_FirstName.autocorrectionType = UITextAutocorrectionTypeNo;
txt_FirstName.keyboardType = UIKeyboardTypeDefault;
txt_FirstName.returnKeyType = UIReturnKeyDone;
txt_FirstName.clearButtonMode = UITextFieldViewModeWhileEditing;
txt_FirstName.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
txt_FirstName.delegate = self;
[frameView addSubview:txt_FirstName];
[txt_FirstName release];

framey1=framey1+50;

txt_MiddleName=[[UITextField alloc]initWithFrame:CGRectMake(framex1, framey1, framex2, framey2)];
txt_MiddleName.borderStyle = UITextBorderStyleRoundedRect;
txt_MiddleName.font = [UIFont systemFontOfSize:15];
txt_MiddleName.placeholder = @"Middle Name";
txt_MiddleName.autocorrectionType = UITextAutocorrectionTypeNo;
txt_MiddleName.keyboardType = UIKeyboardTypeDefault;
txt_MiddleName.returnKeyType = UIReturnKeyDone;
txt_MiddleName.clearButtonMode = UITextFieldViewModeWhileEditing;
txt_MiddleName.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
txt_MiddleName.delegate = self;
[frameView addSubview:txt_MiddleName];
[txt_MiddleName release];

A: Please use this, but Implement UITextField delegate in your .h file. but You should have to change your place holder according to your requirement like 1 for FirstName, 2 for MiddleName etc.
First create common function like this,
-(void)setTextfieldStyle:(UITextField *)pTmpTextField
{
        pTmpTextField.borderStyle = UITextBorderStyleRoundedRect;
        pTmpTextField.font = [UIFont systemFontOfSize:15];
        pTmpTextField.placeholder = @"First Name";
        pTmpTextField.autocorrectionType = UITextAutocorrectionTypeNo;
        pTmpTextField.keyboardType = UIKeyboardTypeDefault;
        pTmpTextField.returnKeyType = UIReturnKeyDone;
        pTmpTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        pTmpTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        pTmpTextField.delegate = self;
}

and use this for creating UITextFiled,
int y = 0;
for(int i=0;i < 5;i++)
{
    UITextField *txtTemp=[[UITextField alloc]initWithFrame:CGRectMake(0, y, 300, 31)];
    txtTemp.tag = i;
    [self setTextfieldStyle:txtTemp];
    [self.view addSubview:txtTemp];
    [txtTemp release];
    y+=36;
}

This is UITextField's delegate method,
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSLog(@"%@",textField.text);
}

Hope this works for you..

A: If you want to set attributes of a bunch of text fields in a loop, you could also do something like:
NSMutableArray* allTextFields = [NSMutableArray array];

// create the textFields here, I'm assuming you need to keep individual
// references to them.
txt_FirstName=[[UITextField alloc]init];
pTmpTextField.placeholder = @"First Name";
[allTextFields addObject:txt_FirstName];

// now add the common style stuff and frame
[allTextFields enumerateObjectsUsingBlock:^(UITextField* textField, NSUInteger idx, BOOL* stop) {
    textField.frame = CGRectMake(framex1, framey1 + ( 50 * idx), framex2, framey2);
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.font = [UIFont systemFontOfSize:15];
    textField.placeholder = @"First Name";
    textField.autocorrectionType = UITextAutocorrectionTypeNo;
    textField.keyboardType = UIKeyboardTypeDefault;
    textField.returnKeyType = UIReturnKeyDone;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    textField.delegate = self;
}];


text:
Q: Python - Bar plot issue I am pretty new to Python & I am trying to slice my numpy array data with a third column in Power BI
m1=np.ceil((np.array(inp_data["IValue"])))
m2=np.ceil((np.array(inp_data["IValue_conventional"])))
m3=np.array(inp_data["ABC"])

ax.bar(m3, (m1), width = 0.55, edgecolor ='grey')
ax.bar(m3, (m2), width = 0.25, edgecolor ='grey')
ax.patch.set_facecolor('xkcd:white')
plt.show()

The above code works & generates a plot but I actually require sum of m1 & m2, so when I change above code to
ax.bar(m3, np.sum(m1), width = 0.55, edgecolor ='grey')
ax.bar(m3, np.sum(m2), width = 0.25, edgecolor ='grey')

the visual gets generated but it is the sum of all elements are being present to all data points in x axis. I would like to have any help that I can get.
Thanks in Advance!


text:
Q: Logstash and Grok always show _grokparsefailure I am using https://grokdebug.herokuapp.com/ to build grok filters for logstash, but even though grokdebug shows corrected parsed message, my kibana showing _grokparsefailure
message [2015-12-01 08:53:16] app.INFO: Calories 4 [] []
pattern %{SYSLOG5424SD} %{JAVACLASS}: %{WORD} %{INT} %{GREEDYDATA}

What am I doing wrong? Notice that first filter with tag "google" and GREEDYDATA works, and second always fails

A: Ok so I found the solution. Correct pattern is:
\[%{TIMESTAMP_ISO8601:timestamp}\] %{DATA}%{LOGLEVEL:level}: Calories %{WORD:calories_count} %{GREEDYDATA:msg}
Even tough I used https://grokdebug.herokuapp.com to find the pattern, it was completely irrelevant.


text:
Q: Get the cell value of a particular column from html table in Jquery I want to get the cell value of a particular column from html table using JQuery. I have table that contains data of transaction, fetched from database. Along with this, contains a column having button that inserts transaction. What I want is that, when I click on that button, I should be getting the cell value from that particular row.

I have tried following line of code, but that didn't work.
$(".btn").click(function () {
    var texto = $('table tr:nth-child(1) td:nth-child(2)').text()
    alert(texto)
});

A: here you need to point out the row in which you have clicked the button and in that you need to get cell value. Here is my code:

$(".btn").click(function () {
    var $row = $(this).parents('tr');
    var texto = $row.find('td:nth-child(5)').text();
    alert(texto);

});

    date
    name
    department
    departmentcode
    id
    cash
    and<t/d>
    <button class="btn">ADD TRANSACTION</button>

    date2
    name2
    department2
    departmentcode2
    id2
    cash2
    and2<t/d>
    <button class="btn">ADD TRANSACTION</button>

A: https://jsfiddle.net/Liamm12/vca4qdrn/
There's no  in your first

$('.btn').on('click', function(){
  var texto = $('table tr:nth-child(2) td:nth-child(3)').text();
   alert(texto)
});
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}

    Company
    Contact
    Country
    Button

    Alfreds Futterkiste
    Maria Anders
    Germany
     <button class="btn">
     get country Value
     </button>


text:
Q: Could not initialize class com.example.testapp.SomeHelper public class SomeHelper {
    ...
    private int static x;
    static {
        Map<String, String> aMap = new HashMap<>();
        //populate map here
    }
    public static void setX(int value){
       x = value;
    }
}

When SomeHelper.setX is called, I get a "Could not initialize class SomeHelper" exception. I'm not sure how to fix this. Anyone faced this issue? I tried catching the exception and re throwing it as a runtime exception from the static block, but that doesn't help.

A: I think you mean you get a NoClassDefFoundError like this:
NoClassDefFoundError: Could not initialize class SomeHelper

As JavaSE-7 states:

NoClassDefFoundError thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.
The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

Sometimes NoClassDefFoundError occurs if the static bits of your class i.e. any initialization that takes place during the defining of the class, fails.
So first change
private int static x;

to,
private static int x;

Declare setX() as static, or create instance of SomeHelper to invoke setX().
To invoke any method with the class name, the method should be static.
Try this:
public static void setX(int value){
   x = value;
}

SomeHelper.setX(someInteger);

Or this:
SomeHelper someHelper = new SomeHelper (); // default constructor
someHelper .setX(someInteger);

Note that, You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors.

A: i) Make the method static to call it with className.
ii) Class not initialized indicates that initialization did not occur properly which might be due to an exception in static block.
iii) I see that your Map<String, String> aMap is local to static block. Aren't you using it anywhere else?


text:
Q: Locally bounded vs bounded on compacts Let $X$ be a topological space and let $f$ be a scalar-valued function on $X$ (not necessarily continuous).
Then $f$ is called locally bounded if for every $x\in X$ there is a neighborhood $U$ of $x$ such that $f|_{U}$ is bounded. This condition is equivalent to existence of an open cover $\{U_i\}_{i\in I}$, such that $f|_{U_i}$ is bounded, for every $i\in I$.
It is easy to see that every locally bounded function is bounded on every compact set in $X$.
Moreover, the converse is also true if we additionally assume that $X$ is locally compact or metrizable. In the former case, it is trivial; since every convergent sequence in a metric space is a compact set, the negation of local boundedness on a metric space implies negation of boundeness on compacts.
A class of topological spaces that includes metrizable and locally compact spaces if the class of compactly generated spaces. It is natural to ask whether the property holds for this bigger class.

Let $X$ be a compactly generated Tychonoff topological space and let $f$ be a scalar function on $X$, such that $f|_{K}$ is bounded, for every compact $K\subset X$. Is it true that $f$ is locally bounded?

Note that I have included Tychonoff into the hypothesis in order to eliminate some patological spaces which I don't have any intuition about. Of course it would be excellent if one can go with merely Hausdorff axiom.

A: This is false.  For instance, let $X=\bigvee I_n$ be a wedge sum of infinitely many intervals.  Every compact subset of $X$ is contained in a union of finitely many of the $I_n$, so any function $f$ that is bounded on each $I_n$ is bounded on compact sets.  Such a function need not be locally bounded at the wedge point $p$.  For instance, $f$ might be given by $f(p)=0$ and $f(x)=n$ if $x\in I_n\setminus\{p\}$.


text:
Q: How do you check a list in C# for contents before an insert/add? What is the predicate class for? when working with the List class, i have noticed that the boolean i was looking for was:
 if(lstInts.Exists(x)){...}

X is a Predicate of T the same as lstInts.  I was confused as to why you just cant pass int the int in this case, and why X's type isnt of type T.
Example i was testing:
List<int> listInt = new List<int>();
int akey = Convert.toInt32(myMatch.Value);
Predicate<int> pre = new Predicate<int>(akey);  //akey is not the correct constructor param.
if(listInt.Exists(pre)){
   listInt.add(akey);
}

Is there a reason for having the additional Step of Predicate, or.... if i am going about the logic incorrectly?
I also noticed that the predicate constructure does not take an item of type T.  Sort of confused as to how this is suppose to work.

A: You could also use Contains() method
List<int> listInt = new List<int>();
int akey = Convert.toInt32(myMatch.Value);

if(listInt.Contains(akey)){
  listInt.add(akey);
}

Or alternately use Any()
if(listInt.Any(I => I == akey)) {
  // Do your logic
}

A: Predicate<T> is a delegate (returning bool) that allows you to find an item matching some condition (that's why item being checked is passed into it ad an argument).

A: This would be a good use for the HashSet<T> collection type, which does not allow duplicates (just silently ignores them).

A: Well, for your scenario, you should use the Contains method on the List class.
So what's the purpose of exists you might ask? Well, the Contains method uses the Equals method on the object to determine if the item you are checking is contained in the list or not. This only works if the class has overridden the Equals method for equality checking. If it hasn't, well then two separate instances of something that you consider to be equal will not be considered equal.
In addition to that, perhaps you want to use different logic that the Equals method provides. Now, the only way to determine if something is in the list is to either iterate it on your own, or write your own EqualityComparer to checks the equality of an instance.
So, what the list class does is expose some methods like Exists so that you can provide your own logic in an easy way, while doing the boilerplate iteration for you.
Example
Consider you have a list of Dog types. Now, the dog class has overridden the Equals method, so there is no way to check if a dog is equal to another, but they have some information about the dog like it's name and it's owner. So consider the following
List<Dog> dogs = new List<Dog> {
    new Dog { Name = "Fido", Owner = "Julie" },
    new Dog { Name = "Bruno", Owner = "Julie" },
    new Dog { Name = "Fido", Owner = "George" }
};

Dog fido = new Dog { Name = "Fido", Owner = "Julie" };

*

*List.Contains(fido)

*

*Returns false (since Equals method has not been overridden)

*List.Exists(x => fido.Name == x.Name && fido.Owner == x.Owner)

*

*Returns true since you are checking equality on the properties which, being strings, have equality overridden.

If you were to go look at the source code for the list class, you would likely see something like this.
public bool Exists(Predicate<Dog> predicate) {
    foreach (Dog item in Items) {
        if (predicate(item))
            return true;
    }

    return false;
}

Now, if you fill in the predicate I had above, the method would look like this
public bool Exists(Dog other) {
    foreach (Dog item in Items) {
        if (item.Name == other.Name && item.Owner == other.Owner)
            return true;
    }

    return false;
}


text:
Q: Snackbar Multi-line text padding To my surprise, Snackbar natively appears to set extra padding on the TextView if it spans multiple lines. It effectively doubles the height of the Snackbar, and for some reason only affects vertical padding. I found this in the SnackbarContentLayout.onMeasure:
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    if (mMaxWidth > 0 && getMeasuredWidth() > mMaxWidth) {
        widthMeasureSpec = MeasureSpec.makeMeasureSpec(mMaxWidth, MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    final int multiLineVPadding = getResources().getDimensionPixelSize(
            R.dimen.design_snackbar_padding_vertical_2lines);
    final int singleLineVPadding = getResources().getDimensionPixelSize(
            R.dimen.design_snackbar_padding_vertical);
    final boolean isMultiLine = mMessageView.getLayout().getLineCount() > 1;

    boolean remeasure = false;
    if (isMultiLine && mMaxInlineActionWidth > 0
            && mActionView.getMeasuredWidth() > mMaxInlineActionWidth) {
        if (updateViewsWithinLayout(VERTICAL, multiLineVPadding,
                multiLineVPadding - singleLineVPadding)) {
            remeasure = true;
        }
    } else {
        final int messagePadding = isMultiLine ? multiLineVPadding : singleLineVPadding;
        if (updateViewsWithinLayout(HORIZONTAL, messagePadding, messagePadding)) {
            remeasure = true;
        }
    }

    if (remeasure) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

Why does Snackbar do this? Why isn't it mentioned at all in the documentation? What's more is that it seems like this can't be overridden even after invalidating the views and requesting layout. Is there a way to work around this without creating a custom view?
EDIT: Looking back at the material design docs for the Snackbar, there are examples of the multi-lined snackerbars without the additional vertical padding, which is what I'm aiming for. The code above seems to undermine the intended material design for multi-lined messages. For reference:
https://material.io/components/snackbars/#anatomy

A: Currently (1.1.0-beta01 and 1.2.0-alpha01) there isn't an official way to customize the padding with 2 lines.
The only workaround (but it can stop to work in the next releases) is to define in the dimens.xml
<dimen name="design_snackbar_padding_vertical_2lines">14dp</dimen>

or
  <dimen name="design_snackbar_padding_vertical_2lines">@dimen/design_snackbar_padding_vertical</dimen>

Before and after:


text:
Q: payment method - radio button list Hi to all magento experts. I have problem on custom payment method in magento system. On payment information step in checkout progress i need to show radio button list under my payment method. Here is code:
<ul class="form-list" id="payment_form_<?php echo $_code ?>" style="display:none;">

<?php echo $this->getMethod()->getConfigData('message');?>

        <input type="radio" title="<?php echo $this->__('option1') ?>" id="<?php echo $_code ?>_option1" name="payment[]" value="1" checked="true"><?php echo $this->__('option1') ?></input>

        <input type="radio" title="<?php echo $this->__('option2') ?>" id="<?php echo $_code ?>_option2" name="payment[]" value="2" ><?php echo $this->__('option2') ?></input>

        <input type="radio" title="<?php echo $this->__('option3') ?>" id="<?php echo $_code ?>_option3" name="payment[]" value="3" ><?php echo $this->__('option3') ?></input>

The problem is that I can't continue my process. Something is wrong and I suspect on validation. Please look at name attributes. They must all be equal so I can only chehk one of radio button, but I am not sure is it OK with magento?
Can please someone help me with this? I am new in magento world.
Thank you!

A: Hope this will help. You can download the 'WebShopApps MatrixRate – #1 Multiple Table Rates Extension' which is free and check how it has been developed. Here's the link.
http://www.magentocommerce.com/magento-connect/webshopapps-matrixrate-1-multiple-table-rates-extension-certified-bug-free.html

A: Your first input field has the attribute "checked" but with the wrong value. If you use HTML5 you only need to write "checked" - without an attribute value. If you prefer the XHTML style the correct value to use is "checked".
HTML5:
<input type="radio" checked />
XHTML:
<input type="radio" checked="checked" />
Hope this helps!


text:
Q: Regex to match string until first occurrence of decimal point followed by a tab I'm looking for a regex to achieve the following: From a list I just want all strings that have a tab after the first occurrence of a decimal point. These strings can only be at the beginning of each line. With my current regex /^(\S+\.)/gm I even get the string that does have 2 or more decimal points.
Here's some example code (spaces are tabs in reality):
aaa.            86400
ns1.dns.nic.aaa.    172800  IN  A   156.154.144.2
ns1.dns.nic.aaa.    172800  IN  AAAA    2610:a1:1071:0:0:0:0:2
abarth.         86400   IN  RRSIG   NSEC 8 1 86400 20180728050000 20180715040000 41656 .
a0.nic.abarth.      172800  IN  A   65.22.24.17
a0.nic.abarth.      172800  IN  AAAA    2a01:8840:1a:0:0:0:0:17
ai.
ns2.offshore.ai.    172800  IN  A   108.166.113.245
whois.ai.       172800  IN  A   209.59.119.1
xn--node.ns.anycast.pch.net.    172800  IN  A   204.61.216.88
d.nic.xn--mxtq1m.   172800  IN  AAAA    2001:c50:ffff:1:0:0:0:185
d.nic.
xn--ngbc5azd.       172800  IN  NS  a.nic.xn--ngbc5azd.

What I need from that is aaa., abarth., ai. and xn--ngbc5azd. but not a0.nic.abarth. or whois.ai or any other string with more than 1 decimal point.
Thanks!

A: You may use
'~^[^.\r\n]+\.(?=\t)~m'

See the regex demo. NOTE: you do not need \r\n and m modifier if you pass the lines as separate strings).
Details

*

*^ - start of line (as the m modifier makes ^ match start of line positions)

*[^.\r\n]+ - 1+ chars other than ., LF and CR

*\. - a dot

*(?=\t) - there must be a tab right after ..

PHP demo:
if (preg_match_all('~^[^.\r\n]+\.(?=\t)~m', $str, $m)) {
    print_r($m[0]);
}

Output:
Array
(
    [0] => aaa.
    [1] => abarth.
    [2] => ai.
    [3] => xn--ngbc5azd.
)

A: Late answer, but you can also use:
preg_match_all( '/^([^.]+\.)\t/m', $x, $m, PREG_PATTERN_ORDER );
print_r( $m[1] );

Array
(
    [0] => aaa.
    [1] => abarth.
    [2] => ai.
    [3] => xn--ngbc5azd.
)

Regex101
Ideone


text:
Q: Kendo Combobox inside kendo grid edit not working I have a kendo combobox inside a kendo grid. I use MVVM binding to bind the combobox to the items in the list. The problem is, when i select an item from the combobox dropdown everything is fine, but when i manually type something into the combobox the value does not save... Here is my grid and combobox code:
grid:
    $("#specificJoinGrid-" + this.gridID).kendoGrid({
        dataSource: this.dataSource,
        autoBind: true,
        toolbar: ["create"],
        sortable: {
            mode: "multiple",
            allowUnsort: true
        },
        columns: [
            { field: "ToField", title: OlapManagerLabels.Field, width: "20%", editor: fieldDropDownEditor.bind(this), template: "#=ToField#" },
            { field: "SpecificOperator", title: OlapManagerLabels.Operator, width: "15%", editor: operatorDropDownEditor.bind(this), template: "#=OlapManagerNamespace.getOperator(SpecificOperator)#" },
            { field: "SpecificValue", title: OlapManagerLabels.Value, width: "30%", editor: valueDropDownEditor.bind(this), template: "#=SpecificValue#" },
            { field: "SecondSpecificValue", title: OlapManagerLabels.SecondValue, width: "30%", editor: secondValDropDownEditor.bind(this), template: "#=SecondSpecificValue#" },
            { command: { name: "x", width: "5%" } }
        ],
        editable: { createAt: "bottom" },
        edit: function(e) {
            var model = e.model; // access edited/newly added model
            // model is observable object, use set method to trigger change event
            model.ID = BINamespace.guid32();
            model.set("id", model.ID);
        },
        selectable: true
    });

dataSource:
 this.dataSource = new kendo.data.DataSource({
        data: DataSource,
        batch: true,
        schema: {
            model: {
                id: "ID",
                fields: {
                    ToField: { editable: true, required: true },
                    SpecificOperator: { editable: true, required: true, defaultValue: 6 },
                    SpecificValue: { editable: true },
                    SecondSpecificValue: { editable: true },
                    DataSourceID: { defaultValue: this.dataSourceID },
                    ID: {},
                    Type: { defaultValue: 1 },
                    ToTableID: { defaultValue: this.tableID }
                }
            }
        }
    });

ComboBox:
valueDropDownEditor = function (container, options) {
    var grid = $("#specificJoinGrid-" + this.gridID).data("kendoGrid");
    var row = grid.select();

    if (options.model.SpecificOperator != 1 && options.model.SpecificOperator != 0) {
        $('<input data-text-field="Key" data-value-field="Key" data-bind="value:' + options.field + '"/>')
            .appendTo(container)
            .kendoComboBox({
                autoBind: false,
                dataSource: this.globalsDropDownDS,
                template: "#=Description# (#=Key#)",
                change: value1Changed.bind(this)
            });
    }
    else {
        grid.closeCell(container);
    }
}

A: So in case anyone else runs into this problem, I found the solution. Once i removed the autobind: false property from my editor the combobox works exactly as desired.. not sure why it took me so long to figure this out but hope it helps someone along the way!


text:
Q: Is is possible at build time to merge Android applications? This question is related to this one. I have two Android projects inside Eclipse. One activity of one project calls an activity of the other project. This results in two independent applications being deployed on Android phone.
Is there any way to merge at build time (inside or outside Eclipse) both applications in only one so only an APK is generated?

A: You can declare one of the projects as a library and include it's activities in the other.  Eclipse will take care of merging the code, resources, and apk's.  See this for more details.


text:
Q: Custom MTOM binding and Max upload size I'm using the binding configuration below for my upload service,
<binding name="FileUploadSTSBinding">
          <security authenticationMode="UserNameOverTransport"
                    requireDerivedKeys="false"
                    keyEntropyMode="ServerEntropy"
                    requireSecurityContextCancellation="false"
                    requireSignatureConfirmation="false">
          </security>
          <mtomMessageEncoding/>
          <httpsTransport
            transferMode="Streamed"
            maxReceivedMessageSize="2147483647"/>
        </binding>

But with this setting, I'm not able to upload big files like more than 1mb, server response is bad request.

Any thoughts?

A: You need to set the maxRequestLength attribute as well for the upload to work. It can here found in the web.config file here:
<configuration>
   <system.web>
      <httpRuntime>

Check that the IIS app pool identity has the right to write to the temp folder to be able to temporarily store the incoming data.


text:
Q: Angularjs display given ISO formatted date I'm looking for way to display/format date given in ISO format (with timezone).
From API i got encoded date: "2015-04-17T06:00:00.000-05:00" and i want to display it in human readable format.
When i use {{"2015-04-17T06:00:00.000-05:00" date: 'hh:mm'}} i got time converted to local timezone. I need only format it.
A searched Internet, but only found only huge libs like moments.js or others.
There did not found working answer here also...
If there is no angularjs solution i can use pure javascript, but not found that one either.
Thanks

A: You can set the timezone yourself with the date filter:
(It accepts format strings like "+0000" and simple integer strings like "0")
{{"2015-04-17T06:00:00.000-05:00" | date:'hh:mm':'0' }}


text:
Q: What symmetric encryption algorithms implemented in both of c# and php do not requires fixed lenght of input data? Currently I use AES and have a problem, if user choose to decode unencrypted file, my prog always ends up with exception, even when try catch placed and running out of debugger.
public static byte[] AES_Decrypt(byte[] data, string[] aes_key)
{
    RijndaelManaged aes = new RijndaelManaged();
    aes.KeySize = 256;
    aes.BlockSize = 256;
    aes.Mode = CipherMode.CBC;
    aes.Padding = PaddingMode.PKCS7;

    aes.Key = Encoding.Default.GetBytes(aes_key[0]);
    aes.IV = Encoding.Default.GetBytes(aes_key[1]);

    if (data.Length % (aes.BlockSize / 8) != 0)
        return null;

    var decrypt = aes.CreateDecryptor();

    using (MemoryStream ms = new MemoryStream())
    {
        using (CryptoStream cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write))
            try { cs.Write(data, 0, data.Length); } //crash here "data lenght for decryption is invalid" and "Padding is invalid and cannot be removed".
            catch (Exception exc) { return null; }

        return ms.ToArray();
    }
}

I am not that interested why try and catch don't work, I need some workaround to avoid crash... And changing the encryption method is fine.

A: From my point of view you shouldn't hide the exception at that level. Throwing an exception when an user tries to decrypt an unencrypted piece of data seems the expected behavior of a cryptography module to me.
Instead, you should deal with this exception at a higher level (outside the cryptography module). For instance, you could have something like this in your UI layer:
try
{
    var encryptedFilePath = ShowOpenFileDialog();
    var decryptedFilePath = TryDecryptFile(encryptedFilePath);
    ShowMessagePopup("Your file has been decrypted to: " + decryptedFilePath);
}
catch (CryptographicException)
{
    ShowErrorPopup("Unable to decrypt file!\n" +
     "Please make sure the file you selected is valid");
}


text:
Q: Protractor, internet explorer stops at "initial start page for the WebDriver server." I have successfully created and executed test suites in Protractor for Chrome and Firefox. However I am unable to run tests with Internet Explorer. It stops at "initial start page for the WebDriver server" and displays this error in the powershell:
[11:02:10] I/launcher - Running 1 instances of WebDriver
[11:02:10] I/hosted - Using the selenium server at http://localhost:4444/wd/hub
[11:02:46] E/launcher -
[11:02:46] E/launcher - WebDriverError
at WebDriverError (C:\Users\user\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\error.js:27:5)
at parseHttpResponse (C:\Users\user\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\http.js:521:11)
at doSend.then.response (C:\Users\user\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\http.js:440:13)
at process._tickCallback (internal/process/next_tick.js:109:7)
From: Task: WebDriver.createSession()
at Function.createSession (C:\Users\user\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\webdriver.js:777:24)
at createDriver (C:\Users\user\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\index.js:167:33)
at Builder.build (C:\Users\user\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\index.js:632:14)
at Hosted.getNewDriver (C:\Users\user\AppData\Roaming\npm\node_modules\protractor\lib\driverProviders\driverProvider.ts:60:29)
at Runner.createBrowser (C:\Users\user\AppData\Roaming\npm\node_modules\protractor\lib\runner.ts:225:39)
at q.then.then (C:\Users\user\AppData\Roaming\npm\node_modules\protractor\lib\runner.ts:391:27)
at _fulfilled (C:\Users\user\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:834:54)
at self.promiseDispatch.done (C:\Users\user\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:863:30)
at Promise.promise.promiseDispatch (C:\Users\user\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:796:13)
at C:\Users\user\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:556:49
[11:02:46] E/launcher - Process exited with error code 199

This is my protractor config:
// Protractor configuration file
exports.config = {
seleniumAddress: "http://localhost:4444/wd/hub",
multiCapabilities: [
//{ browserName: "chrome" },
{
  browserName: 'internet explorer',
}
//{ browserName: "firefox" }
  ],
  framework: "jasmine2",
  jasmineNodeOpts: {
defaultTimeoutInterval: 2500000,
showColors: true, // Use colors in the command line report.
isVerbose: true,
includeStackTrace: true
  },
  specs: [
"specs/login-spec.js",
  ],
    resultJsonOutputFile: "./Report.json",
};

I read tens of posts on StackOverflow but didn't find any solusion to my problem. I have tried to change IE settings but they always go back to its defaults due to corporation setup.
The error stacktrace doesn't give my much information on what's wrong actually. I'm not very familiar with WebDriver source.
Any suggestions? Did anyone face similar problem?


text:
Q: gigabit cat6 cable connecting 100Mbps only (Electrical interference?) I have a gigabit switch and I am connecting my laptop to it using a cat6 ethernet cable.
The problem is it is connecting to 100Mbps only instead of 1Gbps.
This is what i found :

*

*The is a zone in which the cat 6 cable passes where there are electrical connections and wires... at some point the cat 6 cable crosses an electrical wire

*I tried to remove the cat 6 cable from this zone where there are electrical wires ... when I do this my laptop connects at 1Gbps

*So I am pretty much sure there are some kind of interference with the electrical wires

*I have tried to make the cat 6 cable cross the electric wire perpendicularly instead of parallel to it... this does not work .. I stil get 100Mbps

I am obliged to pass the cat 6 cable in this zone.. there is no other route... what are the solutions to this problem? How to avoid interference with the electrical wires??

A: IIRC - You need to cross power cables at a 90 degree angle.
https://diy.stackexchange.com/questions/11492/can-i-run-cat5-6-cables-parallel-to-electrical-cables

A: I understand that moving the network cable or electrical wiring isn't practical for you. If that's the case, then if electrical interference is the problem, electrical shielding is the solution.
I guess the cheapest experiment is to contrive a simple shield from aluminum foil, and ground it. (I assume that doesn't violate any building or electrical codes.) If that works, you might be able to run your network cable through some electrical metallic tubing (EMT).


text:
Q: Nginx-proxy docker receives stderr output from php-fpm docker (resulting in 502 errors) I have a (quite standard) setup where nginx-proxy serves static files and sends php requests to a php-fpm docker. Simplified version of the compose file:
services:
  php:
    image: php:7-fpm-alpine
    volumes:
      - ./my-src:/var/www
  web:
    image: nginx:alpine
    volumes:
      - ./my-src:/var/www
    ports:
      - "80:80"

Now, whenever I request a php page, notices get dumped in the stderr of the php docker:
NOTICE: PHP message: [info] Matched route "game_index".
NOTICE: PHP message: [debug] Checking for authenticator support.
NOTICE: PHP message: [debug] Checking support on authenticator.
[...]
NOTICE: PHP message: [debug] Notified event "kernel.finish_request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleAwareListener::onKernelFinishRequest".
NOTICE: PHP message: [debug] Notified event "kernel.terminate" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelTerminate".
172.18.0.2 -  03/Feb/2021:20:20:20 +0000 "GET /index.php" 200

which is good and as expected. However, these messages appear in nginx' docker logs, too
2021/02/03 20:20:20 [error] 7#7: *8 FastCGI sent in stderr: "PHP message: [info] Matched route "game_index".
PHP message: [debug] Checking for authenticator support.
PHP message: [debug] Checking support on authenticator.
[...]
PHP message: [debug] Notified event "kernel.finish_request" to listener "Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener::onKernelFinishRequest".
PHP message: [debug] Notified event "kernel.finish_request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleAwareListener::onKernelFinishRequest"" while reading response header from upstream, client: 172.18.0.1, server: , request: "GET /game/ HTTP/1.1", upstream: "fastcgi://172.18.0.3:9000", host: "localhost"
172.18.0.1 - - [03/Feb/2021:20:20:20 +0000] "GET /game/ HTTP/1.1" 200 437 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:85.0) Gecko/20100101 Firefox/85.0" "-"

Which results in an error, and if the text gets too long, a 502 Bad Gateway. In dev, Symfony is quite chatty and I run into this 502 often. In prod, the issue disappears, but I'd like to fix the root cause.
If I adjust the settings in /usr/local/etc/php-fpm.d/docker.conf so the error_log and the access.log point not to /proc/self/fd/2 as per default but to /dev/null instead, the php docker goes silent, but the nginx docker still returns the error.
If I adjust point the files to /proc/self/fd/2 as suggested here, both logs get filled like before.
How can I make sure the logs in the php docker stay the same, but the stderr is not sent to nginx?
(Just tested the full solution in the other thread succesfully: setting log_limit to 1024 as suggested there and discouraged here actually stops the 502 from happening. Still, the stderr output seems to be handled poorly in this setup)
[EDIT]
Following the comment of Ilia Yatsenko, I added this to the Dockerfile:
RUN cp "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
RUN echo 'fastcgi.logging=0' >> "$PHP_INI_DIR/php.ini"

A: It's been a while since I configured alpine php-fpm in a Docker setup, but if I remember correctly, I had to do a few overrides to the default php-fpm.conf.
This is what I have in a similar setup... when the image is being built, the config is copied to /etc/php7/php-fpm.conf.
[www]
listen = 127.0.0.1:9000
clear_env = no

; if we send this to /proc/self/fd/1, it never appears
access.log = /dev/stdout

; Ensure worker stdout and stderr are sent to the main error log.
catch_workers_output = yes
decorate_workers_output = no

pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

[global]
error_log = /dev/stdout


text:
Q: Big-O runtime of while-loop with nesten if-statements I am trying to determine the Big-O notation of these code-snippets:
#1:
public static void printProducts (int n) {
    int a = 0; // O(1)
    int b = n; // O(1)

    // O(n)?
    while (a < b){
        // O(?) This if is checked n times, but how many times is it ran?
        if (a * b == n) {
            System.out.println( a + "*" + b + "=" + a*b ); // O(1)
            a++;                                           // O(1)
            b--;                                           // O(1)
        }
        else if ( a * b > n ) {
            b--;                                           // O(1)
        }
        else if ( a * b < n ) {
            a++;                                           // O(1)
        }
    }
}

#2:
public static void printProducts2 (int n) {
        int a = 1; // O(1)
        int b = n; // O(1)

        // O(log n)
        while (a < b){
            if (a * b == n) {
                System.out.println( a + "*" + b + "=" + a*b ); // O(1)
                a++;                                           // O(1)
                b--;                                           // O(1)
            }
            else {
                if ( a * b > n ) {
                    b = n/a;                                   // O(log n)
                }
                else if ( a * b < n ) {
                    a++;                                       // O(1)
                }
            }
        }
    }

I have concluded that the Big-O notation of the first code is O(n), and O(log n) for the second, but I'm uncertain if it's correct or not. Am I on the right track here?
I have tried looking at this question, before asking my own question, but I couldn't quite understand how it applies here.

A: O(n) and O(sqrt(n)) respectively.
The first one is indeed O(n). You rightly say that the while loop runs O(n) times, and everything within the loop is constant time*, so it does not matter how often the if-conditions are true.
The second one is more interesting. You're correct to point out that the faster decrease of b makes the function less complex. In fact, what this function does is increase a stepwise and then sets b to the appropriate value such that a*b==n, if such a b exists. This means that b can only change when a has changed, and so at least half the time that the loop is entered, a is altered. That is, the loop is entered a constant amount of times for each increase in a.
Now we only need to figure out how often a gets increased. The loop stops when a > b. Because b is equal to n/a, this means that the loop stops when a gets larger than the square root of n. Therefore, the function is in O(sqrt(n)).
* Actually the time it takes to divide, multiply and compare numbers can scale with the size of the numbers, but we'll ignore that for now, as it doesn't seem like that is the focus of the question.


text:
Q: Run iOS Application from Command Line I am in process of doing some Continuous Integration work under which i would download the .ipa from the server install it on the device and finally need to invoke the application installed and perform some automated tests.
I have been able to figure out on how i would download the .ipa from server and deploy it on the device(using ios-deploy) but i am stuck on how can i automatically invoke the application. I know i can do this via Instruments but i don't want to follow that path.
Is there any way this can be done??
P.S - I am not using Instruments for Automation.

A: Did you have a try with ios-deploy ? here is the link https://github.com/phonegap/ios-deploy


text:
Q: pySerial can write, but not read I am trying to use pySerial on a Windows 10 machine (Python 3.6.4, 32 bit) to read serial data from a piece of lab equipment that would normally log its data to a serial ASCII printer. Connecting using a USB-to-serial adaptor.
If I connect the computer to the printer, I can print using serial.write(), so I know my adaptor is working. However, when I connect the computer to the lab equipment and try to read data using the following code, I get nothing all:
import serial
ser = serial.Serial('COM5')
while True:
    if ser.in_waiting != 0:
        datastring = ser.read(size=ser.in_waiting)
        print(str(datastring))

I know the lab equipment is transmitting when I run the code. Have also tried connecting two USB-to-serial adaptors to the computer with a serial cable in-between the adaptors and sending data from one serial port to the other. Again, I can write without problem, but the other port receives nothing.
EDIT: I turned out to have a hardware problem. I had connected the lab equipment to my USB-to-serial adaptor (and, for testing purposes, the two USB-to serial adaptors to each other) using a standard serial cable. Connecting using a null modem solved the problem.

A: you may have a problem of baud rate you should declare something that look like :
import serial
ser = serial.Serial('COM5', 9600, timeout=None) #<- 9600 is the baud rate

while True:
    data = ser.readline()
    print(data)

EDIT
While True:
    bytesToRead = ser.inWaiting()
    data=ser.read(bytesToRead)
    print(data)

A: There are many causes to this kind of problem, the first things that comes to my mind is that you have a low timeout for your serial, and you close the connection before anything can be received:
ser = serial.Serial('COM5', timeout=None)

other values that you may check are the following:
ser = serial.Serial('COM5', baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=False, rtscts=False)

A: I had a similar problem on Win10 system. For me it was related to hardware handshaking.
Inserting:
ser.rts = False
ser.dtr = False

just before reading the waitingstatus may help (it did for me).


text:
Q: jQuery `.click` handler not working after return to page with browser back button
I was able to find the answer before posting. Thought I would share the post anyway for future ref.

The issue was the turbolinks gem preventing the JS to be loaded without refreshing the page.
To fix, Remove:
gem 'turbolinks' from Gemfile  &
//= require turbolinks from application.js

start of initial question (skip, unless interested in what didn't work)

Rails app using CoffeeScript
I have a page that displays the .project-container div along side of a .profile-click. When .profile-click is clicked the .project-container slides out of the way to show the '.profile-container' div.
This all works perfectly on the initial load or refresh of this page. The .click handlers do not function when the page is 'revisited' after a click of the browser's back button. (the divs targeted by .click are not on the page from which the browser back button is clicked)
Also, this is only an issue if I visit another page within the same app (ie main.com/sub -> browser back clicked -> main.com). Not a problem if the page is 'revisited' after going to another domain.
Hoping to gain some insight in to why this is happening.

$(document).ready ->
  $('.project-overlay').click ->
    $('.project-container').animate 'right': '8.5vw'
    $('.project-overlay').animate 'right': '8.5vw'
    $('.project-overlay').css 'z-index': '0'
    $('.profile-container').fadeOut()
    $('.profile-click').fadeIn()
    return

  $('.profile-click').click ->
    $('.project-container').animate 'right': '65vw'
    $('.project-overlay').animate 'right': '65vw'
    $('.project-overlay').css 'z-index': '1'
    $('.profile-container').fadeIn()
    $('.profile-click').fadeOut()
    return
  return

I understand that $(document).ready isn't being fired on the reload (browser caching). This was confirmed by calling alert('ready') which only popped up on the initial load.

what didn't work

I tried to call .ready on a different div container that only exists on the initial page but it gave the same results.
.onpageshow is not working either
Tried to prevent caching in application_controller with no luck.

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :prevent_caching

  protected

  def prevent_caching
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "0"
  end
end

A: The issue was the turbolinks gem preventing the JS to be loaded without refreshing the page.
To fix, Remove:
gem 'turbolinks' from Gemfile &
//= require turbolinks from application.js


text:
Q: Why did coder assign value of struct pointer to a static struct? Apologies if this is a duplicate, in which case I couldn't find the right keywords to search.
This is in reference to some old (MUD) code I'm working on which is pasted below.  I'm confused by purpose of the foo_zero and *foo = foo_zero parts of the code below.  This is a pattern it uses throughout the codebase.  My guess is that it's a way of initializing all of the members of foo to zero/NULL without having to explicitly set them.
typedef struct FOO {
    int buzz;
    char *bazz;
} FOO;

FOO *init_foo(void)
{
    static FOO foo_zero;
    FOO *foo;

    foo = malloc(sizeof(*foo));
    *foo = foo_zero; // <-- why?
    return foo;
}

A: Yes, the lines
static FOO foo_zero;

and
*foo = foo_zero;

arrange that every new instance of struct FOO allocated by init_foo() is initialized just as if someone had said
struct FOO new_foo = { 0 };

Specifically, all integer fields will be initialized to 0, all floating-point fields will be initialized to 0.0, and all pointer fields will be initialized to null pointers (aka NULL, or nullptr in C++).
This is a nice technique, because it's both simpler and, strictly speaking, more portable than other techniques.
There's a discussion percolating in the comments about the alternative possibilities of doing
foo = malloc(sizeof(*foo));
memset(foo, 0, sizeof(*foo));

or
foo = calloc(1, sizeof(*foo));

Both of these would initialize the brand-new struct FOO to all-bits-0.  The subtle problem here -- which is so subtle that many programmers would not call it a problem at all -- is that it is theoretically possible for a processor and/or operating system to represent a floating-point value of 0.0, or a null pointer, with a bit pattern of something other than all-bits-0.
But if you're on such a processor, then doing
float f = 0;

or
char *p = 0;

will do the right thing, initializing the variable with the proper zero value, even if it's not all-bits-0.  And for an aggregate such as struct FOO, doing
struct FOO new_foo = { 0 };

is equivalent to explicitly initializing each of its members with 0, meaning you get the proper zero value, even if that's not all-bits-0.  And, finally, any time you declare a variable with static duration, as in
static FOO foo_zero;

you get an implicit initialization as if you'd said = { 0 };, and therefore the default (static) initialization, too, gives you those correct zero values no matter what.
If you're still curious about calloc's all-bits-0 guarantee, you can read a bit more about it in question 7.31 of the C FAQ list.

A: In fact this declaration
static FOO foo_zero;

is equivalent to the following
static FOO foo_zero = { .buzz = 0, .bazz = 0 };

So in this assignment statement
*foo = foo_zero;

an object pointed to by the pointer foo is zero initialized the same way as the static variable foo_zero.
The function return a pointer to a zero initialized object.
For this simple case you could achieve almost the same effect if instead of malloc you
used calloc.
FOO *init_foo(void)
{
    return calloc( 1, sizeof( struct FOO ) );;
}

But sometimes a non-trivial initialization is required. So the approach you showed has a meaning. For example
struct FOO
{
    size_t n;
    char s[10];
};

struct FOO * init_foo( void )
{
    static struct FOO default_foo = { .n = 6, .s = "Hello" };

    struct FOO *foo = malloc( sizeof( *foo ) );

    if ( foo ) *foo = default_foo;

    return foo;
}

A: Why complicating?
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef struct {
    int buzz;
    char *bazz;
} FOO;

init_foo() above actually just returns new foo made on the heap. All clean. So let's just do that:
static inline FOO * new_foo(void)
{
    return calloc(1,sizeof(FOO));
}

Usage and check:
int main (void)
{
    FOO * foo = new_foo();

   printf("buzz: %d, bazz: %s", foo->buzz, foo->bazz );

   free(foo);

    return 42;
}

Godbolt shows new struct FOO nicely empty
Program returned: 42
buzz: 0, bazz: (null)


text:
Q: Loading level data from xml file in XNA I am creating a tile-based game in XNA and will be loading the level information from xml files. I have no problem with loading xml data but I would like feedback on the approach I'm thinking of using for reading the xml file.
The code has a class hierarchy such that:
A Level class contains:
- a collection of TileLayers
- a collection of Tilesets
A TileLayer class contains
- a collection of Tiles
A Tileset class contains:
- a collection of TilsetTiles
A TilesetTile class contains:
- a TileId
- a collection of TileProperties
- a TileRectangle
Each of the above classes requires some information from the xml level file.
When I load a level I would like to simply call Level.Load();
My intention is that each class will have a Load() method that will:
1. Load any specific info it needs from the xml file.
2. Call Load() on its children.
The problem I see is that the code for processing the xml will be scattered around in different files making changes difficult to implement (for instance if I decide to encrypt the xml file), and no doubt breaks several aspects of the SOLID principles.
I have this idea that I could create an xmlLevelReader class whose sole purpose is to read an xml level file.
This class could then expose methods that can be called from the Load() method in each of the classes described above.
For example the TileLayer class Load() method could call xmlLevelReader.GetTiles() which would return an IEnumerable<Tile>
Do you think this approach will work?
Can you foresee any difficulties?
Is this approach too simplistic/complicated?
Any constructive criticism welcomed!
Thanks

A: Based on your comment, I see that you are using Tiled Map Editor. This lead me to suggest that you use TiledLib. Here is a brief explanation of how you can get up and running with importing your .tmx files for use in game.
Content Pipeline Overview
File -> Content Import -> Content Process -> Content Write -> .xnb -> ContentRead -> Game Object
TiledLib
TiledLib only handles the ContentImporter part of the above diagram. It will essentially handle reading the .tmx XML and allow you to process the data into whatever objects you need at run time. Fortunately, the TiledLib author has provided a Demos section in the download as well.
Basic Tiled Map Processor Demo

*

*BasicDemo main game project which contains the ContentManager.Load call.

*BasicDemoContent project which has the .tmx file from Tiled

*BasicDemoContentPipeline project which has the ContentProcessor

*TiledLib which has the ContentImporter
You really only need to worry about how the ContentProcessor works because TiledLib handles all the importing for you. Although I do suggest looking through the different classes to understand how it is deserializing the XML (for educational purposes).
The example ContentProcessor in the Basic Demo project takes in a MapContent object from the ContentImporter (TiledLib) and outputs a DemoMapContent object which is serialized to .xnb at build time and deserialized to a Map object at run time. Here are the classes that represent the map after being processed completely:
[ContentSerializerRuntimeType("BasicDemo.Map, BasicDemo")]
public class DemoMapContent
{
    public int TileWidth;
    public int TileHeight;
    public List<DemoMapLayerContent> Layers = new List<DemoMapLayerContent>();
}

[ContentSerializerRuntimeType("BasicDemo.Layer, BasicDemo")]
public class DemoMapLayerContent
{
    public int Width;
    public int Height;
    public DemoMapTileContent[] Tiles;
}

[ContentSerializerRuntimeType("BasicDemo.Tile, BasicDemo")]
public class DemoMapTileContent
{
    public ExternalReference<Texture2DContent> Texture;
    public Rectangle SourceRectangle;
    public SpriteEffects SpriteEffects;
}

*

*A Map contains a tile width, tile height, and a list of MapLayers.

*A MapLayer contains a width, a height, and a list of Tiles.

*A MapTile contains a texture, a source rectangle (proper rectangle in the tileset), and optional sprite effects (I've never used any).

How It's Made
I suggest reading the comments of the ContentProcessor to understand what is happening, but in brief, this is the basics:

*

*Load texture data for tile set

*Get source rectangles for each tile from within the texture

*Iterate over all layers of the map

*For each layer, iterate over all tiles

*For each tile, get the proper texture and source rectangle

*Assign all data from the input to the output properly

Caveats
As long as you stick to basic types (vague, I know), you also do not need to worry about ContentWriter and ContentReader parts of the content pipeline. It will automatically serialize and deserialize the .xnb files at build and run time, respectively. See a question I asked about this: here.
Also, you'll notice that if you're using object layers from within Tiled, the demo does not show you how to process those. TiledLib does properly import them, you just need to pull the data out and stick it in your proper classes. I'll try to edit this answer later with an example of how to do that.

A: If you are just wanting to load in XML without manipulating the data at all, you can just use the built in XNA Content Serializer.
Essentially you define a class which maps to your xml format, and then read the XML into an instance of that class.
For example. Here I define the class I want to load into:
SpriteRenderDefinition.cs
I chose this one because it has nested classes like the case you describe. Note that it goes into the ContentDefinitions project of you XNA solution.
Now here is the xml file that fills in the content of a SpriteRenderDefinition:
Sprite.xml
The format of that XML maps directly to the member names of SpriteRenderDefinition.
And finally, the code to actually load that XML data into an actual Object at runtime is very straight forward:
SpriteRenderDefinition def = GameObjectManager.pInstance.pContentManager.Load<SpriteRenderDefinition>(fileName);

After calling that line, you have a SpriteRenderDefintion object populated with all the content of the XML file! That is all the code I wrote. Everything else is built into XNA. It's really quite slick and useful if you take an hour or so to figure it out!


text:
Q: OpenGL GLPaint threaded rendering I am currently using a library that is based on the GLPaint example by Apple used for drawing on screen in Open GL. Currently whenever the canvas saves and restores the session the lines are drawn (progress is visibly seen) and it takes quite a bit of time if there are a lot of points to render. Is there any way to get this to render in parallel or quicker?
This is the drawing code I'm using:
CGPoint start = step.start;
CGPoint end = step.end;

// Convert touch point from UIView referential to OpenGL one (upside-down flip)
CGRect bounds = [self bounds];
start.y = bounds.size.height - start.y;
end.y = bounds.size.height - end.y;

static GLfloat*     vertexBuffer = NULL;
static NSUInteger   vertexMax = 64;
NSUInteger          vertexCount = 0,
count,
i;

[EAGLContext setCurrentContext:context];
glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);

// Convert locations from Points to Pixels
CGFloat scale = self.contentScaleFactor;
start.x *= scale;
start.y *= scale;
end.x *= scale;
end.y *= scale;

// Allocate vertex array buffer
if(vertexBuffer == NULL)
    vertexBuffer = malloc(vertexMax * 2 * sizeof(GLfloat));

// Add points to the buffer so there are drawing points every X pixels
count = MAX(ceilf(sqrtf((end.x - start.x) * (end.x - start.x) + (end.y - start.y) * (end.y - start.y)) / kBrushPixelStep), 1);
for(i = 0; i < count; ++i) {
    if(vertexCount == vertexMax) {
        vertexMax = 2 * vertexMax;
        vertexBuffer = realloc(vertexBuffer, vertexMax * 2 * sizeof(GLfloat));
    }

    vertexBuffer[2 * vertexCount + 0] = start.x + (end.x - start.x) * ((GLfloat)i / (GLfloat)count);
    vertexBuffer[2 * vertexCount + 1] = start.y + (end.y - start.y) * ((GLfloat)i / (GLfloat)count);
    vertexCount += 1;
}

// Render the vertex array
glVertexPointer(2, GL_FLOAT, 0, vertexBuffer);
glDrawArrays(GL_POINTS, 0, (int)vertexCount);

// Display the buffer
glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
[context presentRenderbuffer:GL_RENDERBUFFER_OES];

A: OpenGL is not multi-threaded. You have to submit OpenGL commands from a single thread.
You have a couple of choices:

*

*You can factor your code to use concurrency to build the data that you send to OpenGL, then submit it to the OpenGL API once it is all available.

*You can refactor it to do your calculations using shaders. This pushes the computation off the CPU and onto the GPU, which is highly optimized for parallel operation.
Your code above is using realloc to reallocate a buffer repeatedly while in the for loop. This is dreadfully inefficient, since memory allocation is one of the slowest RAM-based operations on a modern OS. You should refactor your code to calculate the final size of your memory buffer up-front, and then allocate the buffer at it's final size once, and not use realloc at all. This should give you a many-times increase in speed with very little effort.
Glancing at your code it should not be hard at all to refactor your for loop to break the vertex calculation into blocks and submit those blocks to GCD for concurrent processing. The trick is in breaking the tasks into work units that are large enough to benefit from parallel processing (there is a certain amount of overhead in setting up a task to run in a background queue. You want to do enough work in each work unit to make that overhead worth it.)

A: I believe the dialog in the comments above revealed the main part of your performance problem. Unless I completely misunderstood it, the high level structure of your code currently looks like this:
loop over steps
    calculate list of points from start/end points
    render list of points
    present the renderbuffer
end loop

It should be massively faster to present the renderbuffer only after all the steps were rendered:
loop over steps
    generate list of points from start/end points
    draw list of points
end loop
present the renderbuffer

Even better, generate a Vertex Buffer Object (aka VBO) for each step as part of creating it, and store the coordinates of the points for the step in the buffer. Then your draw logic becomes:
loop over steps
    bind VBO for step
    draw content of VBO
end loop
present the renderbuffer


text:
Q: Integration of Socket.IO with VUE Framework Hello I am trying to implement socket.io with vue.js however I cannot access the emits in the different views.
After configuring main.js I can get emits on the APP, but I can't get them on HOME.
Is it possible to help with this situation.
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import vuetify from "./plugins/vuetify";

import * as io from "socket.io-client";
import VueSocketIO from "vue-socket.io";

Vue.use(
  new VueSocketIO({
    debug: true,
    connection: io("http://localhost:3001"),
  })
);

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  vuetify,
  render: (h) => h(App),
}).$mount("#app");

Here I have the implementation of the first view, and here I have access to the socket.io emit!
<template>
  <v-app id="inspire">
    <v-app-bar app color="white" flat>
      <v-container class="py-0 fill-height">
        <v-avatar class="mr-10" color="grey darken-1" size="32"></v-avatar>

        <v-btn v-for="link in links" :key="link" text>
          {{ link }}
        </v-btn>

        <v-spacer></v-spacer>

        <v-responsive max-width="260">
          <v-switch
            v-model="switchLogIn"
            label="login"
            color="success"
            hide-details
          ></v-switch>
        </v-responsive>
      </v-container>
    </v-app-bar>

    <v-main class="grey lighten-3">
      <v-container>
        <v-row>
          <v-col cols="2">
            <v-sheet rounded="lg">
              <v-list color="transparent">
                <v-list-item v-for="n in 5" :key="n" link>
                  <v-list-item-content>
                    <v-list-item-title> List Item {{ n }} </v-list-item-title>
                  </v-list-item-content>
                </v-list-item>

                <v-divider class="my-2"></v-divider>

                <v-list-item link color="grey lighten-4">
                  <v-list-item-content>
                    <v-list-item-title to="/about">
                      {{ nextSip["Estado Processo"] }}
                    </v-list-item-title>
                  </v-list-item-content>
                </v-list-item>
              </v-list>
            </v-sheet>
          </v-col>

          <v-col>
            <v-alert icon="mdi-database-outline" prominent text type="info">
              FILA DE TRABALHO COM {{ workFlowSize }}.
            </v-alert>
            <v-sheet min-height="70vh" rounded="lg" v-if="switchLogIn">
              <router-view></router-view>
            </v-sheet>
          </v-col>
        </v-row>
      </v-container>
    </v-main>
  </v-app>
</template>

<script>
export default {
  data: () => ({
    links: ["Dashboard"],
    switchLogIn: false,
    workFlow: "",
    workFlowSize: 0,
    nextSip: Object,
  }),
  sockets: {
    connect: function () {
      this.$swal("Conectado com Sucesso", "Servidor Localhost:3001", "success");
      console.log("socket connected");
    },
    workFlowSize(data) {
      this.workFlowSize = data;
    },
    nextSip: (data) => {
      console.log(data);
    },
  },
  watch: {
    switchLogIn: function (value) {
      if (value == true) {
        console.log("Im LOGIN");
      }
    },
  },
};
</script>

but not here
<template>
  <div class="home">
    <SipForm/>
  </div>
</template>

<script>
import SipForm from "@/components/SipForm.vue";

export default {
  name: "Home",
  components: {
    SipForm,
  },
  data: () => ({
    workFlowSize: 0,
  }),
  sockets: {
    connect: function () {
      this.$swal("Conectado com Sucesso", "Servidor Localhost:3001", "success");
      console.log("socket connected");
    },
    workFlowSize(data) {
      this.workFlowSize = data;
    },
    nextSip: (data) => {
      console.log(data);
    },
  },
};
</script>