text:
Q: Unable to resolve host: URL No address associated with hostname I have an web service call to bring down a JSON object and it only works if I have the IP address and not the host name. I have been fine using IP addresses but now I need to have the host name.
Here is my code
    StringBuilder stringBuilder = new StringBuilder();
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
    HttpConnectionParams.setSoTimeout(httpParams, 7000);
    DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
    HttpPost httpost = new HttpPost(URL);
    try {
        HashMap<String,String>  params = new HashMap<String,String>();
        // Login info
        params.put("username", edtUserName.getText().toString());
        params.put("password", edtPass.getText().toString());
        params.put("deviceOS", "Android");
        params.put("deviceOSVersion", android.os.Build.VERSION.RELEASE);
        params.put("language", "0");
        //JSON object holding the login info
        JSONObject holder = new JSONObject(params);

        StringEntity se = new StringEntity(holder.toString());

        httpost.setEntity(se);

        httpost.setHeader("Content-Type", "application/json");
        //Executing the call
        HttpResponse response = httpClient.execute(httpost);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            inputStream.close();
        } else {
            returnCode = -1;
            Log.d("JSON", "Failed to download file");
        }
    } catch (Exception e) {
        returnCode = -1;
        Log.d("readJSONFeed", e.getLocalizedMessage());
    }

    return stringBuilder.toString();

I dont know why that doesn't work. I am testing on a phone with Wifi connection, My manifest has the <uses-permission android:name="android.permission.INTERNET" /> and <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
This web service does work. Just not on Android
If anyone has an idea that would be great, Thanks.

A: I fixed it by removing these lines
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
HttpConnectionParams.setSoTimeout(httpParams, 7000);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);

And replacing it with this code
HttpClient httpClient = MainActivity.createHttpClient();

public static HttpClient createHttpClient(){
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 15000);
        HttpConnectionParams.setSoTimeout(params, 5000);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}


text:
Q: Will_paginate, render next page I'am using will_paginate gem to paginate my posts. And I want to do infinite scroll. I watch few video and read couple of posts, but thats not really what I need (because of my app structure). You see, home.html.erb (to be short), looks like:

  <%= render 'posts/posts_for_all', posts_variable: @posts %>

And my _posts_for_all.html.erb (to be short), look like (to be short):
<% posts_variable.each do |post| %>
  <%= link_to post.theme, post %>
<% end %>
<% will_paginate posts_variable, :next_label => "More" %> # => i need it every
time the page is loaded

I've already wrote JS for all, except one line:
$('.news-lent').append('<%= j render *some_thing* %>')

Well, I don't know what pass to render. I cannot pass my @posts(it will return error(missing partial posts/_post)), and @posts.next_page(it will return 2), and #{posts_path(@post)}?page=#{@post.current_page+1}(but this don't work too) and other problems.
Can you help me, I need something to put inside j render so it rendered next page?
UPDATE
I reworked everything with RailCast videos, and same way like @Szilard Magyar tell me to do, but now it keep rendering the same (first page) all time and it not rendering second page at all, what can create such problem?
UPDATE
Follow railcast video (reworked my app structure), and a new problem appears:
My home.js.coffee:
jQuery ->
  url = $('.pagination .next_page a').attr('href')
  $(window).scroll ->
    if url && $(window).scrollTop() > $(document).height() - $(window).height() - 50
      $('.pagination').text("Fetching...")
      $.getScript(url)

My index.js.erb:
$('.one').append('<%= j render @posts, posts_variable: @posts %>');
  <% if @posts.next_page %>
    $('.pagination').replaceWith('<%= j will_paginate(@posts) %>');
  <% else %>
    $('.pagination').remove();
  <% end %>
<% sleep 3 %>

My index.html.erb:

    <%= render @posts, posts_variable: @posts %>

    <%= will_paginate @posts, :next_label => " Еще" %>

But now, when I'am on first page and scroll down it rendering second page, but 2x times, and when I again scrolling to bottom and it rendering second page (it not rendering third page). I don't know how to fix it, can you land me again?

A: index.html.erb

  <%= render @products %>

  <%= will_paginate @products %>

No more products.

_product.html.erb

<%= product.name %>

<%= product.oneliner %>

products.js
if ($('#infinite-product-scrolling').size() > 0) {
  $(window).on('scroll', function() {
    $('#infinite-product-scrolling').hide();
    var more_products_url;
    more_products_url = $('#infinite-product-scrolling .pagination .next_page a').attr('href');
    if (more_products_url && $(window).scrollTop() > $(document).height() - $(window).height() - 60) {
      $('.pagination').html("");
      $('#infinite-product-scrolling').show();
      $.getScript(more_products_url);
    }
  });
};

index.js.erb
$('.new-product-insert').append('<%= j render @products %>');
<% if @products.next_page %>
  $('.pagination').replaceWith('<%= j will_paginate @products %>');
<% else %>
  $(window).off('scroll');
  $('.pagination').remove();
  $('.no-more').delay(1000).fadeIn(1500);
<% end %>

A: Solve it, the problem appears because of my mistake. In here:
jQuery ->
  url = $('.pagination .next_page a').attr('href')
  $(window).scroll ->

url variable was assigned only one time, before scrolling and that was my mistake. So if url was save, so it always rendered second page and never third. We have to move our url lower, under .scroll event and it will always check, what page have been rendered. Like this:
jQuery ->
  $(window).scroll ->
  url = $('.pagination .next_page a').attr('href')

By the way, I will recommend to all (if they are using jQuery from RailsCast tutorial) to add some script to prevent multiple page load when user scroll
jQuery ->
  $(window).scroll ->
    url = $('.pagination .next_page a').attr('href')
    return if(window.pagination_loading) # -> add this
    if url && $(window).scrollTop() > $(document).height() - $(window).height() - 50
      window.pagination_loading = true # -> and this
      $('.pagination').text('Fetching products...')
      $.getScript(url).always ->
        window.pagination_loading = false # -> and this

And for prevent bugs etc. to url variable you need to add a, so it look like url = $('.pagination .next_page a').attr('href') and not like in RailsCast tutorial: url = $('.pagination .next_page').attr('href')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problem with executing an SQL insert statement in access using VBA I'm trying this SQL statement but I keep getting an error
Run-time error '3061':
Too few parameters. Expected 4.

The statement I am trying to execute is:
sSQL = "INSERT INTO MasterTable (AdmissionNumber, Surname, Forename, TutorGroup) VALUES (intAdmissionNo, strSurName, strForeName, strTutorGroup)"
CurrentDb.Execute sSQL, dbFailOnError

The 4 values intAdmissionNo, strSurName, strForeName and strTutorGroup all have values and the fields all exist.
Any help is much appreciated, thanks! :)

A: I haven't done that from VBA, but unless I'm mistaken you're not sending in the variables as you think you are. Try this line instead of your current one:
sSQL = "INSERT INTO MasterTable (AdmissionNumber, Surname, Forename, TutorGroup) VALUES (" & intAdmissionNo & ", " & strSurName & ", " & strForeName & ", " & strTutorGroup & ")"


text:
Q: How to generate PKCE code verifier and challenge I'm writing a small C library for my projects to do oauth authentication and I am not sure how to generate the code verifier and challenge and what libraries I should use. I would like to use as few dependencies as possible.
I've seen it done in this google example but I'm not sure how to implement it in C.
https://github.com/googlesamples/oauth-apps-for-windows/blob/master/OAuthUniversalApp/OAuthUniversalApp/MainPage.xaml.cs
...
string state = randomDataBase64url(32);
string code_verifier = randomDataBase64url(32);
string code_challenge = base64urlencodeNoPadding(sha256(code_verifier));
const string code_challenge_method = "S256";
...

A: I figured it out in the end. I coded my own base64 encoding, this wikipedia article was very useful https://en.wikipedia.org/wiki/Base64. Then I also coded a random (url safe) string generation function. And last but not least grabbed this small standalone sha256 library https://github.com/amosnier/sha-2
In the end my code looks something like this.
char* code_verifier = base64_url_random(32);
uint8_t hash[32];
char hash_string[65];
calc_sha_256(hash, code_verifier, strlen(code_verifier));
hash_to_string(hash_string, hash);
char* code_challenge = base64_url_encode(hash_string);


text:
Q: Trigonometric differential equation Is it possible to solve the following ordinary differential equation:
$\theta'(t)=x(t)\sin(\theta(t))-y(t)\cos(\theta(t)),\ \forall t\in I$, $I-$ interval from $\mathbb{R}$,
where $x,y:I\to\mathbb{R}$ are two given continuous functions?

A: A simplificationcan be obtained in the following way: Write
$$\bigl(x(t),y(t)\bigr)= r(t)\bigl(\cos\alpha(t),\sin\alpha(t)\bigr)\ ,$$
where the functions $t\mapsto r(t)>0$ and $t\mapsto\alpha(t)$ can be considered as given. The ODE then becomes
$$\theta'(t)=r(t)\>\sin\bigl(\theta(t)-\alpha(t)\bigr)\ .\tag{1}$$
Now introduce a new independent variable $\tau$ by means of
$$\tau:=\psi(t):=\int_0^t r(s)\>ds\ ,$$
and denote differentiation with respect to $\tau$ by a dot. The ODE $(1)$ then becomes
$$\dot\theta(\tau)=\sin\bigl(\theta(\tau)-\tilde\alpha(\tau)\bigr)\ ,$$
where $\tilde\alpha(\tau):=\alpha\bigl(\psi^{-1}(\tau)\bigr)$ can again be considered as given.

A: This is not a full answer to the question but it seems to be too long for a comment.
The ordinary differential equation you posted seems incredibly complex and I really wonder if there is any way to approach a solution.
I tried using $x(t)=a$ and $y(t)=b$ just to see the kind of result we could get. Even for a CAS, the problem does not look very simple and the answer is $$\theta(t)=2 \tan ^{-1}\left(\frac{\sqrt{a^2+b^2} \tanh \left(\frac{1}{2} \sqrt{a^2+b^2}
   \left(c-t\right)\right)-a}{b}\right)$$
I later tried  using $x(t)=a+bt$ and $y(t)=c+dt$ and I (the CAS !) did not arrive anywhere. Any other, even simple, functions I tried led to the same lack of success.


text:
Q: SQL Server 2008 error - cannot allocate space for object I'm using SQL Server 2008 Express.
The properties of my database say the DB size is 4GB.
My DB has 2 main tables, each with about 2GB.
I'm getting the following Error when I try to insert a new record:

[Microsoft][ODBC SQL Server Driver][SQL Server]
  Could not allocate space for object 'dbo.Futures_Tick'.'IX_Futures_Tick' in database 'Prices_Live' because the 'PRIMARY' filegroup is full. Create disk space by deleting unneeded files, dropping objects in the filegroup, adding additional files to the filegroup, or setting autogrowth on for existing files in the filegroup.

