text:
Q: how to send data (filled in a application form in my android app) to website( my local host)? I am a new android developer . I am building an app , in which a registration form is filled and its contents data is to be stored on the local host of mine . I have made the form but i don't know how to code for sending the data to local host. help me code from the basic so that WHEN A SEND BUTTON IS CLICKED , THE DATA FILLED IN THE FORM GETS STORED ON THE LOCAL HOST.
this is my code..................................
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_activity_server);
    send1 = (Button)findViewById(R.id.Send);

    send1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            // TODO Auto-generated method stub
            testInput ti=new testInput();
                //Create the intent

               ti.postData("Sent Data");

            TextView num1View = (TextView) findViewById(R.id.T5);
            num1View.setText("your data is stored");

            //Create the intent

        }
    });

}
public void postData(String toPost) {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("my local host name");

    //This is the data to send
    String name = toPost;
    String number= toPost;
    String email =toPost;
    String suggestion= toPost;//any data to send

    try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("action", name));
    nameValuePairs.add(new BasicNameValuePair("action", number));
    nameValuePairs.add(new BasicNameValuePair("action", email));
    nameValuePairs.add(new BasicNameValuePair("action", suggestion));

    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String response = httpclient.execute(httppost, responseHandler);

    //This is the response from a php application
    String reverseString = response;
    Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show();

    } catch (ClientProtocolException e) {
    Toast.makeText(this, "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
    // TODO Auto-generated catch block
    } catch (IOException e) {
    Toast.makeText(this, "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
    // TODO Auto-generated catch block
    }

    }//end postData()

A: *

*You will need to get the values of your fields. Assuming they are EditText, write something like yourEditText.getText().toString() to parse it as Strings and get the fields you will send.

*To send them, you may want to read Android Volley Tutorial - Making HTTP GET, POST, PUT, DELETE Requests

A: Follow this few steps
1) collect data into variable or in Array
2) make connection with database
3) get your database in writeable mode
4) fire insert query and close your database


text:
Q: $L^p$ norm of diagonal is $\leq$ Schatten $L^p$ norm Let $A = (a_{ij})$ be an $n\times n$ symmetric matrix. Its Schatten norm is defined by $\|A\|_{S^p}^p = \sum_{j=1}^n |\lambda_j|^p$, where $\lambda_j$ are the eigenvalutes of $A$. I am trying to prove that $\sum_{j=1}^n |a_{jj}|^p \leq \|A\|_{S^p}^p$.
I know we can find an orthogonal matrix $Q$ with $Q^T A Q = diag(\lambda_j)$. So, we need to show that the $L^p$ norm of the diagonal of $Q^T A Q$ is at least the $L^p$ norm of the diagonal of $A$. However, I cannot find a way to do this. Any suggestions?

redpajama_set_name: RedPajamaStackExchange


text:
Q: json to postgis stored in csv I have a csv file Author, Name, Geometry.
The Geometry column in the csv has rows like this
{"type": "Point", "coordinates": [11.6285463, 42.4193742]}

How do I import the json as geometry?
I can import the csv to an existing table using the following:
copy locations FROM path/to/file/pleiades-locations.csv' DELIMITERS',' CSV HEADER;

I have the geometry column set as json, but no geospatial data is available when I connect with QGIS, do I have to do some conversion?

