text:
Q: Why does Bundler.require not require dependencies? I am developing a gem at the moment. Here's how the .gemspec looks like:
gem.add_dependency 'activerecord', '~> 4.2'
...

gem.add_development_dependency 'rails', '4.2.5'
...

and here's my Gemfile:
source 'https://rubygems.org'

gemspec

I am setting up my main file, lib/my_gem.rb like so:
module MyGem
  module Lib
  end
end

ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)

require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
Bundler.require

However, if I start bundle console from my gem's folder, the dependencies are not required:
$ bundle console
Resolving dependencies...
irb(main):001:0> Rails
NameError: uninitialized constant Rails
...
irb(main):002:0> ActiveRecord
NameError: uninitialized constant ActiveRecord
...

What am I doing wrong?

A: I believe dependencies included via the gemspec command in the Gemfile are not automatically required by Bundler.require. Only gems listed directly in the Gemfile itself are.
Additionally, gems included in only certain Bundler groups, like 'development', may not be required by a Bundle.require even if they were included directly in the Gemfile, you need to tell bundler to require groups other than default.
You can always require gems manually though, like require 'rails'. Bundle.require doesn't do anything but require gem for each gem in your Gemfile (or at least default group in your Gemfile), it's doing any magic other than looking up all the gems in your Gemfile and requiring them.  Bundle.require is considered by some to be a bad practice anyway, you should just require the dependencies you need in the files you need them, some say. Although Rails doesn't agree, and Rails apps have their own somewhat complicated way of auto-loading things.
But if you are in a Rails app, as your example dependencies suggest... why are you doing any require 'bundler/setup' or Bundle.require yourself at all though, instead of letting Rails boot process take care of it?  Rails boot process will take care of requiring the Bundler groups you probably expect too (like the "development" group when in Rails.env == 'development').
You can use the bundler api yourself directly like you're doing, it's not too hard. But Rails ordinarily takes care of this for you, and if you are using Rails, rails probably already has done a Bundler.setup and Bundler.require as part of Rails boot process.


text:
Q: Bar Stack Category Column I have the following implementation:
http://jsfiddle.net/7dhb4jh0/1/
Even though I have data for men and women category, all data displayed in one column. Women category is missing.
   {
     "series": "item5",
     "category": "Men",
     "value": 54
   },
   {
     "series": "item7",
     "category": "Women",
     "value": 50
    },

A: For the grouping to work, you need the same item names for men and women:
{
 "series": "item5",
 "category": "Men",
 "value": 54
},
{
 "series": "item5",
 "category": "Women",
 "value": 50
},

Updated FIDDLE

redpajama_set_name: RedPajamaStackExchange


text:
Q: python uploading a remote file to GCS , without saving it in the machine i have a  API which is supposed to give me a zip file , which contains a CSV file within...
my main task is to upload this to GCS
now, the simple approach we could take is

*

*Download zip

*extract CSV and save it locally somewhere

*Send that locally save CSV to GCS

My question here is , is there any way using which I can bypass the 2nd step, like I dont want to save the extracted CSV locally...instead I want to pass it directly to the GCS


text:
Q: With Google's #! mess, what effect would a redirect on the converted URL have? So Google takes:
http://www.mysite.com/mypage/#!pageState

and converts it to:
http://www.mysite.com/mypage/?_escaped_fragment_=pageState

...So... Would be it fair game to redirect that with a 301 status to something like:
http://www.mysite.com/mypage/pagestate/

and then return an HTML snapshot?
My thought is if you have an existing html structure, and you just want to add ajax as a progressive enhancement, this would be a fair way to do it, if Google just skipped over _escaped_fragment_ and indexed the redirected URL. Then your ajax links are configured by javascript, and underneath them are the regular links that go to your regular site structure.
So then when a user comes in on a static url (ie http://www.mysite.com/mypage/pagestate/ ), the first link he clicks takes him to the ajax interface if he has javascript, then it's all ajax.
On a side note does anyone know if Yahoo/MSN onboard with this 'spec' (loosely used)? I can't seem to find anything that says for sure.

A: If you redirect the "?_escaped_fragment_" URL it will likely result in the final URL being indexed (which might result in a suboptimal user experience, depending on how you have your site setup). There might be a reason to do it like that, but it's hard to say in general.
As far as I know, other search engines are not yet following the AJAX-crawling proposal.

A: You've pretty much got it.  I recently did some tests and experimented with sites like Twitter (which uses #!) to see how they handle this. From what I can tell they handle it like you're describing.
If this is your primary URL
 http://www.mysite.com/mypage/#!pageState

Google/Facebook will go to
 http://www.mysite.com/mypage/?_escaped_fragment_=pageState

You can setup a server-side 301 redirect to a prettier URL, perhaps something like
 http://www.mysite.com/mypage/pagestate/

On these HTML snapshot pages you can add a client-side redirect to send most people back to the dynamic version of the page. This ensures most people share the dynamic URL.  For example, if you try to go to http://twitter.com/brettdewoody it'll redirect you to the dynamic (https://twitter.com/#!/brettdewoody) version of the page.
To answer your last question, both Google and Facebook use the _escaped_fragment_ method right now.


text:
Q: p:commandLink doesn't trigger p:blockUI I am using PrimeFaces. Here is the code:
<h:form>
    <p:dataTable...>
        <p:column...>
            <p:commandLink id="featuresLinkId"...>
        </p:column>
    </p:dataTable>
</h:form>

<p:blockUI block=":smForm" trigger="featuresLinkId">
    <p:graphicImage alt="loader image" value="/images/loader.gif"/>
</p:blockUI>

When the page is being loaded, I see the following error:
javax.servlet.ServletException:
Cannot find component with identifier "featuresLinkId" in view.

Seems like commandLink can't be used to trigger blockUI in such a scenario. What could the problem be?

A: Because it won't find that compnent because its inside the form/datatable.
Make changes as
1-
<h:form id="formId">

2-
<p:dataTable id="tbl">

3-
<p:blockUI block=":smForm" trigger=":formId:tbl:featuresLinkId">

Try above .

A: There's a bug in Primefaces 3.5 I think
see: How to reference p:commandLink in p:dataTable from p:blockUI trigger?
You could try using JQuery BlockUI http://www.malsup.com/jquery/block/


text:
Q: Fusioncharts couple angulargouge to a database and Double arrow message showing up I'm trying to find a way to get information out of a database and use this information in a graph. Im using a libery (FusionCharts), this has some examples but not with data out of a database. So far i came up this this but im getting an error

Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW)

The example im using is this one Example angulargauge
 if ($result) {

$arrData6 = array(
  "chart" => array
  (
            "caption" => "Sended mail",
            "lowerlimit" => "0",
            "upperlimit" => "100",
            "lowerlimitdisplay" =>"0%",
            "upperlimitdisplay" => "100%",
            "palette" => "1",
            "numbersuffix" => "%",
            "tickvaluedistance" => "10",
            "showvalue" => "0",
            "gaugeinnerradius" => "0",
            "bgcolor" => "FFFFFF",
            "pivotfillcolor" => "333333",
            "pivotradius" => "8",
            "pivotfillmix" => "333333, 333333",
            "pivotfilltype" => "radial",
            "pivotfillratio"=> "0,100",
            "showtickvalues"=> "1",
            "showborder" => "0",
        ),

    "colorRange" => array (
    "color" => array
        (
            "minValue" => "0",
            "maxValue" => "50",
            "code" => "#e44a00"
        ),
        (
            "minValue" => "50",
            "maxValue" => "75",
            "code" => "#f8bd19"
        ),
        (
            "minValue" => "75",
            "maxValue" => "100",
            "code" => "#6baa01"
        )
),
"dials" => array (
    "dial" => array (
        "value" => "$precentage"
    )
)
  );

  $arrData6["data"] = array();

  $jsonEncodedData6 = json_encode($arrData6);

  $angularChart = new FusionCharts("AngularGauge", "chart4" , "100%", "200", "chart-5", "json", $jsonEncodedData6);
    // Render the chart
    $angularChart->render();
}

I can up with this by using the information on the page but since this one got more informatiesets (chart,dials and colors) I haven't been able to figure out how to do it yet.Database how to explaination i used
The $percentage is the result of the total - the not sended mail


text:
Q: python2.7 decorate function from external module used in another external module I have 3 files a.pyc, b.pyc, and c.py
file a.pyc:
def f(x):
    # do something with x and get y
    return y

file b.pyc:
from a import f

def g(x):
    z = f(x)
    # process z and get w
    return w

I can't modify these files but I can c.py and code in it will be executed before b.pyc question is can I add decorator (and how) in file c.py to function f and when function f will be called in g code in decorator will execute?

A: # a.py

class A:

    def __init__(self):
        pass

    def f(self, x):
        xx = x+100
        print xx
        return xx

# b.py

from a import A

class B:

    def __init__(self):
        self.a = A()

    def g(self):
        x = self.a.f(3) + 1000
        print x
        return x

# c.py

from functools import wraps
from a import A

def run_before(module, func_name):
    def decorator(callback):
        func = getattr(module, func_name)

        @wraps(func)
        def run_before_wrapper(*args, **kwargs):
            callback(*args, **kwargs)
            return func(*args, **kwargs)

        setattr(module, func_name, run_before_wrapper)
        return callback

    return decorator

def run_after(module, func_name):
    def decorator(callback):
        func = getattr(module, func_name)

        @wraps(func)
        def run_before_wrapper(*args, **kwargs):
            res = func(*args, **kwargs)
            callback(*args, **kwargs)
            return res

        setattr(module, func_name, run_before_wrapper)
        return callback

    return decorator

@run_before(A, 'f')
def sstart(*args, **kwargs):
    print "start"

@run_after(A, 'f')
def sstop(*args, **kwargs):
    print "sstop"

from b import B

bb = B()

print bb.g()

returning
start
103
sstop
1103
1103


text:
Q: What is the purpose of the "forKey" parameter when adding a CAAnimation to a layer? I am very new to iOS programming, Objective-C, and programming in general, so please excuse me if you find this question frustratingly simple-minded.
The docs on Apple's website are usually great, but I'm having some trouble trying to wrap my head around certain parts of Core Animation. I want to explicitly animate the position of a CALayer. From what I understand, I need to create a CABasicAnimation object, configure it with fromValue, toValue, etc., then add it to a layer using this method:
- (void)addAnimation:(CAAnimation *)anim forKey:(NSString *)key