I'm not sure what to do. I don't see how to free up space in the primary filegroup as the error message is telling me (I'm not even sure what the primary filegroup is).
I'm a little new to DB admin things... I just know the basic SQL commands (Insert, Update, Delete).
help??

A: Pretty sure SQL Server 2008 Express is limited to max 4 GB databases. You need to upgrade to 2008R2 or later to overcome it. As 2012 is the most recent that should be the best option unless you have legacy code.
Find it here: 2012 Express Edition. And here is the supported upgrade paths.
As @marc_s pointed out in a comment, this version is still limited to 10 GB, so you might want to look into the the paid version if you demand more.


text:
Q: Calculate the sum of the acquisition price of works of art for each year Need some help with this question on SQL query based on the following table (TRANSACTION) attributes. Appreciate the help.
TRANSACTIONID
DATEACQUIRED
ACQUISITIONPRICE
DATESOLD
ASKINGPRICE
SALESPRICE
CUSTOMERID
WORKID
Calculate the sum of the acquisition price of works of art for each year (for example, if there were two works of art purchased for $1500 and $1000 in 2007, and one work of art purchased for $500 in 2008, then the sums would be $2500 and $500, for 2007 and 2008 respectively). The result table should show year and sum of acquisition price.

A: In MySQL that would be:
SELECT YEAR(DATEACQUIRED), SUM(ACQUISITIONPRICE) FROM table GROUP BY YEAR(DATEACQUIRED)

or
SELECT EXTRACT(YEAR FROM DATEACQUIRED), SUM(ACQUISITIONPRICE) FROM table GROUP BY EXTRACT(YEAR FROM DATEACQUIRED)

assuming DATEACQUIRED is actually a full date.


text:
Q: How to decrypt an owin cookie in Node.js I'm working in a node.js  application where I'need to decrypt cookies . for cookie enceyption use owin .
plz tell me how to decrypt owin cookie in node.js .it save in browser .
thx in advance .

A: I'm not even sure if this is something you can/should do(from a security perspective) since you would need to know the machine encryption configuration. I'd suggest considering if this is something really necessary to do.
To do this you need to understand how to Decrypt the Cookie on ASP.NET side, and then "port" this to node. You can check this link:
https://lbadri.wordpress.com/2014/11/23/reading-katana-cookie-authentication-middlewares-cookie-from-formsauthenticationmodule/
The critical part will the decryption part. You can decrypt using the MachineProtect.UnProtect method to do this by loading the underlying "encryption" configuration for the machine. Maybe you could try setting a specific machineKey configuration with keys and algorithms and then try unencrypting with those setting from Node.js. However you will need to know how to include the correct "purposes" in the decryption process.
To understand better how Unprotect works check this out:
https://github.com/Microsoft/referencesource/blob/master/System.Web/Security/MachineKey.cs#L190
You can browse the reference and see if you can make any sense out of it.


text:
Q: Combining CSV files into 1 CSV I am combining multiple CSV's in a folder into one CSV and for some reason when I run the code it keeps copying the same files into the 1 and repeating itself. Sorry if that is vague. Here's the code that I am running, this will probably explain it better than I did.
import csv
import glob

fo = open("CombinedLog.csv", "ab")

list = glob.glob('*.csv')
print list

for file in list:
  ifile  = open(file, "rb")
  reader = csv.reader(ifile)
  for row in reader:
    row = ",".join(row) + "\n"
    fo.write(row)
ifile.close()

fo.close()

A: You opened the CombinedLog.csv for appending; every time you run this script more data will be added to the end, and the old data already there is retained.
Your code is working fine otherwise, but I'd use csv.writer() to format the output rows instead of using ','.join(); you can feed the csv.reader() object directly into the csv.writer() .writerows() method and be done with it.
I'd also use the file objects as context managers with the with statement and have them closed automatically:
import csv
import glob

with open("CombinedLog.csv", "wb") as fo:
    fo_writer = csv.writer()

    csv_files = glob.glob('*.csv')
    for filename in csv_files:
    with open(file, "rb") as ifile:
        reader = csv.reader(ifile)
        fo_writer.writerows(reader)

A: If that is all you are doing, and you don't want a whole program for it... In windows command prompt from that directory, you can just run:
copy *.csv all.csv

This uses the wildcard * to copy all CSVs and creates a new file called "all.csv" that contains all of the data.
Edit:
If you want inside of python:
import os
os.system('copy *.csv all.csv')


text:
Q: Как задать стиль объекту унаследованному от Button? Есть класс:
public class GLine : Button
{
    public int x, y;
    Game game;
    public GLine(int x, int y)
    {
        this.x = x;
        this.y = y;
        Grid.SetRow(this, y);
        Grid.SetColumn(this, x);
        DataContextChanged += GLine_DataContextChanged;
    }

    private void GLine_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        game = (Game)DataContext;
        Click += game.PlayerClick;
    }
}

Как задать объекту этого класса стиль, описанный в разметке UserControl'a, в который этот объект помещается?
TargetType = "Button" - не работает.

A: Просто укажите наименование класса, ну и не забудьте про пространство имен XAML, например:
<Style TargetType="local:GLine" ...


text:
Q: Preventing the Osama Facebook worm There is a javascript worm spreading on facebook.  The worm tricks users into executing javascript by copying and pasting the payload into the address bar. This is not xss,  this is social engineering.   If you read the worm's source code you'll see that its riding on the session and forging requests like the Sammy worm.  What are some way that a web application can prevent this type of attack?

A: If we're talking about a malicious user script manipulating the DOM (like this one seems to be doing):
You could ensure all the native JS code is hidden away from the global scope (through closures) and then hijack the document property of window. There can be ways a worm can circumvent this, but it will surely make things harder.
This is not something I've actually attempted and have proven to work, but the basic idea is:
(function () {
    // Initialize page

    // When we're done, make document inaccessible
    window.document = null;
})();

The pretense is, all native code that's executed during page initialization (including jQuery code etc.) should be bound to the actual document object through closure. It should not be possible for "javascript:" code in the address bar to access the actual document by executing in the global scope.
Again, I might be missing something blatantly flawed with this idea, and I'm ready to embrace all the downvotes. Maybe there are additional steps that need to be taken to completely hide away document.

A: Education is the best and only way.

A: For social engineering worms such as this exceedingly simple one, it should all come down to education. It is an awareness issue, as are most social engineering problems.
I see so many individuals who seem to fall for every facebook scam, and this one should be way more simple to avoid than most as it actually requires a user to type in commands. But people are desperate to see pictures of a dead terrorist. WTF?
The tricky thing is how to persuade them that while what they are doing may not hurt them directly, it does cost. It is the same problem as trying to persuade home users to run antivirus and firewalls - many don't even care if they are infected and are running as part of a botnet, as long as they can play their games and surf the net.
Technically - it could be done by facebook, but it won't be. You could prevent this propagating by simply pattern matching and removal of key signatures. It would just take too much effort, and as soon as you had sorted a specific issue there would be a way round it.
tl;dr - Educate EVERYONE! Long job, and unwinnable, but worth keeping on trying.

A: A very simple fix is to force your users to use a browser window without an address bar.  Although this solution comes with its own problems.
Another solution is using javascript and/or flash its possible to interact with the clipboard. A check could execute whenever a ctrl+c event (or a timer) is fired. If the message starts with javascript: then a blank message or a warning is copied to the clipboard.

A: If you're talking about ways to protect your website's users against this form of attack (ie. cookie stealing) I'm assuming that the following basic steps would help, of course there's a lot more you could do and this small list isn't at all comprehensive:

*

*Don't let users post Javascript! :-)

*Encrypt your cookies' data with a private key so that only your web app can utilise the data within

*Lock down sessions to IP, so if somebody stole the cookie / session cookie, it could not be reused

A: Unfortunately, there's really no way to stop the user from executing javascript in the context of your web app.  You could post a note warning users not to paste scripts that they don't understand in the address bar, or you could try to obfuscate your client code, but none of this will do much to stop the problem.  In the case of obfuscated code, it just takes a little more work for the scammer to write usable code.
Since the code executes in the context of your webapp, you have no foolproof way to tell apart legitimate user actions from script-based actions once the request gets to the server.  The best you can do is try to use a heuristic to detect fishy requests and stop them.


text:
Q: Errors When trying to Update SQL Field Hi All I have the following MSSQL update query
UPDATE Campaign **c**
**INNER JOIN** (
    SELECT CampaignID, sum(Amount) as total
    FROM Donation
    GROUP BY CampaignID
) t ON c.CampaignID = t.CampaignID
SET c.AmountDonated = t.total

It looks like it should work fine, however I am getting an error with the suffix for the Campaign Table (c) and then an error for the INNER in INNER JOIN, I don't understand why though. Can anyone point me in the right direction please?

A: Please, try this query:
UPDATE c
SET c.AmountDonated = t.total
FROM Campaign c
INNER JOIN (
    SELECT CampaignID, sum(Amount) as total
    FROM Donation
    GROUP BY CampaignID
) t ON c.CampaignID = t.CampaignID

Use FROM and JOINS at end of query.


text:
Q: Propensity score matching - different sample size I have a dataset with death outcome and around 25 independent variables.
I am planning to use logistic regression with PSM to understand the effect of treatment (a specific drug) which is one of the input variables on the outcome variable.
I am using PSM for the first time and have been following tutorials here,here.
Are the below called as different propensity score matching methods?
PS matching
PS weighting
PS stratification
PS as covariate

Are the above the different PS matching methods? If they are not, can you please let me know what are the different Propensity score matching methods?
Why is it said that we may/will get different pairs of data when we use different PSM methods? For ex, matching method 1 might give us 300 pairs of data (out of 2000 records in a dataset), another method gives only 100 pairs of data (out of 2000 records in a dataset). Why is this happening?
How will this impact when we compute balance measures such as SMD? Because the findings of SMD from each method may provide us different conclusion. Is there anything that we should do to address this?
Can someone help me with this in ordinary laymen terms and link to step-step tutorial if any please?

