text:
Q: Shared element transitions with Navigation Components and FragmentContainerView I have a shared element transition between two fragments with worked perfectly well when using a NavHostFragment <fragment> as the container for my navigation graph fragments.
Nowadays it seems that instead of <fragment> one should use <androidx.fragment.app.FragmentContainerView> which supposedly brings many fixes, especially to how transitions are handled.
However, for me it breaks all my shared element transitions. I'm defining them like so (navigating from Fragment A to Fragment B):
fragment_a.xml
<ImageView
    android:id="@+id/logo"
    android:transitionName="logo" />

fragment_b.xml
<ImageView
    android:id="@+id/logo"
    android:transitionName="logo" />

FragmentA.kt
navController.navigate(
    FragmentADirections.actionFragmentAToFragmentB(),
    FragmentNavigatorExtras(logoView to "logo")
)

FragmentB.kt
override fun onCreate(savedInstanceState: Bundle?) {
    sharedElementEnterTransition = TransitionInflater.from(context).inflateTransition(R.transition.trans_logo_shared_element)
}

trans_logo_shared_element.xml
<?xml version="1.0" encoding="utf-8"?>
<transitionSet xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="375"
    android:interpolator="@android:interpolator/fast_out_slow_in"
    android:transitionOrdering="together">
    <changeClipBounds />
    <changeTransform />
    <changeBounds />
</transitionSet>

The documentation of FragmentContainerView states that transitions are disabled for the container for Android L and up and that one should use FragmentTransaction.setCustomAnimations(int, int, int, int) instead. However I could not figure out how to get shared element transitions with Navigation Components to work with it.


text:
Q: Rebuild lost database in Ruby on Rails app I have an existing ruby on rails app that was on a VPS. I pulled the app off the VPS but never got the database data backed up. I was looking through the source code and see that there is no schema.rb file but I do have all the migration files.
My question is, will there be a way to rebuild the entire database the way it was before?

A: rake db:migrate should give you back the table schema, but you don't get any of the data.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convergence of Random Series; Determine Limit Infimum Let $(Y_{n})_{n=1}^{\infty}$ be independent random variables such that $P(Y_{n} = n - 1) = \frac{1}{n}$ and $P(Y_{n} = - 1) = 1 - \frac{1}{n}$. Check that $E[Y_{n}] = 0$ and $X_n := \sum_{i=1}^{n} Y_{n}$ is a martingale. I would like to determine $\liminf X_{n}$ and $\limsup X_{n}$.
By second Borel-Cantelli lemma, we have $$P(Y_{n} = n-1 \text{ i.o.}) = 1 = P(Y_{n} = -1 \text{ i.o.}).$$ The following argument shows that $\limsup_{n\to\infty} X_{n} = + \infty$ a.s. Let $T_{0} \equiv 1$ and $T_{k} = \inf\{ n > T_{k-1} : Y_{n} = n - 1\}$. Check that $T_{k}$ are a.s. finite (strictly increasing) stopping times, and that
    $$
  X_{T_{1}} = Y_{1} + \dots + Y_{T_{1} - 1} + Y_{T_{1}} = 1 = T_{0},
 $$
    because $Y_{1} \equiv 0, Y_2 = \dots = Y_{T_{1} - 1} = - 1$ and $Y_{T_{1}} = T_{1} - 1$. Inductively, we can observe that
    $$
  X_{T_{2}} = X_{T_{1}} + (X_{T_{2}} - X_{T_{1}}) =  T_{0} + T_{1}
 $$
    and
    $$
  X_{T_{n}} = \sum_{k=0}^{n-1} T_{n} \geq n
 $$
    since $T_{k}$ is strictly increasing and $T_{0} = 1$. It follows that $\limsup_{n\to\infty} X_{n} = + \infty$ a.s.
But it is unclear to me if $\liminf_{n} X_{n} = + \infty$ or $\liminf_{n} X_{n} = - \infty$.

A: It is $- \infty$. To see it, note that this is a renewal process, so every time you hit the $n+1$, now, you have a positive chance of getting $2n$ of $-1$s one after another ($(1 - \frac{1}{n})^{2n} $ has a limit of $e^{-2}$). By Borel Cantelli, this will happen infinitely many times, so you will reach arbitrarily small numbers almost surely.


text:
Q: Speed up solving time of this function This function is working fine but it takes too much time to solve. Please suggest me how to improve the solving time.
from sympy.solvers import solve
from sympy import Symbol

QD = 25.45
CDI = 0.65
AIN = 33.6
GTL = 10
GTSELV = 2300.1
CDGT = 1.9

def fun(HWE):
    TWE = Symbol('TWE')
    expression = (CDI*AIN*(2*9.81*(HWE-TWE))**0.5) - (CDGT*GTL*(TWE-GTSELV)**1.5)-QD
    solution = solve(expression)
    return solution

Function fun(2303) gives [2302.23386564786] which is correct but solving time is about 30 seconds. I need to run this for many arguments.