A: Use ST_GeomFromGeoJSON to cast your geometry from geojson to PostGIS geometry.  (The converse is ST_AsGeoJSON).  If more convenient, you can always add a geometry column (since you've imported everythign already) and then use the cast to set its value for each row.

Assuming you have the table imported, it will be just a normal database table with no true geometry column (in the PostGIS understanding of the term).  You need to first add a geometry column (see SQL in documentation).  Then do your update (asuming you have called the geometry column 'geom' and the existing json geometry column is (say) 'geomjson':
UPDATE table_name SET geom = ST_GeomFromGeoJSON(geomjson);

I'm not sure there is a way to do the import directly as per your comment below.  Using ogr2ogr you can do it if the geometry is in the the form of WKT, XYZ etc or you can tell it lat and lon columns (see here).  But there are no options in OGR or Postgis that I know of to directly handle the JSON on import.  However, the above is very simple and you could even rename the JSON column to something else if you want to use the name 'geometry' for the geometry column (though the shortened 'geom' is a common naming convention).  As your data have already been imported, this is also the quickest solution in this case.

A: It turned out I needed to set generic geometry! Here's my solution:
ALTER TABLE locations ALTER COLUMN geom SET DATA TYPE geometry;
UPDATE locations SET geom = ST_GeomFromGeoJSON(geometry);


text:
Q: Unable to Resolve Module React Native + Android I seem to consistently be getting an error similar to below whenever I reach this specific point when working w/ React Native apps.

I create an /App folder with an AppContainer.js file I create a functional component in app/index.js (App & app are two different directories) which renders the AppContainer component. app/index.js looks like this.
import React from 'react'
import { AppContainer } from '~/containers'

export default function SnapshelfApp (props) {
    return (
        <AppContainer />
    )
}

I export AppContainer in containers/index.js
export AppContainer from './App/AppContainer'

It seems like always around this point I get an error saying it's unable to resolve the module and gives me some weird route that doesn't exist.
In iOS I've had this issue and I run react-native start --reset-cache and that solves the issue. I tried the same thing w/ Android but still getting the same error.
I'm also using babel-root-import but my babelrc file is setup fine so I don't see that being the issue.
My project structure is below. The error seems to be skipping over the /app directory.

Any suggestions?


text:
Q: Approximate my grade in a class, based on knowledge of the curve that was used Suppose I took an exam in a class and I know the raw percentage I scored. The average of the class was low, so the professor decides to curve the scores. Now, the professor provides a list of letter grades (US grading system) and the lowest raw percentage necessary to score into that letter. Example:

*

*A+: 95%

*A: 89%

*A-: 84%

*B+: 79%

*etc...

Each of the letters corresponds to a percentage, so A+ means 97%, A means 93%, A- means 90%, etc. With the information I have, I know which letter grade "bucket" I fall into (i.e. which percentage range my curved score falls into).
The problem I'm interested in solving is this: given only the above information, what would be the best way to approximate the percentage score I have with the curve? I know which range of percentages I have, but how would I make a good estimate of my actual percentage? I'm not so much interested in this question for practical purposes, but mainly out of curiosity.
Additionally, I may or may not know the mean, median, and standard deviation of the entire class's raw scores. However, since I don't know the type of curve the professor used, I'm not sure if that's relevant for solving this problem.


text:
Q: Mac Python 3.4.4, importing files/images, tkinter I am having difficulty displaying an image on a canvas using tkinter. I believe the problem arises from me improperly loading the image. Below is the code that I am trying to make work. The " file='Users/ramos1992/Desktop/test_image.gif' " is my attempt at loading an image from my desktop.
from tkinter import *
tk = Tk()
canvas = Canvas(tk, width=400, height=400)
canvas.pack()
my_image = PhotoImage(file='Users/ramos1992/Desktop/test_image.gif')
canvas.create_image(0, 0, anchor=NW, image=my_image)

mainloop()

What is the correct method of loading files using a Mac and how can I make the code work?

A: The path /Users/ramos1992/Desktop/test_image.gif, which a leading slash, is an absolute path: it starts at the top of your hard disk, gets the directory named Users there, then gets the directory named ramos1992 there, and so on.
The path Users/ramos1992/Desktop/test_image.gif, without a leading slash, is a relative path: it starts in the current working directory. Which may be, say, /Users/ramos1992/Documents/Python Projects. So, you end up looking in /Users/ramos1992/Documents/Python Projects/Users/ramos1992/Desktop/test_image.gif, and of course there's no such location.
See absolute and relative paths on Wikipedia for more details.

Just in case you (or someone else reading this) was a classic Mac expert back in the old days and is confused: absolute vs. relative paths have almost the exact opposite syntax between classic Mac OS-style paths and modern Mac OS X-style (Unix) paths. The old-style Drive:Folder:Folder:File with no prefix is /Drive/Folder/Folder/File, while the old-style :Folder:File with a prefix is ./Folder/File, which is effectively the same as Folder/File, with no prefix.


text:
Q: Which of these is a better php function? Given below are two PHP functions which basically does the same thing, What i want to know is which one of these is the best to use?
$lang is an array which stores other values
$lang = array(

    'default' => 'This is the default text',

    'site' => array(
        'name' => 'Website',
        'url' => 'website.com',
    ),

    'logo' => 'images/logo',

);

and please note that i will be using one of these function throughout the application for displaying text as the application i am building support multiple languages.
Function 1:
function lang($text='default') {

    global $lang;

    $text = explode(',',$text);

    if(!empty($text[1])) {
        $newtext = $lang[$text[0]][$text[1]];
    }
    else {
        $newtext = $lang[$text[0]];
    }

    echo $newtext;

}

Usage : <?php lang('default'); ?> or <?php lang('site,name'); ?>
Function 2:
function lang($text='default', $text2='') {

    global $lang;

    if(!empty($text2)) {
        $newtext = $lang[$text][$text2];
    }
    else {
        $newtext = $lang[$text];
    }

    echo $newtext;

}

Usage : <?php lang('default'); ?> or <?php lang('site','name'); ?>

A: In my opinion, second function is more logical by the arguments.
And explode function in first one is slower than operations with arrays in second.

A: I prefer function 2:  it is far more obvious that there are two parameters.

A: The second, but I would rather split it into two methods.
Ex:
GetLanguage($site)
   returns an associative array of strings

And
GetLanguageKeyValue($site, $key)
    returns value as string


text:
Q: NetworkXError: Adjacency matrix not square: nx,ny=(737, 39) How can I solve this error?
import networkx as nx
df=pd.read_excel('peso-ao-nascer.xlsx')

G=nx.from_numpy_matrix(array)
So I have this:
NetworkXError: Adjacency matrix not square: nx,ny=(737, 39)

A: Adjacency matrices must be square because the "index" of the rows and columns are from the same set, the set of the nodes in the graph.
From Wikipedia:

In graph theory and computer science, an adjacency matrix is a square matrix used to represent a finite graph. The elements of the matrix indicate whether pairs of vertices are adjacent or not in the graph.

Therefore, in order to fix your issue, you have to determine why there is a case where a non-square matrix is being used as an adjacency matrix.
Likely:

*

*There is an issue with where you are getting that matrix, and they did not provide an appropriate adjacency matrix

*You are using a matrix which was not meant to be an adjacency matrix

*You do not mean to use that matrix as an adjacency matrix

Sorry if my answer is a bit general, it is hard to provide a more specific answer without more information.


text:
Q: loading same jquery code in multiple jquery tabs I have jquery datepicker in my document a few times, dependent on which "" is called.
If I have datepicker more than 1 time in the document, it doesn't load at all.
How do I overcome this problem?

TITLE

<input onFocus="blur();" class="appt_date" id="day_selected">

ITEM

ITEM

ITEM

                    <input type="hidden" class="link" value="confirmation" />

                    TITLE

<input onFocus="blur();" class="appt_date" id="day_selected">

ITEM

ITEM

ITEM

                    <input type="hidden" class="link" value="confirmation" />

`

A: The problem is that you have multiple IDs named "datepicker" on your site.
You must not use an ID more than once.
Rewrite your code to use a class:

Then in your JavaScript:
$('.datepicker').datepicker();


text:
Q: Build OS X takes too much time
*

*I'm using the latest version of Android Studio

*it's not a project issue because on two other 3 others pcs (one OS X and two Windows) it compiles well

*I'm encountering this problem with all AS projects on this Mac

When I open the project and gradle try to build debug variant after have downloaded all dependencies, the build never finish, it remains to:
Gradle: Resolve dependencies ':app_debugCompile'

I tried also to speed it up using in gradle.properties
org.gradle.parallel=true
but it doesn't work.
Can someone help me to understand what could be happened on this Mac?
SOLVED
It was a dependency in an external repository that doesn't work with a long connection timeout.

A: The problem is because of dependencies in an external repository Gradle cannot connect to, and the connection doesn't fail immediately but only after a very long timeout.
Either use repositories that are more reliable to connect to, or copy the dependencies locally to your project.


text:
Q: IE compatibility mode forced when using internal ip Im working a web app in asp.net, using ajax and jQuery, and C# as the programming language on VS2010. The prod server is a 2008 R2 and users use Internet Explorer 9 (cant use Chrome or other) on Win7 PCs.
My issue is that users are seeing my webpage in compatibility mode in IE causing the update panels to stop working, inserts are not showed, cascade drop-downs doesn't update and CSS rounded corners doesn't show.
If users access the site via the external domain everything works great, but most users doesnt have access to internet and use the internal IP, then theres when the issue shows up.
How can I make the site open in normal mode when users use the internal IP?
Thanks in advance.

A: Add in head section of html document this line:
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />


text:
Q: Inserting profile in a linked list This code is for adding an employee profile at the beginning of a linked list. For some reason, which i cannot identify, this code worked once, and then it just printed the printf and then exited the loop. Even after entering numerous records, it was still doing the same thing. So can anyone identify the problem??
void insert_tobeg() {
    char name[15];
    struct employee *newPtr;
    printf("\n\n\tEnter the record to be entered:");
    gets(name);

    if(strcmp(start->name, name) == 0) {
        curr = (struct employee*)malloc(sizeof(struct employee));
        employee_entry();
        curr->newPtr = start;
        start = curr;
        printf("\n\n\tRecord has been added at the beggining!");
        return;
    }
}

A: Did you mean while loop instead if, and remove return statement.

A: You manage it incorrect, you overwrite the name in first element, you need to write to the currently allocated ellement.
Try something like this
curr = (struct employee*)malloc( sizeof(struct employee));
employee_entry();
if( strcmp( curr->name, name) == 0)
{
    curr->newPtr=start;
    start = curr;
    printf("\n\n\tRecord has been added at the beggining!");
    return;
}
else
{
    free(curr);
}

And don't cast malloc result in C


text:
Q: Editar un archivo de texto o html desde bat He hecho una variable donde se el usuario introduce un nombre y se guarda en esa variable:
@echo off

echo Introduce el CID de tu RIF:
set /p cid=

PAUSE>Nul

Ahora lo que necesito es que lo que el usuario introduzca en esa variable se escriba en un archivo .js


text:
Q: iOS branch.io Pass an user developer identity to an install event in webhook We use a webhook for an install event. In our iOS app we set the identity with the method Branch.getInstance().setIdentity() before calling Branch.getInstance().initSession(launchOptions:...). But in the JSON response from a branch server about the INSTALL event we don't see developer_identity value. (But this value exist in an OPEN event)
Is it correct behavior?

A: The INSTALL event occurs before the setIdentity() call in the lifecycle. Hence, this is the intended behavior and the INSTALL event will never have the developer identity.

A: That's correct. You will need to use the IDFA/GAID from the Install event to tie it back.


text:
Q: Consume PDF stream into jsp I am trying to display PDF report inside jsp

*

*I have PDFstream available using following code
private void generatePDFReport(OutputStream stream, JasperPrint jasperPrint) throws JRException {
JRPdfExporter jrpdfexporter = new JRPdfExporter();
jrpdfexporter.setExporterInput(new SimpleExporterInput(jasperPrint));
jrpdfexporter.setExporterOutput(new SimpleOutputStreamExporterOutput(stream));
SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
jrpdfexporter.setConfiguration(configuration);
jrpdfexporter.exportReport();

}
now I am outputstream which is basically PDF Stream which i want to display into jsp, I dont want to set whole response contenttype as application/pdf but i want to embed pdf into part of jsp output
So i convrted pdfstream output into bytearray and trying to display using following
<script language="Javascript">
function loadDoc() {
    alert('called loadDoc');
    var xhr = new XMLHttpRequest();
    alert('called xhr');

    xhr.responseType = 'arraybuffer';
    alert('called responseType');

    alert('called xhr.onload ');

    // Create the Blob URL:
    var buffer = xhr.response;
    var blob = new Blob([<%=byteCharSet%>], {
        type: 'application/pdf'
    });
    var objectURL = URL.createObjectURL(blob);
    alert(objectURL);

    // Create an iframe to demonstrate it:
    var iframe = document.createElement('iframe');
    iframe.className = 'sample-iframe';
    iframe.src = objectURL;
    document.body.appendChild(iframe);
    console.log(objectURL);

    //xhr.open('GET', 'https://cors-anywhere.herokuapp.com/http://www.xmlpdf.com/manualfiles/hello-world.pdf', true);
    //xhr.send();
}
</script>

but when I am trying to execute javascript couldn't understand bytearray output it simply getting failed blob value getting displayed as below in view page source
     var blob = new Blob([%PDF-1.4
    %����
    3 0 obj
   <</Filter/FlateDecode/Length 625>>stream
   x���M��0@��>��um�'�v�������C
   ^���V�����Ķ�H����3�?�}� �    �q�D3�
   q�`�e��˼'��Do?1�(Ξ�h��2s�S(^�����gĈ^�/b��a�r"\"���_���Г�Lw

A: I used Iframe to solve this issue.
In iframe for src i used another jsp.
       out.write("<iframe src= displayPDF.jsp" + " " + "type=application/pdf width=100% height=600px ");
            out.write("</iframe>");

following is the displayPDF.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%><%
    byte[] pdfByteArray = (byte[]) session.getAttribute("PDFbyteArray");
    if (pdfByteArray == null)
        System.out.println("pdfByteArray is null");
    response.setHeader("Content-Disposition", "inline; filename=\"MyFile.pdf\"");
    response.setContentType("application/pdf; name=\"MyFile.pdf\"");
    ServletOutputStream serv_out = response.getOutputStream();
    serv_out.write(pdfByteArray);
    serv_out.flush();
    serv_out.close();
    out.clear();
    session.removeAttribute("PDFbyteArray");%>


text:
Q: How to retrieve the target value key for a target value that is contained within a dictionary of lists of values without using a for loop? I have the following dictionary.  Each key contains a list of unique values:
d = {1:[10,11,12],2:[13,14],3:[15,16,17,18],4:[19],5:[20]}

I want to return the key for specified target value as per the example below (this does return the desired result).
keys = list(d.keys())

values_lst = list(d.values())

target_value = 20

for i,values in enumerate(values_lst):
    if target_value in values:
        index = i

keys[index]

5

However, is there a way to achieve this result without deploying the for loop (at least explicitly).  The solution that I have does not feel particularly pythonic.
Thanks!

A: There always must be a loop somewhere, but you can do it with an one-liner:
d = {1: [10, 11, 12], 2: [13, 14], 3: [15, 16, 17, 18], 4: [19], 5: [20]}

target_value = 20

key = next(k for k, v in d.items() if target_value in v)
print(key)

Prints:
5

A: A more Pythonic solution, but still with an explicit for:
index = -1
for key, values in d.items():
    if target_value in values:
        index = key
        break
print(d[index])

This may be more readable than a one-liner (as in the other answer), but YMMV.


text:
Q: Centering a variable width grid while aligning its elements to the left Consider the following

          ....

Using images, basically what I have is something like this

As you can see the green blocks and the container are aligned to the left
What I want to acheive is something like this.

The .unit elements have constant width
The .grid element should expand with width (so that more unit elements would fit into 1 line) while being always centered within .container.
Any clue how to achieve that using only CSS (and maybe some html wrappers if necessary) ?

A: Let me begin by saying that this is an interesting question and my first thought was that flexbox is the way to solve this.  I have tried all manner of flexbox arrangements, but this type of solution eluded me.  So, below is the solution that uses floating, clearing, and media queries.
For this example, I have assumed that each row would have at least 3 and no more than 9 boxes.  However, you can extend this solution to handle anywhere between 1 and more than 9 boxes.
Here's HTML:

Here's a CSS that (1) performs a mini-reset to eliminate browser-applied paddings and margins that may interfere with sizing and (2) formats the .grid and its div children:
* {
    margin: 0;
    padding: 0;
}

.grid {
    display: table;
    outline: 1px solid blue;
    min-width: 330px;
    margin: 0 auto;
}

.grid > div {
    width: 100px;
    height: 61px;
    margin: 5px;
    background-color: teal;
    float: left;
}

The .container block was eliminated because .grid is displayed as a table.  The latter is a block that shrinkwraps around its children and margin: 0 auto can be applied to center it on the page.  The .grid's min-width of 330px assures that a minimum of three blocks can fit per line.  Whenever floating happens within a table element, its margins do not collapse, therefore no explicit clearing of floats (e.g., via clearfix) is necessary.
Each .grid div child takes 110px of horizontal space (100px width + 10px in left and right margins).  This number is important for the media queries code that follows below:
@media screen and (min-width: 330px) and (max-width: 439px) {
    .grid > div:nth-of-type(3n + 1) {
        clear: left;
    }
}

@media screen and (min-width: 440px) and (max-width: 549px) {
    .grid > div:nth-of-type(4n + 1) {
        clear: left;
    }
}

@media screen and (min-width: 550px) and (max-width: 659px) {
    .grid > div:nth-of-type(5n + 1) {
        clear: left;
    }
}

@media screen and (min-width: 660px) and (max-width: 769px) {
    .grid > div:nth-of-type(6n + 1) {
        clear: left;
    }
}

@media screen and (min-width: 770px) and (max-width: 879px) {
    .grid > div:nth-of-type(7n + 1) {
        clear: left;
    }
}

@media screen and (min-width: 880px) and (max-width: 989px) {
    .grid > div:nth-of-type(8n + 1) {
        clear: left;
    }
}

@media screen and (min-width: 990px) {
    .grid > div:nth-of-type(9n + 1) {
        clear: left;
    }
}

The rationale behind the code is this: if there is enough space to include only n blocks per line, then every (n + 1)th block's left edge is cleared, which moves the block to a new line.
And, here's a fiddle: http://jsfiddle.net/5hWXw/.  Resize the preview window to see the adjustments.

A: In your CSS, make sure:
1. In the .grid rule, text-align is set to center
2. In the .unit rule, display is set to inline-block. The div element is a block-level element and so each new element is displayed on a new line. Giving the display property a value of inline-block forces all the divs with class unit to be displayed on the same line (until there's no more space). Also text-align : center doesn't work with elements with display property set to block, and block-level elements have a display value of block by default.

A: You have to just give value to your classes like this,
.grid { text-align:center; }

.unit { display:inline-block; }

I hope this will solve your issue.
If not, than please show your full code via Jsfiddle.

A: @DRD's answer is nice but requires lots of media queries. If the following floats your boat however: don't look too far when it can be simple: set a padding-left/-right on your container...
.grid {
  padding: 0 5%;
}

You'll notice the whitespace is not even when the width isn't a multiplication of the .unit 's entire box (padding, margin, border, width). Setting a %-based width can help here.
See this fiddle for a test case. I've added a tiny bit of Javascript to adjust the padding dynamically, remove it to see the CSS-only result. EDIT: @DRD created a jQuery function which works better than my JS, see it here (don't forget to include jQuery if you want to use it).

A: It seems that a solution to this is similar to that in here Flex-box: Align last row to grid
First of all setting .grid to inline, then adding more div's with height: 0 would do the trick, number of extra div's should be atleast equal to max-number of units in 1 line (minus 1).
This is a bit incontinent, but still easier than defining multiple @media as @DRD suggested, and doesn't require javascript/window.resize() handling

.container {
   display: block;
   text-align: center;
}

.empty {
   height: 0 !important;
}

.grid {
   display: inline;
}

I still hope for a better solution using only css


text:
Q: Order of font and line-height in a rule set I didn't think the order of CSS within a rule set mattered, as long as there weren't implicitly duplicate rules (such as border and border-top).
In fact, many CSS Style Guides recommend an arbitrary order such as "By group" or "Alphabetically."
However, the order of font and line-height within a rule set can make a big difference:

div {border: 1px solid gray; float: left;}
#D1 {font: 20px arial; line-height: 3;}
#D2 {line-height: 3; font: 20px arial;}

This is a test

This is a test

A unitless line-height should be a multiplier of the font size.
But why does the font rule have to precede the line-height rule for this to happen?

A: Despite its name, line-height is actually part of the font shorthand. The shorthand declaration sets line-height to its initial value of normal, which overrides your previous line-height declaration.
To this end, you can incorporate line-height into the shorthand, as shown below with the addition of a #D3 element:

div {border: 1px solid gray; float: left;}
#D1 {font: 20px arial; line-height: 3;}
#D2 {line-height: 3; font: 20px arial;}
#D3 {font: 20px/3 arial;}

This is a test

This is a test

This is a test


text:
Q: For XML Union with a temp table I know how to do union's and spit out an XML file from different tables, however, I need to create  a temp table that will house 3 records that I need to be a part of the XML File. The structure is exactly the same as the other tables.
How would I go about doing this?
select * from
(
  select ID_Number as [ID], CLAST as [name/last], CFIRST as [name/first], '' as extension]
  from dbo.users as a
  union all
  select PID as [ID], NID as [name/last], NAME as [name/first],  PREF_TITLE as [extension]
  from dbo.Person
) as a
FOR XML PATH('employee'), ROOT('employees')

So I would need 3 lines of data, which will fill ID, name/last, name/first and extension.
What would be the best recommendation?

A: Create the temp table, fill it and add it into the query as another UNION ALL. There are different types of temporary table, here's some code that uses a table variable, the most simple type...
DECLARE @tempTable TABLE
(
  ID int,
  Surname varchar(30),
  FirstName varchar(30),
  Title varchar(30)
)

INSERT @tempTable VALUES (7, 'Siobhan', 'Green', 'Ms')
INSERT @tempTable VALUES (8, 'Paul', 'Jones', 'Mr')
INSERT @tempTable VALUES (9, 'Sam', 'Morrison', 'Mrs')

SELECT * FROM
(
  SELECT ID_Number as [ID], CLAST as [name/last], CFIRST as [name/first], '' as [extension]
  FROM users as a
  UNION ALL
  SELECT PID, NID, NAME, PREF_TITLE
  FROM Person
  UNION ALL
  SELECT ID, Surname, FirstName, Title
  FROM @tempTable
) as a
FOR XML PATH('employee'), ROOT('employees')

Click here to see it in action at SQL Fiddle


text:
Q: Questions regarding the degree of freedom and test statistic for the chi-squared test When using $\chi^2$ to test for goodness of fit, if there are $k$ categories then the $\chi^2$ distribution has $k-1$ degrees of freedom. I've seen explanations that the reason there is $k-1$ degrees of freedom is because if  we know the number of times the $k-1$ categories occurred (and sum of the $k$ categories), then we can figure out the number of times the last category occurred.

*

*Given that a $\chi^2$ distribution with $k-1$ degree of freedom is the sum of squares of $k-1$ independent standard normal distributions, is there a way to show that the number of occurrence of the $k-1$ categories are independent for an experiment testing the fairness of a die? If I know the number of times $1$ occurred (say 35 of 36 rolls are $1s$), doesn't that change the probability for the number of times $2, 3$, etc. can occur?

*For the test statistic $\chi^2 = \sum_{i=1}^{k}\frac{(O_i-E_i)^2}{E_i}$, if only $k-1$ categories are independent, why does the computation include the sum of all $k$ categories?

*Unrelated to the above, for a 2x2 contingency table (test for independence), if the 2 rows sum to $a$ and $b$, and the 2 columns sum to $c$ and $d$, such that $n = a + b + c + d$, is the expected value $E_{1,1}$ (for cell $(1,1)$), sampling with replacement $a$ times each with probability $c/n$? If so, why is this valid, if we select $a$ objects out of $n$ aren't we sampling without replacement?


text:
Q: ReactServer#RenderToString not rendering correctly I'm trying to accomplish server side rendering with React components in Express and templating with Jade. However I'm running into some issues.
Here is my server code, the entry point.
var app = require('express')();
var http = require('http').Server(app);
var React = require('react');
var ReactDOMServer = require('react-dom/server');

//Component
var Index = require('./views/components/index.jsx').default;

app.set('port', process.env.PORT || 3000);
app.set('views', `${__dirname}/views`);
app.set('view engine', 'jade');

app.get('/', (req, res) => {
  var reactHTML = ReactDOMServer.renderToString(<Index/>);
  res.render('test', { reactHTML: reactHTML });
});

http.listen(3000, () => {
  console.log(`listening on port ${app.get('port')}`);
});

Here is my Index component, it's actually just rendering a div with my ChatTextBox component, which is this:
import React, { Component } from 'React';

class ChatTextBox extends Component {

  constructor(props) {
    super(props);
    this.state = { term: 'test' };
    this.termChange = this.termChange.bind(this);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(event) {
    console.log('this was clicked');
    this.setState({ term: '' });
  }

  termChange(event) {
    console.log(event.target.value);
    this.setState({ term: event.target.value });
  }

  render() {
    return (

        <input type="text"
        value={this.state.term}
        onChange={this.termChange} />
        <button onClick={this.handleClick}>Send Message</button>

{this.state.term}

    );
  }
}

export default ChatTextBox;

edit:
Here is my jade template, test.jade
html
  body
    div#container
      #{reactHTML}

Problems:
1) It's not rendering properly. Here is the result:

It's rendering the component twice, along with the '<', '>' symbols..?
2) None of the hooks work, in terms binding state and rendering dynamically. This makes sense though, I'm rendering static HTML in jade. So how would I accomplish this dynamically? (I think this is a bit off topic, I can make a separate concern for this).
Thank you for reading, hopefully this post was clear enough.