A: The word "matching" can sometimes be vague. Stuart (2010) defines matching "broadly to be any method that aims to equate (or "balance") the distribution of covariates in the treated and control groups". This would include PS matching, PS stratification, and PS weighting, but not PS as a covariate. Ho, Imai, King, and Stuart (2007) consider matching as nonparametric preprocessing to reduce model dependence. This would include PS matching and PS stratification, but not PS weighting or PS as a covariate. More specific definitions of matching refer to matching as subsetting (and optionally, but typically, pairing) the treated and control groups in order to equate the distribution of covariates in the treated and control groups, in which case only PS matching fits this definition. Don't get too hung up on the definition of "matching"; just try to be consistent and clear when describing what you are doing.
The four methods you mentioned all involve the propensity score, but that doesn't make them all matching methods. PS as a covariate is essentially a regression method just like covariate adjsustment but summarizing all the covariates into a single value. This method is almost always used improperly and has poor statistical performance when used improperly, so I recommend you do not use it if you are just starting out.
PS matching methods offer flexibility with the number of units retained. It's also important to know that the number of units retained is not the sole measure of the precision of the sample; for example, full matching retains all units but that doesn't mean no precision is lost when using it. Different ways of performing the matching can yield different numbers of remaining units. The simplest case is 1:1 nearest neighbor matching without replacement and without a caliper. This involves matching one control unit to each treated unit, so the number of remaining units should be twice the original size of the treated group. You can also add a caliper; this involves disallowing any pairs that are farther apart than some threshold set by the user. Any units without a close enough match will be discarded, so using a caliper will result in fewer units remaining. Matching with replacement allows each control unit to be matched to multiple treated units. If one control unit is a good match for many treated units, then fewer control units need to be used to find matches for all treated units, resulting in fewer units remaining. K:1 matching involves matching more than one control unit to each treated unit; this obviously increases the number of units remaining.
Different matching methods will produce different balance statistics. The whole point of matching is to try many matching methods and find the one which achieves the best balance in your dataset without discarding too many units. It is critical that you do not involve the outcome variable in this process.
The articles on the MatchIt website attempt to provide a tutorial for the use of matching, as well as descriptions of many matching methods, best practices in balance assessment, and effect estimation after matching. They include many references, which you should read before proceeding.
One thing I want to stress is that propensity score methods are advanced statistical methods that require highly specialized training to use correctly. Every single systematic review of the use of propensity score methods in published research indicates that many researchers are using the methods incorrectly. Tutorials may help you understand the basics of using the methods in the most ideal cases, but the most basic uses of these methods often yield the worst performance. I highly recommend you consult or collaborate with a statistician trained in the use of these methods before proceeding on your own.


text:
Q: How to deduce the triangle vertices in fragment shader If I draw triangles using OpenGL, how do I deduce their vertices for each fragment? Sending the position from vertex shader interpolates it, leading to the loss of information.

A: From a geometry shader you may access all three vertices of your triangle, thus you may pass them to the fragment shader via in/out (aka varying) variables. To prevent them from interpolating, just use flat interpolation qualifier.


text:
Q: Alinhar paginação do Bootstrap na direita Estou com um projeto que foi desenvolvido na versão Bootstrap v4.0.0-alpha.4. Nesse projeto tem uma paginação que segue os padrões do framework.

Anterior

1

2

3

Próximo

O problema está no alinhamento, pois quando uso o dessa forma:

      Anterior

1

2

3

      Próximo

Não funciona... porém se eu retirar:
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">

E colocar:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