A: The dReal system can handle these sorts of problems, using the notion of delta-satisfiability. (See http://dreal.github.io for details.)
This is how your program is coded using dReal's Python interface (To install, see the notes at https://github.com/dreal/dreal4#python-binding):
from dreal import *

QD     = 25.45
CDI    = 0.65
AIN    = 33.6
GTL    = 10
GTSELV = 2300.1
CDGT   = 1.9

def fun(HWE):
    TWE = Variable("TWE")
    expression = (CDI*AIN*(2*9.81*(HWE-TWE))**0.5) - (CDGT*GTL*(TWE-GTSELV)**1.5)-QD
    return (expression == 0)

result = CheckSatisfiability(fun(2303), 0.001)
print(result)

When I run it on my now 3 year old computer, I get:
$ time python a.py
TWE : [2302.2338656478555, 2302.2338656478582]
python3 a.py  0.03s user 0.01s system 92% cpu 0.044 total

So, it takes about 0.044 seconds to go through, which does include loading the entire Python echo-system. (So, if you run many problems one after another, each instance should go even faster.)
Note that dReal shows you an interval for the acceptable solution, within a user-specified numerical error bound. The bound is the second argument to CheckSatisfiability, which we set at 0.001 for this problem. You can increase this precision at the cost of potentially more computation time, but looks like 0.001 seems to be doing quite well in this case. Also note that you get an "interval" for the solution for each variable. If you increase the precision, this interval might get smaller. For instance, when I change the call to:
result = CheckSatisfiability(fun(2303), 0.0000000000001)

I get:
$ time python a.py
TWE : [2302.2338656478569, 2302.2338656478569]
python3 a.py  0.03s user 0.01s system 84% cpu 0.050 total

where the interval has reduced to a single-point, but the program took slightly longer to run. For each problem, you should experiment with an appropriate delta to make sure the interval you get for the results is reasonable.

A: Use solve when you want a solution in terms of symbols. Use nsolve when you want a numerical solution. In your case, replace solve with nsolve and add the argument HWE to the call statement (i.e. nsolve(expression, HWE)). That 2nd argument is a guess at where the solution is near. Alternatively, give fun a 2nd arg guess and use that as the 2nd arg for nsolve. If you slowly change some parameter, using the last solution as the guess for the next solution will speed up the process (which is already quite fast).
If you know that the solution is real then you might want to take the real part of it with re(solution) since the solution comes back with a small imaginary component.


text:
Q: Solve system of equations $ \sqrt{2}x+3y= a $ and $x-\sqrt{3}y=4$ $$ \sqrt{2}x+3y= a $$
$$x-\sqrt{3}y=4$$
What is the easiest way to solve this system? I always seem to get square roots of 2 and 3s and don't know what to do.

A: By elimination we have

*

*$ \sqrt{2}x+3y= a$

*$x-\sqrt{3}y=4\implies \sqrt 2x-\sqrt{6}y=4\sqrt 2$

and subtracting

*

*$3y+\sqrt 6 y=a-4\sqrt 2 \implies y=\frac{a-4\sqrt 2}{3+\sqrt 6 }$

and then we can find $x$ from

*

*$x-\sqrt{3}y=4\implies x=4+\sqrt{3}y=4+\sqrt{3}\frac{a-4\sqrt 2}{3+\sqrt 6 }$

A: While it may not be the easiest way, here is a very systematic way:
It's a linear system that can be written as
$$
\begin{pmatrix}
\sqrt{2} & 3\\
1 & -\sqrt{3}
\end{pmatrix}
\begin{pmatrix}
x\\y
\end{pmatrix}
=
\begin{pmatrix}
a\\4
\end{pmatrix},
$$
so, due to
$$
\det{
\begin{pmatrix}
\sqrt{2} & 3\\
1 & -\sqrt{3}
\end{pmatrix}
}
= -\sqrt{6}-3\neq 0
$$
there exists a unique solution. We can compute this solution by left multiplying the above equation with the inverse of the matrix which yields
$$
\begin{pmatrix}
x\\
y
\end{pmatrix}=
\begin{pmatrix}
\sqrt{2} & 3\\
1 & -\sqrt{3}
\end{pmatrix}^{-1}
\begin{pmatrix}
a\\4
\end{pmatrix}.
$$
I guess you know how to compute this inverse.


text:
Q: cant access var outside jquery var = msg
$.get('json-signup-erros.php',{},function(data){msg=data},'json');

function focushint()
{
   alert (msg) // this works
}
$("input").focus(focus);

 alert(msg) //this doesnot work

can anyone tall me way??

A: You are making an AJAX request which is asynchronous.
msg will contain the value only after the request has been made.
You should put the code that uses msg into the Ajax request's success callback (the function(data)).
(There is the theoretical possibility to make the request synchronous using async: false but that is not good practice and should be used only if it's unavoidable.)

A: I agree with Pekka - you need to consider something like this:
var = msg;

$.get('json-signup-erros.php',{}, function(data, response)
{
   if(response == "success")
   {
       msg = data;
       alert(msg);
   }
   else
   {
       alert("Whoops something went wrong, please try again.");
   }
},'json');

function focushint()
{
   alert (msg); // this works
}

$("input").focus(focushint);

NB. I put a "success" check in the $.get... I see this all the time - you should not assume that your Ajax Http Request is going to return a 200 response! i.e. if no data get's returned due to an error (404, 500, 401) you can't alert it and you may want to warn the user that something went wrong by adding an else clause.

A: var = msg;

$.get('json-signup-erros.php',{}, function(data, response)
{
   if(response == "success")
   {
       msg = data;
       alert(msg);
   }
   else
   {
       alert("Whoops something went wrong, please try again.");
   }
},'json');

function focushint()
{
   alert (msg); // this works
}

$("input").focus(focushint);
alert(msg); // this is still does not work

If you want to access the msg outside a jQuery function like focushin that will be in the same scope


text:
Q: 404 for products in subcategories in WooCommerce I'm new in WooCommerce, and the last week i'm trying to solve problem with permalinks for WooCommerce in WP.
My client want a certain structure for products URL's:
site.com/category/product or site.com/category/subcategory/product
In WP Permalinks settings I definite that structure:
Products Custom: /%product_cat%/%product% In this case everything works fine except one thing, the URL of product page become:
site.com/category/product/product or site.com/category/subcategory/product/product/product
But if I setup this structure: /%product_cat% I just receive 404 on every product.
Sorry for my english, please help with that problem.

A: Did you flush your permalinks after changing the settings?
There shouldn't be any need to include %product%in the Product permalinks setting.
Simply use Custom: /%product_cat% and it should work.


text:
Q: rails 4 undefined local variable rendering partial has_many_through I'm trying to display all of the comments on all of a user's posts in a has_many_through association.
routes.rb:
resources :posts do
  resources :comments
end

models:
class User < ActiveRecord::Base
  has_many :posts, dependent: :destroy
  has_many :comments, :through => :posts, dependent: :destroy
end

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :comments, dependent: :destroy
end

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
end

users_controller.rb
def activity
  @user = current_user
  @posts = @user.posts
  @comments = @user.comments
end

activity.html.erb

My Activity

  <%= render @comments.last(3) %>

_comment.html.erb
<div class="comment" id="comment-<%= post.id %>-<%= comment.id %>">
    <%= link_to smavatar_for(comment.user), user_path(comment.user.name) %>
    <%= link_to comment.user.name, user_path(comment.user.name) %>

    <%= simple_format(comment.content) %>

The line <%= render @comments.last(3) %> in activity.html.erb gives the error

undefined local variable or method `post' for Class

for the line <div class="comment" id="comment-<%= post.id %>-<%= comment.id %>"> in _comment.html.erb.  I know I probably need to pass local variables to the partial, I just can't figure out how to do it. <%= @comments.last(3) %> instead of <%= render @comments.last(3) %> prints all the comment params to the view, so it's recognizing the collection.  Add locals: { comment: @comment, post: @post } still gets me undefined local variable post for Class, and post: @comment.post gets a nilClass error.  I've been all over SO and the RoR Guides backwards and forwards on rendering partials, and I'm still very unclear on what to pass when, so any help there in general is appreciated.

A: Reference the Post from the Comment itself
Assuming every Comment has a belongs_to :post association
Call the partial using the shortcut syntax exactly as you had
<%= render @comments.last(3) %>

Inside the partial, use comment.post or comment.post_id to get Post data
E.g.
<div class="comment" id="comment-<%= comment.post_id %>-<%= comment.id %>">
    <%= link_to smavatar_for(comment.user), user_path(comment.user.name) %>
    <%= link_to comment.user.name, user_path(comment.user.name) %>

    <%= simple_format(comment.content) %>

No need to use locals in this scenario
Notice that you tried to pass @post in through the locals option, however in your controller you have a @posts variable (plural), not @post singular.
Because each of the Comment records may belong to a different Post, there is no single option you can pass for Post.
The only other way to use locals is if you broke out the partial into a loop and rendered each Comment individually, e.g.
<% @comments.last(3).each do |comment| %>
   <%= render comment, post: comment.post %>

   <%= render partial: "comments/comment", locals: { comment: comment, post: comment.post } %>
<% end %>

Notice we still need to call comment.post to get the Post associated with the Comment. Because of this, it's much simpler to just use the shortcut syntax and reference the Post from the Comment within the partial.

A: Different perspective you just need to change post.id to comment.post.id in _comment.html.erb without pass locals, it more clearner and simple
<div class="comment" id="comment-<%= comment.post.id %>-<%= comment.id %>">
  <%= link_to smavatar_for(comment.user), user_path(comment.user.name) %>
  <%= link_to comment.user.name, user_path(comment.user.name) %>

    <%= simple_format(comment.content) %>

does it work?


text:
Q: How Long Would Take to Upgrade an 1T Oracle DB from 10g to 11g? How long would take to upgrade an Oracle DB which has 1T data from 10g to 11g usually/roughly? I need to estimate the down time for it since it is a prod db. Thanks much!

A: Presumably, you have a development and test instance of this database running on similar hardware with a similar data volume and the same database components installed, correct?  And, presumably, you will be upgrading these lower environments (and testing that whatever applications use this database still function correctly), correct?
Assuming that is the case, I'd time how long it took to upgrade the development database and use that as your estimate of the time required to upgrade the other instances.  There are, obviously, a number of factors that determine how long the actual upgrade will take.  My guess is that the downtime would likely only need to be an hour or two but you're much better off using the actual time required to upgrade dev.

A: 30-90 minutes according to Oracle's Best Practices for Upgrading.   This is about the closest estimate you will get given all the unknowns in this situation.
The size of the database really matters very little in determining how long the upgrade will take.  Here are the main factors effecting the duration (from the Oracle.com upgrade blog):

*

*Number of installed database components and options - the more components/option gotten installed, the more upgrade scripts will have to be run, the longer it'll take

*Valid and non-stale dictionary statistics - even though creating dictionary statistics in some older releases of Oracle wasn't a brilliant idea since desupport of the rule based optimizer the data dictionary should be analyzed. Especially right before an upgrade. Otherwise this will happen during the upgrade while the database is started in a restricted upgrade mode causing additional downtime.

*Number of rows in AUD$ if audit_trail is set to DB

*Number of synonyms when upgrading from Oracle 9i - synonyms will be touched and get a new dependency in the dictionary in DEPENDENCY$ - if there's a high number (such as 100,000) this can eat up some time

*Number of objects in XDB

*At a very low rate if COMPATIBLE will be increased: Number of datafiles and the size of the redologs
Here are some additional factors you may want to consider that aren't related to the core of the upgrade itself:

*

*Whether the pre-upgrade script has been run and issues resolved.

*How many invalid objects there are.

*If the upgrade is being done in place (vs. Import/Export, Streams, Data Guard, etc.)

*Whether the DBUA or scripts are used to do the upgrade.

*If new Oracle home pre-installed.

*Disk speed and throughput.

*Other CPU/Disk activity occurring at the same time.

*Archive Log Mode.

*Other changes being made with the upgrade.

*If a cold backup is necessary before and/or after the upgrade.

*Any patch sets or one off patches that will also be applied.

*How much verification of the upgrade needs to be done before it can be made available.

Probably the biggest factor effecting the upgrade is the unknown factor.  Even when the upgrade is practiced in advance on similar hardware with similar data sets, etc. things can still occur that were unanticipated and can drastically effect the duration.  With that in mind you should mimic the production environment as closely as you can for the test upgrades.  That is, as close as your budget will allow.
If space is the issue preventing you from testing the upgrade, consider restoring the database to a test box excluding some of the larger user tablespaces.  This won't give you an exact feel for the time, but it should give you a closer ballpark and allow you to work through more of the unknowns.


text:
Q: How to write a value to the workflow container Below is my workflow inbox content

STEP 1: ln HTML table, the user can approve or reject WBS by checked radio
STEP 2: When user click confirm, then the workflow will update status for each WBS that shown in the table.
Purpose:
I need to get the user's action from step 1.
For now I've enhanced SAPEVENT and make it called my Function Module.
In my function function module I can use 'SAP_WAPI_READ_CONTAINER' properly but I cannot use 'SAP_WAPI_WRITE_CONTAINER' to write the value to workflow.
There was error msg 900  occurs.
Please see my code below:
        DATA: LT_CONTAINER TYPE STANDARD TABLE OF SWR_CONT,
        LT_MSG_LINES TYPE SAPI_MSG_LINES,
        LT_MSG_STRUC TYPE SAPI_MSG_STRUC.

        DATA: LV_RETCODE TYPE SY-SUBRC.

        *** Get workflow container by using 'SAP_WAPI_READ_CONTAINER' ***

        CALL FUNCTION 'SAP_WAPI_READ_CONTAINER'
            EXPORTING
                WORKITEM_ID      = IV_WORKITEMID
            IMPORTING
                RETURN_CODE      = LV_RETCODE
            TABLES
                SIMPLE_CONTAINER = LT_CONTAINER
                MESSAGE_LINES    = LT_MSG_LINES
                MESSAGE_STRUCT   = LT_MSG_STRUC.

        *** then I change data inside LT_CONTAINER as my requirement below ***

        REPLACE |type="submit" id="ALLAPPV"| IN TABLE LT_CONTAINER[]
        WITH |type="button" id="ALLAPPV" hidden|.

        *** use SAP_WAPI_WRITE_CONTAINER in order to write value to workflow container but it return error msg 900 ***

        CALL FUNCTION 'SAP_WAPI_WRITE_CONTAINER'
            EXPORTING
                WORKITEM_ID                  = IV_WORKITEMID
                DO_COMMIT                    = 'X'
                OVERWRITE_TABLES_SIMPLE_CONT = 'X'
            IMPORTING
                RETURN_CODE                  = LV_RETCODE
            TABLES
                SIMPLE_CONTAINER             = LT_CONTAINER
                MESSAGE_LINES                = LT_MSG_LINES
                MESSAGE_STRUCT               = LT_MSG_STRUC.


text:
Q: Remove specific cell border in table
The <colgroup> tag is useful for applying styles to entire columns, instead of repeating the styles for each cell, for each row.

I applied colgroup to my table by adding
<colgroup>
  <col span="6" style="border-right: 1px solid #b7b7b7">
</colgroup>

below
 tag.
So now all the cells have right border in all rows
but I need to delete border in specific cell.
How can I do that ?

    .details-map:before{
        content: '';
        display: block;
        height: 70px;
    }
    .details-map:after{
        content: '';
        display: block;
        height: 50px;
    }
    .noborder{
     border-right: 1px solid transparent;
     border-bottom: 1px solid transparent;
    }
    .noborderall{
     border-right: 1px solid transparent;
     border-left: 1px solid transparent;
    }
    .noborderr{
     border-right: 1px solid transparent;
    }

                        <colgroup>
                            <col span="6" style="border-right: 2px solid red">
                        </colgroup>

                            Rank
                            School
                            Student to Faculty Ratio
                            Acceptance Rate
                            Graduation Rate
                            Median Debt Incurred
                            Median Earnings/Total Expense

                              1
                              Lorem Ipsum Dolor
                              XX/1
                              XX%
                              XX%
                              $XX,XXX
                              $XX,XXX/$XX,XXX

                              2
                              Lorem Ipsum Dolor
                              XX/1
                              XX%
                              XX%
                              $XX,XXX
                              $XX,XXX/$XX,XXX

                              Lorem Ipsum Dolor

                                  <button class="buttons">School website</button>
                                  <button class="buttons">Financial Aid Office</button>
                                  <button class="buttons">Prospecitve students</button>

                              Expense Ratio

                              XX/10

                              Acceptance Rate Score

                              XX/10

                              Graduation Rate Score

                              XX/10

                              ROI/Value

                              XX/10

                              Student to Faculty Ratio

                              XX/10

About the scores

                                  Using a complex algorithm our review tool examines all of the schools in Pennsylvania that offer Computer Science Majors and provides a score for several categories.

                              3
                              Lorem Ipsum Dolor
                              XX/1
                              XX%
                              XX%
                              $XX,XXX
                              $XX,XXX/$XX,XXX

Padding doesn't work in tbody so I used before and after pseudo elements to add space. In this space I need to delete the border.

A: you can give an id or class to your choice of col (which should not have border) and add the border:none property to it
HTML :
<colgroup>
  <col span="6" style="border-right: 1px solid #b7b7b7">
<col span="6" style="border-right: 1px solid #b7b7b7">
<col span="6" style="border-right: 1px solid #b7b7b7">
<col span="6" class="tb" style="border-right: 1px solid #b7b7b7">
</colgroup>

CSS :
.tb{
 border:none;
}

A: I have created demo for remove specific cell border.
Demo Table Link
CSS
tr:nth-child(5) td:nth-child(2) {
  border-right: hidden;
}


text:
Q: ZPL How to Center Barcode (Code 128) i'd like to know how to center barcode code 128.
on the picture you should see that it is right now left justified.

my zpl:
^XA
^LH10,10
^FO0,0^XGE:SWESE001.GRF^FS
^FO440,0^XGE:SWESE000.GRF^FS
^FO0,70^FB550,50,0,C,0^AQN,25,30^FDSpraynozzle 50mm^FS
^FO0,130^BY2^BCN,30,Y,Y,N,N^FDS/N:941001-0114-0001^FS
^FO180,170^AQN,23,20^FDwww.swepro.com^FS
^XZ

A: There is no ZPL command to center a code.  Your program that generates the ZPL would need to auto calculate the position based on the size of the code and position using the coordinates.

A: I'm posting my solution in case someone is looking for it. As E_S mentions, in order to center a barcode in a label you have to calculate it by code following these steps:

*

*Check your narrow bar width, in your case 2 (^BY2)

*Find out your label total width in dots. For this you have to know what is your printer's resolution (eg: 8 dots / mm). so if you have a 80 mm wide label, 80 * 8 = 640 dots

*Count each character in your barcode, including invocation codes and check digit as specified below. For information on invocation codes see: https://www.zebra.com/content/dam/zebra/manuals/en-us/software/zpl-zbi2-pm-en.pdf (Page 95)

*Note that invocation codes (">:", ">5", etc.) count as one character, and that characters in mode C are stored in pairs. For more information on mode C, refer to http://en.wikipedia.org/wiki/Code_128

*If your barcode is >:S/N:941001-0114-0001 you have to count [start code B] + [20 characters] + [check digit] = 22

*If your barcode is >:S/N:>5941001>6->50114>6->50001 you have to count [start code B] + [4 characters for 'S/N:'] + [mode C invocation] + [3 characters for '941001'] + [mode B invocation] + [1 characters for '-'] + [mode C invocation] + [2 characters for '0114'] + [mode B invocation] + [1 characters for '-'] + [mode C invocation] + [2 characters for '0001'] + [check digit] = 20

*Every character occupies 11 units mixing spaces and bars, with the exception of stop code that has 2 extra units (that is a total of 13)

*Here comes the good stuff... The barcode width is: ((chars counted [22 or 20] * 11) + (stop char * 13)) * narrow bar width = 510 dots or 466 dots

*Now all we have to do is round((label width - barcode width) / 2) and use that to position the barcode with ^FT
That's it! Hope it helps someone!

A: Another solution to this problem, not as elegant as by Nicolas Garfinkiel, but much much simpler, is the following one.
Fundamentally the problem with Code 128 is that it is variable width. But is real life situation, we anyway use it as fixed width. This needs explanation. We position the code somewhere, and we expect it be no wider than some, otherwise it wouldn't fit, and we must reserve (keep empty) the space it is allowed to fill. Thus, even though it's variable width, we always need to allocate for it fixed area on a label.
So the solution to the centering problem would be to make Code 128 fixed-length.
If this is subset C (pairs of digits), then you need:

*

*Get any big enough number, of the form 100000..., so there are in total even number of digits.

*Add you code to it.

For example, if your code was 94100101140001, then you can add it with 10^16, and get this:
10000000000000000
   94100101140001
=================
10094100101140001

Thus the code becomes fixed-width, and can be hard-centered.
If your code is not subset C, and contains text, then (in pseudocode) you do:
my_code = "S/N:941001-0114-0001"
const_max_code_length = 24  (for example)
if my-code.length > const_max_code_length then error
padding_char = "="
result = ""
for (0..(const_max_code_length - my_code.length)) do
    result += padding_char
end_for
result += my_code

In case of your code, it will produce:
====S/N:941001-0114-0001

Then, no matter what text you put into it, it'll always be fixed length, and so will be positioned consistently.
I used it myself, before found this post. It's not OK, it's a hack, and what Nicolas Garfinkiel suggested is more right. The most appropriate solution would be, though, if ZPL itself would support code centering, and unfortunately it doesn't.

A: Click on the Checkbox "Print BarCode as a Graffic" in Barcode Proprieties.
It worked in my case.

A: you must to tray to use :
 ^FO10,170^AQN,23,20^FDwww.swepro.com^FS

. where
 . ^FOX,Y^AQN,...^FSX=x-axis location and Y=y-axis location


text:
Q: Can I parameterize OAuth options for my users? I want to present a list of mobile apps that my users can choose to grant OAuth access to.
I want to parameterize this list in my database, so I can easily add new mobile apps to the list by adding that app's unique details to my database table.  I expect the parameters will include the various OAuth URLs needed, the unique ApplicationID I got when I registered with them, and so on.  When the member clicks on one from my list, it presents the appropriate prompts to collect their username/password, etc. for that app.
Can I make a generic parameterized OAuth authorization system like this?  Or will each mobile app require me to do unique custom coding to set up the user's authorization?
I had heard we'd need to install a unique DLL on my Windows web server, for each mobile app maker, just to do OAuth.  (Not the actual data-calls, just establishing the OAuth.  I know that many app makers publish .NET DLLs to simplify the data calls...I'm not talking about that.)
Possible?  Can anyone point me to documentation if it is possible?
Many thanks,
- Tom


text:
Q: glDrawArrays() behaving weirdly on Mac OS X I am practicing the usage of VBOs in OpenGL with Java and LWJGL (using this tutorial, and basically copying it's code: http://www.arcsynthesis.org/gltut/index.html) and right now something really weird is happening.
I have a window set up and this is my render() function, called inside the main loop:
public void render() {

    FloatBuffer buffer = BufferUtils.createFloatBuffer(3 * 3);

    buffer.put(-1);
    buffer.put(-1);
    buffer.put(0);

    buffer.put(0);
    buffer.put(1);
    buffer.put(0);

    buffer.put(1);
    buffer.put(-1);
    buffer.put(0);

    buffer.flip();

    int vbo = glGenBuffers();

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, buffer, GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);

    glVertexAttribPointer(0, 3, GL_FLOAT, false, 3 * 4, 0);

    glDrawArrays(GL_TRIANGLES, 0, 3);

    glDisableVertexAttribArray(0);

}

As you can see, it's very simple code which should draw a triangle. But what I get on a Mac OS X Mountain Lion laptop, running Intel HD 4000 graphics is this:

And what I get on Windows 7, running AMD HD 6850 graphics is this:

Why is that? I really see no reason for this to happen, both of the video cards support OpenGL 2.0, which is what I'm using, right?

A: I devoted a lot of time to solving this issue when I first started to use VAO objects. It was very frustrating to say the least.
I ultimately figured it out and I guess it comes down to a glitch in the compatibility profile that  requires you to have used glLinkProgram and glUseProgram on a shader prior to calling glGenVertexArrays, even though the program requirement should have been relaxed outside the Core profile...
The easiest solution is to simply replace:
GL30.glGenVertexArrays with APPLEVertexArrayObject.glGenVertexArraysAPPLE
GL30.glBindVertexArraywith  APPLEVertexArrayObject.glBindVertexArrayAPPLE
GL30.glDeleteVertexArrays with APPLEVertexArrayObject.glDeleteVertexArrayAPPLE
You can also overcome the problem by compiling a shader and calling glUseProgram prior to using GL30.glGenVertexArrays ...


text:
Q: OCaml time profiling on OS X In the absence of a working gprof, what other tool can I use to profile on OS X?
(I know about the poor man's approach but would prefer something that does not require manual code instrumentation)
I have so far refrained from installing the full Xcode and tried using Activity Monitor but I am not sure I am doing things right?
Details:
I have managed to compile my project for time profiling using ocamlbuild and the ".p.native" build target. I then use Activity Monitor on Mac OS X 10.9 to sample the running process. This gives a whole lot of output about OCaml internals such as garbage collection but I am not seeing properly annotated function names from my module.
A fragment of the output:
Call graph:
    2109 Thread_55861   DispatchQueue_1: com.apple.main-thread  (serial)
      542 .L1099  (in atest.p.native) + 18  [0x101a89956]
      + 210 caml_weak_get  (in atest.p.native) + 278  [0x101ac79e6]
      + ! 87 caml_alloc_small  (in atest.p.native) + 22  [0x101ab75e6]
      + ! : 70 mcount  (in libsystem_c.dylib) + 32,37,...  [0x7fff87545620,0x7fff87545625,...]
      + ! : 10 mcount  (in libsystem_c.dylib) + 59  [0x7fff8754563b]
      + ! : | 10 moncount  (in libsystem_c.dylib) + 0,1,...  [0x7fff8754d3a5,0x7fff8754d3a6,...]
      + ! : 7 DYLD-STUB$$moncount  (in libsystem_c.dylib) + 0  [0x7fff875c549e]
      + ! 68 caml_alloc_small  (in atest.p.native) + 1,128,...  [0x101ab75d1,0x101ab7650,...]
      + ! 46 caml_alloc_small  (in atest.p.native) + 87  [0x101ab7627]
      + ! : 40 caml_minor_collection  (in atest.p.native) + 90  [0x101ab624a]

I see a lot of symbols similar to .L1099 above but almost none that have a proper name of the type  Module-name_function-name_unique-number which is what I expect from reading the OCaml manual. Confusingly a few symbols do appear that are human readable - but not enough to be useful.
Another fragment in which the very last line is a function from my own module
Sort by top of stack, same collapsed (when >= 5):
        mcount  (in libsystem_c.dylib)        617
        caml_weak_get  (in atest.p.native)        256
        caml_alloc_small  (in atest.p.native)        97
        caml_modify  (in atest.p.native)        94
        moncount  (in libsystem_c.dylib)        93
        caml_c_call  (in atest.p.native)        67
        mark_slice  (in atest.p.native)        42
        caml_weak_set  (in atest.p.native)        36
        caml_page_table_lookup  (in atest.p.native)        34
        camlRandom__bits_1038  (in atest.p.native)        30
        sweep_slice  (in atest.p.native)        24
        DYLD-STUB$$mcount  (in atest.p.native)        23
        DYLD-STUB$$moncount  (in libsystem_c.dylib)        18
        compare_val  (in atest.p.native)        16
        .L327  (in atest.p.native)        15
        .L621  (in atest.p.native)        15
        .L1202  (in atest.p.native)        14
        .L1205  (in atest.p.native)        14
        .L1173  (in atest.p.native)        12
        .L1113  (in atest.p.native)        11
        .L1281  (in atest.p.native)        11
        .L1310  (in atest.p.native)        11
        caml_fl_allocate  (in atest.p.native)        11
        caml_oldify_one  (in atest.p.native)        11
        caml_weak_blit  (in atest.p.native)        11
        .L1099  (in atest.p.native)        10
        .L1150  (in atest.p.native)        10
        .L135  (in atest.p.native)        10
        .L149  (in atest.p.native)        10
        .L295  (in atest.p.native)        10
        caml_alloc_shr  (in atest.p.native)        10
        .L148  (in atest.p.native)        9
        .L268  (in atest.p.native)        9
        invert_pointer_at  (in atest.p.native)        9
        .L1135  (in atest.p.native)        8
        .L1154  (in atest.p.native)        8
        .L1278  (in atest.p.native)        8
        allocate_block  (in atest.p.native)        8
        .L1114  (in atest.p.native)        7
        .L1118  (in atest.p.native)        7
        .L1172  (in atest.p.native)        7
        .L131  (in atest.p.native)        7
        camlReact__occurs_1470  (in atest.p.native)        7
        camlReactor__compare_1235  (in atest.p.native)        7

A: A usable solution is the landmarks library which allows manual or automatic instrumentation of code and incorporates CPU cycle counters, allocation info from the GC and wall clock timing. Works fine on OS X and allows fine-grained profiling where necessary.

A: Poor man's profiler doesn't require any code instrumentation at all. See this example of usage, albeit for allocation profiler but the idea is the same.
<shameless plug>You can also use ready-made pmp script.</shameless plug>

A: since nobody came up with a positive answer, it seems that there is currently no tool available for easy-to-use time profiling of ocaml programs on os x.


text:
Q: GlusterFS How to add replica brick to system I am trying to add two bricks to a Gluster Volume. The two new nodes are in the network, and can be verified with:
root /# gluster peer status

Also the volume:
Status of volume: mainvolume
Gluster process                     Port    Online  Pid
------------------------------------------------------------------------------
Brick Node-1:/storage                   49152   Y   1162
NFS Server on localhost                 2049    Y   4004
Self-heal Daemon on localhost               N/A Y   4011
NFS Server on 104.xxx.xxx.xxx           2049    Y   3024
Self-heal Daemon on 104.xxx.xxx.xxx         N/A Y   3031
Brick 45.xx.xx.xx:/storage-pool         N/A N   N/A
NFS Server on 45.xx.xx.xx               N/A N   N/A

There are no active volume tasks

The last brick was accidentally added and needs to be removed. I been looking at the Gluster docs as well as someone's github cheat sheet, but I can't seem to add the two nodes. I started off only wanting to add one node, but then I accidentally removed a node. So now I have two nodes to add. Below is some sample code of what I am trying:
gluster volume add-brick mainvolume replica 2 Node-2:/storage Node-3:/storage
--> volume add-brick: failed:

Log File:
[2015-09-07 02:57:44.475415] I [input.c:36:cli_batch] 0-: Exiting with: -1
[2015-09-07 03:04:31.229023] I [input.c:36:cli_batch] 0-: Exiting with: -1
[2015-09-07 02:49:54.270231] E [glusterd-brick-ops.c:492:__glusterd_handle_add_brick] 0-management:
[2015-09-07 02:52:48.909897] E [glusterd-brick-ops.c:454:__glusterd_handle_add_brick] 0-management: Incorrect number of bricks supplied 1 with count 2
[2015-09-07 02:16:46.498829] E [client-handshake.c:1742:client_query_portmap_cbk] 1-mainvolume-client-2: failed to get the port number for remote subvolume. Please run 'gluster volume status' on server to see if brick process is running.

I am add a loss for what to do, my next step is going to be to recreate the network if I can't figure it out.

A: you can remove the brick Brick 45.xx.xx.xx:/storage-pool if it is not needed. while removing give correct replica number.
gluster volume remove-brick mainvolume replica 1 45.xx.xx.xx/storage-pool force

Then you make sure no extended attributes are on node-2 and node-3, by doing
setfattr -x trusted.glusterfs.volume-id /brick-path
setfattr -x trusted.gfid /brick-path

rm -rf /brick-path/.glusterfs

ie,
setfattr -x trusted.glusterfs.volume-id /storage
setfattr -x trusted.gfid /storage

rm -rf /storage/.glusterfs

on both new nodes.
Then try to add-brick by giving correct replica number, here in this case 3, since we have three bricks including the existing one.
gluster volume add-brick mainvolume replica 3 Node-2:/storage Node-3:/storage force


text:
Q: Why is my code telling me to initialize a variable that is already initialized? I have the below code:
public String palindrome(String str)
{
    String str, reverse = "";
    Scanner in = new Scanner(System.in);
    int length = str.length();
    for ( int i = length - 1; i >= 0; i-- )
        reverse = reverse + str.charAt(i);
    if (str.equals(reverse))
        System.out.println("Entered string is a palindrome.");
    else
        System.out.println("Entered string is not a palindrome.");

    return "";
}

It has an init() method that calls it when the character 'p' is typed and it is to check whether the current string is palindromic or not.
However ,when I compile it states there is an error in the line:
String str, reverse = "";

The error states that the variable may not have been initialized. However, when I initialize it another error message comes up stating that str has already been initialized.

A: You have str duplicated, once as a parameter and once as a local variable. Besides that...
String str, reverse = "";
...does initialize reverse with "", but not str:
String str, reverse = "";
System.out.println(str); // error here "The local variable str may not have been initialized"

But...
String str = "", reverse = "";
System.out.println(str); // works fine

A: String str, reverse = "";

this mean that reverse = "" and str is not initalized
String str = "" , reverse = "";

A: You are attempting to declare str twice
  public String palindrome(String str)

  String str, reverse = "";

Almost certainly you did not intend to do that. Change it:
   String reverse = "";

It was that second str that was not being initialised

A: You should initialize all the local variable in a method.You didnt initialize the variable str in your program .
you should have written like
String str="",reverse="";

A: Please note that in function parameter too you have a str.

variable str is already defined in method palindrome(String)

*

*Consider renaming of the parameter str or local variable str or

*simply remove the local variable since it doesn't seem required and parameter passed str would suffice for the required functionality.

Also, consider the following statement:
String str, reverse = "";

String str isn't initialized but only reverse is initialized to ""(an empty string).
You may use:
 String str="", reverse = "";

Why do you have a return type as String as you are printing in the same function? Also, note it is simply returning "" in either case.
public String palindrome(String str)
{
    String strTmp = "", reverse = "";
    Scanner in = new Scanner(System.in);
    int length = str.length();
    for ( int i = length - 1; i >= 0; i-- )
        reverse = reverse + str.charAt(i);
    if (str.equals(reverse)){
        strTmp = str;
        System.out.println("Entered string " + str + " is a palindrome.");
        }
    else
        System.out.println("Entered string " + str + " is not a palindrome.");

return strTmp;

}

A: The Compiler is confused. Look at your code:
public String palindrome(String str)<-------- str as parameter
{
 String str, reverse = "";  <-------- str as local variable [Also Not Initialized]
Scanner in = new Scanner(System.in);
int length = str.length(); <------------ Which str??? parameter or local Variable???
for ( int i = length - 1; i >= 0; i-- )
    reverse = reverse + str.charAt(i);
if (str.equals(reverse)) <------------ Which str??? parameter or local Variable???
    System.out.println("Entered string is a palindrome.");
else
    System.out.println("Entered string is not a palindrome.");
return "";

}
Change the name of your local variable or parameter and use accordingly.

A: This error is because your parameter variable and local variable are the same. So str.length is the local variable .
Simply you can change the local variable as String str1="" or String str=""
and you find no error.

A: Rename local variable or palindrome method's parameter str.
public static void main(String[] args) {
    palindrome("hello");

}

public static String palindrome(String palindromeValue) {
    String str = palindromeValue, reverse = "";
    // Scanner in = new Scanner(System.in);
    int length = str.length();
    for (int i = length - 1; i >= 0; i--) {
        reverse = reverse + str.charAt(i);
    }
    if (str.equals(reverse)) {
        System.out.println("Entered string is a palindrome.");
    } else {
        System.out.println("Entered string is not a palindrome.");
    }

    return "";
}

A:
You don't need a String return type as you're printing the value in the function itself.

Change you method declaration to void
public void palindrom(String str)

Your String str is already defined in your parameters.

There is no need to define it again, just use it.

public void palindrome(String str)
    {
        String reverse = "";
        int length = str.length();
        for ( int i = length - 1; i >= 0; i-- )
            reverse = reverse + str.charAt(i);
        if (str.equals(reverse))
            System.out.println("Entered string is a palindrome.");
        else
            System.out.println("Entered string is not a palindrome.");
    }

What happens if I declare the String again
public void palindrome(String str)
{
  String str, reverse = "";
}

Your str variable is redefined here. The parameter value conflicts with the same name and your program won't compile.

A: you are getting str as a argument and you are declaring it again


text:
Q: jQuery focus without scroll using custom-scrollbar-plugin I am using custom-scrollbar-plugin
in that i need  to select the current concept without scroll (ex. is bellow the visible area)
How can I set the focus without scrollbar movement? I need to stay the scrollbar in the original place.
This is my jquery code
$(".content_1").mCustomScrollbar({
    theme:"dark",
    advanced:{
    autoScrollOnFocus: true,
    updateOnContentResize: true
    }
});


text:
Q: Redirect with Javascript and set request attribute I'm trying to perform a redirect to a different page in Javascript AND also set a request attribute for that redirect.
I don't want a request parameter like so:
window.location.href="www.somesite.com/id=123"

because I don't want the user to see the value being passed in the address bar.
One way I see is to have a form in the page with a hidden field and to set the field and submit the form from Javascript.
Is there some easier way?
Thanks...

A: Use a Form and post it via window.onload.
<form method="post" id="myForm" action="/someurl">
<input type="hidden" name="param" value="X" />
</form>

<script>
window.onload=function(){ document.getElementById('myForm').submit(); }

and you're done.

A: You can not post data using javascript... You can use ajax to do that. or you can use something like this in your javascript to achieve what you are trying to:
var post_url = 'http://www.somesite.com/id=123';
var form = $('<form action="' + url + '" method="get">' +
'<input type="hidden" name="id" value="123" />' +
'</form>');
$(form).submit();

Hope this helps.


text:
Q: Correct way of updating checkbox with keyboard press in React I've got the following code:
export default function Tag(props: { tag: ITag, setTag: (tag: string) => void }) {
    const [checked, setChecked] = useState(false)

    const handleTagChange = () => {
        props.setTag(props.tag.abbreviation);
        var element = document.getElementById(props.tag.abbreviation);
        if (!checked) {
            element?.classList.add("label-toggle")
        }
        else {
            element?.classList.remove("label-toggle")
        }
        setChecked(!checked)
    }

    return (

            <input id='check' key={props.tag.hotkey} checked={checked} onChange={handleTagChange} type="checkbox" />

{props.tag.abbreviation}

{props.tag.hotkey}

    )

Everything works as expected if I use mouse click to trigger the checkbox. It works both if I press on the checkbox or the surrounding div with function handleTagChange()
I've added a key listener, so that the checkbox can be triggered with a keyboard key press.
const handleHotKey = (e: KeyboardEvent) => {
    if (e.key == props.tag.hotkey) {
        handleTagChange();
    }
}

useEffect(() => {
    document.addEventListener('keydown', e => { handleHotKey(e) }, false)
}, [])

Key listener works, key press is detected, however the value of the checked state simply does not update.
I have no clue what I'm doing wrong. What is the correct way to achieve this?
Thanks.

A: In such cases, it's common practice to wrap an input element inside a label, which are programmatically associated with each other.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label
The standard way of handling events is to use the event, which is passed into the onChange callback. When a checkbox is changed, you can access its checked state through the event.target.checked attribute.
I've also noticed a common mistake of directly manipulating DOM elements. React was created to solve this particular problem. In your example, there's no need to work with elements in this way.
type Props =  {
    tag: ITag,
    setTag: (tag: string) => void
}

export default function Tag({ tag, setTag }: Props) {
    const [checked, setChecked] = useState(false)

    const handleTagChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        setChecked(event.target.checked);
        setTag(tag.abbreviation);
    }

    // React will guarantee a consistency
    const className = `label-button ${checked ? '' : 'label-toggle'}`

    return (

            <input checked={checked} onChange={handleTagChange} type="checkbox" />

{tag.abbreviation}

{tag.hotkey}

    )


text:
Q: C++ equivalent of .NET's List<>? I'm curious as to the most common C++ equivalent to .NET's List<>? There are many libraries, and I'm not sure which one has the best performance characteristics.
Here is the .NET code that demonstrates List<>:
List<double> x = new List<double> {1};
x.Add(2);
Console.WriteLine("{0},{1}",x[0], x[1]);

A: The exact equivalent is std::vector<>.  Exact same perf characteristics, only the exponential back-off growth algorithm for resizing the underlying array is slightly different.  Common std::vector<> implementations favor growing the array by x1.5, .NET collections grow by x2.
Note that it is not std::list<>, the equivalent for that one in .NET is LinkedList<>.  Best avoided, it has very poor cache locality.

A: You could use vector as follows :
#include <vector>

using namespace std;
vector<double> v;
v.push_back(12);

A: Unless you have a reason for choosing otherwise, the standard container that you should adopt by default is std::vector (which is, by the way, the equivalent of .NET's List<> container).
std::vector allocates its element in a contiguous region of storage, which makes operations faster because of a higher rate of cache hits. This usually dominates the impact of linear computational complexity on operations such as insertions and removals from the middle of the container:
#include <vector> // <== Necessary for std::vector
#include <iostream> // <== Necessary for overloads of operator << and std::cout

std::vector<int> temp = { 1 };
temp.push_back(42);
std::cout << temp[0] << "," << temp[1];

Here is a live example.
For more technical information on why std::vector should be your default choice for a container, see this paper by Bjarne Stroustrup.


text:
Q: Database Errors while running dbt run I am new to dbt and I am trying to run dbt from cli, which is connected to snowflake. I have successfully created a profile.yml, dbt_profile.yml and dbt debug shows everything is connected. but when I run dbt run to create the example models I get this error
  Running with dbt=1.0.1
  Found 2 models, 4 tests, 0 snapshots, 0 analyses, 179 macros, 0 operations, 0 seed files, 0 sources, 0 exposures, 0 metrics
Encountered an error:
Runtime Error
  Database error while listing schemas in database "LEE_Test"
  Database Error
    002043 (02000): SQL compilation error:
    Object does not exist, or operation cannot be performed.

A: okay there might be a  problems in your dbt profile in which u have given the snowflake detials there is some mistake there  probably in naming or either
here is an exmaple on how you can connect to snowflake
default:(profile name )
  outputs:

    dev: # User-Password config
      type: snowflake
      account: snowflake_account_link
      user: DBT_CLOUD_DEV
      password: *******
      role: your role of snowflake
      database: your data base name
      warehouse: name of your warehouse
      schema: <your schema name >
      threads: 2
      client_session_keep_alive: False

  target: dev

let me know if this works or not


text:
Q: What do more than 2 single quotes mean in SQL Server (T-SQL)? In this one stored procedure being called by an API to update a record, there's lots of instances of this:
SET @NewField = REPLACE(ISNULL(@InputField, ''), '''', '''''')

I get the ISNULL part, and I know '' escapes a single quote, but I cannot figure out what the intent of four and six quotes is?

A: A literal quote in a string literal needs to be escaped by doubling it.
So the (interpreted, runtime) value of '''' is just one single quote.
Replacing what looks like four quotes by what looks like six quotes is t-sql syntax to mean:
Search the string for occurrences of a single quote, and replace each with two consecutive single quotes.
Thus SQL's syntax is weird sometimes would become SQL''s syntax is weird sometimes.
One application of this I've seen is to prepare a string for subsequent literal execution (with the "execute" command). This is a sensitive area of SQL programming because it deals with security: Correctly escaping single quotes is one building block of safe-for-scripting queries.


text:
Q: How can I make .push work in FileReader.onload()? I have the following code in which I'm trying to read a file using FileReader and put its contents in an array. Only after all the data has been pushed do I want to continue. Here's what I have currently:
    const confirm = () => {

        var reader = new FileReader();
        let images = [];
        reader.onload = function(e) {
            images.push(e.target.result);
        };
        reader.readAsDataURL(formValues.images[0].file);
        console.log('images base 64');
        console.log(images); // this prints the empty array.

    };

I want to continue on only after images have been updated with the file contents. How can I do that?
-- edit --
I want to in fact add multiple files to the array, so I tried the following.
    var reader = new FileReader();
        let images = [];
        reader.onload = function(e) {
            images.push(e.target.result);
            console.log('images base 64');
            console.log(images);
        };
        for (let i = 0; i < formValues.images.length; i++) {
            reader.readAsDataURL(formValues.images[i].file);
        }

But this gives the error "InvalidStateError: The object is in an invalid state."

A: You are trying to the result before it load. Move the console.log(images) inside onload function.
const confirm = () => {
        var reader = new FileReader();
        let images = [];
        reader.onload = function(e) {
            images.push(e.target.result);
             console.log(images);
        };
        reader.readAsDataURL(formValues.images[0].file);
        console.log('images base 64');
    };

A:
it works for me try like this , surly

this.file64=[];
    reader.onloadend =(e) =>{

                  var result = reader.result;
                      console.log(result)
                      this.file64.push(result)
                };


text:
Q: Loading a big RData File I can't load a RData file, I get the following error message
> load("GPL570_matrix.Rdata")
Error: cannot allocate vector of size 8.9 Gb
In addition: Warning messages:
1: Reached total allocation of 5941Mb: see help(memory.size)
2: Reached total allocation of 5941Mb: see help(memory.size)
3: Reached total allocation of 5941Mb: see help(memory.size)
4: Reached total allocation of 5941Mb: see help(memory.size)

I tried to increase the memory limit using
memory.limit(size=11264)

But R ends up crashing. Here's my session info
> sessionInfo()
R version 2.14.2 (2012-02-29)
Platform: x86_64-pc-mingw32/x64 (64-bit)

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] tools_2.14.2

Thanks in advance.


text:
Q: print datatables footer columns functioning incorrectly I want to print a table - 5 columns - with a footer.
The footer:

        Total:

The problem is: in the print view, the footer appears with 'Total' from columns 0 to 3.
I saw this answer by the author of Datatables, Allan
https://www.datatables.net/forums/discussion/comment/88923/#Comment_88923
and it looks like there's no official solution. Maybe do some workaround.

A: I did some workaround, it affects slightly the appearance of the table, but prints the total in the right place.

        Total:

By changing colspan to 3, writing "Total" in the fourth column, and printing the total value in the fifth.


text:
Q: Finding string in text file, and then printing several characters beyond that in Python Using Python, I need to search a text file for a string "that/"
I then need get the line number (currently doing so by using enumerate), and print off
"that\" + the remaining text until the next space.
Example text: First/LS thing/NN I/PRP want/VBP to/TO ask/VB is/VBZ if/IN you/PRP remember/VBP any/DT books/NNS that/IN you/PRP read/VBP as/IN a/DT child/NN
Example output: that/IN 14
Here is the code I have right now, which functions correctly, but wherever it should print "that/xx" it prints nothing.
with open(filename) as f:
            for num, line in enumerate(f, 1):
                if 'that/' in line:
                    myString = line
                    mySub = myString[myString.find('that/'):myString.find(' ')]
                    print(mySub, str(num))
                    formattedLines.append(mySub + ' ' + str(num) + '\n')

A: I think myString.find(' ') is the problem. That could find a string before 'that/', so you could trying to get myString[50:3].
Instead, try this:
with open(filename) as f:
    for num, line in enumerate(f, 1):
        if 'that/' in line:
            start = myString.find('that/')
            offset = myString[start:].find(' ')
            end = start + offset if offset != -1 else len(myString)
            mySub = myString[start:end]
            print(mySub, str(num))
            formattedLines.append(mySub + ' ' + str(num) + '\n')

A: I think the problem is that the whitespace can happen before the that/. Start your search for the whitespace at the index where that/ was found:
with open(filename) as f:
    for num, line in enumerate(f, 1):
        if 'that/' in line:
            myString = line
            where_is_that = myString.find('that/')
            mySub = myString[where_is_that:myString.find(' ', where_is_that)]
            print(mySub, str(num))
            formattedLines.append(mySub + ' ' + str(num) + '\n')

A: I decided to take a different approach, and use regex:
import re

def analyze(line, word):
    regex = r'\b{0}/[^\W]*'.format(word)
    match = re.search(regex, line)
    return match.group() if match else None

def extract(filename, word):
    output = []
    with open(filename) as f:
        for num, line in enumerate(f, 1):
        result = analyze(line, word)
        if result:
            output.append(result + ' ' + str(num) + '\n')
    return output


text:
Q: Facebook oauth dialog redirect after login problem on mobile touch site We redirect users to below URL on mobile phones for application authorisation:
https://m.facebook.com/dialog/oauth?client_id=XXXXXX&redirect_uri=http://www.server.com/callback.php&scope=offline_access,user_likes,publish_stream,publish_checkins,user_checkins&display=wap
If the user is logged in to Facebook on his/her phone, no problem, Facebook automatically redirects to oauth dialog page.
If user is not logged in, Facebook asks them to login first.
On wap site(A Nokia phone), it redirects to oauth dialog without any problem after login.
But on touch site(An iPhone), it add hastags to URL, redirects user to his/her Facebook homepage.
Even display=wap parameter on URL doesn't help on this issue.
Any ideas on how to solve this problem?
Thank you

A: Actually, here's a cleaner solution. (I hadn't seen the API for getLoginUrl at the time of my previous post. http://developers.facebook.com/docs/reference/php/facebook-getLoginUrl)
require_once("facebook.php");

$config = array(
    "appId" => APP_ID,
    "secret" => APP_SECRET
);

$facebook = new Facebook($config);

$params = array(
    "scope" => "offline_access,user_likes,publish_stream,publish_checkins,user_checkins",
    "redirect_uri" => "http://www.server.com/callback.php",
    "display" => "touch"
);

$url = $facebook->getLoginUrl($params);

header("Location: $url");

A: I experienced the same problem and had troubles isolating it since it worked in Chrome on the desktop but not while using the iPhone's Safari browser.
I did a urlencode around the redirect_url parameter and set display to touch. So to use your link above as an example, I'd try this:
https://m.facebook.com/dialog/oauth?client_id=XXXXXX&redirect_uri=http%3A%2F%2Fwww.server.com%2Fcallback.php&scope=offline_access,user_likes,publish_stream,publish_checkins,user_checkins&display=touch
I sincerely hope that works for you. It seemed to have brought me luck.


text:
Q: Adding quotes to an appveyor.yml echo line I have this line that adds some version info to my build:
install:
  - 'echo "export const VERSION = Git Hash: %APPVEYOR_REPO_COMMIT%" > version.js'

obviously that is no valid JS because the quotes are missing. Could someone help me so I can get this string written to my version.js file:
export const VERSION = 'Git Hash: some_hash'

I did try some variations of escaped and unescaped quotes but build times are somewhat agonizing.

A: You are wasting the use of single quotes by quoting that sequence element. You can not have a plain scalar (because of the mid-sentence colon+space), but it often much better to use literal block style scalars. The following is equivalent to your YAML:
install:
  - |-
    echo "export const VERSION = Git Hash: %APPVEYOR_REPO_COMMIT%" > version.js

And so you can use single quotes for the echo parameter and still have double quotes within those:
install:
  - |-
    echo 'export const VERSION = "Git Hash: %APPVEYOR_REPO_COMMIT%"' > version.js

(the - after | is needed to strip the final newline)
Alternatively, assuming Appveyor uses a relatively standard echo, you might be able to use its -e option:

    -e     enable interpretation of backslash escapes

in which case you don't need to use literal block style scalars to get something less readable:
install:
  - 'echo -e "export const VERSION = \"Git Hash: %APPVEYOR_REPO_COMMIT%"" > version.js'

Please note that, according to the official YAML FAQ, whenever possible, the correct extension for a YAML file, is .yaml. You can tell Appveyor not to default to the .yml extension, using the Custom configuration .yml [sic!] file name. For my YAML parser I have also set this to be a hidden file: .appveyor.yaml


text:
Q: How to get the total number of partitions in Azure Data Factory? I'm trying to set split file names by a pattern but I don't know how to get the total number of partitions.
The name I'm looking for the files is my_file_name_pattern_[n]of[N].txt
The partitions are getting set dynamically by a key column.

How can I get [N]?

A: Well I got an answer from Microsoft:

We are adding a new "cached lookup" feature to AzDF that builds upon the existing Lookup/Sink transformation where for example we can access the output from an aggregation and use that value in another transformation in the dataflow.

Update!
Now we can set values in a dataflow without the need of using sink to load a file in Blob store and using extra activities to read it. Check Cached lookup documentation:
Cache Sink
Cached lookup
In the Sink we can select Cache instead of Dataset...

Then we can use that value in any of the other activities:
like mySinkName#outputs()[myRowNumber].yColumnName

workaround before Cached lookup
While this new feature is released. I got an approach using As data in column opt instead of Pattern to name the files, here the solution:
In the data flow I have two sources:

*

*Source1: get the number of partitions from a calculation. The output will be in a Select transformation with one value:

    | partitions |
    |      3     |

*

*Source2:

*

*connect to a table (Synapse/Hive) you want to split in multiple files

*add a Surrogate Key transformation starting at 1, column name SK

*add an Union transformation and use Custom (cross) join, in condition use true()

*add a Derived column to get the key column to split the files partition_number = mod(SK, partitions) + 1

*add another Derived column to get the column files names = concat($target_folder, '/', $fileName, '_', toString(partition_number), 'of', toString(partitions), '.', $extension)

5.1. in Optimize use partition_number column in the option Key

*add a Sink to ADLS and in the setting tab set As data in column and use file_name column for Column with file name

6.1. in Mapping tab use rule-based mapping to ignore the temp columns created in the flow.
- Input Columns: !in(['SK','partition_number','partitions','file_names'], name)
- Output Columns: $$

Note: At work we have a custom AzDF and some of the activities are locked or disable for us. That's why this workaround instead of using SP and Lookup at the pipeline level. Also I don't like the idea of saving some data in ADLS in any delimited format and then use it with a lookup activity to extract the value and set some parameter... It seems over steps for a simple solution.

A: Updated
You need two dataflow activities and one Lookup activity to achieve this.

*

*This is the preview of dataflow4. It's purpose is to get the Total number(21).

*In the Aggregate1, we define the Group by and Aggregates to group by the partition column

*In the SurrogateKey1 activity, we can generate the Row_No for the rows.

*In the Aggregate2 activity, we can use max(row_count) to get the max value of the Row_No.

*We set the sink to store the Total Num(21) to a csv file.

*Use the Lookup1 activity to lookup the file which dataflow4 generated previously.

*In the dataflow3, we can define a parameter Total and use pipeline expression @activity('Lookup1').output.firstRow.Prop_0 to get the total num.

*In the sink of dataflow3, we can use concat('Loan_payments_data[n]of',$Total) to define the filename after partition.

*Then after we run debug, the result is as follows:


text:
Q: Configuring Logger in Razor Pages application I'm trying to get up to speed on ASP.NET Core Razor Pages so I was trying to step through the article Logging in .NET Core and ASP.NET Core.
A lot of the documentation I've been finding is not panning out for one reason or another, and I didn't get very far through this article either. Near the top, it contains the following code snippet.
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.AddConsole();
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

But that code just won't even compile for me.

I've tried Ctrl+. and everything else I could think of, but WebHostBuilderContext just doesn't have the methods shown in this article.
Can someone tell me what I'm doing wrong?

A: Assuming you are also using .NET Core 3,
the sample works for me out of the box with no issues if i create a new ASP.NET Core MVC app in VS 2019 selecting .NET Core 3,
you might not have created a project in that way, are you sure you have this using at the top? if not, add this at top of program.cs and if does not resolve means you have to first add the reference to this assembly.
using Microsoft.Extensions.Logging;


text:
Q: What does offsetStackFrame do in JVM Specification What does  offsetStackFrame Prolog predicate do in JVM Spec?
Although I'm not a Prolog expert I could get a grasp of all the other predicates in Prolog in this Spec but I can't understand this one.
Here is the definition of this predicate in JVM Spec on page 174:
offsetStackFrame(Environment, Offset, StackFrame) :-
 allInstructions(Environment, Instructions),
 member(stackMap(Offset, StackFrame), Instructions).

On page 178 instruction is defined as:
instruction(Offset, AnInstruction)

And here is the definition of stackMap on page 180:
stackMap(Offset, TypeState)

Also TypeState is defined as below:
frame(Locals, OperandStack, Flags)

I can't understand what does member(stackMap(Offset, StackFrame), Instructions) do in the definition of offsetStackFrame. I consider Instructions as [instruction(offset, AnInstruction)] and stackMap(Offset, TypeState) as [(Offset, frame(Locals, OperandStack, Flags))]. So what is the purpose of this predicate?

A: I'll come back and improve this answer later. If I don't please comment to send me a notification as I don't have much time right now. I have run the prolog in the spec so I should be able to provide a IRL example.
Basically to aid the verification process classfiles contain the type state of the operand stack/locals at certain key bytecode offsets(typically after branches where control flow merges). These type states are called stackmap frames. The prolog code has a predicate which combines the known stackmap frames and instructions(called mergeStackMapFrames or something). Then it iterates over the merged result to verify that all the state transitions are valid/match the instruction in question.
How the predicate above fits into that is that it asserts that a particular stackmap frame is present in the merged instruction/stackmap frames.
Due to the nature of prolog you can use this assertion to construct the merged list in the first place.


text:
Q: Smooth scrolling down after component with pdf is displayed in reactjs I would need smooth scrolling down to component with generated pdf. But it looks like that first is scrolled to view and then
component is mounted. How can I set waiting to component is displayed and then scroll to view this component?
When I click to button, the pdf will start to generate. After generating this pdf, I would like scroll to view this PDFViewer.
My solution does not work. 'await' has no effect on the type of this expression. OR Object is possibly 'null'.
I use reactjs 17.0.2, react-pdf/renderer 3.0.1, typescript.
Code:
import { PDFViewer } from "@react-pdf/renderer";

export const Print: NextPage = () => {
  const [pdfGenerationEnabled, setPdfGenerationEnabled] = useState<boolean>(false);

  const generatePDFAndView = async () => {
    setPdfGenerationEnabled(true);
    await document.getElementById("generated-pdf-view")?.scrollIntoView({ behavior: "smooth" });
  }

  return (
    <DownloadAndPrint>

Generating PDF

        Some long text
        Some long text
        Some long text
        .
        .
        .

      <Button
        className="btn-generate-pdf"
        onClick={() => { generatePDFAndView() }}
      >
        Vygenerovať pdf súbory
      </Button>
      {pdfGenerationEnabled
        ?
          <>

              <PDFViewer showToolbar={true} style={{ height: "45vh", width: "100%" }}>
                <ComponentPrint
                  data={data}
                />
              </PDFViewer>

          </>
        : ""
      }
    </DownloadAndPrint>
  );
};

EDITED: After added delay, it's works. After 3 seconds smooth scrolled to the pdf viewer. But I don't know how many seconds it should waiting? Sometimes generated pdf has 3 pages, sometimes 300 pages. According to the data.
const delay = (n) => new Promise(r => setTimeout(r, n*1000));

const generatePDFAndView = async () => {
  setPdfGenerationEnabled(true);
  await delay(3.0);  // waiting 3s
  document.getElementById("generated-pdf-view")?.scrollIntoView({ behavior: "smooth" });
}

A: My solution with delay and calculation time to wait according to the data. Maybe somebody it helps.
import { PDFViewer } from "@react-pdf/renderer";

export const Print: NextPage = () => {
  const [pdfGenerationEnabled, setPdfGenerationEnabled] = useState<boolean>(false);
  const itemsPerPage = 5;

  const calculateTimeToDisplayPdfViewer = () => {
    const numberOfItems = data?.items?.length;
    if (numberOfItems > 0 && itemsPerPage > 0) {
      let time = (numberOfItems / itemsPerPage) / 5;  // 1 page = 1/5s = 0.20s
      time = parseFloat(time.toFixed(2));
      console.log("Waiting " + time + "s.");
      return time;
    } else {
      return 2.0;
    }
  }

  const delay = (n) => new Promise( r => setTimeout(r, n*1000));  // waiting in seconds

  const generatePDFAndView = async () => {
    setPdfGenerationEnabled(true);
    await delay(calculateTimeToDisplayPdfViewer());
    document.getElementById("generated-pdf-view")?.scrollIntoView({ behavior: "smooth" });
  }

  return (
    <DownloadAndPrint>

Generating PDF

        Some long text
        Some long text
        Some long text
        .
        .
        .

      <Button
        className="btn-generate-pdf"
        onClick={() => { generatePDFAndView() }}
      >
        Vygenerovať pdf súbory
      </Button>
      {pdfGenerationEnabled
        ?
          <>

              <PDFViewer showToolbar={true} style={{ height: "45vh", width: "100%" }}>
                <ComponentPrint
                  data={data}
                />
              </PDFViewer>

          </>
        : ""
      }
    </DownloadAndPrint>
  );
};


text:
Q: Why does a white border in a card view appears when load an image? I created a component for my app which I use like a card. It has some textviews and an end image, but the image always appears with some withe border liek in the image bellow:

I tried everything to fix it but I can figure out how and it's important because the component it's used in almost all the app and in all of them the all the images appear with some withe border.
Component code:
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="106dp"
    app:cardCornerRadius="8dp">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:orientation="vertical"
            android:paddingTop="16dp"
            android:paddingBottom="16dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/image_card_end"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center_vertical"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/txt_card_header"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="14dp"
                    app:textType="semibold"
                   />
            </LinearLayout>

            <LinearLayout
                android:id="@+id/second_description_container"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="4dp"
                android:gravity="center_vertical"
                android:orientation="horizontal"
                android:visibility="gone"
                tools:visibility="visible">

                <TextView
                    android:id="@+id/txt_card_second_description"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="bottom"
                    android:textSize="14dp"
                    app:textType="regular"
                   />
            </LinearLayout>
        </LinearLayout>

        <androidx.appcompat.widget.AppCompatImageView
            android:id="@+id/image_card_end"
            android:layout_width="98dp"
            android:layout_height="106dp"
            android:scaleType="fitXY"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:src="@drawable/card_appointment_image" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>

And this is how I use it:
<com.univer.components.card.BasicCard
                android:id="@+id/home_card_auto_evaluation_card"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                app:cardCornerRadius="8dp"
                app:cardDescription="@string/home_card_selfdiagnosis_description"
                app:cardEndImage="@string/image_home_card_symptomchecker"
                app:cardHeader="@string/home_card_selfdiagnosis_header" />

A: Set a background which is easily visible(eg: red) to your cardview and run the app.
If the red section gets visible it means the inner constraint layout isn't wrapping the cardview completely . If that is the case I would suggest experimenting with scale type as so
<androidx.appcompat.widget.AppCompatImageView
            android:id="@+id/image_card_end"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scaleType="center-crop"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:src="@drawable/card_appointment_image" />


text:
Q: Selectively mocking a function on Jest I might be missing something major here, but I can't seem to find a suitable answer from the docs. I'm trying to selectively replace a utility function with a mock implementation in Jest. My reasoning for this is that sometimes I want to force it to fail during testing to see how it impacts the rest of my code, and also to see if my catches are working properly. For example
// actual.js
export const foo = () => {return 'foo'}

//mock.js
export const foo = (returnFoo) => {return returnFoo ? 'foo' : 'bar'}

I can't seem to use jest.mock(actual.js) because the 2 functions have different signatures. I can use jest.setMock() with jest.requireActual(), but it'll mock foo for the entire suite. My current solution is doing
const mock = jest.spyOn(actual, 'foo');
mock.mockImplementation(() => mock.foo(returnFoo));

which can be simplified to

jest.spyOn(actual, 'foo').mockImplementation(() => mock.foo(returnFoo));

which does works. I'm really just wondering if Jest has a better way of doing this than adding a spy on every individual function I want to purposely and manually mock for individual tests. I've also tried doing const actual.foo = jest.fn(), but that doesn't work since foo in actual is a read-only export, and also Object.defineProperty(vendorsRepo, 'updateToken', { value: mockedVendorsRepo.updateToken() }); but that seems like a terrible workaround.


text:
Q: Slow performance Azure 'Web App' + Azure SQL DB I've moved an existing asp.net web-api over from an Azure VM (with IIS and MSSQL installed locally) to an Azure web app and Azure SQL database (both west-europe). I'm noticing a dramatic increase in processing duration between the two for the same workload. Tasks that take 10-15ms on the VM, take at least 150ms in the hosted service environment. Both internal processing, not including network latency to/from the vm or web app. Both with empty databases and the same code-base. Same database schema with the same indexing.
The VM was a simple 2-core/7GB SSD machine. But even when I set my web app to a premium 4-core/7GB and my database to a premium 250DTU, the performance does not increase at all. In fact, its the same on a basic 2-core web app and 10DTU database. So the bottleneck has to be somewhere else.
How would I go about finding out what causes the slow processing? The web app and database show no performance alerts and don't advise scaling up either.

A: Run the following query per session/workload to know what is the type of wait occurring during those workloads:
--your query here
go

select *
from sys.dm_exec_session_wait_stats
where session_id = @@spid
order by wait_time_ms desc

The last SELECT statement will provide you all waits for current session.
You can also enable Query Store.
http://www.sqlcoffee.com/Azure_0010.htm
And run the following query to know what makes queries wait during execution
select  wait_category_desc, sum(total_query_wait_time_ms) as [sum ms], count(*) as [interval cnt],  avg(avg_query_wait_time_ms) as [avg ms], sum(total_query_wait_time_ms / avg_query_wait_time_ms) as [wait cnt]
from sys.query_store_wait_stats
group by wait_category_desc
order by [sum ms] desc

The following article will tell you the meaning of each wait category.
https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-query-store-wait-stats-transact-sql
Hope this helps.

A: I faced the same issue today: Azure Web App with Azure DB resulted in slow performance on anything interacting with the DB.
However when I ran the app locally on my pc the experience was very fast. I therefore checked my app service and location. I was using S1 service located in the US with the database in Australia.
•I therefore upgraded to Premium S2 and
•Located my Web App and DB to be in the same region.
These two changes resulted in a massive performance increase.

Im not sure why having my previous answer be a duplicate is a problem if Im the original poster of the same answer on another question and and if the answer applies and is correct as is. It doesn't make sense to change it just because. Please comment first and allow me to edit before completely deleting...


text:
Q: Access inside folder with.htacces My folder structure is like this: www.testlink.com/angular/dist/my-app.
I have to access this folder when  entering this link : www.testlink.com/angular.
How can I do with htaccess?

A: Its better if you use subdomain
htaccess configuration
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]

Add base url to index.html
<base href="http://subdomain.testlink.com/">

Configure apache
<VirtualHost *:80>
    ServerName www.subdomain.example.com
    ServerAdmin webmaster@localhost
    DocumentRoot /path/of/your/directory

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

A: This probably is what you are looking for, a combination of an external redirection with an internal rewrite:
RewriteEngine on
RewriteRule ^/?angular/dist/my-app(/.*) /angular$1 [QSA,R=301,END]
RewriteRule ^/?angular(/.*) /angular/dist/my-app$1 [QSA,END]

Obviously the rewriting module needs to be enabled inside the http server for that and the interpretation of distributed configuration files (".htaccess") has to be enabled for that location inside the http server.


text:
Q: Why DVD writers only have 24x write speed? I remember CD writers get's twice the speed, now it seems DVD writers can only do up to 24x write speed if internal, and just 8x if it's a portable writer. It's been years since and it seems stuck on this speed. Is this really the fastest it can go?

A: CD and DVD read/write speeds are not equivalent.  For example 1x CD ~= 153KB/s while 1xDVD ~= 1.39MB/s.  24x DVD means moving data at 33.36MB/s.  Burning at the highest speed is typically achievable only at the outer edges of the medium and there are many other factors that can affect actual transfer speeds including the speed of the source medium (hard disk), quality of the dvd drive and quality of the medium itself.  Better write performance is already available using 8x or better blu-ray writers.

A: Because you don't want the disk blowing up on you.  The outer edge of the disk is moving at a substantial fraction of the speed of sound.  You can't compare CD and DVD write speeds, the data densities are different.


text:
Q: Object leaked : allocated object is not referenced later in this execution path and has a retain count of +1 After analyzing application found this message Object leaked : allocated object is not referenced later in this execution path and has a retain count of +1 on these lines
 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"theme"
                                                     ofType:@"mp3"];

 NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];

For this statement it says
   self.audioPlayer.currentTime = 0;

object allocated and stored into fileURL is not referenced later in this exception path and has a retain count of +1
Any ideas how to fix it.
Thanks

A: It's likely it's fileURL that has leaked. You're alloc-ing it but I bet you don't release it after you're done with it.

A: It means there's some path through your code (and it should be willing to show it to you) in which you fail to release fileURL — probably you do some sort of sanity check and exit early under a certain circumstance but fail to clean up?
The obvious solution would be to create fileURL as an autoreleased object and either retain it when you know you definitely want to keep it or simply do that instead of an explicit release further down the method.


text:
Q: Arithmetic overflow error when summing an INT, how do I cast it as a BIGINT? When I try to get the sum of a column from a table I get the error Arithmetic overflow error converting expression to data type int because the resulting number is to big for an INT. So I tried to CAST to a BIGINT using the following
SELECT CAST(SUM(columnname) AS BIGINT) FROM tablename

This gives me the same error. Any ideas what i'm doing wrong?

A: Try converting it before summing. eg.
SELECT SUM(CONVERT(bigint, columnname)) FROM tablename

or
SELECT SUM(CAST(columnname AS BIGINT)) FROM tablename


text:
Q: jquery datatables with ajax error I'm getting "NetworkError: 405 Method Not Allowed - ..." when trying to load Datatable using ajax, I see 'allow': 'put' in the header, wonder if it has anything to do with it?
HTML

   Equipment Number
   Name
   Location
   Description

jQuery
$(document).ready(function() {

$("#my-equipments").dataTable({
    "ajax": "/myapp/equipments/datatable"
});
}

Spring Controller
@RequestMapping(value = "/equipments/datatable", method = RequestMethod.GET)
public @ResponseBody
EquipmentDatatable getEquipmentsDatatable(Model model,
        HttpServletResponse resp) throws Exception {
...
}

Firebug


text:
Q: android bitmap - best practice Developing a graphical app that should work for any screen size requires some thinking
Usually I create high resolution graphics and the scale to fit the screen.
I've seen a recommendation to avoid using "real pixels"
I tried working with density and dp but it seems more complex then using the solution I use
And couldn't find a better way to scale my graphics other then to use the device screen (real pixels)
I created this class to scale my images (based on real pixels)
This solves most of my problems (still some devices have different aspect ration)
and seems to work fine.
public class BitmapHelper {
    // Scale and keep aspect ratio
    static public Bitmap scaleToFitWidth(Bitmap b, int width) {
        float factor = width / (float) b.getWidth();
        return Bitmap.createScaledBitmap(b, width, (int) (b.getHeight() * factor), false);
    }

    // Scale and keep aspect ratio
    static public Bitmap scaleToFitHeight(Bitmap b, int height) {
        float factor = height / (float) b.getHeight();
        return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factor), height, false);
    }

    // Scale and keep aspect ratio
    static public Bitmap scaleToFill(Bitmap b, int width, int height) {
        float factorH = height / (float) b.getWidth();
        float factorW = width / (float) b.getWidth();
        float factorToUse = (factorH > factorW) ? factorW : factorH;
        return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factorToUse), (int) (b.getHeight() * factorToUse), false);
    }

    // Scale and dont keep aspect ratio
    static public Bitmap strechToFill(Bitmap b, int width, int height) {
        float factorH = height / (float) b.getHeight();
        float factorW = width / (float) b.getWidth();
        return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factorW), (int) (b.getHeight() * factorH), false);
    }
}

and my questions are:

*

*Why avoiding "real pixels" is recommended?

*What is the best practice of scaling Bitmaps to screen (a good article of tutorial
are more then welcome)

*What are the cons of using the method I use or what should I be aware of when using this method

Thanks for your advise
[Edit]
I forgot to mention that I usually use SurfaceView for my apps (if it make any difference)

A: *

*Never make your app pixel perfect. It will not work on other resolutions. The way you are handling your image sizes is not needed as Android does this for you when you make good scalable layouts. You should make an image for all dpi types and seperate them in your resources by using resources qualifiers (drawable-ldp folder, drawable-mdp folder, ..etc)

*Don't scale bitmaps yourself, as I said, Android will do this for you. You can influence the way Android scales your bitmaps, see http://developer.android.com/reference/android/widget/ImageView.html#attr_android:scaleType

*Android will calculate the right sizes for you. This way you don't have to do all the maths yourself to try and get everything on the screen. Building a good app that runs on all kind of devices requires effort in making multiple sets of drawables and probably multiple sets of layouts (landscape / portrait, small / large screens) etc.


text:
Q: Power BI Report: How to pass Dynamic Values to Parameters in Report Made with Stored Procedure let
    Source = Sql.Database(MyServer, MyDatabase, [Query="EXEC  [dbo].[spEmployeesRead] '" & ActionCode & "', '" & UserID & "', NULL, NULL, NULL, NULL, '" & Alphabet & "'"])
in
    Source

Above is my Stored Procedure in Query Editor its running fine and getting data as i am passing all parameters dynamically including Server Name and Databasename. My Question is I have Saved and Publish the Report to Power BI Service and then Open the Report and from File Menu get Embed Code and pass parameters to this Report URL so i can access this from other Applications and that Application will pass the parameter values dynamically but seems like things are not working correctly. Can anybody check where i am wrong.
https://app.powerbi.com/reportEmbed?reportId=341f891b-93f8-490a-9a91-62f12f783e2c&groupId=4791121d-01f2-49ad-99fc-9fa3bab7fc3f&autoAuth=true&filter=MyServer eq 'MSSQLSERVER2017' and MyDatabase eq 'TestDB' and EmployeesList/ActionCode eq '1' and EmployeesList/UserID eq '1' and EmployeesList/Alphabet eq 'All'

Attached Image
Attached Image

A: There is no direct url query available for this condition.
You need to add Parameters and then bind your parameters with custom functions after that you can create url like:
ReportURL?filter=tableName/columnName eq 'value'.
You can check bellow video url for creating parameters and custom function:
https://www.youtube.com/watch?v=iiNDq2VrZPY


text:
Q: Find whether a random number is Prime or not and Store in a character value I am writing a game, where it should do below
Randomly generate a number. Check whether it is a Prime or not. Store "y" if its a Prime else "n"
I will ask the user whether it is prime or not. If he answers correctly I will proceed. Otherwise I will say you lost.
Code sample I tried is as follows:
cout<<"\n \n a no. of prime no.s will be displaed to you ,you will have to decide if it is prime or not within the given time\n \n ";
char ch1,ch2;
for(int i=1;i<=20;i++)
{
    int a= rand( ) % 20;
    cout<< "The number is:";
    cout<<a;
    for(int l=2;l<=a-1;l++)
    {
        if(a%l==0)
            ch2='n';
        else
            ch2='y';
    }

    cout<<ch2;
    cout<<"\n\n Enter ""y"" If the number is Prime Else Please enter ""n""\n";
    cin>>ch1;
    if(ch1 == ' ')
    {
        cout<<"\n \n u lost";
        break;
    }
    else if(ch1==ch2)
        continue;
    else if(ch1!=ch2)
    {
        cout<<"\n \n u lost";
        break;
    }
}

My code is not determining whether it is Yes or No. It is everytime storing "Y" only

A: You made a couple of mistakes
#include <math.h>
#include <iostream>
using namespace std;
int main() {
    char ch1, ch2;
    for (int i=i; i<=20; i++) {
        int a = rand () % 20;
        cout << "The number is: " << a << endl;
        ch2 = 'y';
        //You only need to loop until its square root; after that is repetition
        for (int l=2; l<=sqrt(a); l++) {
            //You need to break if a divisor is found, else it is always going to say it's prime
            if (a%l==0){
                ch2 = 'n';
                break;
            }
        }

        cout << ch2 << endl;
        cout << "Enter 'y' if number is prime else 'n'" << endl;
        cin >> ch1;
        if (ch1 != ch2) {
            cout << "You lost" << endl;
            break;
        }
    }
}

I also did some cleanup of your code

A: May be this one helps
#include <iostream>
#include <ctype.h>
#include <string.h>
using namespace std;

int main()
{
  int n, i;
  char res='y';
  char ans;
  n =rand( ) % 20;
  cout << "The Number is:" << n << endl;

  for(i = 2; i <= n / 2; ++i)
  {
      if(n % i == 0)
      {
          res='n';
          break;
      }
  }
  cout << "Enter 'y' if it is a prime number and 'n' if it is a non-prime number"<< endl;
  cin >> ans;
  ans = tolower(ans);

  if (ans==res)
  {cout << "You win";}
  else
  {cout << "You Lost";}

  return 0;
}


text:
Q: react-native How can I put two texts in a row view with left alignment? I'm trying to implement a View with two texts with different styles on it. I have this:
<View style={{flexDirection:'row'}}>
  <Text style={styles.style1}>
    {text1}
  </Text>

  <Text style={styles.style2}>
    {text2}
   </Text>
</View>

Which shows something like:
This is my actual result
But I want to achive this:
My desired result

A: If you just wrap them with a Text component instead of View, it should work:
<Text>
  <Text style={styles.style1}>
    {text1}
  </Text>

  <Text style={styles.style2}>
    {text2}
   </Text>
</Text>

A: <Text>
  <Text style={{fontWeight: "bold"}}>Description: </Text>
  This is an example of the text flow I want to achieve.
</Text>

Live demo


text:
Q: Document does not have the fields uploaded (Firestore) I've been trying to update specific fields in a firebase document but for some reason, it does not get uploaded even though the cloud function gets triggered and performs an upload on the document, the value of the fields never gets uploaded.
The trigger function functions whenever any field is updated in "client details", then it gets the new field values.
A reference is then created on the uploaded document in order to access an array to be iterated.
The document and document id are then passed to a function that iterates through each key: value pair in the updated document and then updates the fields with the same key in a different document.
Everything works without any error but the field values are never updated.

exports.rebuildFormTriggerClientDetails = functions.firestore.
document('clientDetails/{details}').onUpdate((change)  => {

  const afterDoc = change.after.data();
  const documentId = change.after.id

  if (afterDoc)

  {

    let docUsers = db.collection("clientDetails").doc(documentId);

    let caseArray: Array<string>;
    caseArray = afterDoc.CaseRefArray;

    for (var valCase of caseArray) {
      console.log(valCase);
      console.log(documentId);

        createObjectDocument(docUsers,valCase);

    }

  }

  return Promise
});

function createObjectDocument(document: any, caseNumber: String)

{
  document.get().then(function(doc: any) {
    if (doc.exists) {
        console.log("Document data:", doc.data());
        for (let [key, value] of Object.entries(doc.data())) {
          console.log(`${key}: ${value}`);
         if (key != "CaseRefArray")
         {

          db.collection("casesToExport").doc(caseNumber).update({key : value });
         }
        }
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch(function(error: any) {
    console.log("Error getting document:", error);
});

  [1]: https://i.stack.imgur.com/duhkq.png

A: Try to resolve your cloud function instead of returning a promise.
exports.rebuildFormTriggerClientDetails = functions.firestore.
document('clientDetails/{details}').onUpdate((change)  => {

  const afterDoc = change.after.data();
  const documentId = change.after.id

  if (afterDoc)

  {

    let docUsers = db.collection("clientDetails").doc(documentId);

    let caseArray: Array<string>;
    caseArray = afterDoc.CaseRefArray;

    for (var valCase of caseArray) {
      console.log(valCase);
      console.log(documentId);

        createObjectDocument(docUsers,valCase);
    }
  }
}).then(() => {
   console.log("Successfully updated document!");
}).catch((error) => {
   console.error("Error updating document: ", error);
});


text:
Q: How to redirect php pages to nuxt.js standard? I have a website made in php (which was first made in asp) so i redirected .asp webpages to .php in .htaccess file.
Now i am rebuilding the website using vue + nuxt.js and i am not finding how to do this again.
This time i need the .php or .asp pages to be without extension like:
/something/other/2.php

to
/something/other/2

404 redirects is not an option.. tried that my SEO dropped 90%.
I am pretty new to Vue and Nuxt so i'm kind lost here. How can this be done?

A: for deploy purpose nuxt.js provides two methods:

*

*universal

*single page

if your server or host can run node and you can start node server upload all your files there and then run the code (it's probably runs on port 3000 so in your server config you need to redirect port 80 to 3000)
if you are on a static host go to your nuxt.config.js file and make shore that mode is spa and then run npm run generate and it makes a dist folder for you then copy all of data in dist folder to your host and use it like regular html and js files
Hope it helps you