A: It looks like you're using Jade potentially redundantly. The usual approach with reactDOM server-side is to send the result of renderToString() down to the client. If you do need to keep using Jade for whatever reason, you can tell it to unescape HTML strings with !=. So, you can change your template to:
html
  body
  div#container
   #{!=reactHTML}

That should ensure it's not double-rendering everything


text:
Q: Can I run Azure Cmdlets/Powershell scripts from code within an Azure Website? Long story short I have a Azure Powershell script (think Storage Account creation) that I want to run from within an Azure Website - is that possible at all?
If not directly from the website, can I put it in some sort of other resource that can be called?  What is the recommended way of going about this?  Thank you.

A: You can run PowerShell script within an Azure Web App or Web Job (or from Kudu Console). But there are some limitations coming from the sandbox.
If you run into a specific issue with it, feel free to ask a new question that targets that issue specifically.

A: Actually you can't execute a powerShell script within your Azure Website without limitations, but you can host your powershell script in an automation runbook
and execute it with an http call (webhook) from your Azure Website, besides another solution would be to create the storage account using
the Azure Management API.


text:
Q: Is it possible to restrict an input field (UITextView) to a particular pattern? I have a UITextView that I'd like to let the user enter tags in this pattern:

#these #are #four      #tags

and the above would be a valid input.
The following below would be bad input:

