text:
Q: Velocity field in SpriteKit Anyone got Velocity Field in SpriteKit working?
Granted, I'm not sure I understand how it's supposed to work, but I'm wiring it up inside the Xcode UI, not code. My intention is to have dynamic spritenodes be pulled to a direction if they enter the area of that velocity field. Seeing as the velocity field node does not have a size of its own, I just assume I have to add it as a child of another spritenode (calling that areaofvelocityfield) which is not physical, but has a size, so that other dynamic spritenodes can enter into it and get affected by the force. So selecting the Velocity Field node, I select areaofvelocityfield.
Now, whatever I do, any dynamic node is affected by that force, whether or not they are inside areaofvelocityfield or in any vicinity of it. Whatever distance they are from the node containing the velocity field, and the velocity field itself, they are always affected and pulled in the vector of the field.
iOS 9.2.1. Xcode 7.2.

A: So it seems that .region must be set to the SKFieldNode. This cannot be done from Xcode. At least it cannot be done like this, which is my current code which works well:
SKSpriteNode* belt = (SKSpriteNode*)[self childNodeWithName:@"belt"];

SKFieldNode* myfield = (SKFieldNode*)[self childNodeWithName:@"myfield"];
myfield.region = [[SKRegion alloc] initWithSize:CGSizeMake(belt.size.width * 0.5, 10)];

Note that I am trying to make something like a "conveyor belt". The belt sprite is just a rectangle. The myfield is positioned at the same position as the belt. All nodes are placed directly onto the world, rootnode, no parenting is needed. Placing a field inside another node doesn't really have any effect as to the region it affects (or it might have, not sure here). For some reason I had to set the force field's width to half of the visible belt, or it would keep affecting whatever dynamic node that fell down onto the belt for too long.
Other values I used for the field are: strength 1, falloff 10, min. radius 1. Not sure what really made a difference, as this cannot be easily tested in the Xcode interface. A lot of trial and error is needed to figure out how this all works.
Regarding the size of a region: as the docs states, the size protrudes from the origin in all directions which means the width and height will actually be twice what you set.


text:
Q: multiple criteria for sumifs I have two sheets: one is input and the other is master.
A snapshot of my input sheet is shown below:
Workers Name     WEEK     working hrs
a11              w1       40
a22              w5       30
a33              w9       10
a44              w10      80

A snapshot of my master sheet is shown below (NB: the workers names are unique)
Workers Name    W1   W2   W3   W4   W5   W6   W7   W8   W9   W10
a11             40
a22                                 30
a33                                                     10
a44                                                          80

I want a sumifs loop so that it can give result for workers working hrs in my masters table in their respective weeks(w1 to w13).
I am using a sum ifs formula for this:
Sheets("Master").Range("B2:B" & Range("A" & Rows.Count).End(xlUp).Row).Formula = "=SUMIFS(Input!C32,Input!C37,Master!C1,Input!C31,Master!B1)"

Any suggestions how to loop it in VBA
Please help....

A: I'm sorry but I'm not sure you need vba - if you know what your row and column criteria are in master you can write something like
 =sumifs(workinghrs,workersname,$a2,week,b$2)

Then fill it down and across for your grid.
NB I've used named ranges for your input sheet for readability

redpajama_set_name: RedPajamaStackExchange


text:
Q: GraphQl subscription throwing exception when subscribing with Apollo server flutter GraphQl subscription throwing exception "web socket connect failed" when subscribing with Apollo server. Subscription is working fine with graphQl explorer but failing when implemented in flutter
Code and exceptions are attached below.
********** Code ***********
final _wsLink = WebSocketLink(
  '***************',
  config: SocketClientConfig(
    autoReconnect: true,
    inactivityTimeout: Duration(hours: 1),
    // delayBetweenReconnectionAttempts: Duration(seconds: 1),
  ),
);

final Link _link = Link.split((request) => request.isSubscription, _wsLink, httpLink);

client = GraphQLClient(
  cache: GraphQLCache(store: InMemoryStore()),
  link: _link,
);

SubscriptionOptions options = SubscriptionOptions(
  document: gql(query),
  variables: variables);

final result = client.subscribe(options);

result.listen((event) {
  print("Event fired ${event.data}");
  print("Event fired ${event.exception?.graphqlErrors.toString()}");
}).onError((e) {
  print("Received Error ! ${e.toString()}");
});

return result;

************ Exception ***************
I/flutter ( 5204): Disconnected from websocket.


text:
Q: Pulling info by greater than statement in lists (Python) I used the csv module to create lists from a data file. It looks something like this now:
['unitig_5\t.\tregion\t401\t500\t0.00\t+\t.\tcov2=3.000', '0.000;gaps=0',
    '0;cov=3', '3', '3;cQv=20', '20', '20;del=0;ins=0;sub=0']

['unitig_5\t.\tregion\t2201\t2300\t0.00\t+\t.\tcov2=10.860',
    '1.217;gaps=0', '0;cov=8', '11', '13;cQv=20', '20', '20;del=0;ins=0;sub=0']

I need to pull lists and put them into a new file if cov2= (part of the first column above) is equal to some number greater than some specified integer (say 140), so then in that case the two lists above wouldn't be accepted.
How would I set it up to check which lists meet this qualification and put those lists to a new file?

A: You can use regex :
>>> l=['unitig_5\t.\tregion\t401\t500\t0.00\t+\t.\tcov2=3.000', '0.000;gaps=0',
...     '0;cov=3', '3', '3;cQv=20', '20', '20;del=0;ins=0;sub=0']

>>> import re
>>> float(re.search(r'cov2=([\d.]+)',l[0]).group(1))
3.0

The pattern r'cov2=([\d.]+)' will match and combination of digits (\d) and dot with length 1 or more. then you can convert the result to float and compare :
>>> var=float(re.search(r'cov2=([\d.]+)',l[0]).group(1))
>>> var>140
False

Also as its possible that your regex doesn't match the pattern you can use a try-except to handle the exception :
try :

    var=float(re.search(r'cov2=([\d.]+)',l[0]).group(1))
    print var>140

except AttributeError:
    #print 'the_error_message'

A: I would first split the first string by tabs "\t", which seems to separate the fields.
Then, if cov2 is always the last fild, further parsing would be easy (cut of "cov2=", then convert the remainder to float and compare.
If not necessarily the last field, a simple search for the start should be sufficient.
Of course, complexity could be increased indefinitively if error-checking or a more tolerant search is required.

A: lst = [ ['unitig_5\t.\tregion\t401\t500\t0.00\t+\t.\tcov2=3.000', '0.000;gaps=0',
    '0;cov=3', '3', '3;cQv=20', '20', '20;del=0;ins=0;sub=0'],
        ['unitig_5\t.\tregion\t2201\t2300\t0.00\t+\t.\tcov2=10.860',
    '1.217;gaps=0', '0;cov=8', '11', '13;cQv=20', '20', '20;del=0;ins=0;sub=0'], ]

filtered_list = [ l for l in lst if re.match('.*cov2=([\d.]+$'), l) ]

A: You could extract the float value using rsplit if all the first elements contain the substring:
for row in list_of_rows:
    if float(row[0].rsplit("=",1)[1]) > 140:
            # write rows

If you don't actually need every row you should do it when you first read the file writing as you go.
with open("input.csv") as f, open("output.csv", "w") as out:
    r = csv.reader(f)
    wr = csv.writer(out)
    for row in r:
        if float(row[0].rsplit("=", 1)[1]) > 140:
            wr.writerows(row)


text:
Q: Can latent class analysis be used for path analysis? I have been experimenting with latent class analysis (LCA), which I've recently learned is a form of structural equation modeling (SEM). I know some forms of SEM, I know path analysis can be done where a structural model and a measurement model.
Can LCA be used as part of this path analysis? If so, what's a good resource / example of this?

A: Yes it can. It's pretty tricky to parameterize.
I believe that the Mplus manual has examples, and there's also this paper by David Kaplan: https://www.statmodel.com/download/Dkaplan.MarkovModels.pdf

A: Having a latent categorical variable as outcome of a path analysis is standard within the Mplus package. Bengt Muthen, one of Mplus' authors, pioneered incorporating latent categorical variables within the SEM framework in the 1980s.
Here is one example
Yes, you do run into special problems. You can start to get a sense of those from the Mplus manual. The availability of this functionality varies greatly by package.


text:
Q: Cannot access default page even Nginx is running on Ubuntu I am running ubuntu 17.10 on my server, I have nginx installed and running, both
sudo systemctl restart nginx

and
sudo /etc/init.d/nginx status

can be executed and returns it is running
    ● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Fri 2019-05-31 10:54:07 +08; 47min ago
     Docs: man:nginx(8)
  Process: 99211 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid (code=exited, status=0/SUCCESS)
  Process: 99225 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
  Process: 99213 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
 Main PID: 99228 (nginx)
    Tasks: 3 (limit: 19660)
   Memory: 2.3M
      CPU: 10ms
   CGroup: /system.slice/nginx.service
           ├─99228 nginx: master process /usr/sbin/nginx -g daemon on; master…n;
           ├─99229 nginx: worker process
           └─99230 nginx: worker process

May 31 10:54:07 UbuntuSvr systemd[1]: Starting A high performance web serve…r...
May 31 10:54:07 UbuntuSvr systemd[1]: Started A high performance web server…ver.
Hint: Some lines were ellipsized, use -l to show in full.