My problem is that I have no idea what the significance of the forKey: parameter is. From what I've seen in examples online, it's not required? I suppose it has something to do with key-value coding? (I still don't really understand that, either.) Even if it's not required, I'd like to know what it is so that I can take advantage of its usefulness in my app.
Thanks for any help you can offer.

A: CALayer has several methods for getting the animations that have been added to the layer.  If you want to get, replace, or remove a particular animation from CALayer you have to give it the key when you call animationForKey: or removeAnimationForKey:.
You don't have to provide a key, you can use nil for the key if you don't have any particular need to find a particular animation by key.

A: It's just some identifier for your animation. You can call animationForKey: and removeAnimationForKey: methods later with the specified key.
Also because layer may have only one animation per unique key, you can use this value as identifier for some type of animations and all ...ForKey: methods will return/remove/replace most current animation for a given animation type/key.

A: It allows you to override animations. For example, implicit animations created by mutating an implicitly animateable property (such as opacity) will use the name of the property as a key. This way if you modify it again (to produce a new animation), the new animation will replace the old one instead of trying to have both animations running simultaneously.


text:
Q: Injecting Javascript when a Modal is loaded I have a little problem, i am trying to achive what is happening in this fiddle http://jsfiddle.net/yXRSz/ basicly it enables a button when the T&C's have been read.
The problem that i am having is that i want this to happen in a AjaxControlToolkit Modal window. The javascript is not running the scroll function when the modal appears and scroll bar is moved. The scroll bar is the overflow on a div
I expect this is becase the modal is hidden when the JS is loaded, i have tried to add the onload and oninit methods and inject the script to the page with no luck, anyone have any idea on how i inject once then modal has loaded?
Code Below
<asp:Panel ID="pnlAcceptTerms" runat="server">

Terms & Conditions

                                    You have chosen to enter score values, in order for us to proceed with the values you have entered you must accept
                                    that we hold no responsibility for the values that you have entered. If you decline this we will only display the factual information.

Terms and conditions are entered here

Terms and conditions are entered here

Terms and conditions are entered here

Terms and conditions are entered here

Terms and conditions are entered here

Terms and conditions are entered here

Terms and conditions are entered here

Terms and conditions are entered here

Terms and conditions are entered here

Terms and conditions are entered here

Terms and conditions are entered here

Terms and conditions are entered here

Terms and conditions are entered here

Terms and conditions are entered here

Terms and conditions are entered here

Terms and conditions are entered here

Terms and conditions are entered here

Terms and conditions are entered here

Terms and conditions are entered here

Terms and conditions are entered here

Terms and conditions are entered here

Terms and conditions are entered here

                                        <asp:Button ID="btnDeclineTerms" runat="server" Text="I Decline Terms" CssClass="ka-form-submit"
                                            CausesValidation="false" OnClick="btnDeclineTerms_Click" />

                                        <asp:Button ID="btnAcceptTerms" runat="server" Text="I Accept Terms" CssClass="ka-form-submit"
                                            OnClick="btnAcceptTerms_Click" UseSubmitBehavior="true" Enabled="false" />

                    </asp:Panel>
                    <ajaxToolkit:ModalPopupExtender ID="mpeTerms" runat="server" TargetControlID="btnHideMe2"
                        PopupControlID="pnlAcceptTerms" DropShadow="true" BackgroundCssClass="modal-backdrop" OnLoad="mpeTerms_Load" OnInit="mpeTerms_Init">
                    </ajaxToolkit:ModalPopupExtender>

And code behind i have
            string script = "";
        script += "\r\n";

        divScrollScript.InnerHtml = script;

+30 is becasue of the padding on the div
Cheers
Joe.

A: string script = "";
script += "\r\n";

A: Right this took me some time to work out, but i have in fact managed to add a show event to the modal popup extended
Just in case anyone else runs into the same issue my new code is below

The $find(modal popup exender name).add_shown( function () {
adds a function to the modal popups show event, enables you to run script inside there, i got the code for this from http://weblogs.asp.net/yousefjadallah/archive/2010/04/15/add-shown-amp-add-hiding-modalpopupextender-events.aspx
the reason my original code was not working is because the modal on the page load is shown, but when the popup extender loads it hides it, thus rendering the js useless. So by adding the scroll function when the modal is shown the js is active :)
Cheers
Joe.


text:
Q: OOzie Spark: code 101 error I have some problems understanding what kind of error Oozie returns to me.
Explanation:
I created a very simple "job" in Oozie, the XML is that:
<workflow-app name="Massimiliano" xmlns="uri:oozie:workflow:0.5">
    <start to="spark-2adf"/>
    <kill name="Kill">
        <message>Action failed, error message[${wf:errorMessage(wf:lastErrorNode())}]</message>
    </kill>
    <action name="spark-2adf">
        <spark xmlns="uri:oozie:spark-action:0.1">
            <job-tracker>${jobTracker}</job-tracker>
            <name-node>${nameNode}</name-node>
            <master>local[*]</master>
            <mode>client</mode>
            <name>MySpark</name>
              <class>org.XXX.SimpleApp</class>
            <jar>${nameNode}/user/${wf:user()}//prova_spark/SimpleApp1.jar</jar>
        </spark>
        <ok to="End"/>
        <error to="Kill"/>
    </action>
    <end name="End"/>
</workflow-app>

The job.properties is the follow:
nameNode=hdfs://10.203.17.90:8020
jobTracker=10.203.17.90:8021
master=local[*]
queueName=default
oozie.use.system.libpath=true
oozie.wf.application.path=${nameNode}/user/${user.name}/hdfs/user/oozie/share/lib/lib_20160628182408/spark

I tried more and more time to change all the parameters with absolutely no result.
The error that afflicts me is this:
Main class [org.apache.oozie.action.hadoop.SparkMain], exit code [101]

The name node is the Master node;
I don't know if oozie.wf.application.path is sets correctly;
More detail of error:
                    hdfs://nameservice1/user/hdfs//prova_spark/SimpleApp1.jar

=================================================================

>>> Invoking Spark class now >>>

Intercepting System.exit(101)

<<< Invocation of Main class completed <<<

Failing Oozie Launcher, Main class [org.apache.oozie.action.hadoop.SparkMain], exit code [101]

Oozie Launcher failed, finishing Hadoop job gracefully

Oozie Launcher, uploading action data to HDFS sequence file: hdfs://nameservice1/user/hdfs/oozie-oozi/0000117-160804173605999-oozie-oozi-W/spark-2adf--spark/action-data.seq

Oozie Launcher ends

The path hdfs://nameservice1/user/hdfs//prova_spark/SimpleApp1.jar is correct! But I don't know where I have to look to resolve this problem.
Can you help me, please?

A: > Step 1. First capture spark and related jars used to execute. One way would be to execute with spark-submit at command line.
> Step 2. Create lib folder if not exists in the workflow path.
> Step 3. Place all the jars collected in step 1 in the lib folders
> Step 4. Run the workflow.

I think this should fix it. However, I would curious to know if it still didn't work.

A: I have resolved in this manner: for issues that I really don't understand the spark job with Oozie doesn't works very well.
I said "doesn't works very well" because all the errors that occur in syslog and stderr are very general (the description of the errors are very incomprehensible), so it is very difficult to resolve each problem and everytime you have to walk in the shadow to resolve your problem.
So, I have changed the approach and I used the shell job, where I put this code:
d=`date +"%Y-%m-%d_%T" | sed 's/:/-/g'`
echo "START_TIMESTAMP=$d"

export HADOOP_USER_NAME=hdfs

spark-submit --master yarn --deploy-mode cluster --class org.XXX.TryApp TryApp.jar "/user/hue/oozie/workspaces/hue-oozie-1471949509.25"

In practice I have written the "middle solution", so I understand a more little bit Hadoop with Spark.
I lauched the spark job with yarn in cluster mode, and I pass to my jar the path of the file. In my scala-code, this is principal rows:
import ...
import org.apache.hadoop.fs.{ FileSystem, Path }

object TryApp {

  def main(args: Array[String]) {
    val conf = new SparkConf().setAppName("TryApp")
    val sc = new SparkContext()
    val sqlContext = new HiveContext(sc)

    val fs = FileSystem.get(sc.hadoopConfiguration).getUri //hdfs://nameservice1

}

Now, given that the path is //hdfs://nameservice1, it was very simple knowed the rest of the path, and I passed other piece through the variable args(0).
In Hue interface, you have to specify 3 things:

*

*The name of the file sh, without arguments because I have specified this inside the file action.sh

*You have to specify attachments: the first one is the action.sh, the second one is the file jar that we have to launch through Oozie.

This works for me, and I think is better solution because even if you have some problem, the output of the error is very clear and you can correct your code or you job.
I hope to be helpful to someone!

A: I also encountered an similar issue, and it turn out that the jar path
<jar>${nameNode}/user/${wf:user()}//prova_spark/SimpleApp1.jar</jar> shuold be your local path.
You don't need to put your spark jar into HDFS, just use the one on your linux system.
The solution solved my problem so I post it here.


text:
Q: Setting a label to UITableView's tableFooterView - with autolayout When my table view is empty, I want to add a simple label into the tableview footer to display a "no content" message. It was working fine when I was setting the frames of the UILabel and the UIView that I used for footerView, but now I'm trying to convert to using auto-layout, and I can't get it to work.
Here's what I'm doing:
// Create the footer
UIView *tempFooter = [[UIView alloc] init];
UILabel *atext = [[UILabel alloc] init];
tempFooter.translatesAutoresizingMaskIntoConstraints = NO;
atext.translatesAutoresizingMaskIntoConstraints = NO;

atext.numberOfLines = 0;
[atext setText:@"Add Some Text"];
atext.textAlignment = NSTextAlignmentCenter;
atext.font = [UIFont italicSystemFontOfSize:14];
atext.textColor = [UIColor grayColor];
atext.backgroundColor = [UIColor clearColor];
atext.lineBreakMode = NSLineBreakByWordWrapping;

// add label to footer view, and add constraints
[tempFooter addSubview:atext];
NSLayoutConstraint *tvatt1 = [NSLayoutConstraint constraintWithItem:tempFooter
                                                          attribute:NSLayoutAttributeLeft
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:atext attribute:NSLayoutAttributeLeft
                                                         multiplier:1.0
                                                           constant:10.0];

NSLayoutConstraint *tvatt2 = [NSLayoutConstraint constraintWithItem:tempFooter
                                                          attribute:NSLayoutAttributeRight
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:atext
                                                          attribute:NSLayoutAttributeRight
                                                         multiplier:1.0
                                                           constant:10.0];

NSLayoutConstraint *tvatt3 = [NSLayoutConstraint constraintWithItem:tempFooter
                                                          attribute:NSLayoutAttributeTop
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:atext
                                                          attribute:NSLayoutAttributeTop
                                                         multiplier:5.0
                                                           constant:0];

NSLayoutConstraint *tvatt4 = [NSLayoutConstraint constraintWithItem:tempFooter
                                                          attribute:NSLayoutAttributeBottom
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:atext
                                                          attribute:NSLayoutAttributeBottom
                                                         multiplier:1.0
                                                           constant: 0];

[tempFooter addConstraints: @[tvatt1, tvatt2, tvatt3, tvatt4]];

// set the footerview
self.tview.tableFooterView = tempFooter;

When I run this, I get a crash:

2014-09-08 19:57:16.594 SimpleList[49442:60b] * Assertion failure in
  -[UITableView layoutSublayersOfLayer:], /SourceCache/UIKit_Sim/UIKit-2935.137/UIView.m:8794 2014-09-08
  19:57:21.073 SimpleList[49442:60b] * Terminating app due to uncaught
  exception 'NSInternalInconsistencyException', reason: 'Auto Layout
  still required after executing -layoutSubviews. UITableView's
  implementation of -layoutSubviews needs to call super

I'm not sure what I'm doing wrong. I've also tried setting constraints for the self.tview.tableFooterView wrt the tempFooter (pinning against all 4 sides) but that doesn't change the crash. I also call:
[self.tview.tableFooterView layoutSubviews];

but that doesn't help either.
Any ideas what I'm doing wrong?

A: Interestingly, changing the Autoresizing mask in the xib solved my problem.
Constraints not working:

Working:

A: You shouldn't set translatesAutoresizingMaskIntoConstraints to NO for table views, their cells, or table header and footer views (or for your controller's self.view for that matter). It's ok to use constraints for views inside those views (the content view of cells or the header and footer views). I added a simplified version of your code to viewDidLoad, and it worked as expected. Note that you need to give the footer view a height and an x position (the y position and the width are ignored),
    UIView *tempFooter = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 50)];
    UILabel *atext = [[UILabel alloc] init];
    atext.translatesAutoresizingMaskIntoConstraints = NO;
    atext.numberOfLines = 0;
    [atext setText:@"Add Some Text"];
    atext.textAlignment = NSTextAlignmentCenter;
    atext.font = [UIFont italicSystemFontOfSize:14];
    atext.textColor = [UIColor grayColor];
    atext.backgroundColor = [UIColor clearColor];
    atext.lineBreakMode = NSLineBreakByWordWrapping;

    [tempFooter addSubview:atext];
    NSDictionary *dict = NSDictionaryOfVariableBindings(atext);
    [tempFooter addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-10-[atext]-10-|" options:0 metrics:nil views:dict]];
    [tempFooter addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[atext]|" options:0 metrics:nil views:dict]];
    self.tableView.tableFooterView = tempFooter;

I'm not sure what you were trying to accomplish with your constraint, tvatt3. The multiplier (you have 5) doesn't do anything with a top or left constraint since the value of those attributes is 0. I used the visual constraints, rather than the method you used, but when I used your code to add the constraints, it worked also .

A: I was able to make dynamically auto layout table footer width and height by implementing @rdelmar solution for constraints and adding these lines below. Same solution applies to table header view.
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if let tableFooter = tableView.tableFooterView {
        let maxSize = CGSize(width: self.tableView.bounds.size.width,
                             height: CGFloat.greatestFiniteMagnitude)
        let size = tableFooter.systemLayoutSizeFitting(maxSize)
        let height = size.height
        var headerFrame = tableFooter.frame

        // If we don't have this check, viewDidLayoutSubviews() will get
        // repeatedly, causing the app to hang.
        if height != headerFrame.size.height {
            headerFrame.size.height = height
            tableFooter.frame = headerFrame
            tableView.tableFooterView = tableFooter
        }
    }
}

P. S. I prefer Interface Builder for constraints setup

A: hope this will help you
I am not sure of this  but it help me in my project, first add every thing in contentView (all the subview and the constraint)
 [self.contentView addSubview:atext]

and then comes to code part
NSLayoutConstraint *tvatt1 = [NSLayoutConstraint constraintWithItem:tempFooter
                                                          attribute:NSLayoutAttributeLeft
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:atext attribute:NSLayoutAttributeLeft
                                                         multiplier:1.0
                                                           constant:10.0];

code saying for left attribute
 temfooter(must be equal) = 1.0*atext +10.0

i.e
temfooter must be equal to the modified atext , so need to make sure that your constraints are not wrong.


text:
Q: Subtract Time in vb.net Hi guys i need help to subtract the time. 7:31:52 AM - 4:30:32 the ouput is 3hrs 1 mins 20 sec
Dim date1 = New DateTime(Now.Year, Now.Month, Now.Day, 7, 30, 0, 0)
Dim date2 = DateTime.Parse("4:30:00 PM")

If read1("clog") Is (DBNull.Value) Then

Else
    date1 = read1("clog")
    Dim duration As Double = (date2 - date1).Minutes

    Label4.Text = duration
End If

A: Dim time1 As DateTime = #7/20/2016 7:31:52 AM#
        Dim time2 As DateTime = #7/20/2016 4:30:00 PM#
        Dim ts As TimeSpan = time2 - time1
        MsgBox(ts.Days & " day(s) " & ts.Hours & " hour(s) " & _
               ts.Minutes & " minute(s) " & ts.Seconds & " second(s)")

Dim date1 As DateTime

                    Dim date2 = DateTime.Parse("4:30:00 PM")

                    If read1("clog") Is (DBNull.Value) Then

                    Else

                        date1 = read1("clog")
                        Dim duration As TimeSpan = date2 - date1

                        Label4.Text = String.Format("{0} hour(s) {1} minute(S) {2} second(s)", duration.Hours, duration.Minutes, duration.Seconds

                    End If


text:
Q: send updated client list to all connected clients Well, I have this code for my server connection request.
If sckClients(clientCounter).State <> adstateclosed Then sckClients(clientCounter).Close
sckClients(clientCounter).Accept requestID
Command1.Enabled = True
MsgBox "Connected to client."
Combo1.AddItem sckClients(clientCounter).LocalIP & "(" & clientCounter & ")"
clientCounter = clientCounter + 1
Load sckClients(clientCounter)

And this is for updating the client list.
StrMsg = "1~Server~"
For x = 0 To Combo1.ListCount - 1
    If x = Combo1.ListCount - 1 Then
        StrMsg = StrMsg & Combo1.List(x)
    Else
        StrMsg = StrMsg & Combo1.List(x) & "~"
    End If
Next x

For x = 0 To clientCounter - 1
    sckClients(x).SendData StrMsg
Next x

My problem is, how can I send it to every client's combo box client list?

A: If I understand your code correctly, (and based on Bob77's clarification) the message that you are sending to the connected clients could be something like this:
"1~Server~192.168.0.101(0)~69.125.83.76(1)~127.0.0.1(2)"

Then you would simply need to use the VB6's split function to get the information as such:
On Client (pseudo-code):
Private Sub WinSock_OnData(...)
    Dim Buffer As String
    Dim BufferArray() As String
    Dim Index As Long

    Call WinSock.GetData(Buffer, ...)
    BufferArray = Split(Buffer, "~")

    If BufferArray(0) = "1" Then
        Call ComboxBox1.Clear
        For Index = 1 To Ubound(BufferArray)
            Call ComboxBox1.AddItem(BufferArray(Index))
        Next Index
    End If

End Sub


text:
Q: How to group by and get the value for column Y having X max? I have an use-case that I have not came across before. I have the following data frame and would like to select values of "y" where "x" achieves its minimum and maximum respectively for each level of the condition "i".
> library(dplyr)
> df <- data.frame(i=c(1,1,2,2),x=c(1.0,2.0,3.0,4.0),y=c('a','b','c','d'))
> ddply(df, .(i), summarise, Min=min(x), Max=max(x))
  i Min Max
  1   1   2
  2   3   4

which is correct but I'd like to instead have the y whose x is Min or Max.
  i Min Max
  1   a   b
  2   c   d

How can I do that?

A: We can use slice
library(dplyr)
df %>%
   group_by(i) %>%
   slice(which.min(x)) %>%
   #or
   #slice(which.max(x)) %>%
   select(-x)

A: Another option if you are willing to go outside of the tidyverse is data.table:
setDT(df)[, list(min = y[which.min(x)],
                 max = y[which.max(x)]), by = i]

#   i min max
#1: 1   a   b
#2: 2   c   d

A:      library(plyr)
     df <- data.frame(i=c(1,1,2,2),x=c(1.0,2.0,3.0,4.0),y=c('a','b','c','d'))
     ddply(df, .(i), summarise, Min=y[which.min(x)], Max=y[which.min(x)])

A: A solution in base R:
output <- by(df, df[, "i"], with, {
  data.frame(i=i[1], min=y[which.min(x)], max=y[which.max(x)])
})

Gives
> output
df[, "i"]: 1
  i min max
1 1   a   b
------------------------------------------------------------
df[, "i"]: 2
  i min max
1 2   c   d

(the data.frame is necessary to preserve the factor structure of "y" I believe).
The output can be concatenated with do.call(rbind, output)
> do.call(rbind, output)
  i min max
1 1   a   b
2 2   c   d


text:
Q: Weird SSE output From past one week I am working on SSE instruction and auto vectorization. I am having code written in C which contains long running loops performing interpolation on a very big image. Below is the skeleton code.
void Interpolate()
{
    for (unsigned int y = 0; y < dstRegionHeight; ++y)
    {
        //Some code to access pixel from bitmap structure.
        for (unsigned int x = 0; x < dstRegionWidth; ++x)
        {
            //Some code to access pixel from bitmap structure.
            for (register unsigned int i = 0; i < 4; ++i)
            {
                //Interpolation arithmetic
            }
        }
    }
}

I wrote the above code such that it get successfully auto vectorized by VS 2015 but I haven't get any performance difference after vectorization. (Which is expected because of the memory access pattern of the above code and less arithmetic.)
I created the 3 set of compile copy of the above code and tested the execution speed for the same data. Below are the result.
1) Tested code without vectorization and without SSE switch ==> Speed is 1X.
2) No vectorization compile with /Arch:SSE2 ==> Speed is 10X.
3) Successfully auto vectorized all the code and  /Arch:SSE2 ==> Speed is 10.5X
The second copy is just compile by enabling SSE2 instruction set the code doesnot get vectorized at all. How did performance is improved by 10 time just by using SSE2 switch ? without any vectorization
Note : I performed the test on Intel I3 with 4 GB ram and windows 7 32 bit OS, I also tested the code on 64 bit windows, the results are similar.