# this is #wrong ##formatting #bad#

Those are just some sample wrong cases that I came up with now, but the idea is to restrict the allowable input to the former example and then show an alert to re-enter otherwise.
Is there a way to accomplish this?  thank you!

A: Yep sure. You can use regex to restrict text inputs to ones that fit a particular pattern.
Apple NSRegularExpression Class Reference:
https://developer.apple.com/LIBRARY/IOS/documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html
NSRegularExpression Tutorial and Cheat Sheet:
http://www.raywenderlich.com/30288/

A: You can do this in the delegate method textView:shouldChangeTextInRange:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range  replacementText:(NSString *)text
{
    NSMutableString *newText = [NSMutableString stringWithString:textView.text];
    [newText replaceCharactersInRange:range withString:text];

    NSArray *tags = [newText componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    for (NSString *tag in tags) {
        if ([tag length] > 0 && ![tag hasPrefix:@"#"]) {
            return NO;
        }
    }

    return YES;
}

I believe there is a cleaner way using Regular expression than looping over the text


text:
Q: How to establish communication between a computer java application and a android phone? I have to do a project for the university. I have to connect the mobile phone (android application) with a java desktop project in order to exchange data.
below I propose what I have done for now:
Server1.java

package com.pervasive;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Server1 {
    private static Thread Thread1;
    static ServerSocket serverSocket;
    private static PrintWriter output;
    private static BufferedReader input;

    public static final int SERVER_PORT = 6789;

    public static void main(String[] args) throws IOException {

        Thread1 = new Thread(new Thread1());
        Thread1.start();
    }

    static class Thread1 implements Runnable{
        InetAddress inetAddress = InetAddress.getLocalHost();

        Thread1() throws UnknownHostException {
        }

        @Override
        public void run() {
            Socket socket;
            try {
                serverSocket = new ServerSocket(SERVER_PORT);
                System.out.println("Not connected!\nIP: " + inetAddress.getHostAddress() + "\nPort: " + SERVER_PORT + "\n");
                try {
                    socket = serverSocket.accept();
                    output = new PrintWriter(socket.getOutputStream());
                    input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    System.out.println("Connected\n");
                    new Thread(new Thread2()).start();
                } catch (IOException e){
                    e.printStackTrace();
                }
            } catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    private static class Thread2 implements Runnable{
        @Override
        public void run() {
            while(true){
                try {
                    final String message = input.readLine();
                    if(message != null){
                        System.out.println("Client: " + message + "\n");
                    } else {
                        return;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class Thread3 implements Runnable{
        private String message;
        Thread3(String message){this.message = message; }
        @Override
        public void run(){
            output.write(message);
            output.flush();
            System.out.println("Server: " + message + "\n");
        }

    }
}

While the following code is about the Android application.
MainActivity.java

package com.example.clientapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

@SuppressLint("SetTextI18n")
public class MainActivity extends AppCompatActivity {

    Thread Thread1 = null;
    EditText etIP, etPort;
    TextView tvMessages;
    EditText etMessage;
    Button btnSend;
    String SERVER_IP;
    int SERVER_PORT;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etIP = findViewById(R.id.etIP);
        etPort = findViewById(R.id.etPort);
        tvMessages = findViewById(R.id.tvMessages);
        etMessage = findViewById(R.id.etMessage);
        btnSend = findViewById(R.id.btnSend);
        Button btnConnect = findViewById(R.id.btnConnect);
        btnConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvMessages.setText("");
                SERVER_IP = etIP.getText().toString().trim();
                SERVER_PORT = Integer.parseInt(etPort.getText().toString().trim());
                Thread1 = new Thread(new Thread1());
                Thread1.start();
            }
        });
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String message = etMessage.getText().toString().trim();
                if (!message.isEmpty()) {
                    new Thread(new Thread3(message)).start();
                }
            }
        });
    }
    private PrintWriter output;
    private BufferedReader input;

    public void OnReceiveMessage(View view) {

        output.write((String) tvMessages.getText());
    }

    class Thread1 implements Runnable {
        @Override
        public void run() {
            Socket socket;
            try {
                socket = new Socket(InetAddress.getByName(SERVER_IP), SERVER_PORT);
                output = new PrintWriter(socket.getOutputStream());
                input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvMessages.setText("Connected\n");
                    }
                });
                new Thread(new Thread2()).start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    class Thread2 implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    final String message = input.readLine();
                    if (message != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvMessages.append("server: " + message + "\n");
                            }
                        });
                    } else {
                        Thread1 = new Thread(new Thread1());
                        Thread1.start();
                        return;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class Thread3 implements Runnable {
        private String message;
        Thread3(String message) {
            this.message = message;
        }
        @Override
        public void run() {
            output.write(message);
            output.flush();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvMessages.append("client: " + message + "\n");
                    etMessage.setText("");
                }
            });
        }
    }

}

The problem is the following: I can't connect them.
can you help me?


text:
Q: `type commit` in an annotated tag in git Echoing an annotated tag in git with git cat-file -p <hash-of-tag> produces something like this:
object <sha1-hash>
type commit
tag 0.0.1
tagger My Name (...)

Description of tag

object points to a commit object in my case. type commit implies this mustn't be the case necessarily. Are there cases where annotated tags don't point to commits?

A: Yes: an annotated tag object can point to another annotated tag object, or even directly to a tree or blob.  These are all fairly rare though.
The git rev-parse command—really, Git in general; rev-parse is just the user oriented interface to the routines—has the notion of "peeling" a tag, or even a commit, to reach a particular target object type.  For instance, if you want to view the tree attached to a commit or tag or hash ID:
git rev-parse whatever^{tree}
turns the whatever part into whatever it is, then attempts to "drill down" to the point where we get a tree object.  If whatever is an annotated tag, this follows the tag to its object, repeatedly, until it arrives at a non-tag, which by definition is either a commit, tree, or blob:

*

*If we've reached a tree, we are done.

*If we've reached a commit, each commit has one top-level tree, so we extract that commit's tree.

*If we've reached a blob, there is no tree to be found, so the command (whether that's git rev-parse or, e.g., git diff or git diff-tree) errors out.

Commands like git diff-tree that want a <tree-ish> automatically turn whatever argument you give them into the tree, as if you had added the ^{tree} suffix.  As you might expect, there are also ^{commit} and ^{blob} suffixes.  There is also a ^{tag} suffix, which simply verifies that something is indeed a tag (since no other object type can be resolved to a tag), and there is a ^{} suffix that means "resolve a tag to its object", i.e., peel off all annotated tags, then get whatever object remains.
The full rules are described in the gitrevisions documentation.  Note that not every Git command behaves as described: in particular, git checkout tries to treat its argument as a branch name before following the six-step process in gitrevisions.  This means that if the name foo can be both a tag and a branch, git checkout foo finds the branch (i.e., checks out refs/heads/foo), but git show foo shows the result of resolving the tag.

A: Yes you can tag any git object by passing its hash or other way of referencing it to git tag.
In addition to a commit, a tree (the directory listing referenced in a commit), blob (the file contents that are referenced in a tree) or even a tag may also occur in a tag.


text:
Q: Bash substitution cut off end of string I have bash script which should replace some placeholders in text template by users input.
#!/bin/bash
# Run this script as bash command like: bash create-apache-site.sh

read -p 'Write url without www and http prefixes: ' url

template=$(</etc/apache2/sites-available/000-default.conf)
template2=("${template/1*****/$url}")

echo "$template2" > /home/Camo/template.txt

Template file is multi-line string with placeholders (1*****, 2*****, ...) which looks like
<VirtualHost *:80>
        ServerAdmin xxxx.xxxxx@gmail.com
        ServerName 1*****

        ErrorLog ${APACHE_LOG_DIR}/www/2*****/error.log
        CustomLog ${APACHE_LOG_DIR}/www/3*****/access.log combined

        DocumentRoot /var/www/html/4*****
        <Directory /var/www/html/5*****/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                allow from all
                Require all granted
        </Directory>
        RewriteEngine on
        RewriteCond %{SERVER_NAME} = 6*****
        RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

But the result of this script is this damaged file
<VirtualHost *:80>
        ServerAdmin xxxx.xxxxx@gmail.com
        ServerName ooooooooooooooo.com

As you can see substitution cut off the end of the string. Can somebody tell me please what is wrong with it? Thanks a lot.

A: You have to escape your * for the replace to work.
Maybe a better way is to not use * as your placeholder? But I leave that up to you.
Try this:
(I also made the replacement global so that you can reuse the same placeholder several times within the file)
#!/bin/bash
# Run this script as bash command like: bash create-apache-site.sh

read -p 'Write url without www and http prefixes: ' url

template=$(</etc/apache2/sites-available/000-default.conf)
template2=("${template//1\*\*\*\*\*/$url}")

echo "$template2" > /home/Camo/template.txt


text:
Q: C# LINQ Add to list every regex value group I have this code
Regex containsDelimitersInBrackets = new Regex(@"\[(.*?)\]");

foreach (Match match in containsDelimitersInBrackets.Matches(_sequence))
    _separator.Add(match.Groups[1].Value);

I'd like to use LINQ to add each value of each group to the _separator list.
I've tried this.
 _separator.AddRange(containsDelimitersInBrackets.Matches(_sequence).Where(x => x.Groups[1].Value));

but it doesn't work. What would be the correct way to do this?

A: Matches can return 1 or more Matches, so you can get the group 1 value(s) from the Match(es) using Select and then flatten that collection using SelectMany to get each value of each group separately.
Then you can use addRange to add the collection to the _separator list.
For example
List<string> _separator = new List<string>(){"existing item"};
Regex containsDelimitersInBrackets = new Regex(@"\[([^][]*)]");

List<string> _sequence = new List<string>(){"test[1] test[2]", "test[123]"}
.SelectMany(s =>
    containsDelimitersInBrackets.Matches(s)
    .Select(m =>
        m.Groups[1].Value
    )
).ToList();

_separator.AddRange(_sequence);
_separator.ForEach(s => Console.WriteLine(s));