However, when I access my IP:8080 (because I put 8080 on nginx config) or my IP:80 (i just trying) or my IP:8082 (because I build my angular frontend and config apiBaseUrl at http://localhost:8082) it shows
This site can't be reached
ERR_CONNECTION_RESET

on Chrome and
safari can't open the page, ...because server where this page is located isn't responding on Safari.
I have tried to check the firewall:
sudo ufw status

it shows:
Status: active

To                         Action      From
--                         ------      ----
8082/tcp                   ALLOW       Anywhere
8080/tcp                   ALLOW       Anywhere
8082/tcp (v6)              ALLOW       Anywhere (v6)
8080/tcp (v6)              ALLOW       Anywhere (v6)

and other checks:
netstat -natup | grep LISTEN

shows:
tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:3002            0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:27017           0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:5355            0.0.0.0:*               LISTEN      -
tcp6       0      0 :::8080                 :::*                    LISTEN      -
tcp6       0      0 :::80                   :::*                    LISTEN      -
tcp6       0      0 :::86                   :::*                    LISTEN      -
tcp6       0      0 :::22                   :::*                    LISTEN      -
tcp6       0      0 :::5355                 :::*                    LISTEN      -

and sudo netstat -tanpl|grep nginx shows:
tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN      99228/nginx: master
tcp6       0      0 :::8080                 :::*                    LISTEN      99228/nginx: master

here is my /etc/nginx/sites-available/default file content:
> server {
>     listen 80 default_server;
>     listen [::]:80 default_server;
>
>     root /var/www/html;
>     index index.html index.htm index.nginx-debian.html;
>
>     server_name _;
>
>     location / {
>         try_files $uri $uri/ /index.html =404;
>     } }

I have built my frontend site by ng build --prod and copy all the contents under the generated folder (under "dist" folder) into /var/www/html/ folder (where also have "index.nginx-debian.html" file)
Additional info: I have backend running on pm2, nodejs. Database running on mongodb.
Update: my nginx.conf file as required:
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
#
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}

One more thing I observed: if I run this command from my server: curl -I http://localhost:8080 then I get:
HTTP/1.1 200 OK
Server: nginx/1.14.0
Date: Fri, 31 May 2019 06:58:26 GMT
Content-Type: text/html
Content-Length: 700
Last-Modified: Fri, 31 May 2019 02:44:47 GMT
Connection: keep-alive
ETag: "5cf0951f-2bc"
Accept-Ranges: bytes

but if I replace the localhost by myserver IP:
curl -I http://my.server.ip.address:8080

then I got:
curl: (7) Failed to connect to 13.67.51.66 port 8080: Connection timed out

My server is also using Azure cloud service, will this block ICMP and then I cannot use IP to connect to my server from outside? How could I do in this case then ?
I am expecting one of these tries from my local laptop, at least I could get:

but it doesn't.
Do you know any reason for this please and how could I make it works ?
Thank you very much !


text:
Q: Beacons not detected in Android service I'm using the Altbeacon library (stable release 2.1.4) to detect beacons. If I do it in an Activity, I have no problems detecting them. However I can't get this to work from a service. Here's what I've got:
package com.ibeacontest.android;

import java.util.Collection;

import org.altbeacon.beacon.Beacon;
import org.altbeacon.beacon.BeaconConsumer;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.BeaconParser;
import org.altbeacon.beacon.Identifier;
import org.altbeacon.beacon.RangeNotifier;
import org.altbeacon.beacon.Region;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class TestBestzBeaconService extends Service implements BeaconConsumer
{

    private BeaconManager beaconManager;
    private final String BEACON_UUID = "11687109-915f-4136-a1f8-e60ff514f96d";
    private final int BEACON_MAJOR = 3;

    @Override
    public void onCreate() {
        super.onCreate();
        L.p("In TestBestzBeaconService onCreate()");
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand (Intent intent, int flags, int startId) {
        L.p("in TestBestzBeaconService onStartCommand()");

        beaconManager = BeaconManager.getInstanceForApplication(this);
        beaconManager.bind(this);

        //iBeacons ?
        BeaconParser bp0 = new BeaconParser();
        bp0.setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24");
        beaconManager.getBeaconParsers().add(bp0);

        //Bluecats?
        BeaconParser bp1 = new BeaconParser();
        bp1.setBeaconLayout("m:2-3=0201,i:28-29,p:24-24");
        beaconManager.getBeaconParsers().add(bp1);

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        L.p("In TestBestzBeaconService onDestroy()");
        beaconManager.unbind(this);
    }

    @Override
    public void onBeaconServiceConnect() {

        L.p("In TestBestzBeaconService onBeaconServiceConnect()");

        beaconManager.setRangeNotifier(new RangeNotifier() {
            @Override
            public void didRangeBeaconsInRegion(Collection<Beacon> arg0, Region arg1) {
                L.p("In TestBestzBeaconService - anonymous didRangeBeaconsInRegion()");
            }
        });

        Region region = new Region("myregion", Identifier.parse(BEACON_UUID), Identifier.fromInt(BEACON_MAJOR), null); //

        try {
            beaconManager.startRangingBeaconsInRegion(region);
        } catch (RemoteException e) {
            L.p("In TestBestzBeaconService onBeaconServiceConnect(), REMOTEEXCEPTION!");
        }

    }

    private static class L
    {
        public static void p(String s) {
            Log.i("beacon", s);
        }
    }

}

I'm calling this from an Activity as so:
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startService(new Intent(this, TestBestzBeaconService.class));
    }

}

The log output I'm getting is:
03-19 09:56:40.233: I/beacon(25210): In TestBestzBeaconService onCreate()
03-19 09:56:40.233: I/beacon(25210): in TestBestzBeaconService onStartCommand()
03-19 09:56:40.566: I/beacon(25210): In TestBestzBeaconService onBeaconServiceConnect()

Parts added to the AndroidManifest:
<!-- Needed for AltBeacon SDK -->
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

and inside the Application tag:
<!-- Needed for AltBeacon SDK -->
<service android:name="org.altbeacon.beacon.service.BeaconService"/>
<service android:name="com.ibeacontest.android.TestBestzBeaconService" />

...but no signs of beacons or the didRangeBeaconsInRegion log output. Any pointers?

A: As i know Monitoring only works in background while Ranging do not. Try firstly starting a Monitoring and then immediately when you enter Monitoring start Ranging.
Something like:
  //Set Monitoring
mBeaconManager.setMonitorNotifier(new

MonitorNotifier() {
    @Override
    public void didEnterRegion (Region region){
        Log.d("TEST", "ENTERED beacon region");
        //Start Raning as soon as you detect a beacon
        try {
            mBeaconManager.startRangingBeaconsInRegion(mRegion);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
});

//Set Ranging
mBeaconManager.setRangeNotifier(new

RangeNotifier() {
    @Override
    public void didRangeBeaconsInRegion ( final Collection<Beacon> beacons, Region region){
           if (beacons.size() > 0) {
                Log.i(TAG, p("In TestBestzBeaconService - anonymous
            }
    }
});

try
{
    //Start Monitoring
    mBeaconManager.startMonitoringBeaconsInRegion(mRegion);
}

catch(RemoteException e)
{
    e.printStackTrace();
}

Don't forget to add beacon service to Manifest:
        <service
        android:name="org.altbeacon.beacon.service.BeaconService"
        android:enabled="true"
        android:exported="true"
        android:isolatedProcess="false"
        android:label="beacon"></service>
       <service
        android:name="org.altbeacon.beacon.BeaconIntentProcessor"
        android:enabled="true"></service>

note: In meantime check also lib project

A: The posted code is in a library project and contained the correct inserts in the AndroidManifest file, however the actual app project was missing this.
I believe normally this would cause the app to crash, but in this case it just wouldn't show beacons.
Adding this made it work.


text:
Q: delete nodes from xml file having duplicate ID using xsl I have xml as below:
<panel id="MainPanel" x="0" y="0" w="100%" h="100%" backgroundcolor="green" >

  <panel id="somepanel" x="0" y="130" w="100%" h="PANEL_ALIGN" backgroundcolor="red" >
    <panel id="nextpanel" x="0" y="130" w="100%" h="PANEL_ALIGN" backgroundcolor="red" >

     </panel>
  </panel>

Expected is:
<panel id="MainPanel" x="0" y="0" w="100%" h="100%" backgroundcolor="green" >

  <panel id="somepanel" x="0" y="130" w="100%" h="PANEL_ALIGN" backgroundcolor="red" >
    <panel id="nextpanel" x="0" y="130" w="100%" h="PANEL_ALIGN" backgroundcolor="red" >

     </panel>
</panel>

I use below xsl to remove table node but it removes all table node.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template
 match="table"/>
 </xsl:stylesheet>

Could anyone help , as i dont knwo much of xslt.

A: add this to your stylesheet as a top level:
<xsl:key name="kTable" match="table" use="@id"/>

and replace
<xsl:template match="table"/>

with
<xsl:template match="table[generate-id() != generate-id(key('kTable', @id)[1])]"/>


text:
Q: Number of indices mismatch, using Keras LSTM I am trying to build a text classifier using LSTM:
model = Sequential()
model.add(Embedding(vocabulary_dim, 150, input_length=max_length))
model.add(LSTM(150, return_sequences=False))
model.add(Dense(1, activation='softmax'))
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=5, batch_size=128)

Where the parameter vocabulary_dim is calculated by:
temp_list = [element for element in sentence_pad]
vocabulary_dim = len(np.unique(temp_list))

When I run model.fit(...) I get this error:
InvalidArgumentError: indices[3,0] = 25501 is not in [0, 19355)
     [[Node: embedding_2/Gather = Gather[Tindices=DT_INT32, Tparams=DT_FLOAT, validate_indices=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](embedding_2/embeddings/read, _arg_embedding_2_input_0_2)]]

Caused by op 'embedding_2/Gather', defined at:
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\ipykernel\__main__.py", line 3, in <module>
    app.launch_new_instance()
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance
    app.start()
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\ipykernel\kernelapp.py", line 474, in start
    ioloop.IOLoop.instance().start()
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\tornado\ioloop.py", line 887, in start
    handler_func(fd_obj, events)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\zmq\eventloop\zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\ipykernel\kernelbase.py", line 276, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\ipykernel\kernelbase.py", line 228, in dispatch_shell
    handler(stream, idents, msg)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\ipykernel\kernelbase.py", line 390, in execute_request
    user_expressions, allow_stdin)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\ipykernel\ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\ipykernel\zmqshell.py", line 501, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\IPython\core\interactiveshell.py", line 2717, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\IPython\core\interactiveshell.py", line 2821, in run_ast_nodes
    if self.run_code(code, result):
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-14-42e99436b8e4>", line 3, in <module>
    model.add(Embedding(dim_vocabolario, 150, input_length=lunghezza_massima_periodo))
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\keras\models.py", line 422, in add
    layer(x)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\keras\engine\topology.py", line 554, in __call__
    output = self.call(inputs, **kwargs)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\keras\layers\embeddings.py", line 119, in call
    out = K.gather(self.embeddings, inputs)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\keras\backend\tensorflow_backend.py", line 966, in gather
    return tf.gather(reference, indices)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\tensorflow\python\ops\array_ops.py", line 2486, in gather
    params, indices, validate_indices=validate_indices, name=name)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\tensorflow\python\ops\gen_array_ops.py", line 1833, in gather
    validate_indices=validate_indices, name=name)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\tensorflow\python\framework\ops.py", line 2956, in create_op
    op_def=op_def)
  File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\tensorflow\python\framework\ops.py", line 1470, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