text:
Q: How to create lambda expression that returns object's property, having this property's name? I am completely lost on this one. I have a piece of code that does what I need when implemented like this:
return filters.Add(m => m.Metadata.RecordId).IsEqualTo(1);

where m is a TestObj class object and Add method's argument is Expression<Func<TestObj,bool?>>.
Now the problem is that I cannot hardcode m.Metadata.RecordId inside Add, because what I get here is a string that informs me about the property that should be used, in this case "Metadata.RecordId". what I need to do is to construct such an expression with this string that will do the same thing as m => m.Metadata.RecordId does. I need something like this:
string propertyName = "Metadata.RecordId";
Expression expr = null;//create expression here somehow that will do the same as m => m.Metadata.RecordId
return filters.Add(expr).IsEqualTo(1);

How do I do that?

A: I'm not sure what exactly you want there as an output (bool, int and comparing),
But this should get you on the right track...
public static void Test(string propertyPath)
{
    var props = propertyPath.Split('.');
    Expression parameter = Expression.Parameter(typeof(TestObj), "x");
    Expression property = parameter;
    foreach (var propertyName in props)
        property = Expression.Property(property, propertyName);
    Expression<Func<TestObj, int>> lambdaExpression =
        Expression.Lambda<Func<TestObj, int>>(property, parameter as ParameterExpression);
    Add(lambdaExpression);
}
static void Add(Expression<Func<TestObj, int>> paramExp)
{
    TestObj obj = new TestObj { Metadata = new Metadata { RecordId = 1, Name = "test" } };
    var id = paramExp.Compile()(obj);
}

And you can also check this post of Jon's which nicely describes how that works...
Use reflection to get lambda expression from property Name