Output
item one
1
2
123

Note that instead of the non greedy quantifier, you can also use a negated character class to prevent some backtracking.
Regex containsDelimitersInBrackets = new Regex(@"\[([^][]*)]");

See a C# demo.

A: You were close..
We don't use .Where to project value x (i.e. a Match object) into value y (i.e. a string), we use .Select
_separator.AddRange(containsDelimitersInBrackets
  .Matches(_sequence)
  .Cast<Match>()
  .Select(x => x.Groups[1].Value)
);

You also need a .Cast<T>() when working with old school xxxCollection classes to make LINQ work easily with the type returned from their enumerators.. Otherwise the compiler treats it as an enuemration of objects and you don't ver a very helpful intellisense. ( If you wrote foreach(var m in someMatchCollection) then m would be object.. When you write foreach(Match m in someMatchCollection) it takes the type hint from how you declared m)


text:
Q: Implement an algorithm in Scala to determin if a string has all unique characters I am solving trivial problems to learn Scala. Here is what I have come up with
def isUnique(str: String): Boolean = {
    if (str.length > 128) return false
    val uniqueChars = new Array[Boolean](128)

    !(str.map(c => addChar(c, uniqueChars)).find(identity).isDefined)
}

def addChar(ch: Char, uniqueChars: Array[Boolean]): Boolean = {
    if (uniqueChars(ch)) return true else {
    uniqueChars(ch) = true;
    return false
}

Is that it?
Please note that I don't care about the logic or optimization at this point. I only need to learn the Scala way of doing it.
[Edit]
Let's assume we don't want to use the string distinct method. I only need to verify the functional style of Scala.

A: OK, so if you don't to want utilize the distinct library method then recursion is usually the functional way to go.
def isUnique(str: String, chrs: Set[Char] = Set()): Boolean =
  str.length == 0 ||
    !chrs(str.head) &&
      isUnique(str.tail, chrs + str.head)

isUnique("abcdexf")  // true
isUnique("abcdxxf")  // false
isUnique("fbcdexf")  // false
isUnique("abdbexf")  // false

A: You want to "learn scala way of doing it", by actually doing it in a way, that makes no sense to use in scala? Scala way of doing it str == str.distinct. If "you don't want to use distinct", then str.toSet.size == str.length. If you don't want toSet either, then str.groupBy(identity).values.map(_.size).forall(_ == 1).
If you don't want .groupBy then
str.sorted.sliding(2).forall(s => s.head != s.last)
Etc. ... At some point, "scala way" just stops being "scala way" and becomes a java program written in scala syntax.


text:
Q: Adding background image to ScnScene I have an app which uses SpriteKit and emitter particles (sks) which I find to be not as realistic as Scene kit's particles (scnp). So I wish to incorporate that into SKScene but I'm not sure if that is even possible. So I decided to create an SCNScene and particles(scnp). However I want to add a background image and the only 3D effect would be the particles. Can anyone help me set a background image to my SCNScene. Traditionally I would add it like this to an SKScene but I could not find any help online for the SceneKit.
 let backgroundNode = SKSpriteNode(imageNamed: "backgroundImage")
    backgroundNode.size = view.frame.size
    backgroundNode.position = CGPointMake(view.frame.size.width/2, view.frame.height/2)

    self.addChild(backgroundNode)

Thank you in advance

A: Basically the same answer as @Kusal Shrestha, but I was able to put a gradient background using a bunch of different technologies. Still very simple and useful.
    const CGFloat DIVISOR = 255.0f;
    CIColor *bottomColor = [CIColor colorWithRed:(CGFloat)0xee / DIVISOR green:(CGFloat)0x78 / DIVISOR blue:(CGFloat)0x0f / DIVISOR alpha:1];
    CIColor *topColor = [CIColor colorWithRed:0xff / DIVISOR green:0xfb / DIVISOR blue:0xcf / DIVISOR alpha:1];
    SKTexture* textureGradient = [SKTexture textureWithVerticalGradientofSize:scnview.frame.size topColor:topColor bottomColor:bottomColor];
    UIImage* uiimageGradient = [UIImage imageWithCGImage:textureGradient.CGImage];
    self.background.contents = uiimageGradient;

Where "self" is a subclass of SCNScene.
This example requires the category on texture from here: https://gist.github.com/Tantas/7fc01803d6b559da48d6

A: let scnScene = SCNScene()
scnScene.background.contents = UIImage(named: "earth.jpg")

A: I tried using @Kusal Shresthas answer. However the image was not loading when I put the image file in scnassets. But when I put the file in xcassets, it worked.
scnScene.background.contents = UIImage(named: "earth")


text:
Q: OkHTTP AndroidBaseAdapter to ListView from data I've set up okhttp to download data from my server and display it in normal text view.
But I would love to get it to ListView.
I know I need to have base adapter, some item layout and I need help with how to get it working with OKHTTP.
This is code that I use to download it, if you need anything else, please comment.
public class TaskAktualnosci extends AsyncTask<String, Void, String> {

    protected String doInBackground(String... params) {
        try {
            //*OKHTTP ponoć parametry dodaje do buildera*
       //     RequestBody parametry = new FormBody.Builder()
        //            .add("offset", "0")
         //           .add("limit", "50")
          //          .build();

            OkHttpClient klient = new OkHttpClient();
             final Gson gson = new Gson();

           Request request = new Request.Builder()
                    .url("http://www.apirest.poligon.webimpuls.pl/v1/restapi/aktualnosci?offset=0?limit=50")
                   // .post(parametry)
                   .build();

            Response response = klient.newCall(request).execute();
            return response.body().string();

        }catch (Exception e){

            return null;
        }

    }

    @Override
    protected  void onPostExecute(String s){
        super.onPostExecute(s);

        TextView textView = (TextView) findViewById(R.id.ciastko);
        textView.setText(s);
    }

}

}

I'm kinda new to android as whole and using Android Studio.
Can anyone explain it to me in normal way or show code snippet?

A: You need to make your own adapter. I prefer to extend from BaseAdapter and create a own list item class:
class ListItem {
    private long mId;
    private String mContent;

    public ListItem(final long mId, final String mContent) {
        this.mId = mId;
        this.mContent = mContent;
    }

    public long getId() {
        return mId;
    }

    public String getContent() {
        return mContent;
    }

}

public class adapter_akt extends BaseAdapter {
    private List<ListItem> mData = new ArrayList<>();

    public void setData(List<ListItem> data){
        mData = data;
        notifyDataSetChanged();
    }

    public  ListItem getItem(int position){
        return mData.get(position);
    }

    @Override
    public long getItemId(final int position) {
        return getItem(position).getId();
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        if (convertView == null){
            convertView = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent);
            ViewHolder h = new ViewHolder();
            h.textView1 = (TextView) convertView.findViewById(android.R.id.text1);
            convertView.setTag(h);
        }

        ViewHolder holder = (ViewHolder)convertView.getTag();
        ListItem item = getItem(position);
        holder.textView1.setText(item.getContent());

        return convertView;
    }

    public int getCount(){
        return mData.size();
    }

    private class ViewHolder{
        TextView textView1;
    }
}

then all u need is something to set your adapter to your ListView.
Your AsyncTask would look like:
public class Test1 extends AsyncTask<String, Void, String> {

protected String doInBackground(String... params) {
    try {
        //*OKHTTP ponoć parametry dodaje do buildera*
   //     RequestBody parametry = new FormBody.Builder()
    //            .add("offset", "0")
     //           .add("limit", "50")
      //          .build();

        OkHttpClient klient = new OkHttpClient();
         final Gson gson = new Gson();

       Request request = new Request.Builder()
                .url("http://www.apirest.poligon.webimpuls.pl/v1/restapi/aktualnosci?offset=0?limit=50")
               // .post(parametry)
               .build();

        Response response = klient.newCall(request).execute();
        return response.body().string();

    }catch (Exception e){

        return null;
    }

}

@Override
protected  void onPostExecute(String s){
    super.onPostExecute(s);

    List<ListItem> contentList = new ArrayList<>();
    /*
     her u need to read data from s to the list;
     */

    MyListAdapter adapter = find();//here u need to get your Adapter, maybe its member of your fragment class
    adapter.setData(contentList);
}

}


text:
Q: Checking if a variable is a list of unicode strings or just 1 unicode string Im trying to determine if a list of unicode strings is present or just a single unicode string. Of course Id like to take action on both, print the items from the list or print the single string.
Ive attempted to use if isinstance(variable_here, basestring): however as the variable is a list of strings i think its being identified as True in both counts. Any help would be appreciated
Example
Variable could have either 1 item or multiple.
[u'one']
[u'one', u'two']

A: I think you are trying to do something like:
if any(not isinstance(variable, unicode) for variable in variable_here):
     print 'Not a unicode list'
else:
     var_len = len(variable_here)
     if var_len == 1:
         print 'single object'
     elif var_len > 1:
         print 'multiple object'
     else:
         print 'empty list'


text:
Q: How can I deploy a html website using Azure Resource Manager I've got a website (basic html) and I want to deploy it using Azure Resource manager.  It doesn't have a visual studio sln file and I don't want to create one.
I've found this tutorial for an angular website that does something along the lines that I am trying to do.  http://www.azurefromthetrenches.com/how-to-publish-an-angularjs-website-with-azure-resource-manager-templates/
The problem I want to solve is that I have the Microsoft Azure SDK for .NET (VS 2015) 2.8.2 which allows me to add resources to my resource group project.  The tutorial writes everything itself, rather than use visual studio to create the resources.
Does any one know how to do this?
I've got my application to build the website using a website.publishproj (found at the tutorial) so I have my zip file,  what I am now lacking, is how to upload the zip file to azure using the already existing powershell that comes with the 2.8.2 SDK.
So far i've added the below code under the Import-Module statement:
C:\"Program Files (x86)"\MSBuild\14.0\bin\msbuild.exe 'C:\Source\website.publishproj' /T:Package /P:PackageLocation=".\dist" /P:_PackageTempDir="packagetmp"
$websitePackage = "C:\Source\dist\website.zip"