InvalidArgumentError (see above for traceback): indices[3,0] = 25501 is not in [0, 19355)
     [[Node: embedding_2/Gather = Gather[Tindices=DT_INT32, Tparams=DT_FLOAT, validate_indices=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](embedding_2/embeddings/read, _arg_embedding_2_input_0_2)]]

I suppose that there is something wrong with how I have calculated vocabulary_dimension, but I 'm not sure about this.

A: Yes, the problem is in the calculation of vocabulary_dim. From the documentation:

input_dim: int > 0. Size of the vocabulary, i.e. maximum integer index + 1.

In your case, it seems there are gaps in the indices so the length doesn't correspond to the maximum integer index. You should instead:
temp_list = [element for element in sentence_pad]
vocabulary_dim = np.max(np.unique(temp_list)) + 1

Note: this vocabulary dim should be calculated across your entire dataset (including test set) so every word has a unique integer index.

A: The error probably comes because you mapped your words using temp_list, whereas, the mapping should have been done on set(temp_list)
temp_list = [element for element in sentence_pad]
temp_list = set(temp_list)
vocabulary_dim = len(temp_list)

Now, using this temp_list map the words in your dataframe to its index, something like,
word2idx = {v:i for i,v in enumerate(temp_list)}

For example, if your data is something like,
df
     words
0  credits
1   pandas
2     good

X_train = df['words'].map(word2idx)


text:
Q: Display only bicycle mode in MapQuest.js I am going through the MapQuest.js documentation and essentially i'd like to omit the option for automobiles and replace it with a bicycle.
var map = L.mapquest.map('map', {
      center: this.state.center,
      layers: L.mapquest.tileLayer(this.state.baseLayer),
      zoom: this.state.zoom,
      zoomControl: false,
    });
    L.mapquest
      .directionsControl({
        className: 'control-panel',
        routeSummary: {
          enabled: false,
        },
        narrativeControl: {
          enabled: true,
          compactResults: false,
        }
      })
      .addTo(map);
    L.control.zoom({ position: 'topright' }).addTo(map);
  }

I came across this info under MapQuest.js > API Reference > mapquest.directions.route.

A class that acts as an interface to the MapQuest Directions API.
  Performs either a Route, Optimized Route, or Alternate Route call
  depending on the routeOptions. If no callback is provided, the route
  will be automatically rendered on the map. The route markers and
  ribbons can be styled using the setLayerOptions function. If a
  callback is provided, the results of the API call will be passed in
  the error-first callback style.

Can someone show me how I would be able to leverage some of the options in the Directions API?
Am I correct in my thinking this is how you would go about really customizing things?


text:
Q: How to fill a png file in function of a percentage I'm currently building one of my my first projects in HTML/CSS so i'm a newbie.
I want to fill a png in function of a percentage but I don't find anything talking about this.
I tried using a double image but it's not clean and not working very well
It's a preview of what I did on figma
I want to make this in HTML CSS to integrate in a videogame

A: I think this could be considered the quickest approach to the problem using just one img element and a css rule.
The picture is a png image I uploaded myself having a yellow background and a transparent hearth shape in the middle.
The filling is made by the background css attribute using linear-gradient to paint a given % of the picture height as blue. Since the shape inside the picture is transparent, the blue color comes out only there.
The demo includes a range slider to show how you can control that % dinamically via js.

EDIT:
I added the solution proposed by @FernandoBravoDiaz just to show how you could fill its hearth shaped with clip-path. Its solution is good enough to be the accepted one.
The solutions you proposed on comments use svg ... unfortunately I don't know how to make an hearth shape that way and it wasn't explored that far in the answer you cited.
I think you can use the @FernandoBravoDiaz solution and just add the linear-gradient strategy to fill it up with a solid color for a given %. I placed the hearth inside a relative positioned container.

document.addEventListener("DOMContentLoaded", ()=>{

  document.querySelector('#giveSupport').addEventListener('change', ()=>{
    sliderPercentage = window.event.target.value;

    document.querySelector('img.hearth').style.background =
      `linear-gradient(to top, blue ${sliderPercentage}%, transparent 0)`;

    document.querySelector('.hearthvectorial').style.background =
      `linear-gradient(to top, blue ${sliderPercentage}%, transparent 0)`;
  });

});
/*
---------------------------------------
 Original Solution - Using picture mask
---------------------------------------
*/

.hearth{
  width: 200px;
  /* here you are controlling the % */
  background: linear-gradient(to top, blue 49%, transparent 0);
}

/*
---------------------------------------
 Svg Solution - proposed by
---------------------------------------
*/

.backgroundpage{
  width: 100%;
  height: 200px;
  background: red;
  position: relative;
}

.hearthvectorial {

  /*position absolute will be relative to the container having position:relative*/
  position: absolute;
  top: 44px;
  left: 48px;

  /*this is when display: block*/
  /*
  margin-left: 42px;
  margin-top: 42px;
  */

  /*size*/
    width: 24px;
    height: 24px;

  /*hearth shape*/
    clip-path: path("M12 4.419c-2.826-5.695-11.999-4.064-11.999 3.27 0 7.27 9.903 10.938 11.999 15.311 2.096-4.373 12-8.041 12-15.311 0-7.327-9.17-8.972-12-3.27z");
    transform: scale(5);

  /*background strategy to fill %*/
  background: linear-gradient(to top, blue 100%, transparent 0);
}

<input
  type="range"
  id="giveSupport"
  style="cursor:pointer;"
  min="0"
  max="100" />

Solution proposed by @FernandoBravoDiaz

A: You could also use CSS crop on some divs instead of an image, that will make your code something like this:
A container, two hearth shaped divs and a button for triggering the fill

<button onclick="fillHearth()" >Fill Hearth</button>

The styles
.container {
  margin: 70px;
  display:flex;
  flex-wrap: wrap;
  gap: 10px 120px;
  position: relative;
}
.hearth {
  position: absolute;
  width: 24px;
  height: 24px;
  clip-path: path("M12 4.248c-3.148-5.402-12-3.825-12 2.944 0 4.661 5.571 9.427 12 15.808 6.43-6.381 12-11.147 12-15.808 0-6.792-8.875-8.306-12-2.944z");
  transform: scale(5);
}
.base {
  background: #cecece;
}
.color {
  background: transparent;
}

The script that fills the hearth in an interval of half a second
function fillHearth(argument) {
    let current = 0;
    console.log('Filling hearth');
    const interval = setInterval(() => {
        console.log('Current: ', current);
        document.querySelector('div.color').style.background =
              `linear-gradient(to top, #FF5252 ${current}%, transparent 0)`;
        current += 10;
        if (current > 100) clearInterval(interval);
    }, 500);
}

The crop shape was taken from here


text:
Q: single query is double query in my url(js problem or symfony error) <form method="GET">
    <input type="text" class="form-control" placeholder="Search"
      name="keywords" value="{{ keywords }}">
     <button class="btn btn-primary" type="submit">Cauta</button>
</form>

my url on first click http://localhost:8090/xxxkeywords=tu
on second click http://localhost:8090/xxx?keywords=tu&keywords=tu


text:
Q: Linux daemon waiting for a socket connection I would like to create a simple Linux daemon which will...

*

*open a tcp/ip server socket on localhost and specified port

*wait for a connection

*after someone connects, it will read the first line from the client's socket (ended by \n)

*if the line is foo, it will run command bar

*after the bar command is finished (or if the line wasn't foo), the daemon will wait for another connection and do the same (in infinite loop)...

Is it possible to write this in bash? (And how?)
Also, I would like to be able to start and stop the script with service my-foobar-daemon start / stop (on Ubuntu), how can I do that?
Thanks :)

A: The following snippet uses bash and nc to implement the requirements:
#! /bin/bash
while true; do
    coproc nc -l -p 8080
    if read -u "${COPROC[0]}" line; then
        case "$line" in
            foo)
                bar
                ;;
            *)
                echo "$line: unknown command" >&2
                ;;
        esac
    fi
    kill "$COPROC_PID"
    wait "$COPROC_PID"
done

A: #! /bin/bash
coproc nc -l -p 8080
while true; do
    if read -u "${COPROC[0]}" line; then
        case "$line" in
            foo)
                bar
                break
                ;;
            *)
                echo "$line: unknown command" >&2
                ;;
        esac
    fi
done
kill "$COPROC_PID"


text:
Q: How can I prevent Telerik RadChart from generating an onerror attribute? We're using the Telerik Rad Controls for ASP.Net Ajax on an ASP.Net MVC project. The RadChart generates the following HTML:
<img onerror="if(confirm('Error loading RadChart image.\nYou may also wish to check the ASP.NET Trace for further details.\nDisplay stack trace?'))window.location.href=this.src;" src="ChartImage.axd?UseSession=true&ChartID=e25ad666-e05b-4a92-ac0c-4f2c729b9382_chart_ctl00$MainContent$AverageCTMChart&imageFormat=Png&random=0.501658702968461" usemap="#imctl00_MainContent_AverageCTMChart" style="border-width: 0px;" alt="">

I'd like to remove the onerror attribute; I don't really want the customers being offered the option to see a stack trace if something goes wrong. I can't see any way to control the markup that this control generates. Google searches provide no help. Has anyone dealt with this before?
How do I remove the onerror attribute?

A: The onerror only ever shows in debug configuration. Once you deploy your app in Release the attribute does not get rendered!

A: You could do something like this, just add it to the bottom of the page or call removeOnError in a load event somewhere.
function removeOnError(){
    //Grab all images
    var imgs = document.getElementsByTagName('img');
    for(var i=0;i<imgs.length;i++){
        //If they've got the onerror attribute
        if(imgs[i].onerror){
            //set it to null
            imgs[i].onerror = null;
        }
    }
}
//Call the function above
removeOnError();