A: What about this call:
return filters.Add(m => ReflectionMagic(m, "Metadata.RecordId").IsEqualTo(1);

The method would have this signature:
public object ReflectionMagic(object source, string property);

If that would work, you could do something like this:
var propertyTree = property.Split('.');

foreach(var propertyName in propertyTree)
{
     var propInfo = source.GetType().GetProperty(propertyName);
     var source = propInfo.GetValue(source, null);
}

return source;

Be aware that any kind of argument and return value checks are missing and are left as an excercise to the reader.


text:
Q: How to Convert SASS on the fly to CSS in Python? I come from a PHP-background, more specific Symfony2. Symfony2 has a feature via Assetic to autmagically convert SASS file into CSS.
Now I am working on my first python project using the bottle framework, and I am wondering if there exists a likewise way to have an on-the-fly CSS-generation of SASS files.
Is there an equivalent to Assetic filters in the python world?
Manually running compass in the background is not an option. I want to use SASS, but the whole ordeal should be very coy on my workflow.

A: Thinking about this differently, I thought I could just have my python script run sass --watch source.sass:target.css and so I followed up how to run bash commands in python. Hence my __init_.py now includes:
bashCommand = "sass --watch ./css/main.sass:./css/main.css"
import subprocess
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)

This leads to the sass file being automagically converted to css without me having to worry about the whole sass conversion aspect.

A: I recommend you use Boussole. It uses libsass-python and watchdog to watch and automatically compile any given file or directory! Just use the command boussole watch and specify the source and target file/directory.


text:
Q: Logical Operations in a For Each Row Iteration I'm updating a table of capacities which are based on an availability code. Availability codes in specific ranges have the same capacity (with a few exceptions). Each availability code is listed in column "F". The associated capacity is to be listed in column "I".
The goal of the code is to:

*

*Read the availability code in cell "F" - can be any nnn from 300-799

*Determine the range in which it falls - 300-499, 500-599, 600-699, 700-799, with exceptions 762, 763, 764, 765, 768

*Assign a capacity in cell "I" - currently using Row.Offset

*Iterate down one row and repeat to the last "F" cell with data
Sub Capacity()

Dim ACNum As Range
Dim WB As Workbook
Dim WS As Worksheet

Set WB = ActiveWorkbook
Set WS = WB.ActiveWorksheet
Set ACNum = WS.Range("F:F")

For Each Row In ACNum.Cells
Set AC = WS.Cells(WS.Rows.Count, "F").End(xlUp).Offset(1)
If (AC = "762" Or AC = "763" Or AC = "764" Or AC = "765" Or AC = "768") Then
    Row.Offset(0, 3).Value = "72"
ElseIf (AC >= "300" And AC <= "499") Then
    Row.Offset(0, 3).Value = "181"
ElseIf (AC >= "500" And AC <= "599") Then
    Row.Offset(0, 3).Value = "163"
ElseIf (AC >= "600" And AC <= "699") Then
    Row.Offset(0, 3).Value = "124"
ElseIf (AC >= "700" And AC <= "799") And _
    (AC <> "762" Or AC <> "763" Or AC <> "764" Or AC <> "765" Or AC <> "768") Then
    Row.Offset(0, 3).Value = "144"
End If

Next Row

End Sub

Each time I execute this I receive a generic error, highlighted in yellow, at Line 13, the start of the first If statement. If I attempt to use Excel's Evaluate tool, it's options are greyed out and I can't step through the macro.
I'm unable to determine what I'm doing wrong. I haven't worked in Excel VBA for some time so I may be missing a minor detail. This seems so straight-forward.

A: edited: added a "formula" approach solution
this should do
Option Explicit

Sub Capacity()

Dim cell As Range
Dim noNumbers As String
Dim code As Integer

noNumbers = "-762-763-764-765-768-" '<== code exceptions

For Each cell In ActiveSheet.Columns("F").SpecialCells(xlCellTypeConstants, xlNumbers) '<= consider only numbers in "availibility code" column
    With cell
        If InStr(noNumbers, "-" & .value & "-") > 0 Then
            code = 72
        Else
            Select Case .value
                Case 300 To 499
                    code = 181
                Case 500 To 599
                    code = 163
                Case 600 To 699
                    code = 124
                Case 700 To 799
                    code = 144
                Case Else
                    code = -1
            End Select
        End If
        .Offset(0, 3) = code
    End With
Next cell

End Sub

as per your explanation I assumed that "availability code" is actually a number so it's much better to declare and use a variable (code) of type "integer" to handle it and then use Select Case statement to go away with parsing criteria avoiding the repetition of a lot of characters
as Dan Donoghue proposed you may want to use a formula approach. I came up to the following, using the "Median" function as from http://chandoo.org/wp/2010/06/24/between-formula-excel/
Sub Capacity2()

With ActiveSheet.Columns("F").SpecialCells(xlCellTypeConstants, xlNumbers) '<= consider only numbers in "availibility code" column
    .Offset(, 3).FormulaR1C1 = "=if(isnumber(search(""-"" & RC[-3] & ""-"",""-762-763-764-765-768-"")),72," _
                                 & "if(RC[-3]=MEDIAN(RC[-3],300,499),181," _
                                 & "if(RC[-3]=MEDIAN(RC[-3],500,599),163," _
                                 & "if(RC[-3]=MEDIAN(RC[-3],600,699),124," _
                                 & "if(RC[-3]=MEDIAN(RC[-3],700,799),144,-1" _
                                 & ")))))"
End With

which, of course, you may also implement directly in excel cells instead of having a VBA macro running


text:
Q: Show background image through php plugin command I have i guess a bit dirty code. This is a function php with custom wp_nav code.
    $output .= $indent . '

term_id) . $id . $class_names .'>';

So i have plugin that gives images to categories. What i need is that image will apply to the 'li' block and can be seen as a 'background:url(plugin url)' in css if it possible. this one does nothing.
Not sure which should i even use though.
z_taxonomy_image($cat->term_id)

Plugin documentation list - categories image
Rest of the code i think don't that matter. If not , i will add.

EDIT
Found a useful post that i think will solve my problem but i still don't know how to properly use it. How do i inster it in the
?
 if (function_exists('z_taxonomy_image_url')) $background_url = 'background:url(' . z_taxonomy_image_url() . ')';
echo '
slug . '" style="display:none; ' . $background_url . '">';

full help thread stackoverflow

EDIT 2
Figured out myself a proper code
$output .= $indent . '

term_id) . ')"' . $id . $class_names .'>';

it now shows in inspector url of my site instead of picture given by plugin.

EDIT 3
if i add foreach (get_categories() as $cat) it's working, i got the images
foreach (get_categories() as $cat)
    $output .= $indent . '

term_id) : '') . ')"' . $id . $class_names .'>';

But it messed up the whole html code, added tons of
 block and others so it overrides each other. Maybe i should put it somewhere else?
Small edit - code is not working on a index page (it's a block with categories-sidebar), but when you enter any post, it shows you correct picture of category, but also it shows it for EVERY block of categories on a sidebar same picture.
So maybe i ask something imposible and that plugin can't do that.

A: you need to insert the image in style=""
like this maybe:
'
term_id) ')"' . $id . $class_names .'>';

another solution
Why not use json response and append dom elements? insert each picture to the required element.
In the following example, I am receiving a json array of pictures and inset them to a specific element.
you could retrieve the picture and the picture type for instance and inset to elements by type.
this is my first attempt to help, be gentle.
for your example you could set the css of each li element using .css()
$.ajax({
            type: "POST",
            data: {text: text, images: images, images_big: images_big},
            url: "/ajax/" + $(this).attr('data-post') + "/createPostComment",
            dataType: 'json',
            error: function () {
                $el.remove();
                return;
            },
            success: function (r) {
                $el.attr('data-id',r.comment_id);
                if(typeof r.pictures != 'undefined'){
                    for(var i=0; i < r.pictures.length; i++){
                        el.find('.comment-pictures-container').append('');
                    }
                }
                bindCommentGallery($el);
                bindCommentMenu($el);
            }
        });


text:
Q: UIPopoverViewController resized automatically I have a UIPopoverViewController with a Picker View, some text boxes, some labels and some segmented controls. I have the height of the view controller in the storyboard set to 640. When the application loads the popover it seems to be a fixed size and the controls are repositioned and some at the bottom are cut off.
How can I control the height of this popover view controller and what is causing it to resize? Links to any good references would be helpful.
Thanks!
Bob

A: After you instantiate the popoverController, you call - (void)setPopoverContentSize:(CGSize)size animated:(BOOL)animated; to manually set the size of the popover.


text:
Q: How to load fingerprinting js asynchronously and get visitor id I'm using javascript scripting with a legacy version of iMacros (v8.9.7)
And I'm a bit confused about getting fingerprinting JS to work properly.
My use case :
1- load fingerprintingJS from CDN asynchronously
2- store the visitorID into variable
My code :

Components.utils.import("resource://gre/modules/Promise.jsm");
Components.utils.import("resource://gre/modules/devtools/Console.jsm");

    function initFingerprintJS() {
        FingerprintJS.load()
        .then(fp => fp.get())
        .then(result => {
            const visitorId = result.visitorId;
            window.console.log(visitorId);
        });
    }

    const loadScript = (src, async = true, type = "text/javascript") => {
        return new Promise((resolve, reject) => {
            try {
                const el = window.document.createElement("script");
                const container = window.document.head || window.document.body;

                el.type = type;
                el.async = async;
                el.src = src;

                el.addEventListener("load", () => {
                    resolve({ status: true });
                });

                el.addEventListener("error", () => {
                    reject({
                        status: false,
                        message: `Failed to load the script ${src}`
                    });
                });

                container.appendChild(el);
            } catch (err) {
                reject(err);
            }
        });
    };

    function get_fingerprint() {

        loadScript("https://cdn.jsdelivr.net/npm/@fingerprintjs/fingerprintjs@3/dist/fp.min.js")
        .then((data) => {
            window.console.log("Script loaded successfully", data);
            initFingerprintJS();
        })
        .catch((err) => {
            window.console.error(err);
        });
    }
    <button onclick="get_fingerprint()">FINGERPRINT</button>

when I remove the two Components imports and run the bit of script in the console, everything works. But when it's from iMacros interface, it generates errors

GET
https://cdn.jsdelivr.net/npm/@fingerprintjs/fingerprintjs@3/dist/fp.min.js
[HTTP/2.0 200 OK 0 ms] Script loaded successfully Object { status:
true } ReferenceError: FingerprintJS is not defined Trace de la pile :
initFingerprintJS@resource://gre/modules/RemoteAddonsParent.jsm:1102:5
get_fingerprint/<@resource://gre/modules/RemoteAddonsParent.jsm:1142:9
Handler.prototype.process@resource://gre/modules/Promise.jsm ->
resource://gre/modules/Promise-backend.js:932:23
this.PromiseWalker.walkerLoop@resource://gre/modules/Promise.jsm ->
resource://gre/modules/Promise-backend.js:813:7
this.PromiseWalker.scheduleWalkerLoop/<@resource://gre/modules/Promise.jsm
-> resource://gre/modules/Promise-backend.js:747:11

Any helps please


text: Q: Why do we prefer vectors instead of arrays in C++? Because of core dump? Whenever I had to write code in C++ which involved some kind of data structures I was always forced to use vectors instead of arrays. I liked arrays since they are primitive data types but there must be a reason behind it.