A: If you're ultimate goal here is the ability to simply deploy and changes to the Azure Web App, one solution is to setup automated deployment from a local Git repository into an Azure Web App.  Firstly, you'd create the RG in the Azure portal then configure Continuous Deployment.  You can then use something like Visual Studio Code to trigger the deployment from any code changes.
Good run through here: https://azure.microsoft.com/en-us/documentation/articles/web-sites-create-web-app-using-vscode/
Assuming your website is under source control eg. GitHub - you can use an ARM template to point at the GitHub repo, so when it creates a new website it will automatically pull the content into your newly created site.  Great walkthrough here: https://azure.microsoft.com/en-us/documentation/articles/app-service-web-arm-from-github-provision/ or just the code can be found here: https://github.com/Azure/azure-quickstart-templates/tree/master/201-web-app-github-deploy.
You can use Azure CLI from non-Microsoft world to deploy eg.
azure group deployment create...
If this has helped, please mark as answered.


text:
Q: How do I password protect resources in a ModX Website using htaccess and htpasswd? We are trying to protect a couple of different resources in our ModX installation. The current .htaccess code is as follows (not including all of the ModX stuff)
AuthName "Dialog prompt"
AuthType Basic
AuthUserFile /var/www/vhosts/mywebsite.co.uk/.htpasswd

<FilesMatch ^index.php\?q=71$>
    require valid-user
</FilesMatch>

The object of the exercise is to protect the following resources:

*

*http://mywebsite.co.uk/index.php?q=71

*http://mywebsite.co.uk/area/protected
I have tried various combinations of LocationsMatch, Locations, Files and Filesmatch and can't get it to work.
Thank you in advance

A: You probably dont need htaccess. You can send HTTP authentication headers http://php.net/manual/en/features.http-auth.php from correct system event

A: This is what the total solution was:
If anyone else needs to know, I created a snippet called passwordprotect and put at the top of the page: [[passwordprotect]]. I then put in the following code (an adaptation of the above response):
<?php

if(isset($_SERVER['PHP_AUTH_USER']) && ($_SERVER['PHP_AUTH_USER']=='user') &&     ($_SERVER['PHP_AUTH_PW']=='password'))
{
    echo 'You are successfully logged in.';
} else {
    header('WWW-Authenticate: Basic realm="Protected area"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
}

EDIT: If you are finding that this sometimes does work and sometimes doesn't work, this is probably because using [[passwordprotect]], modx will cache the snippet. I got better success with: [[!passwordprotect]] on Revolution. I think the code is [!passwordprotect!] on Evolution. The exclamation marks just denote not to cache the snippet. Hope that helps someone!

A: There is absolutely no reason to do this and voids the entire purpose of the MODX Revolution ACLs. The correct answer is to:

*

*Establish a user group with a minimum role which can access the resources.

*Create a test resources within the resource group.

*Add the site admin to the resource group.

*Create a test user in the resource group.

*Refresh the site cache.

*Log out all users - including yourself.

*Test the ACLs - with the site administrator both in the manager and on the front end.

*Log out or use a completely different browser and test with the test user.

*Once it is working move the protected documents to the resource group.

*Add users to the group who you want to have access.

*Remove the snippet.

If you need more help get a copy of my book or visit my site.


text:
Q: Iterate through JSON object in angular 6 I am new to Angular and probably this might be a silly question. I am trying to get an api response and save it into an array. My API response looks like :
[
    {
        "name1": {
            "name": "name1",
            "api": {
               //somedata
            },
            "t1p": {
               //somedata
            }
        }
    },
    {
        "name2": {
            "name": "name2",
            "api": {
                //somedata
                }
            },
            "t1p": {
                //somedata
            }
        }
    }
]

I get the response from the code
var data = [];

makeRequest(): void {
      this.http
        .get(this.URL1)
        .subscribe((res: Response) => {
          this.data = res;
          console.log(this.data);
        }, err => console.log(err));
    }

Now I want to fetch the "name" value from each of the JSON object. I tried doing this:
var ids:string = [];

for(let result of this.data){
            ids.push(result.name);
            console.log("Added"+result.name);
          }

But I am not able to achieve the same. Can anyone tell me what is wrong with the same.

A: You can implement it with .map and Object.keys()
const result = data.map(item => Object.keys(item)[0]);

console.log(result);   // ['name1', 'name2']

If you want to perform that method to your http call. You can do so by:
this.http
    .get(this.URL1)
    .pipe(map(res => res.map(item => Object.keys(item)[0])))
    .subscribe((res: Response) => {...});

A: Try this !
for(let i = 0; i < this.data.length; i++ )
{
   for(let key of this.data[i])
   {
      if(this.data[i][key].hasOwnProperty("name"))
         ids.push(this.data[i][key][name]);
   }
}

As your object lies inside another object with key as name.

A: makeRequest(): void {
      this.http
        .get(this.URL1)
        .pipe((response) => {
         response.map((re,index)=> re['name'+(index+1)]['name'])
        })
        .subscribe((res: Response) => {
          this.data = res;
          console.log(this.data);
        }, err => console.log(err));
    }

I gave the solution by looking at your response API. Now in the subscriber, you will get the only name.


text:
Q: Can't call function in array I'm trying to call a function inside array like this:
protected $settings = array(
        'prefix' => $this->getPrefix(),
    );

expression is not allowed as field of default value

getPrefix()
public function getPrefix()
{
    return "hello world";
}

I can't do this?

A: Judging by your protected keyword, you are trying to set an object property. According to PHP manual:

They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

In order to set your value, put it into the constructor:
class Settings
{
    protected $settings;

    public function __constructor() {
        $this->settings = array(
            'prefix' => $this->getPrefix(),
        );
    }

    public function getPrefix() {
        return "Hello, World!";
    }
}

A: Your object property must be defined when PHP compiles. However, you could simply initialize the value within your constructor.
class MyClass
{
    protected $settings = array();

    public function __construct()
    {
        $this->settings['prefix'] => $this->getPrefix()
    }

    public function getPrefix()
    {
        return "hello world";
    }
}


text:
Q: Detect if browser is capable to auto-hide address bar I do not intend to force a change on the browsers auto-hide-address-bar behaviour
I only want to detect if the browser will change it's viewports height on scroll / is capable of doing so
Why?
Fixed <img /> with height: 100% and object-fit: cover – Ugly flash when the address-bar is getting hidden.


text:
Q: OpenCV - in OSX is failing to capture the camera Why in OSX my code is not showing any camera capture at all?

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace cv;
using namespace std;

int main() {
  VideoCapture stream1(0);   //0 or 1 or 2 same..

  if (!stream1.isOpened()) {
    cout << "cannot open camera";
  }

  while (true) {
    Mat cameraFrame;
    stream1.read(cameraFrame);
    imshow("cam", cameraFrame);
    if (waitKey(30) >= 0)
      break;
  }
  return 0;
}

A: [Solved] Problem was solved by replacing the value
VideoCapture stream1(2);


text:
Q: How to get current group size after filtering charts I have 2 charts. On filtering of the 2nd chart, how can I get the filtered firstchartGroup size like filtered firstchartDim?
I tried
chart2.on("filtered",function(chart)
{
    console.log(firstchartDim.top(Infinity).length);//including filters
    console.log(firstchartGroup.size());//independent of filters

});

Any suggestions?

A: Crossfilter won't remove bins when they become empty, so you have to manually ignore the zeros when you're counting the bins. Here's one way to do this, adapted from the FAQ:
console.log(firstchartGroup.all().filter(function(d) { return d.value != 0; }).length);


text:
Q: Why javascript setTimeout is not working and setInterval working for the below program I am trying execute a test number slider program, I found that setTimeout is not working and setInterval is worked for the below program. I don't understand why this is happened.
Please help me.