Edit
Looking at Telerik's site it doesn't appear to be an option so the only way that I can think of is to override the Render event for your page and manually rip it out:
protected override void Render(HtmlTextWriter writer)
{
    using (System.IO.MemoryStream MS = new System.IO.MemoryStream())
    {
        using (System.IO.StreamWriter SW = new System.IO.StreamWriter(MS))
        {
            HtmlTextWriter NW = new HtmlTextWriter(SW);
            base.Render(NW);
            NW.Flush();
            MS.Position = 0;
            using (System.IO.StreamReader SR = new System.IO.StreamReader(MS))
            {
                string html = SR.ReadToEnd();
                MatchCollection MC = Regex.Matches(html, "<img.*?(?<OnError>onerror=\".*?\").*?>");
                foreach (Match M in MC)
                {
                    if (M.Success)
                    {
                        html = html.Replace(M.Groups["OnError"].Value, "");
                    }
                }
                Response.Write(html);
                SR.Close();
            }
        }
    }
}

A: Telerik controls check property
HttpContext.Current.IsDebuggingEnabled

to decide whether to generate onError attribute. So to remove these blocks ensure that debug is switched off in 'compilation' node in your web.config
<compilation debug="false">


text:
Q: Python3 boolean if statement while True:

   x = False

   if x == False:
     if (float) <= (price):
        if not safe_mode:
            (Some function)
     x = True
     print(something)

   elif x == True:
     if (float) >= (price):
        if not safe_mode:
            (Some Function)
     x = False
     print(something)

that is my code, and i want that to loop, but what i get is 'x' doesn't want to change value to 'True'... and 'x = True' get grayed out. I don't know why it doesn't want to work, i need all your help pls. i kinda stress finding the problem :(

A: The problem is that you set x back to False at the beginning of each iteration of the while loop, so its value is changed within each conditional block, but then changed back to False right after when the loop starts over.
Just set x = False outside of the while loop and that'll solve it. Example:
x = False

while True:
    # do stuff


text:
Q: Call a common function from a list of objects I am trying to create a Proxy Scraper. For each website I have, I try to scrape the proxies. The scrape code for each website is in a class with the name of the website.
For example:
I have the websites "wwww.proxy.com and www.moreproxy.com"
I have 2 classes: Proxy and MoreProxy with the functions "scrape" that varies for both (since they are different websites).
To get the lists, I do something like this:
//The below code doesn't exist, but just to get my point across
//Each datagrid.Add is in a separate thread
datagrid.Add(new Proxy().scrape());
datagrid.Add(new MoreProxy().scrape());
datagrid.Add(...);
datagrid.Add(...);
//And so on for all the other websites I might add...

Now is there a way to loop this? I was trying something like this, but it does not work:
List<object> objects = new List<object>();
objects.Add(new Proxy(), new MoreProxy(), ..., ...); //I can update this each time I add a new website

foreach(object o in objects)
{
    datagrid.Add(o.scrape());
}

The scrape function looks something like this:
public List<string[]> scrape()
{
        HtmlDocument PageContent = new HtmlWeb().Load("https://free-proxy-list.net/");
        HtmlNode[] nodes = PageContent.DocumentNode.SelectNodes("//td").ToArray();

        List<string[]> proxies = new List<string[]>();

        for (int i = 0; i < nodes.Length; i += 8)
        {
            string[] proxy = { nodes[i].InnerHtml, nodes[i + 1].InnerHtml };
            proxies.Add(proxy);
        }

        return proxies;
}

Does something like this exist? Basically I have several classes with a common function scrape. I want to create a list of all these classes as objects, and execute the function scrape. How would I do that (solution needs to be thread safe)

A: Setup an interface:
public interface IScrape()
{
   object Scrape();
}

Have your proxy classes implement the interface:
// repeat for Proxy
public class MyProxy : IScrape{
  object Scrape()
  {
     return something;
  }
}

then
List<IScrape> objects = new List<IScrape>();
objects.Add(new Proxy(), new MoreProxy(), ..., ...); //I can update this each time I add a new website

foreach(IScrape o in objects)
{
    datagrid.Add(o.Scrape());
}

A: Interfaces are the problems solution.
Like this:
public interface IScrapable {
    void Scrape();
}

public class Proxy : IScrapeable {
    public void Scrape() { ...}
}

Now you can Loop and scrape your objects.
 List<IScrapable> objects = new List<IScrapable>();
objects.Add(new Proxy(), new MoreProxy(), ..., ...); //I can update this each time I add a new website

foreach(IScrapable o in objects)
{
    datagrid.Add(o.scrape());
}

This should do what you want.


text:
Q: Google App Maker updating DB records in batches We are having a Google App Maker app using Google Cloud SQL tables. Our location is Prague, Central Europe and app.saveRecords() takes incredible 240ms at minimum. We have tried many things including changing the location of the instance but it did not solve the problem.
Fortunately, the solution is to insert new records in batches. This was brilliantly solved by the answer in my previous thread [ Google App Maker saving records to DB is taking 240ms per record ].
We would be so grateful if anyone provided us with a simple code to update records in the DB in batches [server-side scripting]. This way, we not only could insert completely new records in batches, but we could update the data of the records already saved in the DB fast way.
Let's say we have a DB with 3 custom fields:
product code | product availability | price

+
an example array with the data:
ourData[0] = ['pc001','in stock','99'];
ourData[1] = ['pc002','out of stock','49'];
ourData[2] = ['pc003','out of stock','199'];
ourData[3] = ['pc004','in stock','149'];
ourData[4] = ['pc005','in stock','299'];

...and we want to assign the availability and price data to the particular DB line using the key "product code". If the product code is not found in the DB, then we insert a new record to the DB.
Multiple single line inserts/updates take Google App Maker users in the EU too long because the query does go to the US even if the SQL instance is located in the EU. Running this in batches could break today's Google App Maker limitations outside the US. Thank you so much for any help to make Google App Maker a great tool for beginners all around the world.

A: With the help of the others here in the thread, I managed to reduce the time to insert or update a record to 50ms. Furthermore, I have tested out to insert/update 10000 records to a table containing 60 fields. In this case, the speed was 60ms per record. Hereby, I am providing anyone (who may find it useful) with my final code. Thank you for all the helpful answers and comments!
/* We use Google Cloud SQL Table "testDB" that contains these fields:
   - Id (the default primary key for DBs in Google App Maker)
   - productCode
   - availability
   - price

   We have an array called "data" which contains the data [productCode, availability, price] we want to save to the database.
*/

function saveDataNew(){
    var data = [];
    data[0] = ['pc1','in stock','99'];
    data[1] = ['pc2','out of stock','129'];
    data[2] = ['pc3','in stock','78'];
    data[3] = ['pc4','in stock','95'];

    //load all the records in the DB (no filter is used)
    var query = app.models.testDB.newQuery();
    var records = query.run();
    console.log("Found " + records.length + " records in the database.");

    //create an array to help us find DB's Id for each unique productCode.
    var helpingArray = [];
    for (var x in records) {
      var product = records[x]; //get each record in the DB
      helpingArray.push([product.productCode,product.Id]); //save this record's productCode and Id into the helping array
    }

    //setting up the writing in batches
    var totalRecords = data.length;
    var batchLimit = 500; //size of a batch round - number of lines for each app.saveRecords();
    var roundlimit;
    if(totalRecords < batchLimit){
      roundlimit = totalRecords;
    }
    else{
      roundlimit = batchLimit;
    }
    var totalRounds = Math.ceil(totalRecords / batchLimit);
    var round = 1;
    var currentItem = 0;

    //start writing in batches
    do{
        var recordsToSave = [];
        //create or update a record in the DB for each line of our data within one batch round
        for(var i=currentItem; i<roundlimit; i++){
          var wantedCode = data[i][0]; //get the productCode of the current line of the data array
          var orderNum = -1; //create a variable to find the order number of the productCode in the helping array
          for(var z=0; z<helpingArray.length; z++){ //search for the productCode in the helping array
            if(helpingArray[z][0]==wantedCode){
              orderNum = z; //save the line's number if the productCode is found in the helpingArray
              continue;
            }
          }
          var productRecord;
          if (orderNum == -1){ //there was no line with the productCode found the helpingArray => create a new record
                productRecord = app.models.testDB.newRecord();
                productRecord.productCode = data[i][0];
          }
          else{ //the productCode was found in the helpingArray => edit the existing record in the DB
                productRecord = records[orderNum];
          }
          //provide the record with the data
          productRecord.availability = data[i][1];
          productRecord.price = data[i][2];

          //cumulate records and save them once the batch round is finished
          recordsToSave.push(productRecord);
        }

        //a batch round has been finished, save records if there are any
        if(recordsToSave.length){
            console.log("Records saved: "+recordsToSave.length);
            app.saveRecords(recordsToSave);
        }

        currentItem += batchLimit;
        round++;

        if (totalRecords < round*batchLimit){
          roundlimit = totalRecords;
        }
        else{
          roundlimit += batchLimit;
        }
    } while(round <= totalRounds);
}

A: This issue can be solved by using the proper server scripting and I strongly encourage you to read how server scripting works in the official documentation. Pay close attention at the Querying records example.
So, taking as base the previous solution example, it can be slightly modified to achieve your needs. This is how it should look:
function saveData(){

    //get the data
    var data = getData();

    var totalRecords = data.length;
    var batchLimit = 2000;
    var totalRounds = Math.ceil(totalRecords / batchLimit);
    var round = 1;
    var roundlimit = batchLimit;
    var currentItem = 0;

    do{
        var recordsToSave = [];

        for(var i=currentItem; i<roundlimit; i++){

            var recordData = data[i];
            var productCode = recordData[0];

            //check if the record already exists
            var query = app.models.testDB.newQuery();
            query.filters.productCode._equals = productCode;
            var productRecord = query.run()[0];

            //if non existent, create a new one
            if(!productRecord){
                productRecord = app.models.testDB.newRecord();
                productRecord.productCode = productCode;
            }

            productRecord.availability = recordData[1];
            productRecord.price = recordData[2];
            recordsToSave.push(newProduct);
        }

        if(recordsToSave.length){
            app.saveRecords(recordsToSave);
        }

        currentItem += batchLimit;
        roundlimit += batchLimit;
        round++;

    } while(round <= totalRounds);

}


text:
Q: when I call a resource show function with an id the retruned page work without the style, NO css + js !! laravel Note: all other pages work fine!!, Except when I call from this function...
action in HTML
<a class="dropdown-item" style="border-right: 5px solid #00ff55;"  href="{{route('room.show',1)}}" >
تقييمات الغرف
</a>