Funciona, porém caga o layout todo :(
Já tentei usar o pull-right e o text-right, mas de nada adiantou.
Infelizmente é a manutenção de um projeto pronto e com isso não posso mudar a estrutura atual. Como posso alinhar a paginação para o lado direito sem impactar no layout?

A: Aparentemente parece que vc está usando uma versão mais simples do Bootstrap que deve ter deixado de fora algumas classes dos Utilities como as classes de Flex. https://getbootstrap.com/docs/4.1/utilities/flex/
Ou então devido a alguma hierarquia de classes tem alguma outra propriedade de flex substituindo a sua.
De qualquer forma vc pode usar esse CSS abaixo que vai resolver seu problema:

.pagination {
    justify-content: flex-end !important;
}
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />

        Anterior

1

2

3

        Próximo


text:
Q: PHP parse error on database search result return I'm trying to get data out of a mysql db and I have the login info saved in another file.  The username is getting sent from my form to the page with the code and i'm getting a

Parse error: syntax error, unexpected '[', expecting ',' or ';' in C:\xampp\htdocs\waladmin\ipfinder.php on line 31.

I don't understand why its saying that though, everything looks fine.
Here's my PHP:
<?php
testinclude('db_login.php');

$con = mysql_connect($db_host,$db_username,$db_password);
//$con = mysql_connect('10.241.10.40','waladmin','waladmin');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

$db_select=mysql_select_db($db_database);
if(!db_select)
{
die("Could not select the database.
".mysql_error());
}

$select = ' Select ';
$column = ' IP_Address,Workstation,Username ';
$from = ' FROM ';
$tables = ' admintable ';
$where = ' where Username = " & ControlChars.Quote & Username & Username &           ControlChars.Quote & "ORDER BY admintable.Time_Stamp DESC';
$query = $select.$column.$from.$tables.$where;

$result = mysql_query($query);
if(!result)
{
die("Could not query the database:
".mysql_error());
}

while($result_row = mysql_fetch_row(($result))){
echo 'Username:  ' . result_row[2] . '
 ';
echo 'Workstation: ' . result_row[2] . '
 ';
echo 'IP Address:  ' . result_row[1] . '
 ';
}
echo $con;
mysql_close($con)
echo $con;
?>

A: change all the result_row[1/2] to $result_row[1/2]

A: You are missing the $ in front of several references to $result_row. Since PHP sees constants, the [ is unexpected.

A: You have problem in last while loop...you missed $ sign and you also missed semicolumn too...
replace this code with respectives..
while($result_row = mysql_fetch_row(($result))){
echo 'Username:  ' . $result_row[2] . '
 ';
echo 'Workstation: ' . $result_row[2] . '
 ';
echo 'IP Address:  ' . $result_row[1] . '
 ';
}
echo $con;
mysql_close($con);
echo $con;


text:
Q: sched_setaffinity nonzero return compiled in 64 bit, zero return in 32 bit I am running RHEL 6.4 64 bit, and I was given a program to compile and execute.  The program has:
cpu_set_t cputset;
CPU_ZERO(&cpuset);
CPU_SET(data->num, &cpuset); //data is a structure, don't think it's relevant to my question
int ret = sched_setaffinity(0, sizeof(cpuset), &cpuset);
//print ret

When compiling for 32/64 bit gcc/icc, there are no compilation errors.  This will return 0 and correctly produce the result when compiled with -m32 (32 bit compiler), but when compiled with a 64 bit compiler, it has returned 1, 2, and 128 seemingly randomly just by running without any recompilation.  Could someone help me troubleshoot / identify what is going wrong with this when I compile it for 64 bit and execute? Thanks for any help.


text:
Q: Quick send bookmarks by mail Is there an addon for firefox which provides quickly sending shared bookmarks via e-mail?
I'm not interested in "sync" addons.

A: There is no such an addon for Firefox at the moment. You may save your bookmarks in .json format (Organize Bookmarks > Import and Export > Backup) and attach that file to your email. It shouldn't take more than a minute.

A: You can right click a folder in your bookmarks toolbar, copy, and paste into an email. That might work in the bookmarks manager as well. Thunderbird formats the links nicely.


text:
Q: time, rate and distance a group of storm chasers is following behind a tornado in order to film it.  The tornado is moving a straight line at 53 km per hour, and the storm chasers are driving in a van in its wake, travelling 90 km per hour.  How long will it be before the van is 4 km behind the tornado.
I did not understand this question, and how to solve it.  The question says that at present the van is in in the wake of tornado and they are behind.  Storm chasers are moving faster than the tornado.  Is this question correct? or am I reading it differently?

A: You are reading it correctly, they are driving faster to catch up.  You don't have enough information to solve the question, though.  You need how far behind they start out.

A: Even though you can't get a number (as Ross pointed out), you can write an equation.
If the goal is to be $4$ km behind, and the van closes in at $90 - 53 = 37$ km/hour, then the time will be $t = (d-4)/37$, where $t$ is measured in hours and $d$ is the starting distance away from the tornado.


text:
Q: Seleccionar mas de un checkbox en una lista Tengo una aplicación para encuestas en react, y debo mostrar las respuestas posibles al usuario en checkboxs para que elija una, el problema es que no me deja seleccionar un checkbox por pregunta.
La info la cargo desde una Api y la mapeo en una lista HTML.
Aqui dejo mi código

A: Hay que relacionar los checkboxs entre sí pasándoles el atributo name.
En este caso le podemos agregar a cada elemento de los arrays listaRes, la propiedad name así:
const preguntas = [
{
  idEncuesta: 7,
  encuesta: "Encuesta2 ",
  idPregunta: 26,
  pregunta: "¿Que tan probable es que le recomiende su jefe/a a un colega?",
  listaRes: [
    {
      idRelacion: 1,
      idPregunta: 27,
      idRespuesta: 1,
      respuesta: "Muy probable",
      name: 1
    },
    {
      idRelacion: 2,
      idPregunta: 27,
      idRespuesta: 2,
      respuesta: "Nada probable",
      name: 1
    }
  ]
},
{
  idEncuesta: 7,
  encuesta: "Encuesta2",
  idPregunta: 27,
  pregunta:
    "¿Qué tan fácil es obtener ayuda de su jefe/a cuando la necesita?",
  listaRes: [
    {
      idRelacion: 3,
      idPregunta: 27,
      idRespuesta: 3,
      respuesta: "Nada facil",
      name: 2
    },
    {
      idRelacion: 4,
      idPregunta: 27,
      idRespuesta: 4,
      respuesta: "No tan facil",
      name: 2
    },
    {
      idRelacion: 5,
      idPregunta: 27,
      idRespuesta: 5,
      respuesta: "Algo facil",
      name: 2
    },
    {
      idRelacion: 6,
      idPregunta: 27,
      idRespuesta: 6,
      respuesta: "Muy facil",
      name: 2
    },
    {
      idRelacion: 7,
      idPregunta: 27,
      idRespuesta: 7,
      respuesta: "Extremadamente facil",
      name: 2
    }
  ]
},
{
  idEncuesta: 7,
  encuesta: "Encuesta2",
  idPregunta: 28,
  pregunta: "¿Qué tan disponible para los empleados esta su jefe?",
  listaRes: [
    {
      idRelacion: 8,
      idPregunta: 28,
      idRespuesta: 8,
      respuesta: "Nada disponible",
      name: 3
    },
    {
      idRelacion: 9,
      idPregunta: 28,
      idRespuesta: 9,
      respuesta: "Poco disponible",
      name: 3
    },
    {
      idRelacion: 10,
      idPregunta: 28,
      idRespuesta: 10,
      respuesta: "Moderadamente disponible",
      name: 3
    },
    {
      idRelacion: 11,
      idPregunta: 28,
      idRespuesta: 11,
      respuesta: "Muy disponible",
      name: 3
    },
    {
      idRelacion: 12,
      idPregunta: 28,
      idRespuesta: 12,
      respuesta: "Extremadamente disponible",
      name: 3
    }
  ]
}
];

Luego al hacer el .map, en el atributo name del <input> le pasamos la nueva propiedad:
name={subitem.name}

Nos quedaría así:
<input
  className="form-check-input"
  type="radio"
  name={subitem.name}
  defaultValue={subitem.idRelacion}
  onChange={handleChange}
 ></input>

Y de esa forma se puede seleccionar solo un checkbox por pregunta.


text:
Q: BASH if - if nothing provided I am trying to perform a task only if a certain file type exists - so I have this
if [ -e  `find /directory -type f -name "*.filetype" | head -1`];
      then ...

this was always evaluating true (even if no filetype like this exists - I eventually realized that this:
if [ -e ]

evaluates as true (i.e. if nothing is given - which happens when my condition did not find the filetype) - Does anyone know what I should be doing to get what I need?

A: I learned this technique recently:
if [[ $(find /directory -type f -name "*.filetype" 2>/dev/null) ]]; then
    ...
fi

*

*We redirect stderr to /dev/null to hide any error messages

*The output of find will be non-blank if the file matched both conditions, otherwise it will be blank.

*The [[ ... ]] evaluates to true or false if the output of find is non-blank or blank, respectively.

I used a different version before:
if find /directory -type f -name "*.filetype" 2>/dev/null | grep -q .; then
    ...
fi

but this is less good, because it uses an extra grep process. The first solution achieves the same with a single find process.

A: Your line would have been correct with
if [ -n "`find /directory -type f -name '*.filetype'`" ] ;

-n tests for non-empty strings.
As noted in the comments, the backtick syntax is deprecated in favor of the $() syntax.


text:
Q: IoC Initialize Service with heavy-work in constructor but avoiding a temporal Init() method Hi I am using an IoC container and I would like to initialize a service (part of which involves 'heavy work' talking to a database) within the constructor.
This particular service stores information that is found by a injected IPluginToServiceProviderBridge service, this information is saved in the database via a UnitOfWork.
Once everything is boot-strapped, controllers with commands, and services with handlers, are used for all other interaction. All commands are wrapped within a lifetime scope so saving and disposing of the UnitOfWork is done by the handler and not the service (this is great for clean code).
The same neatness and separation of concerns for saving and transactions does not apply for the Initializer within the service as everything takes place in the constructor:
public PluginManagerService(
    IPluginToServiceProviderBridge serviceProvider,
    IUnitOfWork unitOfWork)
{
    this.unitOfWork = unitOfWork;
    this.serviceProvider = serviceProvider;

    lock (threadLock)
    {
        if (initialised == false)
        {
            LinkPluginsWithDatabase();
            initialised = true;
        }

        // I don't like this next line, but
        // not sure what else to do
        this.UnitOfWork.Save();
    }
}

protected void LinkPluginsWithDatabase()
{
    var plugins =
        this.serviceProvider.GetAllPlugins();

    foreach (var plugin in plugins)
    {
        var db = new PluginRecord
        {
            interfaceType = plugin.InterfaceType;
            var id = plugin.Id;
            var version = plugin.Version;
        }
        // store in db via unit of work repository
        this.unitOfWork.PluginsRepository.Add(db);
    }
}

A couple of points:
Ideally I want to avoid using a factory as it complicates handling of scope lifetimes, I would be happy to refactor for better separation if i knew how.
I really want to avoid having a separate Init() method for the service, whilst it would allow for transaction and saving via command/handler, lots of checking code would be required and I believe this would also introduce temporal issues.
Given the above, is it acceptable to call UnitOfWork.Save() within my constructor or could I refactor for cleaner code and better separation?

A: Letting your service's constructor do more than just store its dependencies in private fields is considered bad practice when applying dependency injection, since this allows the construction of the object graph to fail, slows down building of the graph, and complicates unit testing.
What I read from your question is that you need to do some initialization when the application starts. That's fine, since it's quite normal to have some initialization phase, but don't do this inside a constructor. Just move this initialization to the end of your application start-up code, after you configured the container (and after you optionally verified your configuration).
I imagine your code to look like this:
public void Application_Start(object s, EventArgs e)
{
    Container container = new Container();

    Bootstrap(container);

    InitializeApplication(container);
}

private void InitializeApplication(
    Container container)
{
    using (this.container.BeginLifetimeScope())
    {
        var pluginManager = this.container
            .GetInstance<PluginManagerService>();

        pluginManager.LinkPluginsWithDatabase();

        var unitOfWork =
            container.GetInstance<IUnitOfWork>();

        unitOfWork.Save();
    }
}

You could even write a decorator for your PluginManagerService, but this might be a little bit over engineered, BUT... it might look like this:
public class InitializingPluginManagerServiceDecorator
    : IPluginManagerService
{
    private static readonly object syncRoot = new object();
    private static bool initialized;

    private IPluginManagerService decorated;
    private Container container;

    public InitializingPluginManagerServiceDecorator(
        IPluginManagerService decorated,
        Container container,
        IPluginToServiceProviderBridge serviceProvider)
    {
        this.pluginManagerService = pluginManagerService;
        this.container = container;
        this.serviceProvider = serviceProvider;
    }

    public void PluginManagerServiceMethod()
    {
        this.InitializeInLock();

        this.decorated.PluginManagerServiceMethod();
    }

    private void InitializeInLock()
    {
        if (!initialized)
        {
            lock (syncRoot)
            {
                if (!initialized)
                {
                    this.InitializeInScope();
                }
            }

            initialized = true;
        }
    }

    private void InitializeInScope()
    {
        using (this.container.BeginLifetimeScope())
        {
            this.InitializeWithSave();
        }
    }

    private void InitializeWithSave()
    {
        var uow =
            this.container.GetInstance<IUnitOfWork>()

        var initializer = this.container
            .GetInstance<PluginManagerServiceInitializer>();

        initializer.Initialize();

        uow.Save();
    }
}

This decorator can be wrapped around an IPluginManagerService, and ensures that the system is initialized just before the IPluginManagerService us used for the first time, and ensures that it only initialized just once. The actual initialization logic is moved to a separate class (SRP), on which the decorator depends:
public class PluginManagerServiceInitializer
{
    private IUnitOfWork unitOfWork;
    private IPluginToServiceProviderBridge serviceProvider;

    public PluginManagerServiceInitializer(
        IUnitOfWork unitOfWork,
        IPluginToServiceProviderBridge serviceProvider)
    {
        this.unitOfWork = unitOfWork;
        this.serviceProvider = serviceProvider;
    }

    public void Initialize()
    {
        var plugins =
            from plugin in this.serviceProvider.GetAllPlugins()
            select new PluginRecord
            {
                interfaceType = plugin.InterfaceType;
                var id = plugin.Id;
                var version = plugin.Version;
            };

        unitOfWork.PluginsRepository.AddRange(plugins);
    }
}


text:
Q: List of prefixes in haskell I am to write a function which returns a list of all prefixes of a given string.
This is where I'm at so far.
prefixess [x] [] = [x]
prefixess [] s = prefixess [s] s
prefixess [x] s  = prefixess [x, (init s)] (init s)
prefixes s = prefixess [] s

It compiles, but when I try running it on a string I get this:
Couldn't match type 'Char' with '[t]'
Expected type: [[t]]
  Actual type: [Char]
Relevant bindings include
  it :: [t] -> [[t]] (bound at <interactive>:18:1)
In the first argument of 'prefixess', namely '"abcde"'
In the expression: prefixess "abcde"
In an equation for 'it': it = prefixess "abcde"

I am out of ideas. Any hints?

A: I don't think this code does what you think it does. You try to pattern match the list x with the pattern [x], which captures the element of a singleton list. If i fix your code like this, it works:
prefixess x [] = x
prefixess [] s = prefixess [s] s
prefixess x s  = prefixess ((init s):x) (init s)
prefixes s = prefixess [] s

This gives the following result:
Main> prefixes "stackoverflow"
["","s","st","sta","stac","stack","stacko","stackov","stackove","stackover","stackoverf","stackoverfl","stackoverflo","stackoverflow"]

But you don't really need an accumulator for a function which calculates prefixes, I would write it like this:
prefixes' (x:xs) = [] : (map (x:) (prefixes' xs))
prefixes' [] = [[]]

This function is also available under the name "inits" in Data.List
Main> import Data.List
Main Data.List> inits "stackoverflow"
["","s","st","sta","stac","stack","stacko","stackov","stackove","stackover","stackoverf","stackoverfl","stackoverflo","stackoverflow"]

A: Point-free style solution for genereting list of all prefixes:
prefixes = foldr (\el acc -> [] : map (el:) acc) [[]]


text:
Q: How get url from bytes array? I have a problem. I have docx file stored as bytes array in database. I need get a url of this file. Url should be like http://my-site.com... but I have no idea how could I reach it. I read many topics with memorystream, filestream, etc. but I still don't understand how I can reach this. I writting in ASP MVC C#.

A: For the ASP.NET MVC part you can use the File method of the controller to return a byte array as file download, like in this example.
public class HomeController : Controller
{
    public ActionResult Download(string id)
    {
        byte[] fileInBytes = GetFileDataFromDatabase(id);

        return File(fileInBytes, "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            id + ".docx");
    }

    private byte[] GetFileDataFromDatabase(string id)
    {
        // your code to access the data layer

        return byteArray;
    }
}

The Url would be: http://.../home/download/{someId}

A: Something like this:
[HttpGet]
[Route("file/{fileId}")]
public HttpResponseMessage GetPdfInvoiceFile(string fileId)
        {
            var response = Request.CreateResponse();
            //read from database
            var fileByteArray= ReturnFile(fileId);
            if (fileByteArray == null) throw new Exception("No document found");
                response.StatusCode = HttpStatusCode.OK;
                response.Content = new StreamContent(new MemoryStream(fileByteArray));
                response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = fileId+ ".docx"
                };
                response.Content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                response.Headers.Add("Content-Transfer-Encoding", "binary");
                response.Content.Headers.ContentLength = fileByteArray.Length;
                return response;

    }

or if you have a Razor Mvc site simply use FileResult: Download file of any type in Asp.Net MVC using FileResult?


text:
Q: How to do a branch per task strategy with git Currently, my team is looking for an agile git branching strategy. I originally thought we could follow this article: http://nvie.com/posts/a-successful-git-branching-model/, but unfortunately we do pushes to production too often to work on a branch with multiple tasks in it until it is stable (the next release branch strategy). Also, there is often situations where issues that should only take a few days to finish take a while to resolve due to priories changing. Because we do not have the time to work on these long running tasks they sit in dev or a next release branch and give way to the possibility of breaking production.
I want to adopt a branch per task strategy and want to know how it has been done with git before. I'm not just talking about feature branches, but a branch for every individual task you are assigned. Also, there would be no dev branch since your task branches will be your dev branch. Having a develop branch entices developers to commit directly to that branch which leads to open issues in our main branch.
I came up with this:

I believe adopting this strategy will keep the main branch clean and will also account for when developers are not around to finish their tasks before we do a push to production.
The main idea behind it is that the main branch is a protected branch and there is no development branch. Since the main branch is protected it will force you to create a branch off of it for individual tasks. In order to merge back in you have to request a merge from the administrator. We will tag every release to production and hotfixes will also be branches off of the main branch. We have four test sites set up that we can use to test the different task branches.
I haven't seen any examples of this strategy just yet, so I was hoping to get some feedback on what I have here.
UPDATE
So I know its been a while since this question was posted, but if anyone is looking for a similar strategy it seems that GitHub has adopted it here.

A: The git flow model you mention is designed specifically to solve your problem :). Although it shows commits to develop, all tasks should be done in their own feature branch, and only merged back to develop once complete and tested. That way you know you can always release from develop (i.e. merge to master and tag), so it supports regular and continuous release.
Branch-per-task works really well with git flow because branching is cheap. We also use our issue numbers as prefixes, so git flow feature start PR-123_make-widget has a useable branch name but also highlights issue PR-123 in our JIRA.
Following the git-flow method as described above gives you a stable development branch (or maybe multiple stable development branches if you're working on a major new version branch as well as develop. You are also able to do hot-fixes which are applied directly to master and then merged back into develop.
For your 'request for merge', you could use pull requests (if you're using Github, Stash, Bitbucket, etc) or you could use a tool like Gerrit.
There's a reasonable argument that any branch which passes all tests should be merged back to develop automatically, in which case you could try doing per-commit micro reviews on feature branches. There are loads of options!
Update
If you are going to persevere with your suggested model, I would recommend considering how your release cycle works. Does the release just involve tagging and pushing, or do you feature freeze for some time to carry out additional QA? Might you ever do that in the future? If the answer is 'yes' or 'maybe' then you shouldn't release from master, but should instead create a release branch, carry out your last minute fixes, and then tag and push. Don't forget to merge back as well though.
Update
If you are employing a branch-per-task strategy it might appear that the master branch serves no real purpose. If you are doing continuous release, so every stable develop branch build is deployed to your production environment automatically, this is probably true. In an environment where a build is promoted to production, without a release phase, i.e. the promotion doesn't involve any additional commits the additional branch is possibly unnecessary. The real benefit of the develop/master branching strategy comes when you have a release phase where final release fixes (deployment issues, last minute bugs, etc.) and general housekeeping such as version number bumps are done in a transient release branch.
Using the release branch and then merging that to a master branch means you can continue to merge stable features back into develop even though your release isn't complete yet.
It's also quite nice to have single commit points on the master branch, with each commit representing a release, but that's a purely aesthetic justification so isn't really that valid :).

A:
I want to adopt a branch per task strategy and want to know how it has been done with git before

Git lightweight branching has been specifically designed with exactly this in mind, you can and ideally should create branches for each individual topic.
The following is quite subjective. The successful branching model that you refer to is successful because its plain common sense (and the marketing of calling it successful to reassure the world that branching and merging isn't scary at all). My own evidence is anecdotal, but it stands to reason that everyone who used git on a large enough project with many developers naturally had release, develop, stage, featureX, featureY, etc branches, or variants of thereof, with a common and normalised flow between them.
Your flow, as charted, makes sense, and one shoe doesn't fit all - you shouldn't be afraid to deviate from a successful git branching model where necessary!
Notwithstanding, with every such flow the main question is what's your staging, QA and release strategy. Fixing bugs, developing features, whether on topic branches or common branches isn't much of an issue, code is just code. And git is very good at moving code around between branches, splitting it to new branches, rewinding to code's old state, etc.
So what's more of an issue is how do you plan to QA and release the code. What are your resource limitations? (Build times, webservers, embedded harnesses, test farms, CI build and test boxes, etc.) Just as an example, if branching and moving code around is cheap, but building or re-building a branch takes 8 hours, then having a branch per a minuscule change doesn't make sense. Your flow has to consider this to be a successful one.


text:
Q: No index in Eclipse CDT project checked out from SVN I have checked out a cross-compilation project from SVN on Eclipse (on a Linux system). I am unable to open a functions declaration from the functions's right-click context menu (or by pressing F3). Upon research, I found out I don't even have anything like Index -> .. in the project's right-click menu. I have tried a lot with the Preferences -> C/C++ -> indexer but no useful results. I am not using Eclipse to build it but there are no errors since I can build it using makefile
PS: Though there are a few questions with the matching title, but none of them helped me

A: Here is the solution found after a million attempts. The project should be checked-out as C/C++ project, by selecting import using new project wizard.. The index will NOT be available in the SVN projects checked-out directly. Hope it saves some one's time

A: Eclipse Kepler SR2 on Windows 7 here.
Faced the same issue, the following sequence of inputs made it work for me:

*

*Import...

*"Checkout projects from SVN."

*Select branch etc.

*Check the "Check out project configured using the New Project Wizard" radio button.

*Select "C/C++ -> C Project."

*Pick a toolchain, doesn't matter which if you use an external one.

*Now you can right click on the project (once fully checked out) and rebuild the indexer.

A: I am using Indigo and solved it as follows (without checking out again!)
Right click on project in question and select New->Convert to a C/C++ Project
After selecting toolchain, indexing gets built automatically.


text:
Q: Обработка большого количества информации Есть текстовый документ в котором спаршено с API очень большое количество информации.
Нужно эту информацию посортировать и поукладывать в excel документ, а ненужные данные просто пропустить.
К примеру строка :

{"previous":null,"results":[{"content_object":{"content_type":"movie","resource_url":"https://youtube.win/api/v1/movies/5/?format=json","id":5,"ru_title":"Эверест","orig_title":"Everest","imdb_id":"tt2719848","kinopoisk_id":"739642".

Из этого всего нам нужно

"ru_title":"Эверест" "imdb_id":"tt2719848" "kinopoisk_id":"739642"

Так как данных очень много, нужно в excel распределить по столбцам:

Title       IMDb          Kinopoisk

Эверест     tt2719848     739642
Титаник     tt525442      242
....        ....          ....

Чем это можно сделать?

A: Как написали в комментариях, это возможно разными способами:

*

*Если записей меньше 1.048.576 штук, то возможно разобрать файл с помощью VBA в самом Excel и сложить данные на лист. Однако, для извлечения данных из JSON-объекта, придется использовать дополнительные приложения, вызываемые из кода VBA. Здесь же можно найти примеры подобного извлечения.

*Если записей гораздо больше, то извлечь на лист Excel не получится. В этом случае проще написать скрипт разбора любым доступным языком, в том числе и на python, который имеет очень приятную библиотеку разбора JSON-объектов.


text:
Q: How to put gallery on left and table on right in same line? I want to put image gallery alongside table, as code below, but when run table appears below gallery and takes 100% width.
I need this all to be in one line split 50% gallery and 50% table. On the right there will always be 4 pictures and table will consist of no more than 6 columns and 6 rows.
I'm using only styles that are below.

table{
    width:50%;
    table-layout: fixed;
}

.tbl-content{
    height: 100%;
    overflow-x:auto;
    margin-top: 0px;
}

th{
    padding: 20px 15px;
    text-align: center;
    font-weight: 500;
    font-size: 12px;
}

td{
    padding: 15px;
    text-align: left;
    vertical-align:middle;
    font-size: 12px;
}

.container-gallery {
    display: flex;
    width: 50%;
    padding: 2% 1%;
    box-sizing: border-box;
    height: 70vh;
}

.box-gallery {
    flex: 1;
    overflow: hidden;
    margin: 0 2%;
    box-shadow: 0 20px 30px rgba(0,0,0,.1);
    line-height: 0;
 }

.box-gallery > img {
    width: 200%;
    height: 100%;
    object-fit: cover;
 }

.box-gallery > span {
    font-size: 3.8vh;
    display: block;
    text-align: center;
    height: 10vh;
    line-height: 2.6;
}

.box-gallery:hover { flex: 1 1 50%; }
.box-gallery:hover > img {
    width: 100%;
    height: 100%;
}

                    xxxxxx
                    xxxxxx
                    xxxxxx

                    xxxxxx
                    xxxxxx

                    xxxxxx
                    xxxxxx

                    xxxxxx
                    xxxxxx

                    xxxxxx
                    xxxxxx

A: set section display to flex. This should place the image div and table div side by side.
section {
display: flex;
}

You may also want to set the display direction of your .container-gallery to column, so it would fit in properly into the available space.


text:
Q: Bootstrap datepicker format not working on initialization I am trying to use angular-bootstrap datepicker module in my app and encountered small problem. I use input text and button for displaying date like this:

        <input type="text" class="form-control" datepicker-popup="{{format}}" ng-model="currentDate"
        is-open="opened" datepicker-options="dateOptions" date-disabled="disableDt(date, mode)"
        ng-required="true" close-text="Close" show-button-bar="false" ng-init="" readonly/>

            <button type="button" class="btn btn-default" ng-click="open($event)">

            </button>

And due to using angular google maps I have to manually bootstrap my app. It seems that due to manual bootstrapping, datepicker is unable to properly format the date and displays whole   unformatted date. As I choose any date from datepicker, date is then displayed correctly in the input field. What is more, model changes don't force format to change (e.g. initially I got some dates from json file and they were displayed in the field, but without formatting too).
Example below:

*

*Initial date: Fri Jan 17 2014 01:00:00 GMT+0100 (CET)

*Expected date (and one displayed after choosing the same day): 17 January 2014
Is there any way of refreshing this widget so it knows proper formatting at the beginning or changing it at the proper moment to initialize properly?
EDIT: As I moved datepicker to fragment, it should not have problems with not initialized model (this fragment is loaded later). Still, problem occur - date is not formatted and seems not to be connected with formatter or model at all (e.g. making format dropdown and choosing different values as in tutorial doesn't work until date is chosen inside datepicker).
EDIT 2 Solution from the link provided by camden_kid worked! :) Details in his comment.

A: Answer could be found here:
AngularJS 1.3 - Datepicker initial format is incorrect
I manually formatted the date on initialization as below:
$scope.currentDate = $filter('date')(new Date(), $scope.format);

However, better solution would be to overload directive as follows (taken from the original link):
angular.module('myApp').directive('datepickerPopup', function (dateFilter, datepickerPopupConfig) {
return {
    restrict: 'A',
    priority: 1,
    require: 'ngModel',
    link: function(scope, element, attr, ngModel) {
        var dateFormat = attr.datepickerPopup || datepickerPopupConfig.datepickerPopup;
        ngModel.$formatters.push(function (value) {
            return dateFilter(value, dateFormat);
        });
    }
};

});
When date was changed by datepicker afterwards, datepicker itself handled any date formatting :)
Thanks to @camden_kid for providing the link! :)


text:
Q: How do I use a Button to run an Update Query? We have a large database in which we have multiple table that store data.  We input our customer logging rates into a form and would like to have the information update to our loadsliptbl as well as to our infoconverionratestbl withour haveing to go into a seperate update query and input that information again (already entered into the form).
The update query is as follows:
UPDATE Loggingtbl INNER JOIN Loadsliptbl ON Loggingtbl.LoggingId = Loadsliptbl.LoggingId SET Loadsliptbl.EstConvRate = 1.4289, Loadsliptbl.[LogRate-T] = 24.22
WHERE (((Loadsliptbl.Date) Between #5/19/2012# And #6/1/2012#) AND ((Loggingtbl.TM)="FJ3W66 312") AND ((Loadsliptbl.Stratum)="20-415P"));
WE have to enter the EstConvRate, LogRate-T, the date parameters, TM and Stratum on both the form and then in the update query.
How do I Automate this?
Shelly


text:
Q: Laravel / Consulta Eloquent entre tablas no relacionadas (Muchos a muchos) Mi problema es que tengo una relación de muchos a muchos entre la tabla subject y teacher, por lo tanto, tengo tabla detalle o intermedia ( teacherSubject ).
Debo mostrar en la plantilla blade (vista) de Teacher las subject que se encuentren relacionadas a ese teacher, cómo ven no puedo usar join porque directamente las tablas de subject y teacher no están relacionadas ya que los ID son recuperados en la tabla detalle.
Traté de usar la tabla intermedia para tal fin pero no tengo una idea específica de cómo llamar el atributo.
¿Cómo podría hacerlo?

A: En modelo subject
 public function teachers()
    {
        return $this->belongsToMany('App\Teacher','teacherSubject ','id_subject','id_teacher');
    }

En modelo teacher
public function subjects()
    {
        return $this->belongsToMany('App\Subject','teacherSubject ','id_subject','id_teacher');
    }


text:
Q: Prove that convexity of a function on a interval imples that the second derivative is positive In the following I use this definition of a convex function in $x_0$.
A function $f$ which is differentiable in $ x_0 $ is convex in $x_0$ if there is an interval $(a, b) $ around $x_0$  such that
$$
f(x)> f' \left( x_0 \right) \cdot \left( x-x_0 \right) + f \left( x_0 \right) \quad \text{for all } x \in (a, b) - \left\{ x_0 \right\}.
$$
I want to prove that if a function $f$ is convex on an interval $(a,b)$, then
$$
f''(x)>0 \quad \text{ for all } x \in (a, b).
$$
Note: I know how to prove the opposite, that is using the mean value theorem.


text:
Q: Services don't communicate internally in Docker I am trying to run an ASP.NET Core 2.0 application (REDIS + RabbitMQ + NGINX) on Docker.
When I upload these containers via docker-compose, these services work and are even accessible by Windows, since they are mapped by "HostPORT: ContainerPORT".
However, when testing the App itself, .NET informs in console that it was not possible to connect to the REDIS, for example.
fail: Microsoft.AspNetCore.Server.Kestrel[13]
  Connection id "0HLDGDJNAEB9E", Request id "0HLDGDJNAEB9E:00000001": An unhandled exception was thrown by the application.
  StackExchange.Redis.RedisConnectionException: It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. SocketFailure on PING.

My docker-compose.yml:
version: '3'

services:
  nginx:
    build:
      dockerfile: ./nginx/nginx.dockerfile
      context: .
    image: nginx
    container_name: nginx
    ports:
      - "80:80"
    networks:
      - production-network
    depends_on:
      - "wordSearcherApp"

  wordSearcherApp:
    image: wordsearcherapplication
    container_name: wordsearcherapp
    build:
      context: .
      dockerfile: WordSearcher/Dockerfile
    networks:
      - production-network
    ports:
      - "61370"
    volumes:
      - repository:/repository
    depends_on:
      - redis
      - rabbit

  redis:
    image: redis
    container_name: redis
    ports:
      - "6379:6379"
    networks:
      - production-network

  rabbit:
    image: rabbitmq
    container_name: rabbitmq
    ports:
      - "5672:5672"
      - "15672:15672"
    networks:
      - production-network
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:15672"]
      interval: 30s
      timeout: 10s
      retries: 5

networks:
  production-network:
    driver: bridge

volumes:
  repository:
    driver: local

For Connection in C#, i use this connectionString localhost:6379
How can i do this?
Thanks.

A: Use redis:6379 instead of localhost:6379.
Docker-Compose will use the name you've defined for a service in the docker-compose.yml file as the hostname for its container.


text:
Q: How to load a local html file into webView on iPad I have an iPad Master Detail project and I am trying to display html content in a web view which is called detailWebView.
I have set the content of detailItem in the Master View Controller.
self.detailViewController.detailItem=[[_topicsData
                                       objectAtIndex:indexPath.section]
                                      objectAtIndex: indexPath.row];

I have tried many ways to get the extracted information to display in the web view but it will not.
In configureView I have:
NSString *myString=[_detailItem objectForKey:@"url"];
NSString *myNewString=[NSString stringWithFormat:@"%@%@",myString,@".html"];
NSURL *url = [NSURL URLWithString:myNewString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.detailWebView loadRequest:request];

But nothing I try will load the content.
I know I have the correct detail for url because when I try
NSLog(@"detailItem is %@",url);

I get something like myurl.html

A: You need to add the code in viewDidLoad:
- (void) viewDidLoad {
    [super viewDidLoad];

    self. detailWebView.delegate = self;

    NSString *myString=[_detailItem objectForKey:@"url"];
    NSString *myNewString=[NSString stringWithFormat:@"%@%@",myString,@".html"];
    NSURL *url = [NSURL URLWithString:myNewString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self. detailWebView loadRequest:request];
}


text:
Q: Add whitelist IP to a restricted country We have an application what is only going to be available in the UK -  so using the Developers console, under 'Settings' - 'Advanced' I have put United Kingdom in the 'Country restrictions' settings to block out all other countries.
However, we have a call center in Ireland that I need to provide access to the application -  I have tried adding their IP address to the 'Server IP Whitelist' but they are not able to see the application.
Am I able to have Ireland blocked as a country -  but have specific IP's opened?
Thanks


text:
Q: How to show the C# windows form application? I have an application developed in c#. This application send sms to client. This application was doing good till yesterday but suddenly this morning I find that if I start the application it is starting but not showing anywhere in the desktop not even in the task bar. I tried to stop it  using the Task manager but I could not find it in the task manager. I have included some function in my code which restricts to run two instances of this application at the same time. So, when I try to run again it shows this Application is already running. I can only close it using TCP Viewer which helps to close background program. But I have not written any line of code to run it on the background.
Even when I am debugging it is going to the debug points correctly but not showing the form. Please help me on this.
Here is my form load code as sample:
     private void Form1_Load(object sender, EventArgs e)
    {
        tcnt = 1;
        thistime = DateTime.Now.Date;
        techtime = "09:00:01";
        techdate = DateTime.Now.Date;
        dntime = DateTime.Now.Date;
        rebillingdate = DateTime.Now.Date;

        checkState[1] = true;
        checkState[2] = false;
        checkState[3] = false;

        this.tmrLog.Enabled = true;
        this.stStatus.Text = "Form loading";

        string myDate = DateTime.Now.Date.ToString("yyyyMMdd");
        string myFile = null;
        string myDir = "logs\\schedule\\";
        StreamReader sr = default(StreamReader);
        string str = null;

        DirectoryInfo dir = new DirectoryInfo(myDir);
        //DirectoryInfo DirItem = default(DirectoryInfo);
        FileInfo[] dirfiles = null;
        //FileInfo myf = default(FileInfo);
        this.Controls.Add(lsLog);
        lsLog.Items.Clear();

        if (dir.Exists == true)
        {
            foreach (var DirItem in dir.GetDirectories())
            {
                dirfiles = DirItem.GetFiles();
                foreach (var myf in dirfiles)
                {
                    if (myf.Name.IndexOf("schedule") > 0 & myf.Name.IndexOf(myDate) > 0)
                    {
                        myFile = "logs\\schedule\\" + DirItem.Name + "\\" + myf.Name;

                        if (DirItem.Name == "48" | DirItem.Name == "IPX")
                        {

                            sr = File.OpenText(myFile);
                            while (sr.Peek() != -1)
                            {
                                str = sr.ReadLine();
                                lsLog.Items.Insert(0, str);

                            }
                            sr.Close();
                        }

                    }
                }
            }
        }
        tmrLog.Enabled = true;

    }


text:
Q: Use of "nay" as an adverb I researched help and examples on the uses of the word nay but found these inadequate/insubstantial.
The Free Dictionary has described:

*

*an archaic or dialect (except in voting by voice) word for no

*(noun)  a. a person who votes in the negative    b. a negative vote

*(adverb) (sentence modifier) an emphatic form of no

as an instance for an adverb, I found the following line:

and not only so but; not only that but also; indeed: many good, nay, noble qualities.

I see nay in the latter example as one that contains a compound connotation(s.)
so could the same example be re-written in the following ways?
a)"not only did he have (many) good qualities, he had noble ones too"
or
b)"not only were his qualities good, they were noble too"
I'm very uncertain and critical as to how nay is understood to describe the situations a) and b) because I understood all along that nay was another word for no.
I'm looking for a detailed review and examples of the meaning and utilisation of nay

A: This is from Oxford Dictionaries. It is interesting that it mentions nothing about voting. In the House of Commons, 'nay' is not used, but 'aye' is. When the Speaker calls a division he shouts 'Ayes' to the left, 'noes' to the right.
ADVERB
1  Or rather (used to emphasize a more appropriate word than one just used):
permission to build the superstore will take months, nay years
2 • archaic or • dialect No:
nay, I must not think thus
MORE EXAMPLE SENTENCES
NOUN
Back to top
A negative answer:
the cabinet sits to give the final yea or nay to policies
MORE EXAMPLE SENTENCES
Origin
Middle English (in sense 2 of the adverb): from Old Norse nei, from ne 'not' + ei 'ever' (compare with aye

A: In the (rather old-fashioned sounding) sentence

He has many good – nay, noble – qualities.

the classification of 'nay' (or 'no' in modern English) as an adverb is traditionalist laxity. It signals an adjustment to what is being said in the proposition, an external aid to the listener/reader provided by the speaker/reader. It is a pragmatic marker, specifically a corrective (or, as it is a minor adjustment here, a modificational) pragmatic marker. A true corrective marker usage would be:

He's twenty-eight – no/sorry/correction, eighty-two – next week.

Nothing like the function of an adverb. It's equivalent to crossing out the inaccurate term and writing in the correct one.


text:
Q: Can't validate authenticated message with ECDSA.recover I need to be able to retrieve a document from the contract, have it signed by a users wallet and then send back to the contract and the signature validated.
Here's how I have address0 sign it on the client side:
   let message : string = "check this message signed by account0";
   let messageHash = keccak256(utils.toUtf8Bytes(message));
   let signature = await address0.signMessage(messageHash);
   await hm.connect(address0).verifyMessage(message, signature);

Here's the validator in my contract:
   function verifyMessage(string memory message,
      bytes memory signature)
      public view  returns(bool) {

        //hash the plain text message
        bytes32 messagehash =  keccak256(bytes(message));
        //hash the prefix and messagehash together
        bytes32 messagehash2 = keccak256(abi.encodePacked("\x19Ethereum Signed Messsage:\n32", messagehash));
        //extract the signing contract address
        address signeraddress = ECDSA.recover( messagehash2, signature);
        if (msg.sender==signeraddress) {
            //The message is authentic
            return true;
        } else {
            //msg.sender didnt sign this message.
            return false;
        }
    }

Regrettably, the value returned by ECDSA.recover for signeraddress is not account0's address, and despite a lot
of experimentation I've not been able to derive the correct address of the message sender from the signature.
Would appreciate any pointers.

A: I was able to get an answer from folks over on Openzeppelin.
In case any body else runs into the situation, one issue is the way that the hash is calculated and the signature is computed on the client side
Instead of
   let messageHash = keccak256(utils.toUtf8Bytes(message));

use
    let messageHash = ethers.utils.solidityKeccak256(['string'], [message]);

and instead of
    let signature = await address0.signMessage(messageHash);

use
     let signature = await address0.signMessage(ethers.utils.arrayify(messageHash));

On the server side, the addition of the prefix can be done more simply with `ECDSA.toEthSignedMessageHash() as in the solution below:
using ECDSA for bytes32;

function verifyMessage(string memory message, bytes memory signature) public view  returns(address, bool) {
        //hash the plain text message
        bytes32 messagehash =  keccak256(bytes(message));

        address signeraddress = messagehash.toEthSignedMessageHash().recover(signature);

        if (msg.sender==signeraddress) {
            //The message is authentic
            return (signeraddress, true);
        } else {
            //msg.sender didnt sign this message.
            return (signeraddress, false);
        }
    }


text:
Q: ORACLE SQL group based on values in a reference table Customer table and Acct tables has global scope, they share and increment this value
Below is customer table, SEQ NO 1 is beginning of customer data, SEQ_NO 238 is beginning of another customer data

Another is account table, all accounts with their SEQ_NOs inside a boundary of customer get same group (I want to group those accounts to the same customer, so that I can use listAgg to concatenate account id.), for example, below from SEQ_NO 2 and NO 224 (inclusive) should be assigned to the same group.

Is there a SQL way to do that, The worst case I was thinking is to define oracle type, and using function do that.
Any help is appreciate.

A: If I understand your question correctly, you want to be able to assign rows in the account table to groups, one per customer, so that you can then aggregate based on these groups.
So, the question is how to identify to which customer each account belongs, based on the sequence boundaries given in the first table ("customer") and the specific account numbers in the second table ("account").
This can be done in plain SQL, and relatively easily. You need a join between the accounts table and a subquery based on the customers table. The subquery must show the first and the last sequence number allocated to each client; to do that, you can use the lead analytic function. A bit of care must be taken regarding the last customer, for whom there is no upper limit for the sequence numbers.
You didn't provide test data in a usable format, so I created sample data in the with clause below (which is not part of the query - it's just there as a placeholder for test data).
with
  customer (cust_id, seq_no) as (
    select 101,  1 from dual union all
    select 102, 34 from dual union all
    select 200, 58 from dual union all
    select 130, 90 from dual
  )
, account (acct_id, seq_no) as (
    select 1003,  3 from dual union all
    select 1005, 11 from dual union all
    select 1007, 33 from dual union all
    select 1008, 60 from dual union all
    select 1103, 77 from dual union all
    select 1140, 92 from dual union all
    select 1145, 99 from dual
  )
select c.cust_id,
       listagg(a.acct_id, ',') within group (order by a.acct_id) as acct_list
from   (
         select cust_id, seq_no as lower_no,
                lead(seq_no) over (order by seq_no) - 1 as upper_no
         from   customer
       ) c
       left outer join account a
       on a.seq_no between c.lower_no and nvl(c.upper_no, a.seq_no)
group  by c.cust_id
order  by c.cust_id
;

OUTPUT
CUST_ID  ACCT_LIST
-------  --------------------
    101  1003,1005,1007
    102
    130  1140,1145
    200  1008,1103


text:
Q: Puppet agent very slow runs with large LDAP I have a puppet master that is on a server that uses winbind connected to a Universities large LDAP / active directory. When winbind is on the puppet runs are extremely slow and when winbind is turned off the puppet runs are normal.
I believe that puppet might be looping through every user in active directory or something similar but I'm unsure. It's not an option for me to turn of winbind so I have been just dealing with the long puppet runs and haven't found a solution.
Any help is much appreciated.

A: According to this thread, an active LDAP client configuration on the master host does indeed incur a performance penalty, and an apparent solution is to reconfigure in nsswitch.conf. If that is not an option, a supposed mitigation strategy is a caching nscd.


text:
Q: running out of memory so quickly-tensorflow-gpu when i run https://github.com/cysmith/neural-style-tf project  my gpu has a spike in device manager graphic as shown below.
tensorflow:2.3.0
python:3.7.9
CUDA:11.1
gpu:nvidia 840m
exact moment   then it drops to zero.
and i get "tensorflow allocator (gpu_0_bfc) ran out of memory trying to allocate..." error.
i dont know why  there are tons of topic about it but i couldnt find answer for me.

A: Seems like it's a problem with memory allocation, can you try adding this snippet just after importing TensorFlow?
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
  try:
    for gpu in gpus:
      tf.config.experimental.set_memory_growth(gpu, True)
  except RuntimeError as e:
    print("Error: " + e)

You can also try setting TF_FORCE_GPU_ALLOW_GROWTH to TRUE in your env.
This lets you tell TensorFlow to slowly increase the amount of memory allocated from your graphics card, based on the usage.


text:
Q: Checking digits in string, doesnt work when the string starts with a 0 I have a homework assignment where we have to make a very basic console app for a fitness center, that can create members and employees. My problem occurs when i ask the user to type in the birthday of the new members. It is supposed to check if the birthday is in the format DD/MM/YY, so i check if the answer given is 6 digits, and 6 digits only. And it seems to work, unless someone gives a birth date that start with 0, EG.: 090498.
System.out.println("Please enter the new members birthday, in the format of DD/MM/YY:");
    this.birthdate = console1.nextInt();
    while(String.valueOf(birthdate).length() != 6){
    System.out.println("Please give a valid date of birth in the format of: DD/MM/YY");
    this.birthdate = console1.nextInt();
}

It doesn't give a error message, but only completes the loop if the birthdate IS 6 digits, AND starts with a 1 EG.: 190798.
i know this is probably very simple, but i only started studying CS about a month ago :)

A: As the other answers told you if you start an int with 0 the code will ignore it. You can import a SimpleDate and with a String you can use it. I leave here a link on another question that maybe can help you more.
[link] How can I convert an Integer (e.g 19000101 ) to java.util.Date?
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToDateEXE {
public static void main(String[] args)throws Exception {
    String DateT="31/12/1998";
    Date NDate=new SimpleDateFormat("dd/MM/yyyy").parse(DateT);
    System.out.println(DateT+"\t"+NDate);
}
}

Hope it helped.

A: The problem is that you are accepting an int, and the initial 0 is automatically dropped. And a birthday should not be represented as an integer. My advice is to change that field as a String, and accepting a value of that type as a consequence.

A: You are taking an int and that makes it drop the leading 0. You should accept a String instead. Here's the code corrected to do that
System.out.println("Please enter the new members birthday, in the format of DD/MM/YY:");
this.birthdate = console1.nextLine();
while(birthdate.length() != 6){
    System.out.println("Please give a valid date of birth in the format of: DD/MM/YY");
    this.birthdate = console1.nextLine();
}

This assumes that you changed the type of birthdate to String. You should know that your validation strategy is a naive one since anyone can enter a length 6 string without it being a valid birthdate or a birthdate at all. Use regular expressions as in here for that kind of validations. Regular expressions can be applied to any string with the String.matches() method by passing to it the regular expression. A different approach would be to convert the integer into a date time object.


text:
Q: no such file or directory found error while creating a docker image I want to creat or build a docker image using the command below:
docker build -t project/test:v1 .

I have a Dockerfile in which one command is failing as such:
Step 9/13 : COPY --from=ams-fe /fecode/dist /usr/share/nginx/html
COPY failed: stat /var/lib/docker/overlay2/16fd63a9ce16d7d132ab6bb9c768c76c5670c9fe60a6e06440607ac6e6af911c/merged/fecode/dist: no such file or directory

Can anyone help what is the issue with this command as I am using it for Nginx based web server ?
Below image shows the error in this regard.

Thanks

A: I see two different things:

*

*JavaScript heap out of memory
Try launching docker container with more memory reservation, checking previously that you don't exceed kernel available memory.
cat /proc/meminfo

With this data, do:
docker run --memory-reservation=XXX --kernel-memory=XXX ...

More information in docker documentation

*COPY failed
You're building docker executing docker build in a directory which doesn't have path to /fecode/dist
Note that Dockerfile checks locally existence of files to copy.


text:
Q: Why isnt the acceleration of the first system the same as the acceleration of the second system from a conceptual standpoint? I am having a hard time understanding conceptually why the acceleration of the system is different in the first two cases. Specifically, how could block A possibly know whether block B is a block or just someone pulling on it?

A: Observation #1: The first system has a mass of 300lb.  The second system has a mass of 200lb.
The same net force on each system will create accelerations with different magnitudes.
Observation #2: Looking at the first system with the unequal weights, we expect the system to allow the greater mass to accelerate downward and the lighter mass to accelerate upward.
If the lighter mass is accelerating upward, it must be pulled by a tension that exceeds 100lb of force.  But the second system has a tension of exactly 100lb of force.  So again the systems are not identical.


text:
Q: what's the rationale behind setting margin to @line-height-computed / 2 in bootstrap? I'm reading an article about Vertical Rhythm which promotes the idea of vertically aligning elements according to rhythmic unit. I assumed that perhaps bootstrap's team tries to adhere to that principle when designing their typography styles. But it doesn't seem to be so. For example, having the following presets:
@font-size-base:          14px;
@line-height-base:        1.428571429; // 20/14
@line-height-computed:    floor((@font-size-base * @line-height-base)); // ~20px

body {
  font-size: @font-size-base;
  line-height: @line-height-base;
}

in order to adhere to rhytmic unit of 20px (@font-size-base * @line-height-base) the margin of a paragraph should be 20px (@line-height-computed), where in bootstrap it's currently set as 10px (@line-height-computed / 2).
So what's the idea behind the typography settings in bootstrap (it doesn't seem to be the Vertical Rhythm) ?
PS. Any way I can ask this question to bootstrap's team?


text:
Q: Edit Client-Side Aspxgridview objectdatasource that is in memory I am using VS 2013.  I am trying to create a "work order".  Currently, the user selects the items from an Inventory grid.  Then they click a button "View Selection" and the next page opens with the selected items which are in an Aspxgridview.  Here, the user should enter the quantity for each item.  How do I save the edits?
ViewWorkOrder.aspx/Aspxgridview:
 <dx:ASPxCallbackPanel runat="server" ID="ASPxCallbackPanelList" ClientInstanceName="CallbackPanelList" ClientSideEvents-EndCallback="OnEndCallback" EnableTheming="False">
                    <ClientSideEvents EndCallback="OnEndCallback"></ClientSideEvents>
                    <PanelCollection>
                        <dx:PanelContent>
    <dx:ASPxButton ID="ASPxButtonRequestItems" runat="server" EnableTheming="True" Text="Request Items" Theme="Office2003Olive" >
     </dx:ASPxButton>

  <dx:ASPxGridView ID="GridViewWorkOrder"  ClientInstanceName="GridViewWorkOrder" runat="server" AutoGenerateColumns="False" DataSourceID="InventoryDataSource" EnableTheming="True" Theme="Office2003Olive" KeyFieldName="Item_ID">

      <Columns>
           <dx:GridViewDataTextColumn FieldName="Item_ID" VisibleIndex="7" Visible="False" Width="0px">
               <Settings AllowAutoFilter="False" AllowGroup="False" AllowSort="False" />
          </dx:GridViewDataTextColumn>
          <dx:GridViewDataTextColumn FieldName="Order_ID" VisibleIndex="8" Visible="False">
          </dx:GridViewDataTextColumn>
          <dx:GridViewDataTextColumn FieldName="User_ID" VisibleIndex="9" Visible="False">
          </dx:GridViewDataTextColumn>
          <dx:GridViewDataDateColumn FieldName="Date_Of_Order" VisibleIndex="1" Caption="Date" ReadOnly="True">
          </dx:GridViewDataDateColumn>
          <dx:GridViewDataTextColumn FieldName="Warehouse" VisibleIndex="6" Caption="WH" ReadOnly="True">
          </dx:GridViewDataTextColumn>
          <dx:GridViewDataTextColumn FieldName="Department_Selected" VisibleIndex="10" Visible="False">
          </dx:GridViewDataTextColumn>
          <dx:GridViewDataTextColumn FieldName="Equipment_Selected" VisibleIndex="11" Visible="False">
          </dx:GridViewDataTextColumn>
          <dx:GridViewDataTextColumn FieldName="Item_Selected" VisibleIndex="4" Caption="Item#" ReadOnly="True">
          </dx:GridViewDataTextColumn>
          <dx:GridViewDataTextColumn  FieldName="Quantity_Of_Order" VisibleIndex="2" Caption="Enter QTY" Width="5px" >
              <FilterCellStyle Wrap="True">
              </FilterCellStyle>
              <HeaderStyle Wrap="True" />
              <CellStyle BackColor="#CCFF99">
              </CellStyle>

          </dx:GridViewDataTextColumn>
          <dx:GridViewDataTextColumn FieldName="Cost_Of_Item" VisibleIndex="3" Caption="Cost" ReadOnly="True">
              <PropertiesTextEdit DisplayFormatString="{0:c}">
              </PropertiesTextEdit>
          </dx:GridViewDataTextColumn>
          <dx:GridViewDataTextColumn Caption="Item" FieldName="Item_Description" ShowInCustomizationForm="True" VisibleIndex="5" ReadOnly="True">
          </dx:GridViewDataTextColumn>
      </Columns>

      <SettingsBehavior AllowFocusedRow="True" />
      <SettingsEditing Mode="Batch">
      </SettingsEditing>
      <Settings ShowFooter="True" />
      <SettingsDataSecurity AllowDelete="False" AllowEdit="True" AllowInsert="False" />
  </dx:ASPxGridView>

    <asp:ObjectDataSource ID="InventoryDataSource" runat="server" SelectMethod="GetCheckBoxInventoryItem" TypeName="GetGridData" >
        <SelectParameters>
            <asp:Parameter Name="User_ID" Type="Int64" />
        </SelectParameters>
    </asp:ObjectDataSource>

                </dx:PanelContent>
                </PanelCollection>
            </dx:ASPxCallbackPanel>

There is no code behind other than a page load event that has nothing to do with the grid at this point.
There is no updatemethod set up. This is why I'm getting the error. (see pic, it is the topmost pic.) That's where I need help...
Here is the code that populates the ObjectDataSource:
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.IO
Imports System.Data.SqlClient
Imports System.Web
Imports System.Web.HttpContext
Imports System.Drawing
Imports System.Web.HttpApplication

Public Module GetGridData

    Dim _FilteredInventoryList As New List(Of Inventory)

    Public Function GetCheckBoxInventoryItem(User_ID As Long) As List(Of OrderItem)

        Dim ItemList As Object = Split(mUser.SelectedInventoryCheckBox, "|")
        Dim _OrderItems As New List(Of OrderItem)
        _OrderItems.Clear()
        For Each r As String In ItemList
            Dim SelectedItem As String = Trim(r)
            _FilteredInventoryList = mInventorys.FindAll(Function(x) Trim(x.ID_Number) = SelectedItem)
            Dim _OrderItem As OrderItem
            For Each p In _FilteredInventoryList
                _OrderItem = New OrderItem
                With _OrderItem
                    .Item_ID = p.ID_Number
                    .Item_Selected = p.Item_Number
                    .Item_Description = p.Item_Description
                    .Cost_Of_Item = p.Current_Cost
                    .Quantity_Of_Order = Nothing
                    .Date_Of_Order = Now
                    .Warehouse = p.Warehouse_Location

                End With
                _OrderItems.Add(_OrderItem)
            Next
        Next
        GetCheckBoxInventoryItem = _OrderItems
    End Function

I don't need to update the actual database.  I just mainly want to save it and then click on the "Request Items" button and it will email order to a warehouse.
Thanks in advance!

A: I'm not familiar with VB. So I'll try my best here.
First:
 - You need to create an Update method in GetGridData class;
Public Function UpdateWorkOrder(pUser_id as long, pQuantity_Of_Order as decimal)
{
    /* UPDATE on database WorkOrder code */
}

Second:
 - Go on asp:ObjectDataSource ID="InventoryDataSource" and set the UpdateMethod as the method created above;
<asp:ObjectDataSource
    ID="InventoryDataSource" runat="server"
    TypeName="GetGridData"
    SelectMethod="GetCheckBoxInventoryItem"
    UpdateMethod="UpdateWorkOrder">
    <SelectParameters>
        <asp:Parameter Name="User_ID" Type="Int64" />
    </SelectParameters>
    <UpdateParameters>
        <asp:Parameter Name="User_ID" Type="Int64" />
        <asp:Parameter Name="Quantity_Of_Order" Type="Decimal" />
    </UpdateParameters>
</asp:ObjectDataSource>

If the grid already has an update button on the column that the user is editing, you do not need to do anything else


text:
Q: Create a link in Twig with translate filter I'm trying to create an email link with only Twig tags. I've read numerous posts here but I can't get this one working! The problem I'm facing is that a string must get a translate filter in it.
The link itself is for email purpose.
So what I try to make is a link like this:
http://www.website.com/service/?subject=1234&message=Desired+amount
So what I tried is this:
{{ ('service?subject=' ~ product.code | url_encode) | url }} // This works perfectly

Now I want to add the &message part, so what I did is this:
{{ ('service?subject=' ~ product.code  ~ '&message=' ~ (Desired amount | t) | url_encode) | url }}

As you can see the Desired amount needs to have a translate tag (which is t by the way).
Offcourse this doesn't work.
Does anybody know how to create such link with a filter in it?
I'm really pulling my hair out right now :(

A: Something like this:
configure a route:
# example
acme_demo_service:
    path: /service
    defaults:
        _controller: AcmeDemoBundle:Test:service

Use url function:
{% set link = url('acme_demo_service', {'subject':product.code, 'message':'Desired amount'|trans}) %}
{{ link }}


text:
Q: iptables logging doesn't log I'm trying to log any requests to port 22 into my syslog, so I have following line in my iptables:
LOG        tcp  --  anywhere             anywhere            tcp dpt:ssh LOG level debug

yet, when I ssh in, nothing gets logged. I'm using RHEL6 (6.2)
Any ideas why?

A: I've used the following to log new connections to port 22
iptables -I INPUT -p tcp -m tcp --dport 22 -m state --state NEW  -j LOG --log-level 1 --log-prefix "New Connection "

This rule only logs new connections to port 22. It logs to /var/log/messages on the CentOS box I have to hand

Nov  8 16:20:54 centos6 kernel: New Connection IN=eth0 OUT= MAC=00:0c:29:d2:2c:38:00:0c:29:fe:8e:bb:08:00 SRC=192.168.1.73 DST=192.168.254.188 LEN=52 TOS=0x00 PREC=0x00 TTL=126 ID=9880 DF PROTO=TCP SPT=63861 DPT=22 WINDOW=8192 RES=0x00 SYN URGP=0

Note that iptables actions rules in the order they are defined so if you used iptables -A to add your rule to an existing ruleset then it's possible that packets are being accepted or denied by an earlier rule and your log action is never erm actioned.


text:
Q: Azure SSO with SAML for Communities Setup What endpoints are used for Communities when setting up Azure SSO with SAML via these steps? Particularly in reference to Sign-on URL, Reply URL and Identifier.
The only configuration shown is for actual Org logins but I want community login functionality. How can this be achieved?

A: Go to Setup > Connected Apps and open your connected app.  In the SAML Login Information section, expand the For Communities subsection and you'll see the endpoints for each of your communities.


text:
Q: Does Xcode require me to move Keychain contents to my new Mac? I am moving to a new Mac for the first time since I published my App to the App Store.
I have noticed there are things inside Keychain of kind "certificate" and "private key" called "Apple Development: xxx" "iPhone Developer: xxx", "iOS Developer: xxx", "Developer ID Certification Authority" etc.
What are these and do I need to move them to my new Mac?
Or will the Xcode regenerate all of this?
Also, do I need to move anything else (from the Keychain or elsewhere) to my new Mac in order to be able to continue the development of my apps and be able to upload the updates to the App Store?
Any help would be much appreciated!