text:
Q: Force users to use BCC I want to force users sending mail to my server to use BCC (we're
getting a lot of internal spam created by mailings to 30+ mailing
lists which then reply to all).
I thought spamassassin could be a good place to start since it is already used for spam filtering. However, I'm not sure how to do this (or if spamassassin is really the right place to do it). My idea was to just make a bccfilter.cf which checks the number of To+Cc recipients and mark the mail as spam if it is larger than a number (e.g. 10). What is the best way to do this?
The only thing I came up whit is something like this:
header  LOCAL_FORCE_BCC_TO      To =~ /(.*?,){9,}/
header  LOCAL_FORCE_BCC_CC      Cc =~ /(.*?,){9,}/
meta    LOCAL_FORCE_BCC         (LOCAL_FORCE_BCC_TO || LOCAL_FORCE_BCC_CC)
score   LOCAL_FORCE_BCC         15.0

It basically counts the number of comma's in the To and Cc header and if either one is larger than 9 (=10 recipients) is marks the message as spam. However I don't really like the approach and have the feeling it can be done better. Also I'd like to count the total number of
recipients (To+Cc) instead of seperatly.
Does anyone know how to do
that? Also I'd like to return a custom error message but that doesn't
really matter much.

A: I think this is a great time to look into exim ACL's. You can use them to do your cc: to bcc rewriting.
http://tldp.org/HOWTO/Spam-Filtering-for-MX/exim-smtpdelays.html


text:
Q: How to remove all the date formating in excel VBA? I have the following code. However, what I found in the cell is that the output (i.e. SEP08) is converted to Sep-08 in the cell. How may i just display SEP08 as it is in the excel spreadsheet without the date format?
Dim StartMonth As String
Select Case Month(EarliestDate)
    Case "1"
        StartMonth = "JAN" & Right(Year(EarliestDate), 2)
    Case "2"
        StartMonth = "FEB" & Right(Year(EarliestDate), 2)
    Case "3"
        StartMonth = "MAR" & Right(Year(EarliestDate), 2)
    Case "4"
        StartMonth = "APR" & Right(Year(EarliestDate), 2)
    Case "5"
        StartMonth = "MAY" & Right(Year(EarliestDate), 2)
    Case "6"
        StartMonth = "JUN" & Right(Year(EarliestDate), 2)
    Case "7"
        StartMonth = "JUL" & Right(Year(EarliestDate), 2)
    Case "8"
        StartMonth = "AUG" & Right(Year(EarliestDate), 2)
    Case "9"
        StartMonth = "SEP" & Right(Year(EarliestDate), 2)
    Case "10"
        StartMonth = "OCT" & Right(Year(EarliestDate), 2)
    Case "11"
        StartMonth = "NOV" & Right(Year(EarliestDate), 2)
    Case "12"
        StartMonth = "DEC" & Right(Year(EarliestDate), 2)
    End Select

ActiveCell.FormulaR1C1 = StartMonth