Route in web.php
Route::resource('room', DailyTaskroomController::class);

The show function in the controller
public function show(DailyTaskroom $dailyTaskroom)
{
        $leader = DailyTaskroom::all()->last()->paginate(5);
        return view('tasks.room_view')->with('leader',$leader);
}

And this is the URL that appears in the URL bar.
-> http://127.0.0.1:8000/room/1
This is the wanted page that appears without style!!


text: Q: A query about convexity in $L^p$ spaces It defines the set $H^{p}_{\varepsilon}=\lbrace f \in L^{p}(0,1):\Vert f\Vert _{p}=(\int \vert f\vert^{p}dm)^{\frac{1}{p}}<\varepsilon\rbrace$ with respect to the measuring space $((0,1),\mathbf{B},m)$ I have a great concern about whether when $0<p<1$, then $H^{p}_{\varepsilon}$ is convex? In advance thank you very much for any suggestions


text:
Q: Error message when using "Add current select to filter" in Excel connected to Cube I have an Excel pivot table connected to SSAS cube and it works fine.
But got a problem when filtering dimension attribute (using "Add current select to filter") on the Row Labels. Excel shows the following error msg:

Error message shows here: XML parsing failed at line 1, column
  779979: Illegal xml character. .

mouse over the member
Does anybody know what causes an issue and how to fix it?
I don't think there is something wrong with cube or data since it was successfully processed. Thanks in advance for your answer.


text: Q: Apache2 and Bind I have a domain called tross.ga and I have my bind server running, but when I open the website up on my other computer, the website does not show up. How do I add a web server to a domain?


text:
Q: Select multiple terms when filling in a managed metadata field Is it possible to select multiple terms when filling in a managed metadata field?
When I open the pop-up to select the terms, I am only able to select one term from the treeview and then click select to add it to the selection.
What I would like to do is being able to select multiple terms in treeview (by holding shift for example) and then click on select to add them all to the selection.
We have situations when people need to select a lot of terms and doing it one by one just takes to much time.

A: You can double click the terms in the treeview and then it will be added without clicking Select button.


text:
Q: How does one test the SSL cert on a specific server while testing through a load balancer? I use Linode's NodeBalancer and would like to make sure each of the servers are terminating the SSL correctly.
Right now I'm waiting on DNS propagation to test placing an A record of the format of server1.secure.domain.com where the SSL is valid for secure.domain.com.
Is this the correct method or is there something better?

A: You can just use the openssl tool directly
for example:
openssl s_client -connect www.google.com:443 | openssl x509 -text

This will show you the cert that google has. Run the tool against each of your machines. You can check the subject and the certificate itself against whatever you have purchased and see if it's right.


text:
Q: How can one get local host address in Apache Camel In a route (that exposes a REST service) i need to get the local host address/domain (so as I can build links to be included in a response body)
Is there a way to get the local host address from within camel ?
PS : running camel inside servicemix

A: there isn't a Camel specific way (that I know of), I'd just use an external property file to configure environment specific settings like this...you can then use camel properties to pull this in, etc.

A: A good idea when posting questions is to provide more details.
Which camel component do you use for REST. And which version of SMX/Camel do you use etc.
As you question assume that the rest component in Camel will expose a hostname information.
This questions is not Camel specific per see, as you can use the regular Java API to get the hostname.


text:
Q: Too "big" Arrays. Do I need a DataBase? Or are there other options? I recently encountered an OutOfMemory error in a program due to (I guess) an excessive use of arrays and double multidimensional arrays (one which is around 5000x60 elements). So I'm searching for an alternative to storing the information.
Are databases the only alternative? Or is there any other way to the store the information from the arrays so I can free up memory? I also read about the possibility of manually allocating memory (or splitting it up in chunks? I don't recall what exactly it was) but that's not an option I guess because all the arrays and objects will eventually grow even more in size so sooner or later I'd probably even reach (in theory) the limits of my physical ram. Although I might just be wrong here.
I'm not asking for huge code examples, links to good tutorials or reads (books would be ok too although I should be able to order them in Germany without billions of dollars shipping costs ;-)) would be perfect.
Also: No, I never did anything with databases but I'm willing to learn anything.
Thanks in advance for any help.
edit: fixed "double array" to "multidimensional array".
edit2: I thought there might be an "universal" solution to a problem with huge arrays but you prooved me wrong. Because it's hard to find an alternative if people don't know what I'm doing here's a quick overview of what I'm doing (it's mostly for statistical purposes):

*

*Read data from a CSV file, each line resembles a custom object MyClass1 containing around 60 objects MyClass2.

*Iterate through all the instances of MyClass1, adding or editing properties of each of the MyClass2 objects, depending on various conditions.

If more information is needed, I'll surely post it. The reason I don't post code is because I basically wouldn't know which lines from around 4000 to pick out. I'm not trying to hold any information back because I'm coding something super secret, I simply don't know what else might be useful.
edit3: Question: "could you process each line at a time, or do you need the context of the whole file first?"

*

*I do need the context of the whole file. So for example MyClass1[4000][0] depends on Data from MyClass1[0][0], MyClass1[1][0] etc. More information: Reading the CSV file and creating the "empty" objects works fine. The error gets thrown later on when I iterate through all the MyClass1 objects.

A: EDIT: Okay, now it's slightly clearer what you're doing... but a multidimensional array of size 5000 x 60 is still only 300,000 elements. What is each element? Do you think you actually need more data in memory at a time than your machine can handle?
It's not really clear what you're doing - do you definitely need all the information in memory at once? Perhaps the problem is that you're preventing the arrays from being garbage collected when you're dne with them?
Without knowing what sort of processing you're doing, it's hard to know whether a database is appropriate, but arrays are about as efficient as you're likely to get if you actually need a value for every element. If you could manage with a sparse array, that would be a different matter of course.

A: I think the problem is that when used large structures memory never cleans and when you pass such array to method, all memory are copied, so OutOfMemoryException it's a possible result of such large arrays, read this to solve the problem


text:
Q: Perl - Breaking out of a system/backticks command on keypress if it takes a long time I have a problem I am hoping someone can help with...
I have a foreach loop that executes a backticks command on each iteration, such as greping a folder in a directory for a string (as shown below, greatly simplified for the purposes of explaining my question).
my @folderList = ("/home/bigfolder", "/home/hugefolder", "/home/massivefolder");
my @wordList = ("hello", "goodbye", "dog", "cat");

foreach my $folder (@folderList) {
     foreach my $word (@wordList) {
          print "Searching for this $word in this $folder\n";
          my @output = `grep -R $word $folder`;    #this could take hours so the user needs the option to skip/cancel this iteration and go the next one
          print "@output\n";
     }
}

The problem I am having:
If the folder the backticks grep command is being run against is particularly large or the array of words to check against is particularly large then the backticks command could take hours to complete (which is fine).
But what i want to be able to do is to break out of the inner loop (i.e when a word is being greped for in a folder) and go to the next iteration if it is taking a long time when the user presses a key on the keyboard or enters the word "next" or "exit" for example.
I know that if i wasnt using backticks I could easily break out of a normal loop using something like the following (but the logic of this obviously does not work when a backticks/system call is involved):
use strict;
use warnings;

use Term::ReadKey;

my $n = 0;

while () {
    print '.';
    last if ReadKey(-1);
    $n++;
}

print $n;

There may be a simple solution that I am overlooking but I have never had the need to do this before, so your help is much appreciated, thanks

A: The solution is to run the long-running program in a background process (and remember the process id of the new process), and keep your user interaction in the foreground process. When the foreground is signaled to break, kill the background process.
All the parts I mentioned are well-explained in previous posts on Stack Overflow.

A: You are trying to simultaneously run an external command and process keyboard events, so you need to use some asynchronous framework. Asynchronous frameworks are based on either forks, threads, or event loops, and event loops are not appropriate in this case.
Here's an outline of how you could use a fork:
use POSIX ':sys_wait_h';  # defines WNOHANG

foreach my $folder (@folderList) {
     foreach my $word (@wordList) {
          print "Searching for this $word in this $folder\n";

          my $pid = fork();
          if ($pid == 0) {  # child process
              # we are just printing output from the child process; if you want
              # to move data from the child process back to the parent, well,
              # that's a whole other can of worms
              print `grep -R $word $folder`;
              exit;
          } else {          # parent process
              while (waitpid($pid, &WNOHANG) != $pid) {
                  if (Term::ReadKey(-1)) {
                      kill 'TERM', $pid;    # or maybe kill 'KILL', ...
                      last;
                  }
              }
          }
     }
}

A: I understand what people have said regarding background processes, threads and forking and so on, but the option that suited my arrangement the best (and is probably the easier to implement), although I confess may not be the most efficient, best practice or preferred way of doing it, involved using eval and catching user control-c keypresses.
Very Simple Example:
NEXT:foreach $folder (@folders) {     #label on the foreach

         eval {
               $SIG{INT} = sub { break() };   #catches control-c keypress and calls the break subroutine
               $var1 = `grep -r "hello" $folder`;
         };

         sub break {
              print "Breaking out of the backticks command and going to next folder \n";
              next NEXT;
         }

     } #ending bracket of foreach loop


text:
Q: Show some characters above a picture on hover I would like to show a word above a picture that has a filter on hover.
I'm trying to do this with :before but it doesn't work.
HTML