A: The problem is when the init method is invoked second time(by the setInterval call, this inside the handler does not refer to the object that is retuned by the anonymous function. So in the second call this.init will be undefined so your callback will no longer gets called.
When you use setInterval it need to be called only the first time, then the same callback is called on regular intervals that is why it is working(there is still a bug in calling the setInterval multiple times, which is not needed)
You can use .bind() to pass a function with a custom context like

(function() {
  var i = 0,
    numbers = [10, 20, 30, 40, 50, 60],
    intervalTime = 500;
  return {
    init: function() {
      console.log(numbers[i] + "-" + i);
      document.getElementById("slide").innerHTML = numbers[i];
      if (i < numbers.length - 1)
        i++;
      else
        i = 0;

      setTimeout(this.init.bind(this), intervalTime);
      //setInterval(this.init,intervalTime);

    }

  };

}()).init();


text:
Q: Adobe AEM 6.3 - Creating a Project with LazyBones - Missing acs-commons errors I am following the tutorial here: https://helpx.adobe.com/experience-manager/using/aem_lazybones.html
The errors are encountered when I follow the step listed here: https://helpx.adobe.com/experience-manager/using/aem_lazybones.html#ImporttheLazybonesprojectintoEclipse to import the lazybones project into Eclipse.
When I create a new project, I see 2 errors, both notifying me that a jsp file is missing. I cannot find any information on why the acs-commons is missing from the project, or how I can correct these errors.
Fragment "/apps/acs-commons/components/utilities/errorpagehandler/default.jsp" was not found at expected path /example-project.ui.apps/src/main/content/jcr_root/apps/acs-commons/components/utilities/errorpagehandler/default.jsp default.jsp /example-project.ui.apps/src/main/content/jcr_root/apps/sling/servlet/errorhandler  line 2  JSP Problem
Fragment "/apps/acs-commons/components/utilities/errorpagehandler/404.jsp" was not found at expected path /example-project.ui.apps/src/main/content/jcr_root/apps/acs-commons/components/utilities/errorpagehandler/404.jsp 404.jsp /example-project.ui.apps/src/main/content/jcr_root/apps/sling/servlet/errorhandler  line 2  JSP Problem
Note -- I am a front-end web developer attempting to create a new project for prototype template and component testing. I am utilizing the Eclipse IDE and JDK version 1.8, as listed in the page prerequisites.

A: Evidently, you have to read the note provided at the bottom of this step. Once you delete the two files (404.jsp and default.jsp) from "ui.apps/src/main/content/jcr_root/apps/sling/servlet/errorhandler", the errors go away.


text:
Q: Display 0 or NULL values in output query from a system table I have been trying to research this question, and the answers I find all revolve around using outer joins to solve it.  I am only using a single table for this.  The real problem comes because my resulting query, I would like to use in an SP to run through every database on the server.
The base query looks like this:
SELECT name

FROM sys.database_principals

WHERE type in ('U','G')

AND name LIKE '%$'

Easy enough. If there is a user, the user is returned xyz\user1$.  If there is no user, the line is just blank.  I would like to list the database, user/group/NULL as applicable, and a count of the returns.
I worked my way up to this query:
SELECT DB_NAME () as _Database, name, count (name) as _Count

FROM sys.database_principals

WHERE type in ('U','G')

AND name LIKE '%$'

group by name

This query has the exact same output as the first (blank output with only column headers for no returns).  I have even attempted to do the left join method by trying to join on sys.databases. I have attempted CASE, IFNULL, COALESCE, but I might just misunderstand the finer points. Here is the stored procedure and one of my more flawed attempts to get this to work, but shows at least a middle step of where my head is attempting to go:
Declare @command varchar(1000)

Select @command =

'USE ?

SELECT ''?'' as _Database, p.name, count (p.name) as _Count

FROM sys.database_principals p

left join sys.databases d

on DB_NAME () = d.name

WHERE p.type in (''U'',''G'')

AND p.name LIKE ''%$''

group by p.name'

select @@SERVERNAME as 'Host Name'

exec sp_MSforeachdb @command

A: There is probably another way you could tackle this but using your query as a starting point I added a temp table for the database names. Then used sp_MSforeachdb to update the temp table. Be wary though...that is an undocumented system procedure and it has some flaws. The worst being that sometimes it will decide to skip a database and nobody seems to really know why. You can read more about the problems with that procedure and a better alternative here. https://www.mssqltips.com/sqlservertip/2201/making-a-more-reliable-and-flexible-spmsforeachdb/
create table #DatabaseNames
(
    DBName sysname
    , PrincipalCount int
)

insert #DatabaseNames
(
    DBName
    , PrincipalCount
)
select name
    , 0 --want to default our count to 0
from sys.databases

declare @command nvarchar(max) =
'update #DatabaseNames
set PrincipalCount =
(
    select count (p.name)
    FROM sys.database_principals p
    where p.type in (''U'', ''G'')
        and name LIKE ''%$''
)
where DBName = DB_NAME()
'

exec sp_MSforeachdb @command

select * from #DatabaseNames

drop table #DatabaseNames


text:
Q: React on Visual Studio Stop Is there the possibility to run some code when the Code is stopped when running it from Visual Studio?
I am using the CefGlue library to build a WinForms application and realized that there are issues when pressing the stop button ranging from Exception to two windows with no content opening. A separate process continues to run in the background. In order to stop Cef nicely I need to exectue CefRuntime.Shutdown(); Maybe this is because it does not run the application in a Visual Studio hosting process, because CefGlue has problem with this (see this). This does not affect production but is nasty while developing and testing, but nevertheless I would like to execute some code to fix the problem.
I would guess this is not possible but if it was it would be interesting to know.
So I am looking for a way to execute some code when Visual Studio is stopping the application when pressing the stop button while in development.
Note: I am using Visual Studio 2013 and 2015.
Edit
The issue is not reproducibly with very few lines of code. Nevertheless I have tried to create a simplified example here

A: What you're basicly looking for is a solution using the Visual Studio SDK.
You can build your own add-ins by implementing the IDTExtensibility interface.
In the OnConnection function you can subscribe to different events. Using (DTE2)application you can access a lot of things from VS.
You'll have to subscribe to some of the events that can be obtained from the Events property.
You'll have to find out yourself what events work best for your solution. But the DebuggerEvents would seem like a good place to start.
This does require some research before you can use it. There are likely to be easier solutions.
As a simple example for the OnConnection:
public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
{
    var applicationObject = (DTE2)application;

    var events = _applicationObject.Events;
    var buildEvents = (BuildEvents)events.BuildEvents;
    buildEvents.OnBuildBegin += new _dispBuildEvents_OnBuildBeginEventHandler(OnBuildBegin);
}

This triggers when a build is started. The available documentation isn't great, so it will need some trial-and-error before you find what you need.


text:
Q: jQuery - Get URL of iframe AFTER redirection on same domain Using Jquery, how can I get the URL of an iframe after redirection has occurred to a URL in the same domain?

A: The suggestion from sunn0 should work with this slight amendment.
 $("#iframeid").load(function(){
    alert(this.contentWindow.location);
 });


text:
Q: Kronecker decomposition of a matrix with orthonormal columns Denote $\mathcal{O}(p,r)$ be the collection of all $p$-by-$r$ matrices with orthonormal columns: $\mathcal{O}(p,r)=\{U\in\mathbb{R}^{p\times r}|U^{\intercal}U=I_p\}$. Let $A\in \mathcal{O}(p_1,r_1)$ and $B\in \mathcal{O}(p_2,r_2)$, with $p_i\ge r_i$. It is easy to see that $A\otimes B\in \mathcal{O}(p_1p_2,r_1r_2)$ by $(A\otimes B)^{\intercal}(A\otimes B)=(A^{\intercal}A)\otimes(B^{\intercal}B)=I.$
So here is my question, given a matrix $C\in\mathcal{O}(p_1p_2,r_1r_2)$, is it possible to construct $D\in\mathcal{O}(p_1,r_3)$ and $E\in\mathcal{O}(p_2,r_4)$ such that $\operatorname{col}(C)\subseteq\operatorname{col}(D\otimes E)$? (Here $\operatorname{col}(X)$ stands for the column space of $X$.)
Actually, I was trying to find $D$ and $E$ with $r_3=r_1,r_4=r_2$ s.t. $C=D\otimes E$ at the first sight. Then I notice that it may be impossible to do so. Take $r_1=r_2=1$ for instance, there are always vectors with $p_1*p_2$ length that can not be written as a Kronecker product of two vectors of length $p_1$ and $p_2$. So I relaxed the condition. Obviously when $r_3=p_1$ and $r_4=p_2$ we are able to  meet the requirement. I was wondering if we can find $D\in\mathcal{O}(p_1,r_3)$ and $E\in\mathcal{O}(p_2,r_4)$ while $r_3$ and $r_4$ are only functions of $r_1$ and $r_2$?


text:
Q: What exactly does the word Patch mean when referring to 'submitting a patch'? What exactly does the word patch mean when referring to 'submitting a patch'?
I've seen this used a lot, especially in the open source world. What what does it mean and what exactly is involved in submitting a patch?

A: Richard Jones, a developer at Red Hat, has a nice little primer on submitting code to open source projects which covers making and submitting patches.

A: A patch is usually a file that contains information how to change something (very often to fix a bug, but could also be an enhancement). There are different kind of patches.
A source code patch contains information how one or multiple source code files need to be modified. You can easily generate them using the diff command and you can apply them using the patch command (on Linux/UNIX systems these commands are standard).
However, there are also binary patches. A binary patch contains information how certain bytes within a binary need to be changed. Binary patches are, of course, rare in the OpenSource world, but in the early days of computers I saw them a lot to modify shipped binaries (usually to work around a bug).
Submitting a patch means you have locally fixed something and now you send the file to someone, so he can apply this patch to his local copy or to a public copy on the web, thus other users can benefit of the fix.
Patches are also often used if you have some source code that almost compiles on a certain platform, but some tiny changes are necessary to really have it compile there. Of course you could take the source, modify it and offer the modified code for download. But what if the original source changes again (e.g. bugs get fixed or small enhancements were added)? Then you had to re-download the source, apply the changes again and offer the new modified version. It's a lot of work to keep your modified source up-to-date. Instead of modifying, you create a diff between the original and your modified copy and store it on your server. If now a user wants to download and compile the app from source, he can first download the latest & greatest version of the original source, then apply your patch (so it will compile) and always has the latest version, without you having to change the patch. A problem will only arise if the original source has been changed exactly in one of the places your patch modifies. In this case the system will refuse to apply the patch and a new patch needs to be made.

A: It's a file with a list of differences between the code files that have changed.  It's usually in the format generated by doing a diff -u on the two files.  Most version control systems allow the easy creation of patches but it's generally in that same format.
This allows the code change to be easily applied to someone else's copy of the source code using the patch command.
For example:
Let's say I have the following code:
<?php
  $foo = 0;
?>

and I change it to this:
<?php
  $bar = 0;
?>

The patch file might look like this:
Index: test.php
===================================================================
--- test.php    (revision 40)
+++ test.php    (working copy)
@@ -3,7 +3,7 @@
         <?php
-            $foo = 0;
+            $bar= 0;
         ?>

A: A patch is a file containing all of the necessary information to turn the maintainer's source tree in to your own. It's usually created by tools like diff or svn diff or git format-patch.
Traditionally, open-source projects accept submissions from normal schlubs in the form of patches so they don't have to give others commit access to their repositories.

A: A patch, ususally in the form of a .patch file, is a common flat file format for transmitting the differences between two sets of code files.  So if you are working on an open source project, and make code changes to files, and want to submit that to the project owner to be checked in (usually because you don't have checkin rights), you would do so via a patch.
WinMerge has this functionality built in, as do many other tools like TortoiseSVN.

A: A patch file represents the difference between existing source and source you've modified.  It is the primary means of adding features or fixing bugs in many projects.
You create a patch using the diff command (for example).
You can then submit this patch to the development mailing list and if it received well, then a committer will apply the patch (thus automatically applying your changes) and commit the code.
Patches are applied using the patch command.

A: Generally it implies submitting a unified diff file with the aggregate changeset for a feature. You can read more about patches on Wikipedia. Several version control systems (svn, git, etc.) will create a patch file for you based on a changeset.

A:  1. n. A temporary addition to a piece of code, usually as a quick-and-dirty

remedy to an existing bug or misfeature. A patch may or may not work, and may or may not
eventually be incorporated permanently into the program. Distinguished from a diff
or mod by the fact that a patch is generated by more primitive means than the rest
of the program; the classical examples are instructions modified by using the front
panel switches, and changes made directly to the binary executable of a program
originally written in an HLL. Compare one-line fix.
See the entire definition in the jargon file here

A: Patch is also used in the act of updating system binaries. Microsoft sends out patches all the time but they aren't source code. They are .msp files that install improved binaries. As with all computer science terms, patch is overloaded.

A: I've always believed the term meant a bug fix, like a knee patch Mom used to put on your holey jeans.


text:
Q: WinSCP - edit connection config file? Is there a way to edit all the connections and related parameters in a text file rather than using the GUI?  I have maybe 15-20 to enter, and could add them from a spreadsheet, probably faster in a text edit mode.  Also, there is a pattern in our naming, so many of the parameters are the same (userid, keyfile name, similar).

A: WinSCP can load configuration from an INI file.
You can edit the INI file like:
[Sessions\Server1]
HostName=server1
UserName=user1
PasswordPlain=password1
FSProtocol=2

[Sessions\Server2]
HostName=server2
UserName=user2
PasswordPlain=password2
FSProtocol=2


text:
Q: How to add script/style in SharePoint default list library form in New SPFx? I am using SharePoint 2013 and i want to customize the SharePoint default list form. Is there any way to add script/style to the form in SharePoint New Experience View?.

A: This is not possible yet. Microsoft is currently working on it.
But you can keep customizing in the classic experience , i dont see it going away any time soon.
User voice link - Allow Javascript customization and CSS branding/theming in the new Document Library Experience
Update as per Patrick's comment :
This is not available on SP 2013 On premise, its right now only available on SP Online and SP 2016 after feature pack 1 update.


text:
Q: AWS Amplify PubSub is keeping previous user subscription active even after SignOut Unfortunately i discovered a faulty behavior of AWS Amplify PubSub.
Lets say user A has the authority to subscribe through PubSub library (got it's permission by manually attaching iot policy for the specific user's Cognito identity id).
He is receiving successfully messages from AWS IoT and it's time for him to SignOut (without unsubscribe first) for an other user to SignIn from the same computer.
So user B SignIn but he doesn't have authority to subscribe (no policy has been attached to his Cognito identity id). Unfortunately Amplify will keep the subscription active from the previous user and the Non-authorized user B will receive the mqtt data successfully until he reload the page. Of course the opposite stands too (user A can't recieve cause previously logged in user B didn't had authority to subscribe)
I managed to solve it by running unsubscribe function on componentWillUnmount() but i'm not satisfied with this approach.
Do you think i'm doing something wrong? I'm subscribing with
PubSub.subscribe('myTopic').subscribe({
    next: data => console.log('Message received', data),
    error: error => console.error(error),
    complete: () => console.log('Done'),
});

on redux-action and simply dispatch the message on next: data =>


text:
Q: Laravel - Plantillas blade obtener la respuesta del POST tengo una plantilla en blade que es un formulario de creación de usuario que hace una llamada a una función de un controlador que realiza la inserción del usuario en la BD .
Este controlador tiene un código como este (el código funciona y el usuario se inserta en la BD)
    /**
 * Parses, validate and create a new resource.
 *
 * @param Request $request
 * @return \Illuminate\Http\JsonResponse
 */
public function storeUser(Request $request)
{
    $roles = Input::get('roles');

    $validator = app('validator')->make($request->all(), [
        'name' => 'bail|required|string',
        'email' => 'bail|required|string',
        'status'=> 'bail|boolean',
        'created_at' => 'bail|datetime',
        'created_by' => 'bail|integer',
    ]);

    if ($validator->fails()) {
        return $this->jsonValidatorFailedResponse($validator->errors());
    };

    $userCreated = User::create($data->toArray());

    return $this->jsonCreatedResponse($userCreated);

}

Luego tengo la plantilla que es el formulario desde donde el usuario introduce los datos que es como esta
@extends('layouts.app')

@section('title', trans('messages.User Create'))

@section('content')

{{ trans('messages.User Create') }}

                    <form id="section-form" action="{{ route('admin.users.store') }}" method="post">

                                @lang('messages.name') *
                                <input type="text" id="name" class="form-control" name="name" aria-describedby="name_help" data-validation="required" />

                                @lang('messages.email')
                                <input type="text" id="email" class="form-control" name="email" aria-describedby="email_help" data-validation="required" />

                                ¿Activar usuario?

                                    <input type="checkbox" id="status" class="form-check-input" name="status" value="1" aria-describedby="status_help">
                                    @lang('messages.Enabled')

                                <input class="btn btn-primary" type="submit" value="@lang('messages.Save')"/>

                    </form>

@endsection

Lo que hace es mostrar un formulario donde el usuario introduce los datos y hace una llamada a la función que he puesto anteriormente.
La función anterior devuelve un JSON porque la idea es poder reutilizar ese método en otras plantillas , entonces mi pregunta es desde esta plantilla como puedo hacer que al hacer el POST haga la acción y capture la respuesta de la función y pueda mostrar algo por pantalla o redigir.
Gracias

A: Lo que pasa es que estás retornando la data como JSON en lugar de una vista. Esto es útil cuando se usa Laravel como backend ofreciendo servicios para realizar acciones en el servidor de modo que el frontend puede hacer consultas HTTP sin estado.
En el modo que estás trabajando veo que estás usando Laravel para back (lógica de negocio) y también para el frontend por lo que lo usual es que las vistas se rendericen desde el servidor (retornar vistas en lugar de data - json, xml) entonces para solucionar lo que dices puedes hacerlo de dos modos distintos:
Solución A
Mantener tu modo de trabajo pero retornarnando vistas desde el controlador en lugar de data.
/**
 * Parses, validate and create a new resource.
 *
 * @param Request $request
 */
public function storeUser(Request $request)
{
    $roles = Input::get('roles');

    $validator = app('validator')->make($request->all(), [
        'name' => 'bail|required|string',
        'email' => 'bail|required|string',
        'status'=> 'bail|boolean',
        'created_at' => 'bail|datetime',
        'created_by' => 'bail|integer',
    ]);

    if ($validator->fails()) {
        return $this->jsonValidatorFailedResponse($validator->errors());
    };

    $userCreated = User::create($data->toArray());

    return $this->view('nombre_de_tu_view')->withUser($userCreated);
    // de este modo puedes utilizar el usuario creado en tu vista desde
    // la variable $user
}

Esto no cumple del todo lo que esperas hacer: reutilizar el método para otras vistas. Entonces la estrategia que puedes tomar es crear una clase que gestione esta lógica (como un repositorio o trait) de modo que desde los métodos de tus controladores solo invocas a esa clase para la creación de usuarios, devolviendo la data que desees junto con las vistas que quieras.
Solución B
Realizar las consultar hacia tu servidor desde el frontend a través de llamadas HTTP sin estado por medio de una librería como Axios.
De este modo tus controladores solo devuelven la data que estás retornando actualmente ($userCreated) hacia cualquier vista de tu frontend cuando tú lo desees. Acá te dejo una guía que te dará una pauta más detallada.

A: En tu función coloca un dd($request);
el dd lo que hace es mostrarte lo que estas enviando por parametro.
luego si quieres retornar esto simplemente debes utilizar
return redirect('/url')->with('variable_en_vista', $request);

espero que esto te ayude.


text:
Q: R intersection keep the same length I'd like to do intersection by name and keep the same length as original vector. I want to fill those non-intersected entry to be "NT".
vector1: p7d_A1    p7d_A2     p7d_A3
        "random"  "random"   "random"

vector2: p7d_A1   p7d_A2
         "hello"   "hi"

output: p7d_A1    p7d_A2     p7d_A3
         "hello"    "hi"       "NT"

A: You can use setdiff to get names of vector2 which are not in vector1 and assign it with 'NT'.
vector1 <- c(p7d_A1 = 'random', p7d_A2 = 'random', p7d_A3 = 'random')
vector2 <- c(p7d_A1 = 'hello', p7d_A2 = 'hi')
vector2[setdiff(names(vector1), names(vector2))] <- 'NT'
vector2

# p7d_A1  p7d_A2  p7d_A3
#"hello"    "hi"    "NT"


text:
Q: How to use (or replace) java 8 functional interface with android API below 24? I am developing an android app (minSdkVersion: 23).
In my signIn method, I make a call like that:
RequestClass.doRequestWithApi(this.getApplicationContext(), this.TAG, dataToPass, this::getMyAccount);

And here is the doRequestWithApi method:
public static void doRequestWithApi(Context c, final String TAG, final Map<String, String> paramsToPass, final Function<JSONObject,Boolean> f){

    String urlData = "http://...";
    //For localhost
    //String urlData = "http://10.0.2.2/...";

    Log.i(CAT,paramsToPass.toString());

    URL url = null;
    try {

        url = new URL(urlData);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
        url = uri.toURL();

        Log.i(CAT, "Start Building");

        StringRequest jsObjRequest = new StringRequest(Request.Method.POST, url.toString(),
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.i(CAT, "Reponse : " + response.toString() );
                        try {
                            f.apply(new JSONObject(response));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.i(TAG, error.toString());
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Language", Locale.getDefault().toString());
                return map;
            }

            @Override
            protected Map<String, String> getParams(){
                return paramsToPass;
            }

        };

        jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        // Access the RequestQueue through your singleton class.
        MySingletonRequestApi.getInstance(c).addToRequestQueue(jsObjRequest, TAG);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
}

As you can see, this::getMyAccount is a use of functional interface wich is a java 8 functionality.
I found this page: Java 8 Android support
It shows that java.lang.FunctionalInterface is only supported on API level 24 or higher.
In fact, when I try to run my app on a 6.0 android device (API 23), it throws this error:
E/AndroidRuntime: FATAL EXCEPTION: main
              Process: etsymbiose.defdress, PID: 8296
              java.lang.NoClassDefFoundError: etsymbiose.defdress.LoginActivity$$Lambda$1
                  at etsymbiose.defdress.LoginActivity.onCreate(LoginActivity.java:51)
                  at android.app.Activity.performCreate(Activity.java:6301)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2519)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654)
                  at android.app.ActivityThread.-wrap11(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
                  at android.os.Handler.dispatchMessage(Handler.java:111)
                  at android.os.Looper.loop(Looper.java:207)
                  at android.app.ActivityThread.main(ActivityThread.java:5728)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

How can I solve this problem?

A: In your app level build.gradle file, you can specify compileOptions block like such to use Java-8 features:
android {
  ...

  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

A: If you are using Android Studio, just go to File -> Project Structure -> app and
change Source Compatibility to 1.8 and Target Compatibility also to 1.8 like in the image below: