text:
Q: Measure electrical consumption from electric panel I want to hack my electrical distribution board a little, to measure the energy used by each circuit.
Thus, I want to use a little arduino or maybe a raspberry pi and plug it to my circuits to take measures (I assume I should use things like ampmeter or voltmeter). Then I could make charts about what use energy the most in my home (and eventualy point energy leaks).
Unfortunately, I have less-than-basic knowledge about electricity, so I don't have a clue about how to measure energy.
So here are my questions :

*

*where and what should I plug to my circuits ?

*how many measures would be enough to be valuable ? (one every millisecond ? second ? hour ?)

*would this system consume a non-negligible amount of energy ?

EDIT : as Will Dean stated, I should start with something small. Please consider this question to apply to a simple plug, and not an entire electric panel :-)
FINAL EDIT : I have to admit this seems way too dangerous for me since there is too much information I don't know about the electricity way across my home. So the final answer is : I give up for now. Any advice to how to teach myself is really welcomed

A: With admitted 'less than basic' knowledge about electricity, that means you must not make any connections to the mains on your board.
What you want is a clamp-on current transformer on each wire you want to monitor. This usually takes the form of 2 C-cores, with either a winding round one of them, or Hall sensor or two embedded in them. These will isolate the  mains from your low voltage measurements. I am not going to recommend any particular part numbers, but at least you know what to search for now.
Most people doing this sort of thing would assume constant mains voltage, and unity power factor, and not measure it. It's only worth doing if you are making metering-quality measurements, which it sounds like you're not.

A: Non-intrusive way of monitoring the meter: https://github.com/dkroeske/emon-server
That relies on having one of the modern kind of meters which has a flashing light on it. The light flashes exactly once for each watt-hour consumed. Count the flashes and you can estimate power consumption over time.
The clamp meter approach (Neil_UK's answer) relies on identifying the individual circuits leading out of the board, separating the conductors (if they're not already free of the outer insulation, this will require powering down and very careful cutting), then applying a clamp meter or current transformers.
There's also this which looks interesting, but not very beginner accessible: http://ieeexplore.ieee.org/document/5433631/


text:
Q: Cant match multiple line regex So ive been trying to match in regex(editpadpro) and i want to match POLYLINE,TYPE=0x6,RoadID ONLY, editpadpro flavor =  Perl, Java, .NET any help is appreciated
[POLYLINE]
Type=0x6
Label=Lorong Karyawan 18
EndLevel=1
CountryName=MALAYSIA~[0x1d]MYS
RegionName=PAHANG~[0x1d]PHG
CityName=KUANTAN
Zip=25150
RoadID=1154
RouteParam=2,1,0,0,0,0,0,0,0,0,0,0
Data0=(3.77022,103.27289),(3.76988,103.27201)
Nod1=0,283024,0
Nod2=1,282992,0
Numbers1=0,O,55,41,N,-1,-1
[END]

so far ive used this \[POLYLINE]\W+(?:\w+\W+0x6) that match both polyline and Type=0x6

A: You could use 3 capturing groups starting by capturing [POLYLINE].
For the other 2 capturing groups, you can match all the lines that do not start with Type or RoadID, and then capture the line that does using a negative lookahead.
(\[POLYLINE\])(?:\r?\n(?!Type).*)*\r?\n(Type=.+)(?:\r?\n(?!RoadID).*)*\r?\n(RoadID=.+)

See a Regex demo
Explanation

*

*(\[POLYLINE\]) Group 1 match [POLYLINE]

*(?:\r?\n(?!Type).*)*\r?\n Repeatedly match all lines that do not start with Type

*(Type=.+) Group 2 Match Type= followed by 1+ times any char

*(?:\r?\n(?!RoadID).*)*\r?\n Repeatedly match all lines that do not start with RoadID

*(RoadID=.+) Group 3 match RoadID= followed by 1+ times any char

redpajama_set_name: RedPajamaStackExchange


text:
Q: my rails db:migrate isnt working i tried running rake bd:migrate but it gave me an error and told me to run rails db:migrate RAILS_ENV=development instead but it gave me bunch of errors
C:\Sites\seekhostel.com>rails db:migrate RAILS_ENV=development
== 20180311182801 AddDeviseToUsers: migrating =================================
-- change_table(:users)
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: duplicate column name: email: ALTER TABLE "users" ADD "email" varchar DEFAULT '' NOT NULL
C:/Sites/seekhostel.com/db/migrate/20180311182801_add_devise_to_users.rb:7:in `block in up'
C:/Sites/seekhostel.com/db/migrate/20180311182801_add_devise_to_users.rb:5:in `up'
bin/rails:4:in `require'
bin/rails:4:in `<main>'

Caused by:
ActiveRecord::StatementInvalid: SQLite3::SQLException: duplicate column name: email: ALTER TABLE "users" ADD "email" varchar DEFAULT '' NOT NULL
C:/Sites/seekhostel.com/db/migrate/20180311182801_add_devise_to_users.rb:7:in `block in up'
C:/Sites/seekhostel.com/db/migrate/20180311182801_add_devise_to_users.rb:5:in `up'
bin/rails:4:in `require'
bin/rails:4:in `<main>'

Caused by:
SQLite3::SQLException: duplicate column name: email
C:/Sites/seekhostel.com/db/migrate/20180311182801_add_devise_to_users.rb:7:in `block in up'
C:/Sites/seekhostel.com/db/migrate/20180311182801_add_devise_to_users.rb:5:in `up'
bin/rails:4:in `require'
bin/rails:4:in `<main>'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

i would love to know why it did so and how to fix it

A: By looking at error message I suspect two things happened here:

*

*You already had users table (because new migration has change_table(:users), not create_table(:users) - devise generator recognize that)

*You ran $ rails generate devise command and you didn't inspect autogenerated migration file.

You were supposed to remove line
t.string :email,              null: false, default: ""

from 20180311182801_add_devise_to_users.rb file


text:
Q: Method inside of a class always returns same output while the same logic outside of the class works I have this block of code inside of a class. No matter what data I pass into the class, this will always return "Loss".
def win_loss_unadj(self):
    if self.side == "Long" and (self.getMAE > self.getStop) and (self.getMFE >= self.unadj_T2):
        return "T2_Win"
    elif self.side == "Long" and (self.getMAE > self.getStop) and (self.getMFE >= self.unadj_T1):
        return "Win"
    elif self.side == "Short" and (self.getMAE < self.getStop) and (self.getMFE <= self.unadj_T2):
        return "T2_Win"
    elif self.side == "Short" and (self.getMAE < self.getStop) and (self.getMFE <= self.unadj_T1):
        return "Win"
    else:
        return "Loss"

When I use the same logic outside of the class (using print() instead of return), I get the correct results with the same data.
for i in range(len(tradeList)):
    if Trade.side(tradeList[i]) == "Long" and (Trade.getMAE(tradeList[i]) > Trade.getStop(tradeList[i])) and (Trade.getMFE(tradeList[i]) >= Trade.unadj_T2(tradeList[i])):
        print("T2_Win")
    elif Trade.side(tradeList[i]) == "Long" and (Trade.getMAE(tradeList[i]) > Trade.getStop(tradeList[i])) and (Trade.getMFE(tradeList[i]) >= Trade.unadj_T1(tradeList[i])):
        print("Win")
    elif Trade.side(tradeList[i]) == "Short" and (Trade.getMAE(tradeList[i]) < Trade.getStop(tradeList[i])) and (Trade.getMFE(tradeList[i]) <= Trade.unadj_T2(tradeList[i])):
        print("T2_Win")
    elif Trade.side(tradeList[i]) == "Short" and (Trade.getMAE(tradeList[i]) < Trade.getStop(tradeList[i])) and (Trade.getMFE(tradeList[i]) <= Trade.unadj_T1(tradeList[i])):
        print("Win")
    else:
        print("Loss")

Now, I might be grossly misunderstanding the return command or class methods in general. I am not experienced with python at all and for the life of me I can't figure out what's wrong here.
I checked if there was something wrong with the objects themselves, but there isn't. All the data is correct, so the issue MUST be in the first section of code I posted.


text:
Q: Json array of objects : $.each causes "Cannot read property 'length' of undefined" error I have been spending days trying to figure out why I can't enumerate through the Json result of an Ajax query.  Have got this to work a number of times before but this time it keeps failing when applying $.each.
$.ajax({type: 'GET', url: "/api/RestaurantApi/BindRestaurants/?data=",
    data: request,dataType: "json", contentType: "application/json; charset=utf-8",
    success: function (data) {
    $.each(data, function (index,values) {
    ....

My WebApi method is as follows, note the [ScriptMethod(ResponseFormat = ResponseFormat.Json)] which saves having to put
  var jsdata = JSON.parse(data);

into the Javascript.
Also I simplified the data so that all properties except the RestaurantID return the same simple values, just in case some unusual character was causing problems.
    [Route("BindRestaurants")]
    [HttpGet]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public IEnumerable<Restaurant> BindRestaurants()
    {
        dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
        string City= Guid.Parse(queryJson.City.Value);
        SqlCommand cmd = new SqlCommand();
        using (SqlConnection con = new SqlConnection(DBConn))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                cmd.CommandText = "QryRestaurantsforCity";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("CityID", City);
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    List<Restaurant> listRestaurants  = new List<Restaurant>();
                    if (dt.Rows.Count > 0)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            Restaurant dm = new Restaurant ();
                            dm.RestaurantID = new Guid(dt.Rows[i]["RestaurantID"].ToString());
                            dm.RestaurantName = "dishesnames";
                            dm.RestaurantTypeID = 15;
                            dm.RestaurantTypeName = "wwwwwww";
                            dm.SortOrder = 1;
                            listRestaurants.Insert(i, dm);
                        }
                    }
                    return (IEnumerable<Restaurant>)listRestaurants;
                }
            }
        }
    }

The result looks entirely normal when examining "data" in Javascript, an array of 9 objects as I have used before:
Array[9]

0: Object

RestaurantID: "666a6d14-a62b-4d60-b16e-43005a85047e"

RestaurantName: "restaurantnames"

RestaurantTypeID: 15

RestaurantTypeName: "wwwwwww"

SortOrder: 1

1: Object
2: Object
....
8: Object

On the line
 $.each(data, function (index,values) {

the error it produces:
Uncaught TypeError: Cannot read property 'length' of undefined.
suggests it's not an array but a test of the type shows it is.  I tried switching it to an array of arrays using the following...
var ArrayofArrays = $.map(data, function (n, i) {
   return [[n.RestaurantID, n.RestaurantName, n.RestaurantTypeID, n.RestaurantTypeName]];
});

but the same error occurs.
What am I doing wrong?  My code looks exactly the same as what I have used other times.
Edit: the stringified Json returned is as follows:
[
   {
      "SortOrder":1,
      "RestaurantID":"666a6d14-a62b-4d60-b16e-43005a85047e",
      "RestaurantName":"dishesnames",
      "RestaurantTypeID":15,
      "RestaurantTypeName":"wwwwwww"
   },
   {
      "SortOrder":1,
      "RestaurantID":"061eabcb-38cb-4c78-b26a-e9f626e89233",
      "RestaurantName":"dishesnames",
      "RestaurantTypeID":15,
      "RestaurantTypeName":"wwwwwww"
   },
   {
      "SortOrder":1,
      "RestaurantID":"6c328be5-2132-46bc-8469-0aa074eaff11",
      "RestaurantName":"dishesnames",
      "RestaurantTypeID":15,
      "RestaurantTypeName":"wwwwwww"
   },
   {
      "SortOrder":1,
      "RestaurantID":"b51f2b72-8ec6-40e7-9bc7-8e8db3d10bef",
      "RestaurantName":"dishesnames",
      "RestaurantTypeID":15,
      "RestaurantTypeName":"wwwwwww"
   },
   {
      "SortOrder":1,
      "RestaurantID":"c2ab8f02-6b2a-4490-ac67-7843ad6cf083",
      "RestaurantName":"dishesnames",
      "RestaurantTypeID":15,
      "RestaurantTypeName":"wwwwwww"
   },
   {
      "SortOrder":1,
      "RestaurantID":"807a6c3a-ecc8-478f-be05-892104c5668c",
      "RestaurantName":"dishesnames",
      "RestaurantTypeID":15,
      "RestaurantTypeName":"wwwwwww"
   },
   {
      "SortOrder":1,
      "RestaurantID":"1a81c304-b264-48fb-81f9-a5dc10c7fcb8",
      "RestaurantName":"dishesnames",
      "RestaurantTypeID":15,
      "RestaurantTypeName":"wwwwwww"
   },
   {
      "SortOrder":1,
      "RestaurantID":"3b45b85e-cb28-4e23-ae33-6b2ce622b525",
      "RestaurantName":"dishesnames",
      "RestaurantTypeID":15,
      "RestaurantTypeName":"wwwwwww"
   },
   {
      "SortOrder":1,
      "RestaurantID":"94153e81-bce1-4a00-b8a0-d897bfad7b0a",
      "RestaurantName":"dishesnames",
      "RestaurantTypeID":15,
      "RestaurantTypeName":"wwwwwww"
   }
]

Thanks in advance,
Robert


text:
Q: Decrypt password in pom.xml I have a util class that picks up properties from application.properties(jdbc password are in encrypted format in it) file and encrypts/decrypts it. I there a way to  decrypt the password while using placeholders in pom.xml

A: For, Decrypt password in pom.xml you need to create Create master password with below commands :
mvn --encrypt-master-password

Once you run this command then, create a file called ~/.m2/settings-security.xml and write below content into this file :
<settingsSecurity>
  <master><!-- result of above command --></master>
</settingsSecurity>

after this encrypt your password by rum below commands :
mvn --encrypt-password

after running this command you will get the output, you need to create a file /.m2/settings.xml and  write this output in your maven settings ~/.m2/settings.xml. you can use below sample code to write into /.m2/settings.xml.
<settings>
...
  <servers>
  ...
    <server>
      <id>test.server</id>
      <username><!-- your database username --></username>
      <password><!-- the encrypted password --></password>
    </server>
  ...
  </servers>
...
</settings>

for more you can refer this link.
use below sql-maven-plugin with the configuration into pom.xml.
<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>sql-maven-plugin</artifactId>
  <version>3.0.0-SNAPSHOT</version> <!-- 3.0.0-SNAPSHOT required -->
  <configuration>
    <settingsKey>test.server</settingsKey> <!-- id of server here -->
    <driver>oracle.jdbc.driver.OracleDriver</driver>
    <url>jdbc:oracle:thin:@ip.com:1521:SID</url>
    <!-- username and password are not mentioned anymore -->
  </configuration>
</plugin>


text:
Q: postfix problem sending email "RCPT reject localhost not listed" i am hacing a hard time getting postfix to send emails.
this is the mail.log entry:
Jun 30 18:27:46 vm21 postfix/smtpd[15682]: warning: ::1: address not listed for hostname localhost
Jun 30 18:27:46 vm21 postfix/smtpd[15682]: connect from unknown[::1]
Jun 30 18:27:46 vm21 postfix/smtpd[15682]: NOQUEUE: reject: RCPT from unknown[::1]: 554 5.7.1 <momchilrogelov@gmail.com>: Relay access denied; from=<ubuntu@debeldecibel.com> to=<momc$
Jun 30 18:27:46 vm21 postfix/smtpd[15682]: lost connection after RCPT from unknown[::1]
Jun 30 18:27:46 vm21 postfix/smtpd[15682]: disconnect from unknown[::1]

the /etc/hosts file has
::1     localhost ip6-localhost ip6-loopback

and this is my postconf -n
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
append_dot_mydomain = no
biff = no
broken_sasl_auth_clients = yes
config_directory = /etc/postfix
content_filter = smtp-amavis:[127.0.0.1]:10024
delay_warning_time = 4h
home_mailbox = Maildir/
inet_interfaces = all
inet_protocols = all
mailbox_command =
mailbox_size_limit = 0
mydestination = debeldecibel.com, localhost
myhostname = smtp.debeldecibel.com
mynetworks = 127.0.0.0/8
myorigin = /etc/mailname
readme_directory = no
recipient_delimiter = +
relayhost =
smtp_tls_note_starttls_offer = yes
smtp_tls_security_level = may
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_banner = $myhostname ESMTP $mail_name
smtpd_sasl_auth_enable = yes
smtpd_sasl_local_domain =
smtpd_sasl_security_options = noanonymous
smtpd_tls_CAfile = /etc/ssl/certs/cacert.pem
smtpd_tls_auth_only = no
smtpd_tls_cert_file = /etc/ssl/certs/smtpd.crt
smtpd_tls_key_file = /etc/ssl/private/smtpd.key
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_security_level = may
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtpd_tls_session_cache_timeout = 3600s
smtpd_use_tls = yes
tls_random_source = dev:/dev/urandom

A: The "address not listed for localhost" message is misleading. Use:
mynetworks = 127.0.0.0/8 [::1]/128

A: Check the /etc/hosts file.
Is the ipv6 address for localhost inserted?
The line should be like:
::1     localhost ip6-localhost ip6-loopback

If not add it and restart postfix.
Try to send again the email.


text:
Q: Is there way to exclude the Microsoft default (OOBE) service principals? I want to have a list of all NON-Microsoft-Default service principals in my tenant, exclude all OOBE apps.
I can´t find any property on a service principal object returned by either the Get-AzureADServicePrincipal PS cmdlet or the Graph-API (graph.microsoft.com/beta/servicePrincipals) where i can tell whether its Microsoft default App or a custom one.
At first I thought it might be the tag property and I can filter on those which have the WindowsAzureActiveDirectoryIntegratedApp tag. But it turned out that it indicates wheter the service principal is an enterprise app or not (application type).
Any ideas on which property to filter or which API to use?

A: You can filter out based on appOwnerOrganizationId. For Microsoft created application , this parameter would be same.
I tried using with the graph api
https://graph.microsoft.com/beta/servicePrincipals
You can check what is the defualt guid for MS created apps and then put a filter in your query like **appOwnerOrganizationId != MSAppOwner Org Id**.
Try this and see if it helps.


text:
Q: Discriminant ideal in $\mathbb{Z}$ Given a monic polynomial $f \in \mathbb{Z}[X]$, I would like to consider the ideal $$(f, f')_{\mathbb{Z}[X]} \cap \mathbb{Z}$$ in $\mathbb{Z}$. In particular: is it true that this is generated by the discriminant $\Delta(f)$?
I know at least that $\Delta(f)$ is contained in this ideal.

A: No.
Take $f(x)=x^2+1$ as an example. Then $f'(x)=2x$ and $2=2f(x)-xf'(x) \in (f,f')_{\Bbb Z[X]} \cap \Bbb Z$, but $\Delta(f)=-4$.


text:
Q: Use UIAccelerometer to move CCSprite – cocos2D I want to be able to move a CCSprite using the UIAccelerometer. It should only be moved up and down. The code I use is this:
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
valueX = acceleration.y * 45.0;

int newPos = (int)(valueX + _rocket.position.x);

CGPoint newCenter = ccp(100, newPos);
_rocket.position = newCenter;
}

_rocket is the sprite.
When I run it on my iphone it's just vibrating on the same place, and I'm not able to move it to the top or the bottom. What's wrong?

A: try  int newPos = (int)(valueX + _rocket.position.y);
   instead int newPos = (int)(valueX + _rocket.position.x);
according to your code position.x is always 100.
That's why int newPos = (int)(valueX + _rocket.position.x); not working.


text:
Q: Python Wand convert pdf to black image I'm trying to convert some pdf files to jpg through Wand in Python:
from wand.image import Image as Img
from wand.color import Color

    def importPdf(self):
        filename, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Open File",
                                                            QtCore.QDir.currentPath())
        print(filename)
        if not filename:
            print('error')
            return
        with Img(filename=filename,format='jpeg', resolution=300) as image:
            image.compression_quality = 99
            image.save(filename='file.jpeg')
            self.open_picture()

My problem is that it results is a black screeen. The conversion works fine with png, but I cannot perform the OCR (via tesseract on the png).
I think it comes from a kind of transparent layer, but I have not found the way to remove it, though I did several things such as
image.alpha_channel = False # made the same with True
image.background_color = Color('White')

before saving the file.
I'm using Imagemagick V6.9, because V7 fails with Wand.

A: I had the same problem and fixed it, check my answer here: https://stackoverflow.com/a/46612049/2686243
Adding
image.background_color = Color("white")
image.alpha_channel = 'remove'

solved the issue.

A: Because I did not find -flatten via wand api, I finally did it via os.system + convert.exe of imagemagick.
It does the job.
cmd = "convert -units PixelsPerInch -density 300 -background white -flatten " + filename + " converted_pdf.jpg"
        print(cmd)
        os.system(cmd)


text:
Q: Best choice for javascript random number generator Is math.random() a good method for a random/pseudo-random number generator?

A: getRandomInt()
random() is a pseudo-random number as no computer can generate a truly random number, that exhibits randomness over all scales and over all sizes of data sets.

A: The Math.round() function returns the value of a number rounded to the nearest integer.
console.log(Math.round(0.9));
// expected output: 1

console.log(Math.round(5.95), Math.round(5.5), Math.round(5.05));
// expected output: 6 6 5

console.log(Math.round(-5.05), Math.round(-5.5), Math.round(-5.95));
// expected output: -5 -5 -6

I would say the best method for random numbers is math.random().
good luck!

A: The thing is - only software random number generators cannot provide true random numbers, only approximations to them.
The standard JS way via Math.random() is sufficient for most cases.
//standard JS approach
function random(min,max) {
 return Math.floor((Math.random())*(max-min+1))+min;
}

This can be improved a bit if you use the Crypto API. by Kamil Kiełczewski
//using crypto function
function rand(a, b) {
    return a+(b-a+1)*crypto.getRandomValues(new Uint32Array(1))[0]/2**32|0
}

But the purpose of the numbers is also important. Because both approaches produce consecutive equal numbers in the sequence.
If you use random numbers to output dummy images in the prototype phase of a project, for example, you would have identical images one after the other, which you would rather avoid. For this purpose, good random numbers would be those without producing the same number twice in a row. This can only be done by storing the last number and recursion.
//random sequenz without last number repetition
let last = -1
function rand(a, b) {
    const rnd = a+(b-a+1)*crypto.getRandomValues(new Uint32Array(1))[0]/2**32|0
  if (rand === last) {
    return rand(a, b)
  } else {
    last = rnd
    return rnd
  }
}


text:
Q: Put functions into vector and execute I want to make a vector/deque as function container.
This containter must take diffrent functions with diffrent arguments.
Example functions:
program_data::getInstance().function(int,std::string);
program_data::getInstance().foo(int);
program_data::getInstance().exam(int,std::string,double);

And could you show example code how to put these functions with arguments to std::vector / std::deque and execute?
I think that i should use std::function and std::bind but i dont know how to support diffrent functions with diffrent args size.
With arguments -> my functions (called function foo exam from program_data) do some actions using arguments.
For example: normally i execute this function:
program_data::getInstance().function(10,"halo");
And now i want to put these functions to std::vector // deque and execute with arguments which i put with function. i.e (if i put function above to vector and use (pseudocode) vector[0].run(); then my program run function program_data::getInstance().function(int,std::string);)

A: I would suggest using std::function and lambda expressions:
std::vector<std::function<void()>> functions;
functions.push_back([](){ program_data::getInstance().function(123, 456, "str"); });

This adds one function in your vector 'functions'. By calling functions[0](), this will call the lambda expression which then calls your function with 123, 456 and "str" as arguments.

A: Absolutely, use std::vector<std::function<void()>> - that is, a vector of type-erased function containers that can hold any object that is callable without arguments:
std::vector<std::function<void()>> vector;

// populate the vector
vector.push_back([]{ program_data::getInstance().function(10,"halo"); });

// execute items in the vector
vector[0]();

Here I'm populating the vector with a captureless lambda; you can also use lambdas with captures, bind-expressions (std::bind), and other callable objects.
If you use a lambda with a capture, you need to ensure that captured variables are either captured by value or have a lifetime that contains that of the collection of callables:
std::string tmp;
vector.push_back([&tmp]{ program_data::getInstance().something(tmp); });

A: You can use std::function/std::bind. So first of all you need to determine what will you pass to those functions from caller side ie determine function signature. The principle is the same as with virtual functions. So for example you want to pass a sequence number (in which order functions are called) and return nothing:
#include <vector>
#include <functional>

typedef std::function< void( int ) > Function;
typedef std::vector<Function> Functions;

void func1( int seq, const std::string &str );
void func2( const std::string &str );
void func3( int seq );

void run()
{
    Functions functions;
    // populate functions
    functions.push_back( std::bind( func1, std::placeholders::_1, "foobar" ) );
    functions.push_back( std::bind( func2, "foobar too" ) );
    functions.push_back( func3 ); // you can use std::bind here as well, just to show it can be omitted if function signature matches

    // call them
    for( size_t i = 0; i < functions.size(); ++i ) {
        functions[i]( i );
    }
}

Benefit of this method, it can be used for pre c++11 compiler with boost.


text:
Q: Connect to local HBase Hi all
I tried to develop Scala application which will works with HBase and face with one strange issue.
My environment:
Workstation - Ubuntu 14.04 x64
Java - Oracle JDK 1.7

System variables:
~/.bashsr file:
export SCALA_HOME=/usr/local/scala/scala-2.10.5
export PATH=$SCALA_HOME/bin:$PATH
export HBASE_HOME=/usr/local/hbase-0.94.18
export HBASE_CONF=/usr/local/hbase-0.94.18/conf
export PATH="$JAVA_HOME/bin:$HBASE_HOME/bin:/usr/local/bin:/usr/local/sbin:$PATH"
export SPARK_HOME=/usr/local/spark-1.3.1-hd2.4
export PATH=$PATH:$SPARK_HOME/bin

For my application I downloaded and install HBase 0.94.18 (equals version of HBase from AWS EMR 3.9.0 AMI).
HBase configuration files:
1. $HBASE_HOME/conf/hbase-env.sh contains next settings
export HBASE_LOG_DIR=/home/yustas/hbase/logs
export JAVA_HOME=/usr/lib/jvm/java-7-oracle
export HBASE_OPTS="-XX:+UseConcMarkSweepGC -Djava.security.krb5.realm= -Djava.security.krb5.kdc="

*$HBASE_HOME/conf/hbase-site.xml
<configuration>
 <property>
  <name>hbase.rootdir</name>
  <value>file:///home/yustas/hbase/data</value>
 </property>
 <property>
  <name>hbase.zookeeper.property.dataDir</name>
  <value>/home/yustas/hbase/zookeeper</value>
 </property>
 <property>
  <name>hbase.cluster.distributed</name>
  <value>false</value>
</property>
</configuration>

I can start end stop my local HBase by commands:
start-hbase.sh
stop-hbase.sh

Also, I can open shell by hbase shell and create a table and put some data in this table.
I can see my HBase status by Web UI: http://localhost:60010/master-status
Scala program
I have copy of hbase-site.xml file in {PROJECT}/src/main/resource folder and use it as resource.
I try to run very sipmle code:
import org.apache.hadoop.hbase.{HTableDescriptor, HColumnDescriptor, HBaseConfiguration}
import org.apache.hadoop.hbase.client.{HTable, HBaseAdmin}

object DataLoad {
  var tableName: String = "table"
  var tableCF : String = "field_set"
  var hbaseAdmin: HBaseAdmin = null

  def main(args: Array[String]): Unit = {
    val conf = HBaseConfiguration.create()
    hbaseAdmin = new HBaseAdmin(conf)  //program stops responding in this line, and just hanging out.
    if(!hbaseAdmin.tableExists(tableName)){
      val tdesc = new HTableDescriptor(tableName)
      tdesc.addFamily(new HColumnDescriptor(tableCF));
      hbaseAdmin.createTable(tdesc)
    }
    println("HBase: table " + tableName + " available state is " + hbaseAdmin.isTableAvailable(tableName))
  }
}

ISSUE

My code was compiled and run successfully but in line hbaseAdmin = new HBaseAdmin(conf) program stops responding in this line and just hanging out. I waiting ~ 5 min - no changes.

I would like to know where I have got a bug? I can't find this issue in this and other specific sites today.

A: Try to set this properties too in the hbase-site.xml
<property>
 <name>hbase.master</name>
 <value>localhosts:60000</value>
</property>
<property>
 <name>hbase.zookeeper.quorum</name>
 <value>localhost</value>
</property>
<property>
 <name>hbase.zookeeper.property.clientPort</name>
 <value>2181</value>
</property>

A: check your hbase is running like ;
ps -ef | grep hbase, if hbase is not running, execute
$HBASE_HOME/bin/start-hbase.sh

probably, hbase is not running


text:
Q: Form won't preventdefault after first I tried to do a formular with different steps in my codeigniter with bootstrap4 project.
so I created a form:
<form id="myform" class="myform" action="#">
    ...
    <button type="submit">submit</button>
</form>

This is my js code:
$(document).ready(function(){
$(".myform").on("submit", function (event)
    {
        console.log('submit .myform');
        event.preventDefault();
        ajax_call($(this).serialize(),'myform');
    });
});

The "ajax_call" is a function to send the data and handle the result - this function already works fine.
My problem is a little bit simpler but i cant solve it.
If I send the first form the log-message in the console "submit .myform" will display, the form wont submit and the ajax_call-function is running.
As a result I get the same (new) formula with some error messages from the validation.
So if I want to send this form again, the form will submitted and the "$(".myform").on("submit", function (event) ..." code wont work.
maybe its a problem of delegation? But for that I use the ".on" in the js code!?
What I'm doing wrong?

A: You are not doing delegation, you need to your first selector to bind to a static element and the second parameter for the on function should be your form selector
$("body").on("submit", ".myform", function (event)


text:
Q: Getting Susy and Compass installed with ruby on rails I'm just starting with ruby on rails and one of the first things I tried to do was install the gems compass and susy. After figuring out that I needed to include them in the gemfile (I'm using RubyMine and thought it would do it for me), I still got a missing "Could not find", "susy" error when I tried to import susy into one of my css.scss files.
I have ruby version 1.9.3 (194)
and ruby gems version 1.8.23
Any help on which gems (and versions) I need in my bundle, how to make sure they get in the project bundle, is greatly appreciated.

A: I'm on rails 3.2.7 and use Susy (and Compass) like this.
##### Gemfile:
group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'
  gem 'compass-rails'
  gem 'susy', git: "git://github.com/ericam/susy.git"
  gem 'uglifier', '>= 1.0.3'
end

Then I have several different css files.
application.css.scss, screen.css.scss and _base.scss.css.
application.css.scss
#### application.css.scss:
@import "screen";
# Here you import your normal .scss files as well, like:
# @import "products";

screen.css.scss
#### screen.css.scss
// ---------------------------------------------------------------------------
// Imports
@import "compass";
@import "base";

/* -------------------------------------------------------------------------*/
/* Layout */
// Here you can add layout styling or whatever... :)

_base.css.scss
// ---------------------------------------------------------------------------
// Imports

@import "susy";

// ---------------------------------------------------------------------------
// Basic Grid

$total-columns  : 12;
$column-width   : 4em;
$gutter-width   : 1em;
$grid-padding   : $gutter-width;

$show-grid-backgrounds  : true;

And that's it. Now you can use Susy in all your scss files that you import in application.css.scss.
I hope it helps you to get started.


text:
Q: Specialize function for map like containers I want specialize a function template for vector and map like containers. For vector I can do like below but I don't know how can I have a specialized version of the function that will be used only for map like containers.
#include <iostream>
#include <vector>
#include <map>

using namespace std;

template<typename Iterator>
void print(Iterator begin, Iterator end)
{
    while (begin != end)
    {
        cout << *begin << endl; // compiler error for map like containers
        ++begin;
    }
}

int main()
{
    vector<int> noVec = { 1, 2, 3 };

    print(noVec.begin(), noVec.end());

    map<int, int> nosMap;
    nosMap[0] = 1;
    nosMap[1] = 2;
    nosMap[3] = 3;

    print(nosMap.begin(), nosMap.end());

    return 0;
}

This question is similar but it suggests to use pair in vector which I don't want to do. I know the specialization can be done with SFINAE but don't know what condition to check for. It would be great if I can achieve this with C++ 11 type_traits.

A: The value_type of a map is some pair so you could check if the value_type of the iterator is a std::pair or not, e.g.
#include <vector>
#include <map>
#include <iostream>

template <typename>
struct is_pair : std::false_type
{ };

template <typename T, typename U>
struct is_pair<std::pair<T, U>> : std::true_type
{ };

template <typename Iter>
typename std::enable_if<is_pair<typename std::iterator_traits<Iter>::value_type>::value>::type
print(Iter begin, Iter end)
{
  std::cout << "called with map-like" << std::endl;
  for (; begin != end; ++begin)
  {
    std::cout << begin->second;
  }
  std::cout << std::endl;
}

template <typename Iter>
typename std::enable_if<!is_pair<typename std::iterator_traits<Iter>::value_type>::value>::type
print(Iter begin, Iter end)
{
  std::cout << "called with vector-like" << std::endl;
  for (; begin != end; ++begin)
  {
    std::cout << *begin;
  }
  std::cout << std::endl;
}

int main()
{
  std::vector<int> vec { 1, 2, 3 };
  std::map<int, int> map {{0, 0}, {1, 1}, {2, 4}, {3, 9}};

  print(vec.begin(), vec.end());
  print(map.begin(), map.end());
}

which prints
called with vector-like
123
called with map-like
0149

A: You don't need to specialize anything. All you have to do is to provide an overloaded output operator<< for std::pair, like the example below:
template<typename T1, typename T2>
std::ostream& operator<<(std::ostream &out, std::pair<T1, T2> const &mp) {
  return (out << "(" << mp.first << ", " << mp.second << ")");
}

LIVE DEMO

edit:
The above solution however as @Benjamin Lindley suggested in the comments might conflict with other template overloads of the output operator<< for std::pair.
If this is the case, alternatively you could write in their own namespace (e.g., namespace detail) two template function overloads (e.g., print_elem), like the example below:
namespace detail {
  template<typename T1, typename T2>
  std::ostream& print_elem(std::ostream &out, std::pair<T1, T2> const &mp) {
    return (out << "(" << mp.first << ", " << mp.second << ")");
  }

  template<typename T>
  std::ostream& print_elem(std::ostream &out, T const &elem) {
      return (out << elem);
  }
}

and change your template print like the example below:
template<typename Iterator>
void print(Iterator begin, Iterator end)
{
    while (begin != end) {
        detail::print_elem(cout, *begin) << endl;
        ++begin;
    }
}

LIVE DEMO


text:
Q: JSF : Passing data between 2 views I'm a french computer science student, and I have a small JSF project for school. I'm a little bit noob and I try to pass data between 2 view but I fail.
First I have a view which list all my customers, in a datatable. In this datatable I have a link to show a customer profile. I use, for both view, a CustomerController which is a requestscoped managedbean.
Before I use a global sessionscoped controller but I think it's not the good way to pass data.
Then I found this article :  JSF Best Practices, it recommend to use  to pass object between views. I didn't manage to make it work.
And finally I found also this question from Stackoverflow : f:setPropertyActionListener sets null value instead of intended value which use
My question is : what is the best ways to pass data ? And how manage it ?

A: It's explained in this article from BalusC. You need to send id of your selected item to second view through h:link and catch it then with <f:event>.


text:
Q: Reading line-by-line file in JavaScript on client side Could you please help me with following issue.
Goal
Read file on client side (in browser via JS and HTML5 classes) line by line, without loading whole file to memory.
Scenario
I'm working on web page which should parse files on client side. Currently, I'm reading file as it described in this article.
HTML:
<input type="file" id="files" name="files[]" />

JavaScript:
$("#files").on('change', function(evt){
    // creating FileReader
    var reader = new FileReader();

    // assigning handler
    reader.onloadend = function(evt) {
        lines = evt.target.result.split(/\r?\n/);

        lines.forEach(function (line) {
            parseLine(...);
        });
    };

    // getting File instance
    var file = evt.target.files[0];

    // start reading
    reader.readAsText(file);
}

The problem is that FileReader reads whole file at once, which causes crashed tab for big files (size >= 300 MB). Using reader.onprogress doesn't solve a problem, as it just increments a result till it will hit the limit.
Inventing a wheel
I've done some research in internet and have found no simple way to do this (there are bunch of articles describing this exact functionality but on server side for node.js).
As only way to solve it I see only following:

*

*Split file by chunks (via File.split(startByte, endByte) method)

*Find last new line character in that chunk ('/n')

*Read that chunk except part after last new line character and convert it to the string and split by lines

*Read next chunk starting from last new line character found on step 2

But I'll better use something already existing to avoid entropy growth.

A: Update: check LineNavigator from my second answer instead, that reader is way better.
I've made my own reader, which fulfills my needs.
Performance
As the issue is related only to huge files performance was the most important part.

As you can see, performance is almost the same as direct read (as described in question above).
Currently I'm trying to make it better, as bigger time consumer is async call to avoid call stack limit hit, which is not unnecessary for execution problem. Performance issue solved.
Quality
Following cases were tested:

*

*Empty file

*Single line file

*File with new line char on the end and without

*Check parsed lines

*Multiple runs on same page

*No lines are lost and no order problems

Code & Usage
Html:
<input type="file" id="file-test" name="files[]" />

Usage:
$("#file-test").on('change', function(evt) {
    var startProcessing = new Date();
    var index = 0;
    var file = evt.target.files[0];
    var reader = new FileLineStreamer();
    $("#output-test").html("");

    reader.open(file, function (lines, err) {
        if (err != null) {
            $("#output-test").append('' + err + "
");
            return;
        }
        if (lines == null) {
            var milisecondsSpend = new Date() - startProcessing;
            $("#output-test").append("" + index + " lines are processed Miliseconds spend: " + milisecondsSpend + "
");
            return;
        }

        // output every line
        lines.forEach(function (line) {
            index++;
            //$("#output-test").append(index + ": " + line + "
");
        });

        reader.getNextBatch();
    });

    reader.getNextBatch();
});

Code:
function FileLineStreamer() {
    var loopholeReader = new FileReader();
    var chunkReader = new FileReader();
    var delimiter = "\n".charCodeAt(0);

    var expectedChunkSize = 15000000; // Slice size to read
    var loopholeSize = 200;         // Slice size to search for line end

    var file = null;
    var fileSize;
    var loopholeStart;
    var loopholeEnd;
    var chunkStart;
    var chunkEnd;
    var lines;
    var thisForClosure = this;
    var handler;

    // Reading of loophole ended
    loopholeReader.onloadend = function(evt) {
        // Read error
        if (evt.target.readyState != FileReader.DONE) {
            handler(null, new Error("Not able to read loophole (start: )"));
            return;
        }
        var view = new DataView(evt.target.result);

        var realLoopholeSize = loopholeEnd - loopholeStart;

        for(var i = realLoopholeSize - 1; i >= 0; i--) {
            if (view.getInt8(i) == delimiter) {
                chunkEnd = loopholeStart + i + 1;
                var blob = file.slice(chunkStart, chunkEnd);
                chunkReader.readAsText(blob);
                return;
            }
        }

        // No delimiter found, looking in the next loophole
        loopholeStart = loopholeEnd;
        loopholeEnd = Math.min(loopholeStart + loopholeSize, fileSize);
        thisForClosure.getNextBatch();
    };

    // Reading of chunk ended
    chunkReader.onloadend = function(evt) {
        // Read error
        if (evt.target.readyState != FileReader.DONE) {
            handler(null, new Error("Not able to read loophole"));
            return;
        }

        lines = evt.target.result.split(/\r?\n/);
        // Remove last new line in the end of chunk
        if (lines.length > 0 && lines[lines.length - 1] == "") {
            lines.pop();
        }

        chunkStart = chunkEnd;
        chunkEnd = Math.min(chunkStart + expectedChunkSize, fileSize);
        loopholeStart = Math.min(chunkEnd, fileSize);
        loopholeEnd = Math.min(loopholeStart + loopholeSize, fileSize);

        thisForClosure.getNextBatch();
    };

    this.getProgress = function () {
        if (file == null)
            return 0;
        if (chunkStart == fileSize)
            return 100;
        return Math.round(100 * (chunkStart / fileSize));
    }

    // Public: open file for reading
    this.open = function (fileToOpen, linesProcessed) {
        file = fileToOpen;
        fileSize = file.size;
        loopholeStart = Math.min(expectedChunkSize, fileSize);
        loopholeEnd = Math.min(loopholeStart + loopholeSize, fileSize);
        chunkStart = 0;
        chunkEnd = 0;
        lines = null;
        handler = linesProcessed;
    };

    // Public: start getting new line async
    this.getNextBatch = function() {
        // File wasn't open
        if (file == null) {
            handler(null, new Error("You must open a file first"));
            return;
        }
        // Some lines available
        if (lines != null) {
            var linesForClosure = lines;
            setTimeout(function() { handler(linesForClosure, null) }, 0);
            lines = null;
            return;
        }
        // End of File
        if (chunkStart == fileSize) {
            handler(null, null);
            return;
        }
        // File part bigger than expectedChunkSize is left
        if (loopholeStart < fileSize) {
            var blob = file.slice(loopholeStart, loopholeEnd);
            loopholeReader.readAsArrayBuffer(blob);
        }
        // All file can be read at once
        else {
            chunkEnd = fileSize;
            var blob = file.slice(chunkStart, fileSize);
            chunkReader.readAsText(blob);
        }
    };
};

A: I have written a module named line-reader-browser for the same purpose. It uses Promises.
Syntax (Typescript):-
import { LineReader } from "line-reader-browser"

// file is javascript File Object returned from input element
// chunkSize(optional) is number of bytes to be read at one time from file. defaults to 8 * 1024
const file: File
const chunSize: number
const lr = new LineReader(file, chunkSize)

// context is optional. It can be used to inside processLineFn
const context = {}
lr.forEachLine(processLineFn, context)
  .then((context) => console.log("Done!", context))

// context is same Object as passed while calling forEachLine
function processLineFn(line: string, index: number, context: any) {
   console.log(index, line)
}

Usage:-
import { LineReader } from "line-reader-browser"

document.querySelector("input").onchange = () => {
   const input = document.querySelector("input")
   if (!input.files.length) return
   const lr = new LineReader(input.files[0], 4 * 1024)
   lr.forEachLine((line: string, i) => console.log(i, line)).then(() => console.log("Done!"))
}

Try following code snippet to see module working.

      <title>Testing line-reader-browser</title>

      <input type="file">

Hope it saves someone's time!

A: Eventually I've created new line-by-line reader, which is totally different from previous one.
Features are:

*

*Index-based access to File (sequential and random)

*Optimized for repeat random reading (milestones with byte offset saved for lines already navigated in past), so after you've read all file once, accessing line 43422145 will be almost as fast as accessing line 12.

*Searching in file: find next and find all.

*Exact index, offset and length of matches, so you can easily highlight them

Check this jsFiddle for examples.
Usage:
// Initialization
var file; // HTML5 File object
var navigator = new FileNavigator(file);

// Read some amount of lines (best performance for sequential file reading)
navigator.readSomeLines(startingFromIndex, function (err, index, lines, eof, progress) { ... });

// Read exact amount of lines
navigator.readLines(startingFromIndex, count, function (err, index, lines, eof, progress) { ... });

// Find first from index
navigator.find(pattern, startingFromIndex, function (err, index, match) { ... });

// Find all matching lines
navigator.findAll(new RegExp(pattern), indexToStartWith, limitOfMatches, function (err, index, limitHit, results) { ... });

Performance is same to previous solution. You can measure it invoking 'Read' in jsFiddle.
GitHub: https://github.com/anpur/client-line-navigator/wiki


text:
Q: Angular 4 using setter on @ViewChild I have a demo here
I'm trying to get the height of an element after it is added to the DOM with *ngIf
I'm trying to do this by using a setter on the @ViewChild, the setter should be called one the *ngIf becomes true.
In my example it only seems to work when the element has been added then removed (button is clicked twice).
How can I get this to work when the element is firsy shown.
I know I can do this with [hidden] instead of *ngIf but my actual code has a lot of elements that I dont want to put in the DOM at once
import { Component, Input, ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'child-comp',
  templateUrl: './child.component.html'
})

export class ChildComponent{

  @Input() parent: ElementRef;

  private blockThree: ElementRef;

  @ViewChild('blockThree') set content(content: ElementRef) {
    this.blockThree = content;
  }

  showThree: boolean = false

  blockHeightThree: number

  constructor(){ }

  showBlockThree(){
    this.showThree = !this.showThree
    this.blockHeightThree = this.blockThree.nativeElement.clientHeight;
    console.log('element height '+this.blockHeightThree);
  }

}

A: The reason it only works second time is, that the this.showThree = !this.showThree does not call the setter right away, because whole function finishes first, only then angular actually detects the changes and puts the element in place. It will work if you move the height reading logic into the setter.
That means you cannot read blockHeightThree in the showBlockThree function, because the block three simply is not there yet. But there is an inelegant solution to that. You can put setTimeout() there so the height is read asnychronously. Maybe it would do what you need.
Working Demo
    @ViewChild('blockThree') set content(content: ElementRef) {
      console.log("block three", content)
      this.blockThree = content;
      if (this.blockThree) {
        this.blockHeightThree = this.blockThree.nativeElement.clientHeight;
        console.log(this.blockThree.nativeElement.clientHeight);
       }
    }

    showBlockThree() {
      this.showThree = !this.showThree
      console.log('element height ' + this.blockHeightThree);
      setTimeout(()=> console.log("async block three", this.blockHeightThree));
    }


text:
Q: Как найти максимальное из трех чисел? в программе должно сравниваться три значения, и большее из них должно присваиваться к четвертому значению.
Выглядят ifы примерно так:
if (m1 > m2)
{
    m1 = Mmax;
}
else
{
    m2 = Mmax;
}
if (m2 > m3)
{
    m2 = Mmax;
}
else
{
    m3 = Mmax;
}
if (m3 > m1)
{
    m3 = Mmax;
}
else
{
    m1 = Mmax;
}

A: Если я правильно понял вопрос, и надо найти наибольшее из трех, то всё проще, чем кажется
max = a;
if (b > a)
    max = b;
if (c > max)
    max = c;

Или с использованием тернарного оператора
max = b > a ? b : a;
max = max > c ? max : c;

Или с помощью System.Math
max = Math.Max(a, Math.Max(b, c));

Или с помощью System.Linq
max = new[] { a, b, c }.Max();


text:
Q: Get month from DATETIME in sqlite I am trying to get extract the month from a DATETIME field in SQLite. month(dateField) does not work as well as strftime('%m', dateStart).
Any ideas?

A: I don't understand, the response is in your question :
select strftime('%m', dateField) as Month ...

A: This is a solution without all the case when statements. Hopefully it's helpful.
select substr('JanFebMarAprMayJunJulAugSepOctNovDec', 1 + 3*strftime('%m', date('now')), -3)

A: SELECT strftime('%m', datefield) FROM table

If you are searching the month name, text month names does not seems to be supported by the core distribution of SQLite

A: I guess strftime('%m', dateStart) is not working for you because dateStart variable is date/datetime type.
Then you must use:
strftime('%m', date(dateStart))

A: I'm guessing you want to get the month as a string. Not the most friendly looking but you probably see the point. Just replace date('now') with your variable.
select case strftime('%m', date('now')) when '01' then 'January' when '02' then 'Febuary' when '03' then 'March' when '04' then 'April' when '05' then 'May' when '06' then 'June' when '07' then 'July' when '08' then 'August' when '09' then 'September' when '10' then 'October' when '11' then 'November' when '12' then 'December' else '' end
as month

A: Try using the following:
select strftime('%m', datetime(datefield, 'unixepoch')) as month from table

A: After all those years I think I figured out what was your problem.
You probably store your dates as strings.
This way when you search for data  from let's say May you should write sql like this:
Select * from table where strftime('%m', datefield) = '05'
It's important to write '05' and not '5'. Using '5' will give you zero results.

A: Here is my solution that worked for me
MONTH_DICT={ "Jan" : '01', "Feb" : '02', "Mar" : '03', "Apr" : '04', "May" : '05', "Jun" : '06', "Jul" : '07', "Aug" : '08', "Sep" : '09', "Oct" : 10, "Nov" : 11, "Dec" : 12 }

self.cursor.execute("SELECT * FROM error_log WHERE strftime('%m',Date_column)=?",(MONTH_DICT[query_month],))

print('output:', self.cursor.fetchall())

A: SQLLite does not support monthnames, you need to use substr(Date, 4, 2) as month to get the months

%sql select substr(date,4,2) as month from ;

A: SELECT strftime('%m',datetime_col) as "Month" FROM table_name;
just replace 'datetime_col' with your datetime column


text:
Q: Appending Data from CSV File on Web to Table in Microsoft Power BI There is a CSV data source online that publishes the latest data on COVID-19 cases in Austria.
https://www.data.gv.at/katalog/dataset/2809273e-d0bc-4eb3-a7d3-d01ef2168809
The CSV file consists of one row with the latest number (cases, recovered, hospitalized, deaths, etc). I would like to take the data each time that the CSV file is updated, and add the new data to a new row in a table so that I have a complete set of data. Alternatively, is there a way for me to grab all the data from the source (not just a one row latest update)? From the website, it appears they only make the latest row available. The data is updated approximately 2-3 times a day.
I have searched extensively online and cannot seem to find an answer. I have set up the CSV file as a data source. I also copied and pasted the data into a new query, which can serve as my complete data source. So I have two tables (AllgemeinDaten and Old Data).
I create a new query appending the source (AllgemeinDaten) with Old Data, but it doesn't create a new row keeping the old data from AllgemeinDaten and the new changed data from AllgemeinDaten.


text:
Q: Load a XAML Layout dynamically based on User interaction Good day, I am quite new to windows phone and so please bear with me. I have a requirement to load a XAML layout based on what the user chooses. For example, if i have 4 XAML layouts A, B, C, D, when the user chooses C, the respective XAML layout should be loaded and if A is choosen later, that should come up. I can create different XAML layouts and use the OnNavigateTo Method, but i think its not very efficient. Is there a way, i can group the XAML Layouts together so that it can switch between them easily?.. I have heard of using templates, but can't really find any concrete example of how it works. Any help or links will be greatly appreciated. Thank you.

A: From my understanding you do not need to use templates. Since there are four different actions that have four different views associated with them, there shouldn't really be a problem with having a separate page for each action.
The problem might also be this - how different are the layouts? If data is the only thing that changes across them, you might think about having a view model to bind to and simply change the bindable source.
Bottom line: just use pages, or a single page bound to dynamic data, depending on your scenario.

A: In my knowledge , I ask you to prefer the UserControls implementation in your UI. You can have A,B,C and D layouts as a separate UserControls and can have those UserControls in the same page. Just make the visibility changes based on the condition that recognize it in the code behind. I think it may help you.

A: You can solve this in many different ways. If you are not supposed to load the layout on the same page, create 4 separate pages for each view and navigate to correct page.
If you are required to update the current view, you can choose one of the following:
 - Place all four layouts into each own Grid and set Visibility="Collapsed" for each one. Then, when you need to show a layout, simply change its Visibility to True.
 - Same as above, but use Visual States to add some animations.
 - Create 4 user controls and dynamically create the one you need and add it to the current page.
You need to account for several factors here:
 - Clean code and clean design.
 - Animations and transitions.
 - What about Back key? If user is supposed to navigate back to selection screen once he is done, consider navigating to separate pages.
Don't forget the last point, it may be crucial when choosing the right solution.


text:
Q: How to compare inside list values in python I have to find 6 distincts words in a bunch of lists. For example in first list, there will be word 'me', in second word 'us'.
I've already found the line number using this code:
def creatList(file):
try:
    for i,line in enumerate(file,1):

and pass found values to another function,
line=(line.rstrip()).split()
rawList=[]

rawList.append(line)

creatRuleFile(i,rawList)

inside that function,
def creatRuleFile(p,new):
   print(new)
   print("{0}. {1}".format(p, new))
   lookup ='me'
   if p==1:
      print('found at line:', lookup)

my code is not working as I want... appreciate if you can suggest an answer. Thank you.

A: Has been answered before:
Python: Find in list
use something like
stuff_I_want_to_find = "whatever"
if stuff_I_want_to_find in myList:
    index = myList.find(stuff_I_want_to_find)

now you have to iterate over your lists and over your words, which will essentially be two loops.


text:
Q: Legacy CE vs current I recently updated a SQL server to the current version. I have major performance issues with some queries for example this query takes 8 seconds with legacy CE:
But 5 minutes with CE 150:
https://www.brentozar.com/pastetheplan/?id=Bkj1RbGrP
I updated statistics for the whole DB and ran a full scan update to the tables in this query.
Any idea how can I fix this performance issue?

A: Microsoft has guidance for your scenario where upon upgrading you experience query performance degradation. You may not be able to follow the exact steps outlined here if you were upgrading from a version without Query Store, but the general principles are still the same. It is expected that some queries will run slower after upgrade as Microsoft makes changes to the cardinality estimator. A first defense against that is to find the queries that are running for too long and to force them to use a previous plan. Methods of doing that:

*

*Forcing a previous good plan with Query Store

*Setting compatibility level at the database level or query level

*Enabling the legacy CE at the database level or query level

For the root cause of why this particular query is slow, 98% of the query's time is spent on a nested loop join against Object4. It is hard to give specifics for an anonymized plan, but the following broad principles apply:

*

*Use a temp table or some other method to improve the cardinality estimate coming into the nested loop join. The optimizer is likely picking a loop join because the estimate is just 1 row.

*Define an index on Object4 which allows for more effective seeking against that table. This can only be a partial fix and won't get the query execution time down to 8 seconds.

*If required, force a different join type for the table access on Object4. The nested loop join reads a total of 173,354,476 rows from a table with just 38,775 rows. A hash or merge join would be more efficient.

*If required, achieve a different join order.

As a final note, you really can't expect to get good cardinality estimates for query constructs like this:
Function2(Function3(Object3.Column38)) LIKE Function2(Function3(Object2.Column11)) + ?

It may be true that the legacy cardinality estimator gives you good performance just due to luck. To keep the same performance on a newer CE you may need to use the invasive techniques that I described above.


text:
Q: Azure App Insights Authentication with Python Requests I'm trying to authenticate with Azure AD in order to access the Azure Insights REST API, so that I can ultimately access Azure web apps. However, the authentication example in their documentation is limited to C# and PowerShell. I am trying to do the same thing, but with the Python requests library. This is what I have so far, but I am getting a '404 not found' response back. Any ideas on how I can authenticate to the Insights API using the Python requests library?
AUTH = 'https://login.windows.net/%s' % TENANT_ID
RESOURCE = 'https://management.azure.com/'

def auth():
    s = requests.Session()

    params = {
        'grant_type': 'client_credentials',
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_KEY,
        'resource': RESOURCE
    }

    response = s.post(AUTH, params=params)
    print response.url
    print response.status_code
    print response.reason

auth()

EDIT 1:
The updated auth URL fixed it. Thank you. However, I would still like to exclusively use the Python requests library to get the web apps/resource groups.
RESOURCE_VERSION = '2015-01-01'

RESOURCE_URI = 'https://management.azure.com/subscriptions/%s/resourcegroups' % (SUBSCRIPTION_ID)

s = requests.Session()
payload = {
    'grant_type': 'client_credentials',
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_KEY,
    'resource': RESOURCE
}

response = s.post(AUTHENTICATION_CONTEXT, data=payload).json()
access_token = response['access_token']

s.headers = {
    'Authorization': 'Bearer %s' % access_token,
    'Content-Type': 'application/json'
}

s.params = {
    'api-version': RESOURCE_VERSION
}

response2 = s.get(RESOURCE_URI).json()
print response2

This gives me the following output
{u'error': {u'message': u"The client 'CLIENT_ID' with object id 'OBJECT_ID' does not have authorization to perform action 'Microsoft.Resources/subscriptions/resourcegroups/read' over scope '/subscriptions/SUBSCRIPTION_ID'.", u'code': u'AuthorizationFailed'}}

Based off the response, it seemed like it may be a permissions issue in my Azure app, but I've given the app all the permissions I think it has to have and it still gives me the same error message.

A: The authentication endpoint is incomplete. And in .Net, it is wrapped in .Net SDK, and the complete endpoint for authentication token looks like: https://login.microsoftonline.com/<tenant_id>/oauth2/token
Here is the code snippet:
from azure.mgmt.common import SubscriptionCloudCredentials
from azure.mgmt.resource import ResourceManagementClient
import requests

def get_token_from_client_credentials(endpoint, client_id, client_secret):
    payload = {
        'grant_type': 'client_credentials',
        'client_id': client_id,
        'client_secret': client_secret,
        'resource': 'https://management.core.windows.net/',
    }
    response = requests.post(endpoint, data=payload).json()
    return response['access_token']

auth_token = get_token_from_client_credentials(
    endpoint='https://login.microsoftonline.com/<tenant_id>/oauth2/token',
    client_id='<client_id>',
    client_secret='<client_secret>',
)
subscription_id = '<subscription_id>'
creds = SubscriptionCloudCredentials(subscription_id, auth_token)

resource_client = ResourceManagementClient(creds)
resource_group_list = resource_client.resource_groups.list(None)
rglist = resource_group_list.resource_groups
print rglist

You can refer to Resource Management Authentication for more information.


text:
Q: How to use ExtJS FormPanel with JSF 2.0 Im trying to use ExtJS FormPanel with JSF 2.0 + MyFaces 2.0.4. ExtJS is a great JavaScript framework at all. But it doesnt use DOM of Page. So the main problem starts with here. To put JSF beans in work i must put h:form tag inside the XHTML(or handle viewstate) since it must synchronize with ViewState.
But ExtJS doesnt aware of THE ViewState. How can i make ExtJS aware of THE ViewState and synchronize at all. I wish to put it in FormPanel....items:[{.....}]. But couldnt find any way.
And one more thing; There may be two or more form on a single page. If i cant put it in ExtJS items[{...}] how can i do each forms management.
Thank you.

A: I've used both of these frameworks pretty extensively, and I think you're barking up the wrong tree here. By the time you figure out how to couple these into the JSF lifecycle, I think you could have written the REST resources on your server with that Ext could consume.
Or if you are sticking with JSF, you could try Primefaces or one of the many other JSF component libraries if you're looking for some snazzy data grids. They aren't as nice as Extjs, but if you are a JSF shop it is worth looking into.
There's also Ext GWT, which has nothing to do with JSF of course, but I've never used that.


text:
Q: How to add space How to add space to string.
example:
"Hiwatsup?"
or
"hi,hello"
return
"hi hello"
or
"hi"
"hello"

A: For "hi,hello" you can just replace the "," for a whitespace:
hi = "hi,hello"
print hi.replace(",", " ")

you can also obtain a list of substrings split by a certain character:
print hi.split(',')

but what I really advise doing is looking at the documentation for str:
help(str)

A: Like this
s = "hi,hello"
t = s.split(',')
print ' '.join(t)

And for the other one
>>> s = "Hiwatsup?"
>>> print s[:2] + ' ' + s[2:]
Hi watsup?

Instead of printing, you can assign it to another variable too.


text:
Q: Visual Studio 2012 does not create new SQL table I want to create a simple SQL table in Visual Studio 2012 that th id field is Auto increment primary key, so I do like this :

But when I want to Update  and create table it errors :

** Highlights
     Tables that will be rebuilt
       None
     Clustered indexes that will be dropped
       None
     Clustered indexes that will be created
       None
     Possible data issues
       None

** User actions
     Create
       [dbo].[sotbl] (Table)
       Default Constraint on [dbo].[sotbl].[Id] (Default Constraint)

** Supporting actions

Creating [dbo].[sotbl]... Creating Default Constraint on
  [dbo].[sotbl].... (86,1): SQL72014: .Net SqlClient Data Provider: Msg
  1754, Level 16, State 0, Line 1 Defaults cannot be created on columns
  with an IDENTITY attribute. Table 'sotbl', column 'Id'. (86,1):
  SQL72014: .Net SqlClient Data Provider: Msg 1750, Level 16, State 0,
  Line 1 Could not create constraint. See previous errors. An error
  occurred while the batch was being executed.

A: Remove the default value from the Id column definition.
If it is an identity column the initial entry will be set to the 'Identity Seed' value and subsequent records will be updated based on the 'Identity Increment' value.


text:
Q: Get Current Financial Year In Acumatica Generic Inquiry Is there a way to retrieve the current financial year in Acumatica when building a GI? I have already built a generic inquiry and wanted to limit it to display only the current financial year transactions. I have already joined the Financial Periods table but cannot make this work unless I hardcode the financial year in the parameters
Thanks,
G

A: There is no notion of "current" financial year - you can have multiple financial years open at once. What you could do is retrieve the earliest one open through the FinPeriod table.

A: I was able to do something useful with the Month(Today()) and Year(Today()) feature when writing a formula, I am not sure this was available months ago :) I can now compare the financial year based on the current month and current year (when month > 7, jump to the next year, otherwise the current year). This way, I can pick the FinPeriodID I was after.


text:
Q: Cannot create container groups using @azure/arm-containerinstance I am trying to create container groups unsing azure javascript package @azure/arm-containerinstance but there is very little documentation on an I am struggling to make it work. This is the code that I have implemented :
const name = "SOMECONTAINERNAME";
const image = "someregisterylink.com/somename/someimage:latest-sometag";
const port = 6901;
const environmentVariables = {
  VAR1: "SOMEVAR",
  VAR2: "SOMEVAR"
};

const containerResourceRequests = {
  memoryInGB:1.5,
  cpu:1
};

const containerResourceRequirements = {
  requests:containerResourceRequests
}

const container = {
  image: image,
  resources: containerResourceRequirements,
  command: ['/bin/bash','-c','echo $PATH'],
  ports: [{port: port}],
  environmentVariables: environmentVariables
};
const cgroup_os_type = "Linux";
const cgroup_ip_address = {
  type: 'public',
  ports: [{protocol: "TCP", port: port}]
}

const image_registry_credentials=null;
const cgroup = {
  location: 'westus',
  containers: [container],
  os_type:cgroup_os_type,
  ip_address: cgroup_ip_address
  //image_registry_credentials: image_registry_credentials
}

var response = await azclient.containerGroups.beginCreateOrUpdate(
  resourceGroupName=config.resourceGroup,
  containerGroupName=name,
  cgroup);
console.log(response);

The response is very verbose but this doesn't show any error, and nothing is created on the azure resourcegroup.

A: You can take reference of this Github source Code to create container groups using Azure ContainerInstanceManagement client library for JavaScript.
There is few Prerequisites that you requires .
Install the @azure/arm-containerinstance package.
Install the Azure ContainerInstanceManagement client library for JavaScript with npm:
Currently supported environments

*

*LTS versions of Node.js.

*Latest versions of Safari, Chrome, Edge and Firefox.

For Detailed information Please refer this dcoument


text:
Q: Ext JS mvc: how disable button from controller I have a Ext.grid.Panel which has a button defined as the following
 this.buttons = [ {
            id: 'addInfoBtn',
            text : 'Add Info',
            action: 'createinfo'
        }];

What i want to do is enable/disable this button when the screen loads based on a value i am receiving in the controller. I have the following function in the controller that is receiving either true or false and setting the disabled value to this.
,isDisabled: function() {
        var edit = this.getUrlParams('edit');
        var addInfoBtn = Ext.ComponentQuery.query('#addInfoBtn')[0];
        addInfoBtn.setDisabled(edit);
        console.log(addInfoBtn);
    }

this method is being called when the panel has been rendered by the controller
,init: function() {
        this.control({
           'infolist': {
                itemdblclick: this.viewInfo,
                render: this.isDisabled
            }

I can see from the console that the value of the addInfoBtn.setDisabled() has been set to true but the button is still clickable, what am i doing wrong?


text:
Q: Dispose user created bindingContext knockout In our scenario need to create ko template inside js-render template. Need to create grid like item where

...

....

Ko template

Here we need to create childcontext which is used to render those ko template elements with data.
How we can dispose the child binding context created ?
The concept is to have grid like appearance and we bind datasource (records) to table. Inside table we have the ko template, since we need to bind this template with data externally i am creating new binding context for it with data iteration
 bindingContext = new ko.bindingContext();
        if (!ej.isNullOrUndefined(index)) {
            if (!bindingContext.items)
                bindingContext.items = [];
            bindingContext.items[index] = data;
        } else {
            index = 1;
            bindingContext.items = [data];
        }

and render it using renderTemplate method
for (var i = 0; i < el.length;i++) {
                ko.renderTemplate(template.replace("#", ""), tmpl[template]["bindingContext"]["items"][i], {}, el[i]);
            }


text:
Q: How do I reverse individual words in a string in VBA? I've managed to reverse the string as a whole using the code below:
Dim str As Variant
Dim i As Integer, strLen As Integer
Dim NewStr As String

str = "VBA is amazing"

strLen = Len(str)
NewStr = ""

For i = 1 To strLen
  NewStr = NewStr & Mid(str, strLen - (i - 1), 1)
Next i

MsgBox (NewStr)

The outcome is: gnizama si ABV, but I want it to be: ABV si gnizama
Goal is not to use Split or StrReverse.

A:
Goal is not to use Split or StrReverse.

But those are what to use:
    Dim Straight    As String
    Dim Reversed    As String
    Dim Index       As Long
    Dim Words()     As String

    Straight = "VBA is amazing"
    Words = Split(Straight)

    For Index = LBound(Words) To UBound(Words)
        Words(Index) = StrReverse(Words(Index))
    Next

    Reversed = Join(Words)
    Debug.Print Reversed

    ' ABV si gnizama

If not, you must either roll your own substitutes or run a double loop indentifying spaces and, between these, collect and reverse the words. Slow, but doable.

A: Solution without Split or StrReverse:
Sub RevWords(Optional str As String = "VBA is amazing")
    ' RegExp: need to switch on «Microsoft VBScript Regular Expression 5.5» in menu «Tools/References»
    Dim RegEx As New RegExp
    Dim res As Object, revStr As String, i As Integer, s As Variant

    With RegEx
        .Global = True
        .Pattern = "([^ ]+)"
        Set res = .Execute(str)
    End With

    For Each s In res
        e = Len(s)
        Do While e > 0
            revStr = revStr & Mid(s, e, 1)
            e = e - 1
        Loop
        revStr = revStr & " "
    Next

    Debug.Print str & " >> " & Trim(revStr)
End Sub

' output: VBA is amazing >> ABV si gnizama

A: Try this:
Function CustomReverse(inputString As String) As String
    Dim wordSeparator As String, reversedString As String
    Dim i As Integer, j As Integer, k As Integer, vector As Integer
    reversedString = inputString
    wordSeparator = " "

    i = 0
    j = 1
    Do
        i = InStr(i + 1, inputString, wordSeparator, vbTextCompare)
        If i = 0 Then i = Len(inputString) + 1
        For k = j To i - 1
            If Mid(reversedString, k, 1) = wordSeparator Then Exit For
            vector = i - k - 1
            Mid(reversedString, k, 1) = Mid(inputString, j + vector, 1)
        Next
        j = i + 1
    Loop While i > 0 And j < Len(inputString)

    CustomReverse = reversedString

End Function

Usage:
Sub Test()
    Debug.Print CustomReverse("VBA is amazing")
    'prints: "ABV si gnizama"
End Sub

A: Not sure why you don't want to use Split and StrReverse. The implementation is easy:
Sub Test()
    Dim s As String
    Dim words() As String
    Dim i As Long
    Dim word As Variant

    s = "VBA is amazing"

    words = Split(s, " ")

    i = LBound(words, 1)
    For Each word In words
        words(i) = StrReverse(word)
        i = i + 1
    Next word

    MsgBox Join(words, " ")
End Sub

If, for whatever reason, you cannot use Split or StrReverse then you need something like this:
Sub Test2()
    Const SPACE As String = " "
    Dim lastSpace As Long
    Dim nextSpace As Long
    Dim s As String
    Dim word As String
    Dim newStr As String

    s = "VBA is amazing"

    nextSpace = InStr(1, s, SPACE)
    If nextSpace = 0 Then
        newStr = ReverseWord(s)
    Else
        Do While nextSpace > 0
            word = Mid$(s, lastSpace + 1, nextSpace - lastSpace - 1)
            newStr = newStr & ReverseWord(word) & SPACE
            lastSpace = nextSpace
            nextSpace = InStr(nextSpace + 1, s, SPACE)
        Loop
        word = Right$(s, Len(s) - lastSpace)
        newStr = newStr & ReverseWord(word)
    End If

    MsgBox newStr
End Sub

Private Function ReverseWord(ByVal word As String) As String
    Dim i As Long
    Dim res As String

    For i = Len(word) To 1 Step -1
        res = res & Mid$(word, i, 1)
    Next i
    ReverseWord = res
End Function

EDIT #1
The ReverseWord method can be optimized:
Private Function ReverseWord(ByVal word As String) As String
    Dim i1 As Long: i1 = 1
    Dim i2 As Long: i2 = Len(word)
    Dim c As String

    Do While i1 < i2
        c = Mid$(word, i1, 1)
        Mid$(word, i1, 1) = Mid$(word, i2, 1)
        Mid$(word, i2, 1) = c
        i1 = i1 + 1
        i2 = i2 - 1
    Loop
    ReverseWord = word
End Function

A: other solution from me
Sub test()
    Dim str As Variant
    Dim i As Integer, strLen As Integer, iSp As Integer, n As Integer, f As Integer
    Dim NewStr As String
    Dim wordPart() As String
    f = 0
    n = 1
    str = "VBA is amazing"
    strLen = Len(str)
    NewStr = ""
    iSp = spacesCounter(str) + 1
    ReDim wordPart(iSp)

    For i = 1 To strLen
        If Mid(str, i, 1) = " " Then
            If n = 1 Then
                wordPart(n) = Mid(str, 1, i - 1)
                f = i + 1
                n = n + 1
            Else
                wordPart(n) = Mid(str, f, (i) - f)
                f = i + 1
                n = n + 1
            End If
        ElseIf i = strLen Then
            wordPart(n) = Mid(str, f)
        End If
    Next i

    For i = 1 To iSp
        MsgBox (wordPart(i))
        For j = 1 To Len(wordPart(i))
            If i <> 1 And j = 1 Then NewStr = NewStr & " "
            NewStr = NewStr & Mid(wordPart(i), Len(wordPart(i)) - (j - 1), 1)
        Next j
    Next i

    MsgBox (NewStr)

End Sub

A: Try,
Sub test()
    Dim strL As Variant
    Dim i As Integer, strLen As Integer
    Dim NewStr As String
    Dim s As String, s1 As String

    strL = "VBA is amazing"
    strLen = Len(strL)
    NewStr = ""

    For i = 1 To strLen
        s = Mid(strL, i, 1)
        If s = " " Then
            NewStr = NewStr & s1 & s
            s1 = ""
        Else
            s1 = s & s1
        End If
    Next i
    NewStr = NewStr & s1
    MsgBox (NewStr)
End Sub


text:
Q: Using Python in field calculator to extract highest value from 3 columns I have three columns, one for percentage White, percentage Hispanic, and percentage African American per census tract. I'm trying to use Python to extract the population subtype with the highest percentage into a new column called "highest_percentage". The highest percentage category will have 3 classes: 1,2, and 3. I can not figure out how to set a conditional statement so that I can automatically assign a value of 1,2, or 3 to the census tract to use in a classified map.
I was able to write code to find the highest percentage and assign the new field the same value as that percentage, but i'm trying to find which field has the highest value and assign it 1-3 based on a classification. 3 white, 2 Hispanic, 1 African American
I've attached a screenshot of the table and the code window below.

A: I prefer to use an arcpy UpdateCursor for tasks such as these, mainly because I think the syntax is easier to work with and can be incorporated into larger workflows.
In your case, find the index of the largest percentage in each row. For example:
import arcpy

fc = r'C:\path\to\your\file_geodatabase.gdb\featureclass'

with arcpy.da.UpdateCursor(fc, ("african_american", "hispanic", "white", "index")) as cursor:
    for row in cursor:
        max_val = max(row) # Find the max value in each row
        max_index = row.index(max_val) # Find the index of the max value
        row[3] = max_index + 1 # Apply a correction on the index
        cursor.updateRow(row)

A: Try this
Pre-Logic Script Code:
def maxnum(fields):
    max_value=fields[0]
    return_value=1
    if (fields[1]>max_value):
        max_value=fields[1]
        return_value=2
    if (fields[2]>max_value):
        max_value=fields[2]
        return_value=3
    return return_value

trav_tracts.highest_percent=
maxnum([!trac_tracts.percent_aa!,!trav_tracts.percent_hispanic!,!trac_tracts.percent_white!])


text:
Q: Pusher- Triger an event from android using the POST I am new on using the  pusher service.
At the moment i am not finding any documentation on how to trigger an event from the android application.
Of course I can subscribe to the events being pushed by the server but i don't know how to perform a POST request from android to pusher application website.
It seems that all the libraries available do not target android framework.
Thank you

A: Events are triggered using the .trigger method; for example:
channel.trigger("client-myEvent", "{\"myName\":\"Bob\"}");

See the documentation on triggering events from pusher-websocket-java.
This feature, where clients trigger events directly, is called "client events". You could also have your clients trigger events indirectly, with a post to your server, followed by your server publishing a message.


text:
Q: Why ticklabel_format do not take effect? I am using Matplotlib to plot a 3*4 subplots. I am going to change the style of tick label to 'sci' so that the plotting can be more neat. But using the following code, the ticklabel_format do not even take effect on the axis.
import matplotlib.pylab as pl

fig, axes = pl.subplots(nrows=3, ncols=4)

for i,row in enumerate(axes):
    for j,ax in enumerate(row):
        ax.set_title('title')
        ax.ticklabel_format(styl='plain')

pl.tight_layout()
pl.show()

I have intently make a typo 'styl', but it doesn't report error. So I assume the ticklabel_format function doesn't even run.

A: It not taking effect because ax.ticklabel_format takes any keyword argument and creates a dictionary. To see this take a look at the documentation here and you will see it takes an argument **kwargs.  If you just replace styl with style then your code will work.
I suggest you take a look at this SO post to get a feel of what was going wrong but in brief: the function can take any argument. It then attempts to pass these on to other functions. If none of these require it then the argument is simply lost in the ether. As a result there is no error message!
Try playing around with the following example to get a feel **kwargs.
def f(**kwargs):
    print kwargs
    return

f(anything='something')


text:
Q: SQL Query to identify accommodation booked I need to know what SQL statement to use in an accommodation database looking for a trip user

A: The error message is clear enough: the group by clause needs to be consistent with the select. Some databases are smart enough to understand that the name of the customer is functionally dependent on its id, and do not require that you put the name in the group by - but not SQL Server.
Also, you need to count on something that comes from the left joined table if you want 0 for customers without bookings.
Consider:
select c.customer_id, c.customer_name, count(ab.customer_id) as [number of accomm slots]
from customers c
left join  accommodation_bookings ab on c.customer_id = ab.customer_id
group by c.customer_id, c.customer_name

I would take one step forward and pre-aggregate in a subquery. This is usually more efficient:
select c.customer_id, c.customer_name, coalesce(ab.cnt, 0) [number of accomm slots]
from customers c
left join (
    select customer_id, count(*) cnt
    from accommodation_bookings
    group by customer_id
) ab on c.customer_id = ab.customer_id

You could also express this with a correlated subquery, or a lateral join:
select c.customer_id, c.customer_name, ab.*
from customers c
outer apply (
    select count(*) [number of accomm slots]
    from accommodation_bookings ab
    where c.customer_id = ab.customer_id
) ab

This would take advantage of an index on accommodation_bookings(customer_id) (which should already be there if you have set up a foreign key).
Note: don't use single quotes for identifiers - they are meant for literal strings. In SQL Server, use the square brackets instead.


text:
Q: Android InetAddress.getByName(ip).isReachable(timeout) always returns false I see the 24 similar questions asking about InetAddress.isReachable() but my instance never returns true, when the network is otherwise reachable, with the one exception of tests against 127.0.0.1.
if (InetAddress.getByName("google.com").isReachable(2000))
{
    System.out.println("visible");
}
else
{
    System.out.println("not visible");
}

and with permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

This code is started within a thread (of course).  My App needs to know if a specific IP is accessible (not google, as in the above example).  This behaves the same in the emulator.
Is there a better way to test network connectivity?


text:
Q: HTTP :connect timeout and read timeout for URLStreamHandler with SAAJ working for windows but not working on linux sytem I'm a beginner when it comes to HTTP connections.
Currently i'm working with SAAJ api to have my soap based client, where to handle timeouts i ended up using URLStreamHandler for HTTP connection properties with the endpoints.
Problem is that this timeout works for my windows based system, however it isn't working for the Linux server it is going to go live on.
below is the code for fetching endpoint with set properties. It is a HTTP POST connection.
    URL endpoint = new URL (null, url, new URLStreamHandler () {
        protected URLConnection openConnection (URL url) throws IOException {
            // The url is the parent of this stream handler, so must create clone
            URL clone = new URL (url.toString ());
            HttpURLConnection connection = (HttpURLConnection) clone.openConnection();
            connection.setRequestProperty("Content-Type",
                    "text/xml");

            connection.setRequestProperty("Accept",
                    "application/soap+xml, text/*");

            // If we cast to HttpURLConnection, we can set redirects
            // connection.setInstanceFollowRedirects (false);
            connection.setDoOutput(true);
            connection.setConnectTimeout(3 * 1000);
            connection.setReadTimeout(3 * 1000);
            return connection;

for the SAAJ API part, below is the implementation, pretty basic one
    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory
            .newInstance();
    soapConnection = soapConnectionFactory.createConnection();

    is = new ByteArrayInputStream(command.getBytes());

    SOAPMessage request = MessageFactory.newInstance(
            SOAPConstants.SOAP_1_1_PROTOCOL).createMessage(
                    new MimeHeaders(), is);

    MimeHeaders headers = request.getMimeHeaders();
    headers.addHeader("Content-Type", "text/xml");

    request.saveChanges();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    request.writeTo(out);

    soapResponse = soapConnection.call(request, endpoint);

Is it that system properties would affect connect or read timeout. If so please let me know what could cause this behavior.


text:
Q: How do you pause a CSS animation with an HTML button? I'm trying to pause a CSS animation with an HTML button click, using JS to carry out the pause.  So far I've tried to change the animation state using JS but it isn't working - the animation plays through and the button seems to have no effect.
Here's my JS snippet:

var sun = document.getElementById("sun");

var sky = document.getElementById("sky");

var pauseBtn = document.getElementById("pauseBtn");

function pauseAnimation(){
    if((pauseBtn.clicked) == true){
        sun.style.animationPlayState("paused");
        sky.style.animationPlayState("paused");
    }
}
h2:after {
 content : ' no css!';
 color   : red;
 }

no HTML

Can share more code if necessary, any tips based on what you see with the JS?

A: You can add or remove a class name that you define the CSS animation to when you want to pause or resume the animation.

A: this way

const
  sun  = document.querySelector('#sun')
, btPP = document.querySelector('#PlayPause')
  ;
btPP.onclick = () =>
  {
  btPP.textContent = sun.classList.toggle('pause') ? 'Play' : 'Pause'
  }
article {
  margin:1em;
  }
#sun{
  background-color : orange;
  color            : #fff;
  margin           : auto;
  margin-left      : auto;
  margin-left      : 0;
  border           : 5px  dotted yellow;
  width            : 100px;
  height           : 100px;
  border-radius    : 50%;
  }
.pause {
  animation-play-state: paused;
  }
.animating {
  animation-name            : slide;
  animation-duration        : 3s;
  animation-timing-function : ease-in;
  animation-iteration-count : infinite;
  animation-direction       : alternate;
  }
@keyframes slide {
  from { margin-left : 0   }
  to   { margin-left : 80% }
  }

<button id="PlayPause"> Pause</button>


text:
Q: Where does aws cli store profile information? I'd like to set my aws cli to use a new AWS account on my machine.
So I backed up and deleted ~/.aws/config and ~/.aws/credentials files.
After the deletion, I typed aws configure to set the Access Key ID and Secret Access Key of the new AWS account.
But then I got an error saying

botocore.exceptions.ProfileNotFound: The config profile
  (my_profile_name) could not be found

my_profile_name is the profile name of my old AWS account.
How does aws cli remember my old profile name?
How can I reset it so that I can use new Access Key ID and Secret Access Key?
I also find that typing sudo aws configure is able generate new ~/.aws/config and ~/.aws/credentials files.
But the getting started tutorial doesn't say that you need add sudo before aws command. So I don't think this is a good solution for my case.
The profile I mentioned in this post refers to a setting in ~/.aws/config:
[profile my_profile_name]
region = ap-northeast-1
output = json

A: The AWS CLI look for AWS Credentials in a number of different places in the following order according to their documentaion:
 1. provided as command line option
 2. environment variables
 3. The AWS credentials file (~/.aws/credentials)
 4. CLI configuration file (~/.aws/config)
 5. Instance profile credentials
So in your case, It is first checking the environment variables before checking your ~/.aws/credentials file and since you may have previously set environment variable it is taking that.
Also you can have multiple profiles for multiple aws account set up easily like:
$ aws configure --profile aws_account1
$ aws configure --profile aws_account2

A: Check if you have set AWS_DEFAULT_PROFILE environment variable or AWS_PROFILE environment variable.
See: Configuration Settings and Precedence


text:
Q: In Codeigniter form_error('option[x]') is not working. How can i solve this?? In Codeigniter  set_value('option[".$i."]') ** is working fine, but  **form_error('option[".$i."]') is not working. [where $i is 1 to 10]. How can I solve this??

A: I think its a string closing issue.
u can change that with the following
form_error('option['.$i.']')


text:
Q: How to set a Data Breakpoint, to break when EAX Register is set to a particular value There is a article in MSDN which provides the procedure:
http://msdn.microsoft.com/en-us/library/aa295838(VS.60).aspx#_core_setting_a_breakpoint_when_a_register_expression_is_true
But it seems that i tis for visual studio 6 ... Actually I can not find the "Breakpoint" entry under "Edit" Menu...
Do you know how to do that? I want to break when EAX changes to an error code so I can find the place where this error is returned.

A: Assuming you are using Visual Studio 2008, you can find it in its own Debug menu.

A: You need to create a breakpoint. In the Breakpoint Windows ( Debug->Windows->Breakpoint ) right-click the BP and select condition.
In the condition-field you can just type the expression ( "eax == ebx" ).

A: Just to be explicit about what @DarthCoder said:

*

*First create a plain breakpoint, so there's something to edit

*Then Debug->Windows->Breakpoint brings up the list of breakpoints, including the one you just made

*Right-click on the breakpoint, pick "Condition"

*Enter the condition, such as eax==ebx


text:
Q: Smart Card : Class N terminal for geolocation api testing I have developed UICC.usim.geolocation api.
But for testing this feature I need class N terminal. This class is mentioned in terminal profile returned.
Can anyone help me to get any input related to class N terminal (mobile)?


text:
Q: Recover database from uninstalled SQL Server My SQL Server was accidentally uninstalled. I didn't take a backup of all the databases. Is it possible to recover them?

A: The database files are probably still there - in the directory for data and log files.
Th default one is c:\ProgramFiles\MSSQL\MSSQL\MSSQL10_50\MSSQL\Data.
If not default then you need to locate your files and attach them to SQL Server instance of the same or higher edition.

A: Yes you can
Go to "C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA", here you can see your old db MDF and LDF Fils. and you can open those file in sql server as you used earlier.
Step 1 :
     Open SQL Management Studio
Step 2 :
     Open Connection
Step 3 :
     Right click on the "Database" folder and Click "Attach"
Step 3 :
     Click add Button and go to "C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA"
Step 4 :
     Select your Database MDF file and Click Ok
Hope You are done


text:
Q: Complicated for loop to be ported to a CUDA kernel I have the next for nested loop and I would like to port it to CUDA to be run on a GPU
int current=0;
int ptr=0;

for (int i=0; i < Nbeans; i++){
  for(int j=0;j< NbeamletsPerbeam[i];j++){

     current = j + ptr;

     for(int k=0;k<Nmax;k++){
        ......
     }

     ptr+=NbeamletsPerbeam[i];
 }
}

I would be very happy if any body has an idea of how to do it or how can be done.
We are talking about Nbeams=5, NbeamletsPerBeam around 200 each.
This is what I currently have but I am not sure it is right...
 for (int i= blockIdx.x; i < d_params->Nbeams; i += gridDim.x){
            for (int j= threadIdx.y; j < d_beamletsPerBeam[i]; j+= blockDim.y){
                 currentBeamlet= j+k;
                 for (int ivoxel= threadIdx.x; ivoxel < totalVoxels; ivoxel += blockDim.x){

A: I would suggest this idea. But you might need to do some minor modifications based on your code.
dim3 blocks(NoOfThreads, 1);
dim3 grid(Nbeans, 1);

kernel<<grid, blocks, 1>>()

__global__ kernel()
{
   int noOfBlocks = ( NbeamletsPerbeam[blockIdx.x] + blockDim.x -1)/blockDim.x;

   for(int j=0; j< noOfBlocks;j++){
     //  use threads and compute....
     if( (threadIdx.x * j) < NbeamletsPerbeam[blockIdx.x]) {
       current = (threadIdx.x * j) + ptr;

       for(int k=0;k<Nmax;k++){
          ......
       }

       ptr+=NbeamletsPerbeam[blockIdx.x];
    }
 }
}

This should do the trick and gives you better parallelization.


text:
Q: "ValueError: multiclass format is not supported" roc_auc_score I have been trying to do sentiment analysis on twitter. I am kinda new at coding so I am going paralel with an tutorial. So my csv file basically have two columns. One of them is tweets and the other is sentiments.
from sklearn.model_selection import train_test_split
y = train_tweets.Sentiment
X= train_tweets.Tweets
train_X, val_X, train_y, val_y = train_test_split(X, y, random_state=0)

from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(encoding='iso-8859-9').fit(train_X)
train_X_cv = cv.transform(train_X)

from sklearn.linear_model import LogisticRegression
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
model = LogisticRegression()
model.fit(train_X_cv, train_y)

from sklearn.metrics import roc_auc_score
prediction = model.predict(cv.transform(val_X))
print('AUC: ', roc_auc_score(val_y, prediction))

My code looks like this. When I try to run this code I get "ValueError: multiclass format is not supported" this error. You have any idea what I should do?
Thank you!


text:
Q: PHP between HTML tag echo I need to have PHP between my echo between a html tag, anyone can help ?
If you see my code, I want the li to have a PHP if in between it.
please help. thanks.
echo '
';

I want to echo this :

With this in between
<?php if($currentMenuId == '131') { echo 'class="current active"'; } ?>

A: Simply this:-
<?php
$activeClass = ($currentMenuId == '131') ? ' class="current active" ' : '';
?>

<li id="dm-itm1" <?php echo $activeClass ?>>

A: echo '
';

You where almost correct.

A: try this:
echo '
';

A: ?> <li id="dm-item1" <?php if($currentMenuId == '131') echo 'class="current active"';?> >

Just close the PHP when you are bout to use HTML tags, don't print them. Print only the variable content.

A: Use ternary operator to check condition and concat the result to your echo statement, you can add classname or keep it empty if condition doesn't true.
echo '
';


text:
Q: How do I pass a UDF scalar function into a stored procedure? Trying to put a function call that returns an int into a call for a stored procedure.
Getting "Incorrect syntax near '.'."
usp_Document_ReserveForGrader '98832750-142F-4623-91F7-6E43C6F1A963',
12,dbo.Workflow_FirstProgress()

A: You need to assign the result of the UDF to a variable and pass the variable to the PS:
declare @x int;
set @x = dbo.Workflow_FirstProgress();
exec usp_Document_ReserveForGrader '98832750-142F-4623-91F7-6E43C6F1A963', 12,@x;