CSS
.photo { position: relative; }
.photo:hover { filter: brightness(0.5); -webkit-filter: brightness(0.5); -moz-filter: brightness(0.5); z-index: 9; }
.photo:hover:after { content: "test"; font-family: "arial"; position: absolute; height: 50px; width: 50px; top: 50%; left: 50%; z-index: 99; color: #fff; font-size: 50px; opacity: 0; }

Here is the JSFiddle demo : http://jsfiddle.net/y5j90ccn/
How to resolve this ?

A: Set the opacity in .photo:hover:after to 1:
.photo {
    position: relative;
}

.photo:hover{
    filter: brightness(0.5); -webkit-filter: brightness(0.5); -moz-filter: brightness(0.5); z-index: 9;
}

.photo:hover:after { content: "test"; font-family: "arial"; position: absolute; height: 50px; width: 50px; top: 50%; left: 50%; z-index: 99; color: #fff; font-size: 50px; opacity: 1; }

demo

A: Your problem is that you wrote "opacity: 0;", which sets the opacity of the text to 0 - making it invisible. Just take that css property out and you'll see the text.
Also, this normally doesn't matter and is a bit nit picky, but you generally want to use "::after" instead of ":after".

A: Please try this : http://jsfiddle.net/y5j90ccn/8/

 Hover me

.photo , div{
   float: left;
    position: relative;
    width: auto;
}
    .hover_text{    background: none repeat scroll 0 0 #fff;
        color: #000;
        font-size: 20px;
        height: 50px;
        line-height: 50px;
        opacity: 0.5;
        position: absolute;
        text-align: center;
    bottom: 4px;
        width: 100%; display:none;transition: all 0.5s ease-in;}
    div:hover .hover_text{display:block; transition: all 0.5s ease-in;}

A: You just need to update your css as below, opacity and position of text to change for expacted result.
   .photo {
    position: block;
    -webkit-transition: all 30ms;
    -moz-transition: all 30ms;
    transition: all 30ms;
    max-width: 50%;
}

.photo:hover {
    filter: brightness(0.5); -webkit-filter: brightness(0.5); -moz-filter: brightness(0.5); z-index: 9;
}

.photo:after { content: "test"; font-family: "arial"; position: absolute; height: 50px; width: 50px; top: 30%; left: 20%; z-index: 99; color: #fff; font-size: 50px; opacity: 0; }
.photo:hover:after{ opacity:1; }

A: Seems there are several things to do here in order to accomplish what you want.

*

*Remove opacity: 0 which prevents text from displaying.

*Move position: relative to parent element,
.

*Set
 to inline-block so it doesn't have full width of container and position will work more like expected.

.test {
    position: relative;
    display: inline-block;
}

.test img:hover {
filter: brightness(0.5); -webkit-filter: brightness(0.5); -moz-filter: brightness(0.5);
}

.photo:hover:after {
content: "test"; font-family: "arial"; width: 50px; height: 50px; position: absolute;
top: 40%; left: 40%; color: #fff; font-size: 50px;
}

Take a look: http://jsfiddle.net/y5j90ccn/13/

A: Here is the Solution. JSFIddle, Opacity should be greater then 0.

A: You can achieve that by simply adding a title attribute on your image tag. Like following:


text:
Q: CGAL: How to efficiently calculate the area of facets of a polyhedron? I have a polyhedron whose facets are triangles. I am aware that in CGAL, Triangle_3 class offers 'squared_area' method through which we can calculate the area of a triangle. Is there any way we can apply this to polyhedral facets? Or any ideas as to how to calculate area of each facet?

A: Here is an example:
#include <CGAL/Simple_cartesian.h>
#include <CGAL/Polyhedron_3.h>
#include <numeric>
#include <functional>
#include <boost/iterator/transform_iterator.hpp>

typedef CGAL::Simple_cartesian<double> K;
typedef CGAL::Polyhedron_3<K> Polyhedron;

struct Compute_area:
  public std::unary_function<const Polyhedron::Facet, double>
{
  double operator()(const Polyhedron::Facet& f) const{
    return K::Compute_area_3()(
      f.halfedge()->vertex()->point(),
      f.halfedge()->next()->vertex()->point(),
      f.halfedge()->opposite()->vertex()->point() );
  }
};

int main()
{
  Polyhedron p;
  p.make_tetrahedron(
    K::Point_3(0,0,0),
    K::Point_3(0,1,0),
    K::Point_3(1,1,0),
    K::Point_3(1,1,3)
  );

CGAL_assertion( p.is_pure_triangle() );

  Compute_area ca;

  std::cout <<
    std::accumulate(
      boost::make_transform_iterator(p.facets_begin(), ca),
      boost::make_transform_iterator(p.facets_end(), ca),
      0.)
  << std::endl;
}

EDIT
There is the free function CGAL::Polygon_mesh_processing::area() that is available in recent releases of CGAL.

A: Expanding @sloriot answer, since std::unary_function is deprecated in C++11 and will be removed from C++14 onwards. However the unary_function isn't needed anymore and Compute_area can simply be implemented as
struct Compute_area
{
   double operator()(const Polyhedron::Facet& f) const {
   return K::Compute_area_3()(
     f.halfedge()->vertex()->point(),
     f.halfedge()->next()->vertex()->point(),
     f.halfedge()->opposite()->vertex()->point() );
    }
};


text:
Q: The changes I make to an external JS file of my WP plugin are only applied after I clear my browser's cache I'm making a WordPress plugin which loads an external JS file for some Google Maps related operations. But the problem is that the changes I make to this external JS file are not applied immediately and shown on the Google Chrome browser, but instead I have to delete the "Images and other data" cache of Chrome in order for the changes I make to the JS file to be applied.
For example I have an alert("DynamicMap.js file was loaded succesfully.); in the first line of the file but the changes I make to the text only apply after I clear the cache. Does anyone know why does this happen and if I can prevent it? Thanks in advance. (Note that I'm testing plugin online on my personal website, not on the localhost.)

A: Use function filemtime($path), where $path is a path to your script, in wp_enqueue_script call, as fourth parameter (version). Every time you modify the script, the cache will be bypassed.
Update
Calls to wp_register_script and wp_enqueue_script:
wp_register_script('DynamicMapScript', plugins_url('DynamicMap.js', __FILE__), array('jquery'), filemtime(dirname(__FILE__) . '/DynamicMap.js'));
wp_enqueue_script('DynamicMapScript');


text:
Q: The $\gcd$ operator commutes with functions defined by linear recurrence relations Given $a,b\in\mathbb Z^+$, and let $F_{a,b}:\mathbb N\to\mathbb N$ be a function such that $F_{a,b}(0)=0$ and $F_{a,b}(n+1)=a\cdot F_{a,b}(n)+b\cdot F_{a,b}(n-1)$. $F_{1,1}$ correspond to the Fibonacci function if $F_{1,1}(1)=1$.

Conjecture which I would like to see proved:
If $a,b$ are co-prime and $F_{a,b}(1)\in \mathbb Z^+$, then $F_{a,b}(\gcd(m,n))=\gcd(F_{a,b}(n),F_{a,b}(m))$

I guess that some formulation of the conjecture is true for all homogeneous linear recurrence relations with constant coefficients of degree > 1, but I have only (randomly) tested it for degree 2.
See also A generalization of a divisibility relation for Fibonacci numbers


text:
Q: How to configure JPA to use JNDI? I have a working persistence definition that works on java level tests. Now I want to incorporate that into a web application which defines the database connection as JNDI in the context.xml. What do I need to change to make it work with the JNDI instead of the persistence.xml or at least get the infor from there?

A: Your persistence.xml beginning should be something like this (using EclipseLink as implementation), for a jdbc/MYNAME JNDI name:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
  <persistence-unit name="myPersistenceUnit" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <non-jta-data-source>java:comp/env/jdbc/MYNAME</non-jta-data-source>
    <class>org.test.entity.MyEntity</class>
...
  </persistence-unit>
<persistence>

Of course you should set the configuration suitable for your environment. In the example I use a non-JTA DataSource: according to one of your comments, it seems your DataSource is not JTA-compliant. For Hibernate, the persistence provider should be different.

A: you must use the persistence.xml when you're using JPA. because JPA must check the persistence.xml. so you can use persistence.xml and jndi at the same time.


text:
Q: Python _winreg woes I'm trying to access the windows registry (in Python) to query a key value using _winreg and I can't get it to work. The following line returns a WindowsError saying that the "system cannot find the specified file":
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Autodesk\Maya\2012\Setup\InstallPath', 0, _winreg.KEY_ALL_ACCESS)

After hours of trying, it looks like Python cannot see beyond the "Maya" part of the path (it looks like the "2012\...etc..." sub-path is "invisible" or non-existent). Now I have the Registry Editor open and I guaranty there IS such a path in the HKLM. I'm on Windows 7 64bit. Any idea what I'm doing wrong? This is driving me nuts. Thanks...

A: Are you also using a 64-bit version of Python, or is it a 32-bit Python? (The latter is more common.) If you're using a 32-bit version of Python, the _winreg module will see the 32-bit registry by default, while regedit will show you the 64-bit one. You should be able to tell _winreg to open a different view; see the _winreg module docs on access rights, specifically the subsection on 64-bit specific flags and the MSDN article it references. Unfortunately it doesn't look like there's a way for a 32-bit process to access the 64-bit registry, but I may be missing something.

A: You need to combine the access key with one of the 64bit access keys.
_winreg.KEY_WOW64_64KEY
    Indicates that an application on 64-bit Windows should operate on the 64-bit registry view.
_winreg.KEY_WOW64_32KEY
    Indicates that an application on 64-bit Windows should operate on the 32-bit registry view.
Try:
_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Autodesk\Maya\2012\Setup\InstallPath', 0, (_winreg.KEY_WOW64_64KEY + _winreg.KEY_ALL_ACCESS))


text:
Q: Invalid cast from System.String to MongoDB.Bson.ObjectId while Deserialize Json String .Net I'm learning redis recently, and try to use key-value stringset the model into json string as value. I can serialize the model into json string success, but when I try to deserialize it back to model, an exception come out. If I don't want to change the type of Id to string, is there got other way to solve this problem? Thanks you.
Exception:
Newtonsoft.Json.JsonSerializationException: 'Error converting value "5b5b4df5b8e2e208efb2c0da" to type 'MongoDB.Bson.ObjectId'. Path 'Id', line 1, position 64.'
InvalidCastException: Invalid cast from 'System.String' to 'MongoDB.Bson.ObjectId'.

Model:
public class TblUser
{
    public ObjectId Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

Serialize:
public static string ObjToStr(Object obj)
{
    return JsonConvert.SerializeObject(obj);
}

Deserialize:
public static T StrToObj<T>(string str)
{
    return JsonConvert.DeserializeObject<T>(str);
}


text:
Q: Is C# namespace separator (.) defined somewhere? Full name separator in C# is period character (.). e.g. System.Console.Write.
Is this defined somewhere like Path.PathSeperator, or is it hard coded in .NET reflection classes as well?
(e.g. is Type.FullName implemented as Type.Namespace + "." + Type.Name assuming that it won't change?

A: The delimiter between a type and its namespace is defined in the BCL on the Type.Delimiter field. You'll see this value used in the Reflection APIs and can be reliably used to concatenate a type and its namespace.

A: According to where it's used in the reference sources, @Paul's Type.Delimiter is the answer to your main question, but the answer to your e.g. is yes, '.', as well as '+', as mentioned in @Marc's answer, is hard coded.

A: Basically: the language specification. But actually, Type.FullName uses the BCL definitions, not the C# definitions - and interestingly they disagree. For example:
namespace X {
    public class Y {
        public class Z {}
    }
}

To C#, Z is X.Y.Z; to the BCL it is X.Y+Z. The representation of generics changes too - with the BCL using back-ticks and numbers rather than angular brackets. I believe the BCL uses the CLI's format of types (which has a separate specification), but if you think about it: it is not required to do so (except for during reflection-emit).
AFAIK, these separators are not exposed via anything like Path.PathSeparator - but is, as you say, hard coded into the Type etc classes.


text:
Q: Intellij IDEA 11 Run Configuration Classpath Problems I am using IDEA 11 and need to run a class with a main method but with additional classpath entries - both xml files and jars. I have tried adding them as Global Libraries, as additional source content roots, and as regular additional libraries, however none of these seem to pick up the xml files and so when I execute the run config I get FileNotFoundExceptions.
Please can anyone suggest something else as the printed classpath in the console never contains any of my custom definitions.
If I can't solve this I may have to resort to learning Eclipse just to get stuff done. This is making me a little crazy. I have tried all the suggestions I could find on SO but no luck so far.

A: Did you check the answers to the similar questions?

*

*How load xml files, in IntelliJ IDEA

*Intellij - how do I add a text file to the resources

*Add a properties file to IntelliJ's classpath

*Java - setting classpath
If it still doesn't work, please share a sample project via Dropbox.


text:
Q: Task scheduler for python jobs I have one main function which I want execute with different arguments. It's function which play video on raspberry pi using omxplayer.
I would like to use scheduler which let me to plan executing of specific task, they should define time when task will be executed and/or make a queue, and if I execute this main function, scheduler places this task at the end of queue.
I have tried Python-RQ and it's good, but the problem is that I don't know how I can add new task at the end of queue if I don't know name of previous job..
I have function which should adds jobs to queue.
def add_movie(path):
    q.enqueue(run_movie2, '{0}'.format(path))

Which execute:
def run_movie2(path):
    subprocess.Popen(['omxplayer','-o', 'hdmi', '/home/bart/FlaskApp/movies/{0}'.format(path)])
    return "Playing {0}".format(path)

Do you know scheduler which meet the requirements?
What can you advise with python rq? Is it any way to do it one by one ? How can I always add jobs at the end of queue ?
Thank you.


text:
Q: Code Generator vs Code Refactoring How do you like your CRUD programs.  Code-generated, framework-driven, or manually written?

A: My experience with code generators is that they're a good start but after the changes have settled down I usually want to rewrite the modules by hand.  Of course, that can become a maintenance problem.  But it really turns into a "how long is a piece of rope" question.  Which generators, frameworks, and resources are you dealing with?  Some of them are horrors to deal with, others work all right.

A: I like code generators with custom templates for the following reasons:
   Reduces coding effort
   Easy to make global changes
   Embed architecture in templates ensures developer compliance.
   Less chance of coding errors.
   Consistent functionality
   Less to test.
In fact, using code generators I was able to create, or recreate, the store procedures, entity classes, and DAL from a modified database with 60+ tables in minutes when the schema was updated.  By using custom templates, I was ensured that the all layers worked with my naming rules and ensured proper error handling and prevention of double insertion.
Great for fixed price contracts.  If it is hourly, then you might want to do it by hand :-)

A: If you use .Net use Linq, then it is easy to maintain. LinqToSql makes it easy to update your data model with out having to change the code a whole lot.

A: I like a mixture of framework driven and manually written.  I've done a little bit with NHibernate and LinqtoSql and sometimes the queries they generate for me need a little bit of help.

A: This really depends on the size of your application. Hand-crafted Data Access Layers make the most sense for a very small application as you have ultimate control but for any medium to large size application I would recommend a code generator. I've had various experience with APEX SQL (not great), LINQ and Subsonic (both very good). I'm just about to evaluate a Telerik ORM shortly but I imagine that will be pretty good also.

A: In my opinion code generators are a sign of bad design and violate DRY.  Where as a good framework will have you maintaining less code.  With frameworks you also end up extending and refactoring code rather than a code template.

A: Frameworks are choice one, if I need to use a code generator I like to throw together a quick Perl script that generates the code so I understand exactly what is getting generated and why.

A: They are useful if you view your users as data entry clerks to maintain your database tables for you. They help minimize the programming time required to meet minimum requirements.
If you want the quality of your work to reflect something better than that, the best that can be said for them is they might give you a jumpstart if you're not too sure how to do simple consistent UI screens yourself.
Personally I find that refactoring them into something useful and attractive based on real Use Cases takes longer than doing it from scratch. They're the kind of technique Dilbert's pointy-haired boss would love.

A: I find a good framework for CRUD logic better than code generators.  I have run into situations when a complex set of tables generated a terribly slow query to produce the result.


text:
Q: Rails 4: has_many through associated object never return nil I have two Model, Post and Category. They are connected by has_many through association. Categorization is the through table.
@post= Post.find(params[:Post_id])
@category = @post.categories

Some of my post are not under any category. It is possible to post without selecting any category. Problem is @category never show nil. I perform this check
<% if @category %>

    <% else %>

    <% end %>

This code never goes in else block even though there are no categories. Why is that? How can I check nil in this case?

A: @post.categories returns an activerecord relation,not nil.  Because you're using rails I'd check it's presence using present?
<% if @vertiefungsrichtungs.present? %>
   # do something
<% else %>
   # do something else
<% end %>

A: Chances are that since you have a potential for multiple categories, that you will want to do something with them, not just check if there are any.
In that case one thing you could do is render a partial for each category:
<%= render partial: my_category, collection: @category, as: :category %>

You should have a partial _my_category.html.erb:
<%= category %>

If there are no categories, no my_category partials will be rendered, so, no need for additional logic in the view.


text:
Q: Jira communication using java I am trying to communicate with jira using Java but i am facing an exception as shown below
xception in thread "main" java.lang.NoSuchFieldError: INSTANCE
    at org.apache.http.impl.nio.conn.DefaultClientAsyncConnectionFactory.createHttpResponseFactory(DefaultClientAsyncConnectionFactory.java:105)
    at org.apache.http.impl.nio.conn.DefaultClientAsyncConnectionFactory.<init>(DefaultClientAsyncConnectionFactory.java:74)
    at org.apache.http.impl.nio.conn.DefaultClientAsyncConnectionFactory.<clinit>(DefaultClientAsyncConnectionFactory.java:62)
    at org.apache.http.impl.nio.conn.PoolingClientAsyncConnectionManager.createClientAsyncConnectionFactory(PoolingClientAsyncConnectionManager.java:96)
    at org.apache.http.impl.nio.conn.PoolingClientAsyncConnectionManager.<init>(PoolingClientAsyncConnectionManager.java:72)
    at com.atlassian.httpclient.apache.httpcomponents.DefaultHttpClient$2.<init>(DefaultHttpClient.java:117)
    at com.atlassian.httpclient.apache.httpcomponents.DefaultHttpClient.<init>(DefaultHttpClient.java:115)
    at com.atlassian.jira.rest.client.internal.async.AsynchronousHttpClientFactory.createClient(AsynchronousHttpClientFactory.java:53)
    at com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory.create(AsynchronousJiraRestClientFactory.java:35)
    at com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory.createWithBasicHttpAuthentication(AsynchronousJiraRestClientFactory.java:42)
    at jira.JiraCommunicate.main(JiraCommunicate.java:33)

Exception i am facing at this line
 JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD);
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collection;

import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.JiraRestClientFactory;
import com.atlassian.jira.rest.client.api.domain.BasicProject;
import com.atlassian.jira.rest.client.api.domain.Comment;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.api.domain.SearchResult;
import com.atlassian.jira.rest.client.api.domain.Transition;
import com.atlassian.jira.rest.client.api.domain.User;
import com.atlassian.jira.rest.client.api.domain.input.FieldInput;
import com.atlassian.jira.rest.client.api.domain.input.TransitionInput;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import com.atlassian.util.concurrent.Promise;

public class JiraCommunicate {

     private static final String JIRA_URL = "";
        private static final String JIRA_ADMIN_USERNAME = "";
        private static final String JIRA_ADMIN_PASSWORD = "";

        public static void main(String[] args) throws Exception {
            // Construct the JRJC client
            //System.out.println(String.format("Logging in to %s with username '%s' and password '%s'", JIRA_URL, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD));
            JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
            URI uri = new URI(JIRA_URL);
            JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD);

            // Invoke the JRJC Client
            Promise<User> promise = client.getUserClient().getUser("admin");
            User user = promise.claim();

            for (BasicProject project : client.getProjectClient().getAllProjects().claim()) {
                System.out.println(project.getKey() + ": " + project.getName());
            }

            Promise<SearchResult> searchJqlPromise = client.getSearchClient().searchJql("project = MYPURRJECT AND status in (Closed, Completed, Resolved) ORDER BY assignee, resolutiondate");

            for (Issue issue : searchJqlPromise.claim().getIssues()) {
                System.out.println(issue.getSummary());
            }

            // Print the result
            System.out.println(String.format("Your admin user's email address is: %s\r\n", user.getEmailAddress()));

            // Done
            System.out.println("Example complete. Now exiting.");
            System.exit(0);
        }

    }

Blockquote

Please i need your help..I want to communicate Jira to upload or download Story or create bugs..


text:
Q: How to use result of a function that uses promises I have a function,
  asdf() {
    var a = fooController.getOrCreateFooByBar(param);
    console.log("tryna do thing");
    console.log(a); //undefined
    if (!a.property) {
      //blah
    }

that dies. getOrCreateFooByBar does a
  Model.find({phoneNumber : number}).exec()
  .then(function(users) {})

and finds or creates the model, returning it at the end:
.then(function(foo) { return foo}

How can I use the result of this in asdf()? I feel like this is a fairly easy question but I am getting stuck. If I try to do a.exec() or a.then() I get 'a cannot read property of undefined' error.

A: The main idea about Promises (as opposed to passed callbacks) is that they are actual objects you can pass around and return.
fooController.getOrCreateFooByBar would need to return the Promise it gets from Model.find() (after all of the processing done on it). Then, you'll be able to access it in a in your asdf function.
In turn, asdf() should also return a Promise, which would make asdf() thenable as well. As long as you keep returning Promises from asynchronous functions, you can keep chaining them.
// mock, you should use the real one
const Model = { find() { return Promise.resolve('foo'); } };

function badExample() {
  Model.find().then(value => doStuff(value));
}

function goodExample() {
  return Model.find().then(value => doStuff(value));
}

function asdf() {
  var a = badExample();
  var b = goodExample();

  // a.then(whatever); // error, a is undefined because badExample doesn't return anything

  return b.then(whatever); // works, and asdf can be chained because it returns a promise!
}

asdf().then(valueAfterWhatever => doStuff(valueAfterWhatever));


text:
Q: How to use CoreData to store the best scores for a game (iOS) I've looked at a number of SO questions (for example)..
I don't have one score though. I have an app that tests people's ability to learn another language. So I have a score for each word.
I can read from the model, but I don't know how to set an incremental value.
A score is attached to each word in each language. Ideas would be great.
Right now, my database model is a single entity as follows:

I'm at the point where I have the correct result but don't know what to do with it..
I havent gotten beyond this when my brain blew.
-(void) incrementScore {
    NSLog (@"incrementScore");
     WordEntity * word = nil;

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    int languageKey = [defaults integerForKey:DEFAULT_KEY_LANGUAGE_NUMBER];

    if (languageKey == 0) {
        currentScore  = [word.greekScore integerValue];

    } else {
        currentScore = [word.englishScore integerValue];
    }

    if (languageKey == 0) {
        //NSNumber *tempNumber;
        //word.greekScore setValue:currentScore forKey:<#(NSString *)#>
       // word.greekScore = [word.greekScore +1 ];
        currentScore  = [word.greekScore integerValue];

    } else {
        currentScore = [word.englishScore integerValue];
    }
    currentScore = currentScore + 1;

A: the new farmville age way of doing this is to use gamecenter instead of
killing a fly with a coredata cannon
I suppose that does not answer your question, does it


text:
Q: How to convert yii view page into pdf and download it? This is my view page that i want to download as pdf. My view link: http://localhost/myproject/Applicant/1

I want to put a download PDF button at the right top of that page, When i click on it, The user profile should be downloaded in PDF. Im new to yii so not sure how to do it, But by searching on google, i found some extensions.

*

*yii-pdf

*mpdf1

by following these above extensions, I put those extensions in my protected/extension folder. Then Here is my main/config file..
'components'=>array(
    'user'=>array(
        // enable cookie-based authentication
        'class' => 'WebUser',
        'allowAutoLogin'=>true,
        'returnUrl'=>'/site/index#login',
        'loginUrl'=>array('/Applicant/login'),
    ),
    'ePdf' => array(
        'class'         => 'ext.yii-pdf.EYiiPdf',
        'params'        => array(
            'mpdf'     => array(
                'librarySourcePath' => 'application.extensions.mpdf.*',
                'constants'         => array(
                    '_MPDF_TEMP_PATH' => Yii::getPathOfAlias('application.runtime'),
                ),
                'class'=>'mpdf', // the literal class filename to be loaded from the vendors folder
                /*'defaultParams'     => array( // More info: http://mpdf1.com/manual/index.php?tid=184
                    'mode'              => '', //  This parameter specifies the mode of the new document.
                    'format'            => 'A4', // format A4, A5, ...
                    'default_font_size' => 0, // Sets the default document font size in points (pt)
                    'default_font'      => '', // Sets the default font-family for the new document.
                    'mgl'               => 15, // margin_left. Sets the page margins for the new document.
                    'mgr'               => 15, // margin_right
                    'mgt'               => 16, // margin_top
                    'mgb'               => 16, // margin_bottom
                    'mgh'               => 9, // margin_header
                    'mgf'               => 9, // margin_footer
                    'orientation'       => 'P', // landscape or portrait orientation
                )*/
            ),
        ),
    ),

I have created this action in ApplicantController
public function actionPDF()
{
    $mPDF1 = Yii::app()->ePdf->mpdf();
    $mPDF1->WriteHTML($this->render('UserProfileView',true));
    $mPDF1->Output();
}

What should i do next? how to get the button on that view file which is link to controller action to download file.

A: You need to submit your form to an action.
for example, in your view:
<?php echo CHtml::button('Button Text', array('submit' => array('controller/action'))); ?>

In here the button will call the action in controller and execute what need to be done in that action.

EDITED

If I'm right, you are rendering protected/views/applicant/view.php  so you can add in the sidebar the link to you action:
<?php
/* @var $this ApplicantController */
/* @var $model Applicant*/

$this->breadcrumbs=array(
  'Applicant'=>array('index'),
   $model->id,
);

$this->menu=array(
    array('label'=>'List Applicant', 'url'=>array('index')),
    array('label'=>'Create Applicant', 'url'=>array('create')),
    array('label'=>'Create PDF', 'url'=>array('PDF')),

Don't forget adding to rules in your ApplicantController.php:
public function accessRules()
{
    return array(
        array('allow',  // allow all users to perform 'index' and 'view' actions
            'actions'=>array('index','view','PDF'),
            'users'=>array('*'),


text:
Q: Android-Studio databinding not working I wanted to take a look into data binding for Android so it set up a small project. But i can't seem to get it working for Android Studio.
Basically the problem is it doesn't render my layouts in the Android Studio editor because it complains it cannot find the <Layout> and <data> classes. I could run the project though.
I followed the instructions mentioned in https://developer.android.com/tools/data-binding/guide.html. Although there are remarks about lacking Android Studio integration i couldn't find anything about not being able to view the Layout files, as it would be a major drawback.
I have setup
classpath 'com.android.databinding:dataBinder:1.0-rc1'

and
apply plugin: 'com.android.databinding'

compile 'com.android.support:appcompat-v7:21.0.3'

in the gradle files.
I also have the latest Android Studio installed and i already rebuild my  project.
EDIT:
I found https://code.google.com/p/android/issues/detail?id=176274 discussion. They are mentioning this issue to be fixed in AI-141.2006197 and i am running AI-141.2017176 which should be later and therefore containing this feature, right?
EDIT 2:
Updated now and also tried with AI-141.2218876, still the same issue.

A: Make sure the <layout> tag is not capitalized in your XML file! I see that it is capitalized in your question.  That won't work.
If this isn't the solution, please update our question to include the full activity and XML layout and stack trace of the build failure.


text:
Q: Comparing and extracting similar strings from 2 arrays in java, double words not compared I know that similar question was asked before, however I cannot find the answer to my problem!
I am comparing arrays and extracting similarities with the HashSet.
final String[] abc = nlp_text.split(" ");
final String[] xyz = getResources().getStringArray(R.array.xyz);

    final HashSet<String> set = new HashSet<>();
    for(String a : abc) set.add(a.toLowerCase());
    final HashSet<String> set1 = new HashSet<>();
    for(String a : xyz) set1.add(a.toLowerCase());
    set.retainAll(set1);
    String[] pqr= {};
    pqr = set.toArray(pqr);

This works on single word strings, however does not work on double word strings. For instance, strings "John" and "Doe" will be recognised separately, but "John Doe" will not.
any idea why?
UPDATE: as was pointed out to me it was the nlp_text.split(" ") issue. However, when I tried splitting it with "," and then all other marks, it would not recognise any of the strings. return would be just blank... help, pls!

A: nlp_text.split(" "); splits the words, therefore your "John Doe" String becomes two seperate "John" and "Doe" Strings. I recommend split the nlp_text with commas for example, so that your two word Strings are counted as one String.

A: When you define abc:
final String[] abc = nlp_text.split(" ");
final HashSet<String> set = new HashSet<>();
for(String a : abc) set.add(a.toLowerCase());

you are doing a split by " " so "abc" is only going to have one word strings, so "set" is only going to have one word strings, so later when you do the retain.
set.retainAll(set1);

This means "set" can only retain one word strings, because it only have one word strings.


text:
Q: How can I read context parameter/web.xml values in a non-servlet java file? I've got a regular java file that I use to update and query a mysql database but I need to take configurable options in that file (like host name, password, etc) and put it in the web.xml file (or perhaps another file if that's an option, but ideally in web.xml).
But I don't know how to get access to web.xml values from a regular non-servlet java file.
Or would I need to read the xml (like any other xml file...  or is there a shortcut route to this...)

A: You need to put the required parameters in env-entry entries of your web.xml file:
<env-entry>
    <env-entry-name>dbhost</env-entry-name>
    <env-entry-type>java.lang.String</env-entry-type>
    <env-entry-value>localhost</env-entry-value>
</env-entry>

and then access them via the jndi context
import javax.naming.Context;
import javax.naming.InitialContext;
...
// Get the base naming context
Context env = (Context)new InitialContext().lookup("java:comp/env");

// Get a single value
String dbhost = (String)env.lookup("dbhost");

A: One way is to read xml file and parse it.
You can put it on some static map in after parsing in ServletContextListener

A: You could use context-parameters in your web.xml and a javax.servlet.ServletContextListener to populate some static fields.
In you normal java class you read this this static fields.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
...
<context-param>
    <description>Prameter</description>
    <param-name>myParam</param-name>
    <param-value>123456790</param-value>
</context-param>
...
</web-app>

You can access this context parameter with ServletContext.getInitParameter

A: Implement a ServletContextListener:
package util;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyConfigListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext ctx = sce.getServletContext();

        String hostname = ctx.getInitParameter("my.config.hostname");

        // now go and do something with that
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {}

}

And don't forget to register it in web.xml:
<context-param>
  <param-value>somewhere.example.org</param-value>
  <param-name>my.config.hostname</param-name>
</context-param>
<listener>
  <listener-class>util.MyConfigListener</listener-class>
</listener>

A: Create a static class that would be initialized from one of the servlets init.


text:
Q: Master theorem for $T(n) = 9T(\frac{n}{3}) +4n^6$ based on master theorem, I arrived at $$n^{2} ,f(n)=4n^6$$.
So is the answer $$\theta(4n^6)$$ or is it just $$\theta(n^6)$$.
And also, can this be solved with substitution method?

A: A hint for you - after $k$ substitutions you should have:
$$T(n) = 9^kT(\frac{n}{3^k}) + 4n^6\sum_{i=0}^{k-1}c^i$$
where $c$ is a constant.