A: Precede the string with a back-tick like so: `SEP08
Alternatively, to set a large number of cells use the Cell Formatting (available by selecting a range and typing CTRL-1) and select Text formatting on the Number tab.

A: You should set the cell to text using number format @:
ActiveCell.NumberFormat ="@"
ActiveCell.FormulaR1C1 = StartMonth


text:
Q: Is there a way to transport ships without repackaging them in Eve online? Suppose I have 3 ships fully equipped and rigged which I prepared for some roaming operation. The fleet commander says that the operation starts in A system. I'm currently at B system which is 20 jumps away.
How can I transport those ships from B to A wihtout repackaging them? I don't want to lose the rigs.

A: Flying them there manually is an option for some ships, especially if it it only one smaller ship. In lowsec it is usually enough to fill the low slots with warp core stabilizers and most gate camps won't be able to catch you. I would not try this with a battleship, but it works very well with cruisers.
If you have access to a carrier, they can transport 1 million cubic meters of fitted ships. This of course only works outside of highsec.
Theoretically someone in a Titan could bridge you to your destination if it is inside range, but that is likely not a practical solution and would also only work for one ship at once.
As far as I know freighters can also transport fitted ships if you put them inside a courier contract package. Fitted ships are rather large, and you will only be able to transport something like 3 battlecruisers or 9-10 cruisers that way. If you don't mind paying then you could just contract your ships to Red Frog and let them transport them to your destination. This only works in high-sec, in low-sec and null-sec you would use jump freighters with lower capacity and much higher costs.

A: A new ship has been added. It's bigger than the Orca and can transport ships packaged (dec 9th patch): The Bowhead.
A.) Pay someone for a courier contract to move them.
B.) If you have the skill get a bowhead and move them all at once.
C.) Fly the ships and go back in a pod/shuttle.

A: Another option for high sec only would be an Orca. Much easier to skill into and use compared to a freighter or carrier, less expensive at 600M for just the hull. They have a 400,000 m3 ship hanger for unpackaged ships which is 8-12 cruisers or ~2 battleships. They can be tankier than a freighter when fit correctly (200k+ ehp) and align faster than a freighter. Preferably use an alt with it, especially if you have active wardecs.
I've seen people cart them around low sec, using a webbing alt and scout. Whether you want to take that risk is up to you. I imagine in null sec, it would die at the first bubble.

A: I suspect the easiest way is to fly them there. Then get in a throwaway ship and fly back to pick up the next ship.
The other alternative is the capital ships that you can dock on as Mark Rogers said in comment but I would imagine that unless there is one going in the right direction that it is not a practical solution.

A: If your flying ships from one place to another and have quite a few to do. Don't shuttle/pod back, set your home station to where the ships are, and death warp back. Then fly a ship to where its got to go, then death warp back again, rinse repeat. Make sure you are in a blank clone though. This saves so much time.


text:
Q: C# How to get names of sound input I want to get user-friendly names of sound inputs with this code, but it can give me only first 32 chars of name, but I want it whole.
[DllImport("winmm.dll", SetLastError = true)]
static extern uint waveInGetNumDevs();

[DllImport("winmm.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern uint waveInGetDevCaps(uint hwo, ref WAVEOUTCAPS pwoc, uint cbwoc);

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct WAVEOUTCAPS
{
    public ushort wMid;
    public ushort wPid;
    public uint vDriverVersion;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
    public string szPname;
    public uint dwFormats;
    public ushort wChannels;
    public ushort wReserved1;
    public uint dwSupport;
}

public static string[] GetSoundDevices()
{
    uint devices = waveInGetNumDevs();
    string[] result = new string[devices];
    WAVEOUTCAPS caps = new WAVEOUTCAPS();
    using (StreamWriter sw = new StreamWriter("appdata/audio/name"))
    {
        for (uint i = 0; i < devices; i++)
        {
            waveInGetDevCaps(i, ref caps, (uint)Marshal.SizeOf(caps));
            result[i] = caps.szPname;
            sw.WriteLine(caps.szPname);
        }
        return result;
    }
}

I need this names of sound inputs:

but this code give me only this:

Thank you guys!

A: You may have to use the management interface:
ManagementObjectSearcher objSearcher = new ManagementObjectSearcher(
           "SELECT * FROM Win32_SoundDevice");

    ManagementObjectCollection objCollection = objSearcher.Get();

    foreach (ManagementObject obj in objCollection)
    {
        foreach (PropertyData property in obj.Properties)
        {
            Console.Out.WriteLine(String.Format("{0}:{1}", property.Name, property.Value));
        }
    }

Source: How to enumerate audio out devices in c#

A: You can use WASAPI to get full name of sound devices. It's only limit is that it is not available in Windows XP or older OS.
You need to use IMMDeviceEnumerator::EnumAudioEndpoints method to achieve the goal, but since the library is COM, you need to wrap it to be able to use it in C#.
A sample project is available on CodeProject.
I also couldn't find a way to get full name using WinMM library and finally end up writing a C++ wrapper around WASAPI and used that wrapper in C# through pinvoke!

A: Why screenshots in foreign and totally not understandable language?
There you go. English screenshot 1
You can copy it, that is what the second one means.
The number stands for the usb bus that is used.
When changing the plug keep that in mind.


text:
Q: rails 3.2 check if hidden field has value while sending form I have inside of a form one hidden field, which must be  empty when the form is submitted.
Is any value in it, i want to set a flag in the database column.
How can i realize the check if the value of this hidden field is not filled?
Is it an issue for controllers or for models?

A: It is an issue for the controller. You want to check the value of that field in the create and update actions and store what ever you want to store there.


text:
Q: RegEx for passing all chars except a list of chars I want a pattern that contains all characters except English and Persian numbers. I found this pattern but my problem is how can I do against this pattern.
For example contains * and / and ... but not contains 1 2 3 ۱ ۲ ۳.
This pattern gets all numbers:
^[\u0600-\u06FF\s0-9]+$

A: We might be able to solve this problem by adding our undesired unicodes in a char list, then swiping everything else, which I'm unsure if space would be undesired or not.
Maybe, something like this with modification would work:
([\s\S].*?)([\x{0600}-\x{06FF}0-9]+)?

Demo
We would just replace x with u for JavaScript:

const regex = /([\s\S].*?)([\u{0600}-\u{06FF}0-9]+)?/gmu;
const str = `everthing we wish to have before 1 2 3 ۱ ۲ ۳ and everything else we wish to have`;
const subst = `$1`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

RegEx
If this wasn't your desired expression, you can modify/change your expressions in regex101.com.

A: This should works
/[^\d۱۲۳۴۵۶۷۸۹]/g

Demo
Note: If I forget some Persian digits just add it before ]

A: This is not Ascii, nor Persian numbers
[^0-9\u06F0-\u06F9]+


text:
Q: Variables set in the constructor are forgotten? What I'm trying to do here is first to create the variable $sql_info and set it to a default value, then the constructor takes one argument, which it will then set to the $sql_info variable. If I do echo $sql_info; inside the constructor it all works fine, but if I try to do it in an a different function, it doesn't echo anything to the screen, not even the default value. Why is that?
<?php

class Connection {

    private $sql_info = "default";
    function __construct($Info) {

        //Set new value of $sql_info
        $sql_info = $Info;
    }

    function Connect() {
        global $sql_info;

        //echo the newly set string
        echo $sql_info;
    }
}
?>

Thanks!

A: You need to write $this!
Try this:
<?php

    class Connection {

        private $sql_info = "default";

        function __construct($Info) {

            //Set new value of $sql_info
            $this->sql_info = $Info;
        }

        function Connect() {
            global $sql_info;

            //echo the newly set string
            echo $this->sql_info;
        }
    }
?>

A: Just use the class variable using the "this" keyword. It is declared as a private variable in your code.


text:
Q: data-table nested table should getting in proper format I've use data-table and create table in table for order receipt print for folowing table.
I want export that table in pdf and excel format. I've use following code of datatable

var buttonCommon = {
  exportOptions: {
    format: {
      body: function(data, column, row) {
        data = data.replace(/<.*?>/g, "");
        return data;
      }
    }
  }
};
$('#example').DataTable({
  dom: 'Bfrtip',
  buttons: [
    $.extend(true, {}, buttonCommon, {
      extend: 'copyHtml5'
    }),
    $.extend(true, {}, buttonCommon, {
      extend: 'excelHtml5'
    }),
    $.extend(true, {}, buttonCommon, {
      extend: 'pdfHtml5'
    })
  ],
});

             Franchisee Name:Abc

              Order No:123

              Address:Pune

              Order Date:02/03/2020

                Sr. No
                Product Name
                Price
                Quantity
                Amount

                1
                Pen
                5
                2
                10

but children tables is not print in tabular format in pdf and csv. It should print in tabular format like look on screen. Is format of table is correct?. I've add screenshot of pdf format

A: Does this table work for you?

    sr. No
    Product Name
    Price
    Quantity
    Amount

    1
    Pen
    5
    2
    10

    2
    Crayon
    10
    4
    20


text:
Q: Notification about Database Change I am trying a scenario in which I want to update my desktop UI running on different PCs with changes committed by any user. For example:

*

*Application1 is installed on PC1, PC2 and PC3.

*Assume all PCs are running this application.

*Say User 1 on PC1 changes the data and commit to the database

*the UI on PC2 and PC3 should be updated with changes without polling or pulling the data from the database.

Can anyone suggest a way to notify my middle tier service about the database change which then I can relay it to all registered client. Will SQL Notification Services or Service Broker notify when the table is changed (inserted/updated/deleted)? Any suggestions will be helpful.

A: Query Notifications does exactly this. You will get a notification when data has changed on the server, you have to query the data again to refresh your UI. A simple implementation would be to use LinqToCache and add an OnInvalidated handler to the CachedQueryOptions object.


text:
Q: jQuery .one is executing callback function several times I'm using Animate.css for my animation with jQuery n-th element.
Here is the fraction of my code.

$("tr td:nth-child("+columnIndex+")").addClass("animated flip").one('animationend oAnimationEnd mozAnimationEnd webkitAnimationEnd', function(){
      $("tr td:nth-child("+columnIndex+")" ).removeClass("highlight");
      animationFlag++;
      alert("Getting called several times");
    });

My problem is that callback function that increases the animationFlag is being called several times. Actually, it's getting called number of rows times in the table. Is there any way to call it just once.

A: I found a work around for my question. I just introduce a variable 'called' to keep track of callback function being called.

var called = false;
    $("tr td:nth-child("+columnIndex+")" ).addClass("highlight");
    $("tr td:nth-child("+columnIndex+")").addClass("animated flip").one('animationend oAnimationEnd mozAnimationEnd webkitAnimationEnd', function(){
      if(called==false){
        $("tr td:nth-child("+columnIndex+")" ).removeClass("highlight");
        animationFlag++;
        alert('hahhahahaha working');
        called = true;
      }else{
        return;
      }

    });

Thank you.


text:
Q: Looping through nested Dictionaries in Python i want to get the dynamic keys from this dictionary but i'm getting an error when i loop it.
d= {
    "name": "rex"
    "age": "23"
     "data": {
                "country" :   { "name": "xx", "loc": "ee" , "loc1": "pp" }
                 "country2" : { "name": "tx", "loc": "ef" , "loc2": "rp" }
                 "country2"  :{ "name": "yx", "loc": "ve" , "loc1": "hp" }
              }
   }

I'm trying to parse these info into a neat csv. But this is not looping through the dictionary and stopping abruptly. How to loop concisely through the dictionary catching all the nested values
name= d["name"]
  age= d["age"]
  for i in d["data"]:
      country_name= d[i]["name"]
      country_loc= d[i]["loc"]
      country_loc1 = d[i]["loc1"]

A: You may use
name = d["name"]
age = d["age"]
for i in d["data"]:
    country_name = d["data"][i]["name"]
    #                ^^^
    country_loc = d["data"][i]["loc"]
    country_loc1 = d["data"][i]["loc1"]

    print(country_name)

Or - considered "more pythonic":
for _, country in d["data"].items():
    print(country["name"])

A: If you want to get to a CSV, a simple approach is to leverage the power of pandas. There are various approaches, but one is the below:
import pandas as pd

#create data
d= {
   "name": "rex"
   "age": "23"
   "data": {
       "country" :   { "name": "xx", "loc": "ee" , "loc1": "pp" }
       "country2" : { "name": "tx", "loc": "ef" , "loc2": "rp" }
       "country2" :{ "name": "yx", "loc": "ve" , "loc1": "hp" }
   }
   }

# we reset index so that concatenated objects share an index
df = pd.DataFrame(d).reset_index()
# json_normalise expands our nested data. Concat unions along the rows. We drop the now unneeded data column
out = pd.concat([df,pd.json_normalize(df.data)],axis=1).drop('data',axis=1)
out.to_csv('out.csv')

Looks like:
      index name age name loc loc1
0   country  rex  23   xx  ee   pp
1  country2  rex  23   yx  ve   hp

A: Here is a version of the code that works. I suggest to compare it to the original code and to try to understand the differences:
d = {"name": "rex",
     "age": "23",
     "data": {
              "country": {"name": "xx", "loc": "ee", "loc1": "pp"},
              "country2": {"name": "tx", "loc": "ef", "loc1": "rp"},
              "country3": {"name": "yx", "loc": "ve", "loc1": "hp"}
             }
     }

name = d["name"]
age = d["age"]
for i in d["data"].keys():
    country_name = d["data"][i]["name"]
    country_loc = d["data"][i]["loc"]
    country_loc1 = d["data"][i]["loc1"]


text:
Q: Substract not working as desired in powerBI I have done calculated column:
Delta = OnBoth[Values2022/03] - OnBoth[Trans Amount $ (Pos-Rev)]

But the substract sometimes gives incorrect values, the total should be 2k but it is 14k, see picture

A: Why don't you try this for your Sum Of Delta Measure without building additional column to calculate difference.
Sum Of Delta =
SUMX ( OnBoth, [Values2022/03] - [Trans Amount $ (Pos-Rev)] )


text:
Q: how to insert file into table? code:
<?php
if(isset($_POST["add"]))
{
    extract($_POST);
    $filename = $_FILES['ad']['name'];
    $path = "../../ads";
    $move=move_uploaded_file($_FILES['ad']['tmp_name'],$path.$_FILES['ad']['name']);
    $sql2="insert into advertisement(ad,priority)values('$filename','$priority')";
    $result = mysqli_query($link,$sql2);
    if($result == true)
    {
        $msg .= "
Successfull
";
    }
    else
    {
        $msg .= "
Error
";
    }
}
?>

html code:
<form method="POST" >
<input type='file' name="ad" id="ad" />
<select name="priority" id="priority">
    <option value="">Select Priority</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
    <option value="10">10</option>
</select>
<input type="submit" name="add" value="Submit"/>
</form>

In this code when I click on submit button only priority value insert into database while ad or file is not inserting. what is the problem in this code ? and How can I fix this problem ?
Thank You

A: Add enctype="multipart/form-data" attribute to the form tag. Validate your input before inserting it into the database. Don't use extract function.

A: Please check below link to upload files in PHP.
https://www.w3schools.com/php/php_file_upload.asp

A: it's simple
Add enctype="multipart/form-data" attribute to the form tag. Validate your input before inserting it into the database. Don't use extract function.


text:
Q: How to get existing php/python version number from node.js app I was trying to create a command line node.js app using commander module. This app would download few files based on php version installed in my machine. Can someone help me with sample of how to get the php version number from node.js app
I tried something as below but dint worked, i would replace npm -v with php -v later
var exec = require('child_process').execFile;
exec('npm -v', function(err, data) {
    console.log(err)
    console.log(data.toString());
});

Error:
{ [Error: spawn npm -v ENOENT]
  code: 'ENOENT',
  errno: 'ENOENT',
  syscall: 'spawn npm -v',
  path: 'npm -v',
  cmd: 'npm -v' }

A: child_process.exec() works fine for me:
var exec = require('child_process').exec;
exec('php -r "echo phpversion();"', function(err, stdout, stderr) {
  console.dir(stdout.toString());
});

// Outputs:
// '5.6.11-1ubuntu3.1'

For python you can do something like this:
var exec = require('child_process').exec;
exec('python -c "import platform; print(platform.python_version())"',
     function(err, stdout, stderr) {
  console.dir(stdout.toString());
});

// Outputs:
// '2.7.10'


text:
Q: Remove black border or background in custom dialog I'm showing dialog with custom layout. It works in every android devices except xiaomi devices. In xiaomi devices, it shows dialog with black background on it.
for example :
Custom Dialog with black background
and this is my code :
 public void showPopUp(){
    myDialog.setContentView(R.layout.pop_up_impact);
    myDialog.setCanceledOnTouchOutside(false);

    WindowManager.LayoutParams lp = myDialog.getWindow().getAttributes();
    lp.dimAmount=0.0f;
    myDialog.getWindow().setAttributes(lp);
    myDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
    myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

    Typeface gibsonbold = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/gibsonbold.ttf");
    Typeface gibsonregular = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/gibsonregular.ttf");
    Typeface opensansregular = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/opensansregular.ttf");
    Typeface opensansbold = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/opensansbold.ttf");

    popUpText = (TextView) myDialog.findViewById(R.id.pop_up_text);
    popUpId = (TextView) myDialog.findViewById(R.id.id_pop_up);
    close = (ImageView) myDialog.findViewById(R.id.close_pop_up);
    background = (RelativeLayout) myDialog.findViewById(R.id.background);

    popUpText.setTypeface(opensansregular);

    loadContent();

    close.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Blurry.delete((ViewGroup) mainLayout);
            spm.SetPopUpFirstTimeLauch(false);
            startActivity(getIntent());
            myDialog.dismiss();

        }
    });

    myDialog.show();
}

this is pop_up_impact.xml layout code :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="@dimen/_260sdp"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:clickable="true"
android:gravity="center"
android:layout_gravity="center"
android:orientation="vertical"
android:background="@android:color/transparent"
android:layout_marginLeft="@dimen/_25sdp"
android:layout_marginTop="@dimen/_18sdp"
android:layout_marginRight="@dimen/_25sdp">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/id_pop_up"
    android:visibility="gone"/>

    <RelativeLayout
        android:id="@+id/background"
        android:background="@android:color/transparent"
        android:layout_width="wrap_content"
        android:orientation="vertical"
        android:gravity="center"
        android:layout_marginTop="@dimen/_7sdp"
        android:layout_height="match_parent">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/_40sdp"
            android:layout_centerHorizontal="true"
            android:layout_marginLeft="@dimen/_27sdp"
            android:layout_marginRight="@dimen/_27sdp"
            android:alpha="0.5"
            android:background="#fff"
            android:gravity="center|bottom"/>
        <TextView
            android:id="@+id/pop_up_text"
            android:layout_width="match_parent"
            android:layout_marginTop="@dimen/_9sdp"
            android:layout_marginRight="@dimen/_30sdp"
            android:layout_marginLeft="@dimen/_30sdp"
            android:layout_height="wrap_content"
            android:textAlignment="center"
            android:layout_centerHorizontal="true"
            android:textSize="@dimen/_7ssp"
            android:fontFamily="@font/opensansregular"
            android:text=" "/>
    </RelativeLayout>
<ImageView
    android:id="@+id/close_pop_up"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:src="@drawable/closebox"
    android:layout_alignParentEnd="true"
    />

anyone knows how to fix this? or it is normal?

A: Set your dialog like this
Dialog dialog = Dialog(context)
            dialog.getWindow().setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT));
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(false);
            dialog.setContentView(R.layout.pop_up_impact);


text:
Q: React doesn't read styles from external package I want to add a photo swiper to my website and I sticked to react-id-swiper. In the documentation it says to import the styles like this:
import 'swiper/swiper.scss'

and this is my component, pretty straight forward:
  import React from 'react';
  import Swiper from 'react-id-swiper';
  import 'swiper/swiper.scss'

  const SimpleSwiper = () => (
    <Swiper>

Slide 1

Slide 2

Slide 3

Slide 4

Slide 5

    </Swiper>
  )

  export default SimpleSwiper;

I did like this, no error, sign that the *.scss file is found, but the no style is applied.
Can anyone tell me why? I looked everywhere, but I cannot seem to figure it out.


text:
Q: monkeypatch function in module whose namespace was overwritten I am trying to monkeypatch a function in an external module I use, but monkeypatch can't seem to access the function because the namespace of the module gets overwritten on import.
Concretely, I use a Bio.PDB.PDBList.PDBList object (biopython module) in my code, and I am trying to patch _urlretrieve in Bio.PDB.PDBList to prevent calls to the internet and instead get files from a local directory, without having to mock the instance methods of PDBList which would be substantially more work. But when I try the naïve:
m.setattr("Bio.PDB.PDBList._urlretrieve", mock_retrieve)

pytest complains:
AttributeError: 'type' object at Bio.PDB.PDBList has no attribute '_urlretrieve'

On further inspection of Bio.PDB, I can see that the module namespace .PDBList seems to be overwritten by the class .PDBList.PDBList:
# Download from the PDB
from .PDBList import PDBList

So that would explain why pytest sees Bio.PDB.PDBList as a type object with no attribute _urlretrieve. My question is, is there any way to get monkeypatch to patch this 'hidden' function?

Concrete example of usage of PDBList class:
from Bio.PDB.PDBList import PDBList

_pdblist = PDBList()

downloaded_file = _pdblist.retrieve_pdb_file('2O8B', pdir='./temp', file_format='pdb')

A: You are right - since the PDBList class has the same name as the module Bio.PDB.PDBList, after import Bio.PDB.PDBList you won't be able to access the module by its name (shadowing problem). However, you can still grab the imported module object from the loaded modules cache and monkeypatch that:
import sys
from unittest.mock import Mock
import Bio.PDB.PDBList

def test_spam(monkeypatch):
    assert isinstance(Bio.PDB.PDBList, type)
    with monkeypatch.context() as m:
        m.setattr(sys.modules['Bio.PDB.PDBList'], '_urlretrieve', Mock())
        ...


text:
Q: Background scan for iBeacon stops after kill the application I'm developing an app to scan for iBeacons using android beacon library. I have problem scanning in the background after I kill the application. The moment I kill the application the  In logcat I receive the following information:
2022-06-16 11:56:04.176 4020-4020/? I/ActivityManager: Killing 18682:com.example.beaconbackgroundscan/u0a360 (adj 1001): remove task
2022-06-16 11:56:04.177 4020-6040/? W/NotificationService: Toast already killed. pkg=com.example.beaconbackgroundscan token=android.os.BinderProxy@91a7c6e
2022-06-16 11:56:04.218 4382-4399/? D/LeAppInfo: removeLeacReportedServerApp, appName: com.example.beaconbackgroundscan
2022-06-16 11:56:04.222 4382-18751/? D/LeAppInfo: removeLeacReportedServerApp, appName: com.example.beaconbackgroundscan
2022-06-16 11:56:04.226 4382-4871/? E/BtGatt.GattService: [GSIM LOG]: gsimLogHandler, msg: MESSAGE_SCAN_STOP, appName: com.example.beaconbackgroundscan, scannerId: 7, reportDelayMillis=0

My code to initialize the scan is as following:
override fun onStop() {
        BeaconManager.setDebug(true)
        val beaconManager =  BeaconManager.getInstanceForApplication(this)
        beaconManager.beaconParsers.clear()
        beaconManager.beaconParsers.add(
            BeaconParser().
            setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"))

        beaconManager.isRegionStatePersistenceEnabled = false
        beaconManager.setEnableScheduledScanJobs(false);
        beaconManager.backgroundBetweenScanPeriod = 100;
        beaconManager.backgroundScanPeriod = 1100;
        Toast.makeText(this@MainActivity, "Scanning for beacon...", Toast.LENGTH_SHORT).show()

        val region = Region("all-beacons-region", Identifier.parse("a32237e7-3ec0-c584-864b-b999f98203f7"), null, null)

        beaconManager.startMonitoring(region)
        beaconManager.addMonitorNotifier(this@MainActivity)
        Log.d(TAG, "Scan started")
        super.onStop()
    }

How can I ensure that the scan will continue in the background?

A: I think WorkManager is a good solution. That's the documentation. I'm sure there are a lot tutorials out there too.

A: I posted the same question as an issue on the GitHub of the plugin. The creator's answer is that this behavior is normal. It is caused by the operating system. His suggestion is to use foreground service in this case.


text:
Q: Restore xkb layout I was swapping caps and escape with the following command:
setxkbmap -layout de -option caps:swapescape

Is there an option for reverting back to the original state?

A: To disable the XKB option you set, you can use -option without an argument:
setxkbmap -option


text:
Q: How to place an Image between 2 text string in itextsharp I need to place an Image between 2 text strings. Pl see the code below. As I have tried but the first text overlapping the image. Pl help me to fix the issue.
Code
 // Create a new Phrase and add the image to it
                    var cellContent = new Phrase();

                    var fontHeader = FontFactory.GetFont("Verdana", BaseFont.CP1250, true, 12, 0);
                    cellContent.Add(new Paragraph("\n" + "Default Header", fontHeader));

                    Code39BarcodeDraw barcode39 = BarcodeDrawFactory.Code39WithoutChecksum;
                    System.Drawing.Image img = barcode39.Draw(val[cnt], 25);
                    var pdfImg = iTextSharp.text.Image.GetInstance(ReadImage(img));
                    var width = pdfImg.PlainWidth;
                    if (width > colWidths.ToArray()[0])
                        pdfImg.ScaleAbsoluteWidth(width - 20);
                    cellContent.Add(new Chunk(pdfImg, 0, 0));

                    var font = FontFactory.GetFont("Verdana", BaseFont.CP1250, true, 12, 0);
                    cellContent.Add(new Chunk("\n" + val[cnt], font));
                    cnt += 1;

                    //Create a new cell specifying the content
                    var cell = new PdfPCell(cellContent);

                    //Ensure our label height is adhered to
                    cell.FixedHeight = _label.Height;

                    //Centre align the content
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;

                    cell.Border = IncludeLabelBorders ? Rectangle.BOX : Rectangle.NO_BORDER;

                    //Add to the row
                    rowCells.Add(cell);

A: Change this line:
cellContent.Add(new Chunk(pdfImg, 0, 0));

To:
cellContent.Add(new Chunk(pdfImg, 0, 0, true));

This way, the leading of the Phrase will adapt to the height of the Image.


text:
Q: react-django connectivity issues, 500 internal server errors I'm working on a project using react as the frontend and Django rest api as backend. Unfortunately, I'm having some issues. Here are the issues I'm facing:

*

*From the Django setting.py file, I set the static directory folder to "build" (for css, images and JavaScript) and media folder (for user uploaded files) file to "media" as shown below. But I observed that only the "media" folder shows up in the directory structure and not the "build" folder.   PLEASE WHAT COULD BE PREVENTING THE "BUILD" FOLDER FROM SHOWING?
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'build/static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/medial/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

*I understand that normally when you run "npm build" and copy the build folder generated from the frontend to replace the one in the Django backend, then you can begin to use "localhost:8000" to access your pages rather than continue to use "localhost:3000". I did the above, but I wasn't able to load the pages using "localhost:8000" but instead getting 404 error.
PLEASE WHAT COULD BE THE ISSUES?

*I created some routes (post and get), tested all the routes in postman as well as the browser, and they (routes) are all working perfectly. However, when I run them from the react frontend, they aren't working. By that I mean the data are not submitted to the database (for the post routes) as well not being displayed on the web page (for the get routes). Strangely though, one of the post routes is working (that is, submitting data to the database) from the react frontend. My concern is why the rest routes (post and get) are not working and there is no error message except the vague "500 internal server error" from the console.  I use about the same code logic for virtually all the routes in the "views.py" file as well as from the react frontend files. Here is the views.py file for the only route that is working (i.e., from the react frontend):

*class CreateContactView(APIView):

*
 permission_classes = (permissions.AllowAny, )

*

*
 def post(self, request, format=None):

*
     data = self.request.data

*

*
    try:

*
        contact = Contact(

*
            name=data['name'], email=data['email'], phone=data['phone'], subject=data['subject'], message=data['message'])

*
        contact.save()

*
        return Response({'success': 'Message sent successfully'})

*

*
    except:

*
        return Response({'error': 'Message failed to send'})

and here is one of the others not working. Yet they are of the same code logic
class PartnerCreate(APIView):
    permission_classes = (permissions.AllowAny, )

    def post(self, request, format=None):
        data = self.request.data

        try:
            partners = Partners(
                name=data['name'], email=data['email'], phone=data['phone'],
                gendar=data['gendar'], area_spec=data['area_spec'], year_exp=['year_exp'], passport=['passport'], profile=['profile'])
            partners.save()
            return Response({'success': 'Registration successful'})
        except:
            return Response({'error': 'Something went wrong'})

I HAVE RAISED 4 ISSUES, PLEASE CAN ANYONE HELP ME FIGURE OUT WHAT'S WRONG?
Thanks everyone.


text:
Q: getting festival to talk at start up ubuntu 14.04 using this script:
week=$(date +"%A" )
day=$(date +"%e" )
echo hello $USER you are super awesome i am your processor | festival –tts
echo today is $week $day | festival –tts
echo have a nice day | festival –tts

But it is not working thank you for any help.

A: More simple that you can imagine.
From man festival
-- tts   Synthesize text in files as speech no files means read from stdin (implies no interaction by default)
So --tts and not -tts
Some option is Linux are with 2 -, usually are the less used with long names, some alias to help human to remember a short option (e.g. gzip --best acts as gzip -9 to select the best compression level).
You have to modify each call to festival putting --tts instead of -tts e.g.:
echo have a nice day | festival --tts

Version:
festival: Festival Speech Synthesis System: 2.1:release November 2010.
Notes:

*

*for some reasons in your post there is the symbol – and not the standard minus -. You have to use the minus to specify the option.

*Older version of Festival (<=1.4) didn't seems to support the redirection from echo Bug688940.
If you have an old version you can follow the syntax of the relative version, you can check if is ok this link, or you can update your version with apt-get.
apt-get update && upt-get install festival
Excerpt from the Bug

This is an error due to incorrect syntax for festival. Festival does not
  use the echo and redirects to speak. Correct syntax is documented in the
  manual, available at http://www.cstr.ed.ac.uk/projects/festival/manual/


text:
Q: SSRS Expression to near Monday of last Year In SSRS how can I write an expression to find the Monday of Last year for a date
Example: If I choose 9/26/2016 which is a Monday , I have to find 9/26/2015 is Monday or not . In this case 9/26/2015 Is Saturday , so I have to set the date parameter as the nearest Monday which is 9/21/2015
How can I do it via  an SSRS expression
 =DATEADD(DateInterval.Year,-1,Parameters!BeginDate.Value)

This will helps to find the Last Year same date , but how can I change to make it to select the Monday of last Year

A: =DateAdd
(
    DateInterval.Day
    , 2 - weekday(dateadd(DateInterval.Year,-1,Parameters!BeginDate.Value))
    , dateadd(DateInterval.Year,-1,Parameters!BeginDate.Value)
)

To break the DateAdd function down...
The first argument is simply telling it to adjust by a number of days
The next argument gets the weekday for the parameter date minus a year, we then take this number FROM 2 (which is the weekday value for a Monday) so if the parameter date last year was a Thursday (5) we would get 2-5 which gives us -3 so we'll take three days of our date.
The final argument is the parameter date minus a year which is the date we want to subtract (in this case) 3 days from.
NOTE If you system setting are not default the weekdays returned may not be the same so check and adjust the , 2-(... part accordingly, set it to whatever Monday evaluates to.


text:
Q: Jquery slideToggle & Cookies im still fairly new to jquery and i got this slideToggle container,
but now i want to save a cookie if the container is hidden or not so
if one refreshes the page it keeps its current state.
I heard about the jquery cookie plugin but didn't really understand it to be honest. :(
Can anyone help me out?
My code so far is pretty simple:
$(function(){
 $("#hideslide").click(function(){
  $(this).next().slideToggle();
 });
});

Any help is highly appreciated

A: The jQuery Cookie plugin (found here) is the easiest way to use cookies with jQuery.
To set a cookie, this will do:
$.cookie("name", "content");

Getting a cookie is just as simple:
$.cookie("name");

So you should check on page load if the cookie is set:
if($.cookie("name") != null) {
    // Cookie set, action here
}

And on clicking the item to toggle, check if cookie is set. If it is set, remove it, else, set it:
if($.cookie("name") != null) {
    $.cookie("name", null); (null as value will remove the cookie)
}
else {
    $.cookie("name", "content");
}

I use this plugin myself and this is all you need. Easy.

A: If your client browser targets are IE8+, you could, and I think should, use localStorage for this.
localStorage.setItem('mySlideState', "open");

Then test:
if(localStorage.getItem('mySlideState') == 'open') {
    //do stuff
}

You would achieve this through the callback on slideToggle
$('#highSlide').slideToggle(function () {
    //set localStorage to value here
});

Mozilla docs:  https://developer.mozilla.org/en/DOM/Storage


text:
Q: Existence of limiting random variable that closes the martingale I have the following martingale:
$M_0 = x \in ] 0,1 [$,
$M_n = \begin{cases} M_n^2\quad wp\quad  1/2\\ 2M_n -M_n^2 \quad wp\quad 1/2\end{cases}$
defined with respect to the filtration $(\mathcal{F_n},n\in\mathbb{N})$.
The exercise asks me to compute the following recursive process:
$$ A_0=0, A_{n+1}= A_n + \log \mathbb{E}(\exp(M_{n+1}-M_n)|\mathcal{F_n}) $$According to my own analysis this process is predictible and increasing.
\begin{align}
\log \mathbb{E}(\exp(M_{n+1}-M_n)|\mathcal{F_n}) &= \log\frac{\mathbb{E}(\exp(M_{n+1})|\mathcal{F_n})}{\exp(M_n)} \\ &=\log \exp(1/2\cdot M_n^2+1/2\cdot (2M_n-M_n^2)-M_n) \\ &= 1
\end{align}
My conclusion is that $A_n = n\quad \forall n \in\mathbb{N}.$
Then it asks me if, given that $X_n = \exp(M_n - A_n)$ it is possible to say that $\exists X_{\infty} : \mathbb{E}(X_{\infty}|\mathcal{F_n})= X_n$.
Out of curiousity I proved that $X_n$ is a martingale provided that $M_n$ is bounded. And I also managed to prove that $M_n$ in this case is $\in ]0,1[$. So, for the existence of $X_{\infty}$ I would need that $\sup_n\mathbb{E}(X_n^2)<+\infty$.
$$\mathbb{E}(X_n^2)= \mathbb{E}(\exp(2M_n-2A_n)) \leq \mathbb{E}(\exp(2M_n)) = \exp(2\cdot M_{n-1}) \leq \exp(2).$$
This should prove the existence of $X_{\infty}$, right? It was not necessary to compute the value $A_n$? As long as it was positive I could always upperbound the martingale, right?
Also, could you explain to me why that $X_n$ is a martingale? It seems related to Doob's decomposition of $\exp(M_n)$ which is always a sub-martingale if $M_n$ is a martingale but I don't understand why that construction always leads me to a martingale...


text:
Q: replacing a number with a string in a list with 'for'loop I'm a beginner in python and I'm stuck on a task I need to complete.
I need to define a function that returns a list in a given range in which every time the number 7 appears or the number % 7 == 0 (no remainder), it is replaced with the word 'BOOM', otherwise the number returns the same. is needs to be done using the 'for' loop.
its supposed to look like this:
print(seven_boom(17))
['BOOM', 1, 2, 3, 4, 5, 6, 'BOOM', 8, 9, 10, 11, 12, 13, 'BOOM', 15, 16, 'BOOM']
print(seven_boom(17))

this is what ive tried and i have no idea what to do (end_number is the end of the range in the list but it needs to be included):
def seven_boom(end_number):
 list = [range(0, end_number + 1)]
 for i in list:
   if i % 7 == 0 or i[0:] == 7:
     i+=1
     return list.replace(7, 'BOOM')

A: Something like this should work:

end_number = 18
def seven_boom(end_number):
    List = range(0, end_number + 1)
    boomList = ["BOOM" if (x%7 == 0) or ("7" in str(x)) else x for x in List ]
    return boomList

A: I think this can answer your question.
 listEx= [x for x in range (1,20)] ## creates a list using ints from 1 to 19

def changeList(listex): # get a list as a parameter
text = 'boom' # you can change the text its the element to implement if condition meets
listnew = [item if item % 7 !=  0 and '7' not in str(item) else text for item in listex ] # checks if number is divisible by 7 and changes the appending element
return listnew # return the changed list

it can be done simpler and cleaner but for now it should be enough.
Also check list comprehensions in python List Comprehension

A: I'm sure someone will edit it but next time use the curly brackets to make code easy to read. Also don't use "list" as a variable name as it is a keyword in Python. List will convert your data into a list form. I don't think leaving range in the square brackets is a good idea.
word = []
def seven_boom(end_number):
    numbers = list(range(0, end_number + 1))

    for i in numbers:
        if i % 7 ==0 or '7' in str(i):
            word.append("BOOM")
        else:
            word.append(i)
    return word


text:
Q: Jest test functions that define variables in it I want to write some Jest tests for JavaScript functions in a .mjs file. Within these functions, variables are defined by calling other functions. For example:
export function getCurrentVideo() {
     var currentVideo = VideoList.GetCurrentVideo()
    console.log(currentVideo);
    return "This is the video:" + currentVideo
}

In this case I will receive undefined, right? Because VideoList.GetCurrentVideo can't be reached.
Test will be something like:
const  getCurrentVideo  = import('../').getCurrentVideo;

describe('getCurrentVideo', () => {
    test('if getCurrentVideo will return "This is the video:" + currentVideo', () => {
        expect(getCurrentVideo).toBe('This is the video:" + currentVideo');
    });
});

I know you can add parameters to the function, but that will mean that I have to re-write the functions just for test purposes. It isn't my code, it's a huge project where the owner wants some tests for it.

A: You can mock function, assuming they work correctly (and test them separately):
const  getCurrentVideo  = import('../').getCurrentVideo;
describe('getCurrentVideo', () => {
    it('if getCurrentVideo will return "This is the video:" + currentVideo', () => {
        const currentVideo = 'testCurrentVideo';
        window.VideoList = {
            GetCurrentVideo: jest.fn(() => currentVideo)
        }
        expect(getCurrentVideo).toBe('This is the video:' + currentVideo);
    });
});

Or you can provide a full context of VideoList, so that the two function are tested together.


text: Q: Script editor make my team site go blank Hello I am trying to add custom CSS code into script editor however when I do this into my team site page. the page goes blank. I would like to know what is reason for this happening.


text:
Q: How to fix error :"Unterminated string literal." trying to display html embed stored as a variable I want to create a webpage that displays html news widgets on a globe, I have the globe and I have the html news widget but I don't know how to implement the widget into the code so that it displays on the globe.
the globe:

the widget:

the embed:

my code

    ;

       // Gen random data
      const N = 30;
      const gData =         [...Array(N).keys()].map(() => ({
        lat: (Math.random() - 0.5) * 180,
        lng: (Math.random() - 0.5) * 360,
        size: 7 + Math.random() * 30,
        color: ['red', 'white', 'blue',   'green'][Math.round(Math.random() * 3)]
      }));

      Globe()
       .globeImageUrl('//unpkg.com/three-  globe/example/img/earth-blue-marble.jpg')
        .bumpImageUrl('//unpkg.com/three-globe/example/img/earth-topology.png')
        .backgroundImageUrl('//unpkg.com/three-  globe/example/img/night-sky.png')
       .htmlElementsData(gData)
        .htmlElement(d => {
        const el =   document.createElement('div');
          el.innerHTML = markerSvg;
          el.style.color = d.color;
          el.style.width = `${d.size}px`;

              el.style['pointer-events'] = 'auto';
            el.style.cursor = 'pointer';
            el.onclick = () => console.info(d);
           return el;
         })
         (document.getElementById('globeViz'));
    </script>

currently with the code like this I am getting the error : "JSX expressions must have one parent element"
code from example file (https://github.com/vasturiano/globe.gl/blob/master/example/html-markers/index.html):

live demo
https://shange-fagan.github.io/globe.news/
edit: I am also getting the error "Unterminated string literal." at the end of the html embed


text:
Q: Deploying a stateless Go app with Redis on Kubernetes I had deploy a stateless Go web app with Redis on Kubernetes. Redis pod is running fine but the main issue with application pod and getting error dial tcp: i/o timeout in log. Thank you!!

A: Please take look: aks-vm-timeout.

Make sure that the default network security group isn't modified and that both port 22 and 9000 are open for connection to the API server. Check whether the tunnelfront pod is running in the kube-system namespace using the kubectl get pods --namespace kube-system command.
  If it isn't, force deletion of the pod and it will restart.

Also make sure if Redis port is open.
More info about troubleshooting: dial-backend-troubleshooting.
EDIT:
Answering on your question about tunnelfront:
tunnelfront is an AKS system component that's installed on every cluster that helps to facilitate secure communication from your hosted Kubernetes control plane and your nodes. It's needed for certain operations like kubectl exec, and will be redeployed to your cluster on version upgrades.
Speaking about VM:
I would SSH into the it and start watching the disk IO latency using bpf / bcc tools and the docker / kubelet logs.