Programs & Examples On #Apxs2

How to enable SOAP on CentOS

For my point of view, First thing is to install soap into Centos

yum install php-soap


Second, see if the soap package exist or not

yum search php-soap

third, thus you must see some result of soap package you installed, now type a command in your terminal in the root folder for searching the location of soap for specific path

find -name soap.so

fourth, you will see the exact path where its installed/located, simply copy the path and find the php.ini to add the extension path,

usually the path of php.ini file in centos 6 is in

/etc/php.ini

fifth, add a line of code from below into php.ini file

extension='/usr/lib/php/modules/soap.so'

and then save the file and exit.

sixth run apache restart command in Centos. I think there is two command that can restart your apache ( whichever is easier for you )

service httpd restart

OR

apachectl restart

Lastly, check phpinfo() output in browser, you should see SOAP section where SOAP CLIENT, SOAP SERVER etc are listed and shown Enabled.

How do I configure php to enable pdo and include mysqli on CentOS?

You might just have to install the packages.

yum install php-pdo php-mysqli

After they're installed, restart Apache.

httpd restart

or

apachectl restart

Installing mcrypt extension for PHP on OSX Mountain Lion

I'd create a shell script to install mcrypt module for PHP 5.3 without homebrew.

The scripts install php autoconf if needed and compile module for your php version.

The link is here: https://gist.github.com/lucasgameiro/8730619

Thanks

Install pdo for postgres Ubuntu

Pecl PDO package is now deprecated. By the way the debian package php5-pgsql now includes both the regular and the PDO driver, so just:

apt-get install php-pgsql

Apache also needs to be restarted before sites can use it:

sudo systemctl restart apache2

Static Final Variable in Java

In first statement you define variable, which common for all of the objects (class static field).

In the second statement you define variable, which belongs to each created object (a lot of copies).

In your case you should use the first one.

python : list index out of range error while iteratively popping elements

You are reducing the length of your list l as you iterate over it, so as you approach the end of your indices in the range statement, some of those indices are no longer valid.

It looks like what you want to do is:

l = [x for x in l if x != 0]

which will return a copy of l without any of the elements that were zero (that operation is called a list comprehension, by the way). You could even shorten that last part to just if x, since non-zero numbers evaluate to True.

There is no such thing as a loop termination condition of i < len(l), in the way you've written the code, because len(l) is precalculated before the loop, not re-evaluated on each iteration. You could write it in such a way, however:

i = 0
while i < len(l):
   if l[i] == 0:
       l.pop(i)
   else:
       i += 1

php, mysql - Too many connections to database error

There are a bunch of different reasons for the "Too Many Connections" error.

Check out this FAQ page on MySQL.com: http://dev.mysql.com/doc/refman/5.5/en/too-many-connections.html

Check your my.cnf file for "max_connections". If none exist try:

[mysqld]
set-variable=max_connections=250

However the default is 151, so you should be okay.

If you are on a shared host, it might be that other users are taking up too many connections.

Other problems to look out for is the use of persistent connections and running out of diskspace.

Loading context in Spring using web.xml

You can also specify context location relatively to current classpath, which may be preferable

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext*.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

Traverse all the Nodes of a JSON Object Tree with JavaScript

I've created library to traverse and edit deep nested JS objects. Check out API here: https://github.com/dominik791

You can also play with the library interactively using demo app: https://dominik791.github.io/obj-traverse-demo/

Examples of usage: You should always have root object which is the first parameter of each method:

var rootObj = {
  name: 'rootObject',
  children: [
    {
      'name': 'child1',
       children: [ ... ]
    },
    {
       'name': 'child2',
       children: [ ... ]
    }
  ]
};

The second parameter is always the name of property that holds nested objects. In above case it would be 'children'.

The third parameter is an object that you use to find object/objects that you want to find/modify/delete. For example if you're looking for object with id equal to 1, then you will pass { id: 1} as the third parameter.

And you can:

  1. findFirst(rootObj, 'children', { id: 1 }) to find first object with id === 1
  2. findAll(rootObj, 'children', { id: 1 }) to find all objects with id === 1
  3. findAndDeleteFirst(rootObj, 'children', { id: 1 }) to delete first matching object
  4. findAndDeleteAll(rootObj, 'children', { id: 1 }) to delete all matching objects

replacementObj is used as the last parameter in two last methods:

  1. findAndModifyFirst(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'}) to change first found object with id === 1 to the { id: 2, name: 'newObj'}
  2. findAndModifyAll(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'}) to change all objects with id === 1 to the { id: 2, name: 'newObj'}

jQuery: how do I animate a div rotation?

I needed to rotate an object but have a call back function. Inspired by John Kern's answer I created this.

function animateRotate (object,fromDeg,toDeg,duration,callback){
        var dummy = $('<span style="margin-left:'+fromDeg+'px;">')
        $(dummy).animate({
            "margin-left":toDeg+"px"
        },
        {
            duration:duration,
            step: function(now,fx){
                $(object).css('transform','rotate(' + now + 'deg)');
                if(now == toDeg){
                    if(typeof callback == "function"){
                        callback();
                    }
                }
            }
        }
    )};

Doing this you can simply call the rotate on the object like so... (in my case I'm doing it on a disclosure triangle icon that has already been rotated by default to 270 degress and I'm rotating it another 90 degrees to 360 degrees at 1000 milliseconds. The final argument is the callback after the animation has finished.

animateRotate($(".disclosure_icon"),270,360,1000,function(){
                alert('finished rotate');
            });

how do I create an array in jquery?

Here is an example that I used.

<script>
  $(document).ready(function(){
      var array =  $.makeArray(document.getElementsByTagName(“p”));
      array.reverse(); 
      $(array).appendTo(document.body);
  });
</script>

div inside php echo

You can do this:

<div class"my_class">
<?php if ($cart->count_product > 0) {
          print $cart->count_product; 
      } else { 
          print ''; 
      } 
?>
</div>

Before hitting the div, we are not in PHP tags

'module' object has no attribute 'DataFrame'

For me he problem was that my script was called pandas.py in the folder pandas which obviously messed up my imports.

MS-access reports - The search key was not found in any record - on save

Another possible cause of this error is a mismatched workgroup file. That is, if you try to use a secured (or partially-secured) MDB with a workgroup file other than the one used to secure it, you can trigger the error (I've seen it myself, years ago with Access 2000).

Pandas: Setting no. of max rows

As @hanleyhansen noted in a comment, as of version 0.18.1, the display.height option is deprecated, and says "use display.max_rows instead". So you just have to configure it like this:

pd.set_option('display.max_rows', 500)

See the Release Notes — pandas 0.18.1 documentation:

Deprecated display.height, display.width is now only a formatting option does not control triggering of summary, similar to < 0.11.0.

No content to map due to end-of-input jackson parser

This error is sometimes (often?) hiding the real problem: a failure condition could be causing the content to be incorrect, which then fails to deserialize.

In my case, today, I was making HTTP calls and (foolishly) omitted to check the HTTP status code before trying to unmarshal the body of the response => my real problem was actualy that I had some authentication error, which caused a 401 Unauthorized to be sent back to me, with an empty body. Since I was unmarshalling that empty body directly without checking anything, I was getting this No content to map due to end-of-input, without getting any clue about the authentication issue.

The application was unable to start correctly (0xc000007b)

I tried all the things specified here and found yet another answer. I had to compile my application with 32-bit DLLs. I had built the libraries both in 32-bit and 64-bit but had my PATH set to 64-bit libraries. After I recompiled my application (with a number of changes in my code as well) I got this dreaded error and struggled for two days. Finally, after trying a number of other things, I changed my PATH to have the 32-bit DLLs before the 64-bit DLLs (they have the same names). And it worked. I am just adding it here for completeness.

Visual Studio Code Automatic Imports

Fill the include property in the first level of the JSON-object in the tsconfig.editor.json like here:

"include": [
  "src/**/*.ts"
]

It works for me well.

Also you can add another Typescript file extensions if it's needed, like here:

"include": [
  "src/**/*.ts",
  "src/**/*.spec.ts",
  "src/**/*.d.ts"
]

java.nio.file.Path for a classpath resource

Guessing that what you want to do, is call Files.lines(...) on a resource that comes from the classpath - possibly from within a jar.

Since Oracle convoluted the notion of when a Path is a Path by not making getResource return a usable path if it resides in a jar file, what you need to do is something like this:

Stream<String> stream = new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("/filename.txt"))).lines();

How can I clear the input text after clicking

This worked for me:

    **//Click The Button**    
    $('#yourButton').click(function(){

         **//What you want to do with your button**
         //YOUR CODE COMES HERE

         **//CLEAR THE INPUT**
         $('#yourInput').val('');

});

So first, you select your button with jQuery:

$('#button').click(function((){ //Then you get the input element $('#input')
    //Then you clear the value by adding:
    .val(' '); });

How to INNER JOIN 3 tables using CodeIgniter

For executing pure SQL statements (I Don't Know About the FRAMEWORK- CodeIGNITER!!!) you can use SUB QUERY! The Syntax Would be as follows

SELECT t1.id FROM example t1 INNER JOIN (select id from (example2 t1 join example3 t2 on t1.id = t2.id)) as t2 ON t1.id = t2.id;

Hope you Get My Point!

How to select last child element in jQuery?

Hi all Please try this property

$( "p span" ).last().addClass( "highlight" );

Thanks

Google OAUTH: The redirect URI in the request did not match a registered redirect URI

I think I encountered the same problem as you. I addressed this problem with the following steps:

1) Go to Google Developers Console

2) Set JavaScript origins:

3) Set Redirect URIs:

Apache Spark: The number of cores vs. the number of executors

As you run your spark app on top of HDFS, according to Sandy Ryza

I’ve noticed that the HDFS client has trouble with tons of concurrent threads. A rough guess is that at most five tasks per executor can achieve full write throughput, so it’s good to keep the number of cores per executor below that number.

So I believe that your first configuration is slower than third one is because of bad HDFS I/O throughput

SQLite UPSERT / UPDATE OR INSERT

This is a late answer. Starting from SQLIte 3.24.0, released on June 4, 2018, there is finally a support for UPSERT clause following PostgreSQL syntax.

INSERT INTO players (user_name, age)
  VALUES('steven', 32) 
  ON CONFLICT(user_name) 
  DO UPDATE SET age=excluded.age;

Note: For those having to use a version of SQLite earlier than 3.24.0, please reference this answer below (posted by me, @MarqueIV).

However if you do have the option to upgrade, you are strongly encouraged to do so as unlike my solution, the one posted here achieves the desired behavior in a single statement. Plus you get all the other features, improvements and bug fixes that usually come with a more recent release.

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

Try wrapping your dates in single quotes, like this:

'15-6-2005'

It should be able to parse the date this way.

Powershell send-mailmessage - email to multiple recipients

That's right, each address needs to be quoted. If you have multiple addresses listed on the command line, the Send-MailMessage likes it if you specify both the human friendly and the email address parts.

How do I update a Linq to SQL dbml file?

There are three ways to keep the model in sync.

  1. Delete the modified tables from the designer, and drag them back onto the designer surface from the Database Explorer. I have found that, for this to work reliably, you have to:

    a. Refresh the database schema in the Database Explorer (right-click, refresh)
    b. Save the designer after deleting the tables
    c. Save again after dragging the tables back.

    Note though that if you have modified any properties (for instance, turning off the child property of an association), this will obviously lose those modifications — you'll have to make them again.

  2. Use SQLMetal to regenerate the schema from your database. I have seen a number of blog posts that show how to script this.

  3. Make changes directly in the Properties pane of the DBML. This works for simple changes, like allowing nulls on a field.

The DBML designer is not installed by default in Visual Studio 2015, 2017 or 2019. You will have to close VS, start the VS installer and modify your installation. The LINQ to SQL tools is the feature you must install. For VS 2017/2019, you can find it under Individual Components > Code Tools.

How to update a pull request from forked repo?

Just push to the branch that the pull request references. As long as the pull request is still open, it should get updated with any added commits automatically.

How to test code dependent on environment variables using JUnit?

For JUnit 4 users, System Lambda as suggested by Stefan Birkner is a great fit.

In case you are using JUnit 5, there is the JUnit Pioneer extension pack. It comes with @ClearEnvironmentVariable and @SetEnvironmentVariable. From the docs:

The @ClearEnvironmentVariable and @SetEnvironmentVariable annotations can be used to clear, respectively, set the values of environment variables for a test execution. Both annotations work on the test method and class level, are repeatable as well as combinable. After the annotated method has been executed, the variables mentioned in the annotation will be restored to their original value or will be cleared if they didn't have one before. Other environment variables that are changed during the test, are not restored.

Example:

@Test
@ClearEnvironmentVariable(key = "SOME_VARIABLE")
@SetEnvironmentVariable(key = "ANOTHER_VARIABLE", value = "new value")
void test() {
    assertNull(System.getenv("SOME_VARIABLE"));
    assertEquals("new value", System.getenv("ANOTHER_VARIABLE"));
}

What is the Angular equivalent to an AngularJS $watch?

If, in addition to automatic two-way binding, you want to call a function when a value changes, you can break the two-way binding shortcut syntax to the more verbose version.

<input [(ngModel)]="yourVar"></input>

is shorthand for

<input [ngModel]="yourVar" (ngModelChange)="yourVar=$event"></input>

(see e.g. http://victorsavkin.com/post/119943127151/angular-2-template-syntax)

You could do something like this:

<input [(ngModel)]="yourVar" (ngModelChange)="changedExtraHandler($event)"></input>

How to properly upgrade node using nvm

You can more simply run one of the following commands:

Latest version:
nvm install node --reinstall-packages-from=node
Stable (LTS) version:
nvm install lts/* --reinstall-packages-from=node

This will install the appropriate version and reinstall all packages from the currently used node version. This saves you from manually handling the specific versions.

Edit - added command for installing LTS version according to @m4js7er comment.

PHP: Possible to automatically get all POSTed data?

To add to the others, var_export might be handy too:

$email_text = var_export($_POST, true);

How to open a file for both reading and writing?

r+ is the canonical mode for reading and writing at the same time. This is not different from using the fopen() system call since file() / open() is just a tiny wrapper around this operating system call.

Python: One Try Multiple Except

Yes, it is possible.

try:
   ...
except FirstException:
   handle_first_one()

except SecondException:
   handle_second_one()

except (ThirdException, FourthException, FifthException) as e:
   handle_either_of_3rd_4th_or_5th()

except Exception:
   handle_all_other_exceptions()

See: http://docs.python.org/tutorial/errors.html

The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)

Writing your own square root function

Let's say we are trying to find the square root of 2, and you have an estimate of 1.5. We'll say a = 2, and x = 1.5. To compute a better estimate, we'll divide a by x. This gives a new value y = 1.333333. However, we can't just take this as our next estimate (why not?). We need to average it with the previous estimate. So our next estimate, xx will be (x + y) / 2, or 1.416666.

Double squareRoot(Double a, Double epsilon) {
    Double x = 0d;
    Double y = a;
    Double xx = 0d;

    // Make sure both x and y != 0.
    while ((x != 0d || y != 0d) && y - x > epsilon) {
        xx = (x + y) / 2;

        if (xx * xx >= a) {
            y = xx;
        } else {
            x = xx;
        }
    }

    return xx;
}

Epsilon determines how accurate the approximation needs to be. The function should return the first approximation x it obtains that satisfies abs(x*x - a) < epsilon, where abs(x) is the absolute value of x.

square_root(2, 1e-6)
Output: 1.4142141342163086

How to get pip to work behind a proxy server

The pip's proxy parameter is, according to pip --help, in the form scheme://[user:passwd@]proxy.server:port

You should use the following:

pip install --proxy http://user:password@proxyserver:port TwitterApi

Also, the HTTP_PROXY env var should be respected.

Note that in earlier versions (couldn't track down the change in the code, sorry, but the doc was updated here), you had to leave the scheme:// part out for it to work, i.e. pip install --proxy user:password@proxyserver:port

Check if a row exists, otherwise insert

You could use the Merge Functionality to achieve. Otherwise you can do:

declare @rowCount int

select @rowCount=@@RowCount

if @rowCount=0
begin
--insert....

How to parse a text file with C#

One way that I've found really useful in situations like this is to go old-school and use the Jet OLEDB provider, together with a schema.ini file to read large tab-delimited files in using ADO.Net. Obviously, this method is really only useful if you know the format of the file to be imported.

public void ImportCsvFile(string filename)
{
    FileInfo file = new FileInfo(filename);

    using (OleDbConnection con = 
            new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
            file.DirectoryName + "\";
            Extended Properties='text;HDR=Yes;FMT=TabDelimited';"))
    {
        using (OleDbCommand cmd = new OleDbCommand(string.Format
                                  ("SELECT * FROM [{0}]", file.Name), con))
        {
            con.Open();

            // Using a DataReader to process the data
            using (OleDbDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    // Process the current reader entry...
                }
            }

            // Using a DataTable to process the data
            using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
            {
                DataTable tbl = new DataTable("MyTable");
                adp.Fill(tbl);

                foreach (DataRow row in tbl.Rows)
                {
                    // Process the current row...
                }
            }
        }
    }
} 

Once you have the data in a nice format like a datatable, filtering out the data you need becomes pretty trivial.

PHP Excel Header

The problem is you typed the wrong file extension for excel file. you used .xsl instead of xls.

I know i came in late but it can help future readers of this post.

Convert Map to JSON using Jackson

You should prefer Object Mapper instead. Here is the link for the same : Object Mapper - Spring MVC way of Obect to JSON

How do I read from parameters.yml in a controller in symfony2?

In Symfony 4.3.1 I use this:

services.yaml

HTTP_USERNAME: 'admin'
HTTP_PASSWORD: 'password123'

FrontController.php

$username = $this->container->getParameter('HTTP_USERNAME');
$password = $this->container->getParameter('HTTP_PASSWORD');

Getting CheckBoxList Item values

Try to use this.

        for (int i = 0; i < chBoxListTables.Items.Count; i++)
        {
            if (chBoxListTables.Items[i].Selected)
            {
                string str = chBoxListTables.Items[i].Text;
                MessageBox.Show(str);

                var itemValue = chBoxListTables.Items[i].Value;
            }
        }

The "V" should be in CAPS in Value.

Here is another code example used in WinForm app and runs properly.

        var chBoxList= new CheckedListBox();
        chBoxList.Items.Add(new ListItem("One", "1"));
        chBoxList.Items.Add(new ListItem("Two", "2"));
        chBoxList.SetItemChecked(1, true);

        var checkedItems = chBoxList.CheckedItems;
        var chkText = ((ListItem)checkedItems[0]).Text;
        var chkValue = ((ListItem)checkedItems[0]).Value;
        MessageBox.Show(chkText);
        MessageBox.Show(chkValue);

Convert array values from string to int?

Input => '["3","6","16","120"]'

Type conversion I used => (int)$s;

function Str_Int_Arr($data){
    $h=[];
    $arr=substr($data,1,-1);
    //$exp=str_replace( ",","", $arr);
    $exp=str_replace( "\"","", $arr);
    $s=''; 
    $m=0;
    foreach (str_split($exp) as $k){
        if('0'<= $k && '9'>$k || $k =","){
            if('0' <= $k && '9' > $k){
                $s.=$k;
                $h[$m]=(int)$s;
            }else{
                $s="";
                $m+=1;
            } 
        } 
    } 
    return $h;
}
var_dump(Str_Int_Arr('["3","6","16","120"]'));

Output:

array(4) {
  [0]=>
  int(3)
  [1]=>
  int(6)
  [2]=>
  int(16)
  [3]=>
  int(120)
}

Thanks

static and extern global variables in C and C++

Global variables are not extern nor static by default on C and C++. When you declare a variable as static, you are restricting it to the current source file. If you declare it as extern, you are saying that the variable exists, but are defined somewhere else, and if you don't have it defined elsewhere (without the extern keyword) you will get a link error (symbol not found).

Your code will break when you have more source files including that header, on link time you will have multiple references to varGlobal. If you declare it as static, then it will work with multiple sources (I mean, it will compile and link), but each source will have its own varGlobal.

What you can do in C++, that you can't in C, is to declare the variable as const on the header, like this:

const int varGlobal = 7;

And include in multiple sources, without breaking things at link time. The idea is to replace the old C style #define for constants.

If you need a global variable visible on multiple sources and not const, declare it as extern on the header, and then define it, this time without the extern keyword, on a source file:

Header included by multiple files:

extern int varGlobal;

In one of your source files:

int varGlobal = 7;

What is the difference between SOAP 1.1, SOAP 1.2, HTTP GET & HTTP POST methods for Android?

Differences in SOAP versions

Both SOAP Version 1.1 and SOAP Version 1.2 are World Wide Web Consortium (W3C) standards. Web services can be deployed that support not only SOAP 1.1 but also support SOAP 1.2. Some changes from SOAP 1.1 that were made to the SOAP 1.2 specification are significant, while other changes are minor.

The SOAP 1.2 specification introduces several changes to SOAP 1.1. This information is not intended to be an in-depth description of all the new or changed features for SOAP 1.1 and SOAP 1.2. Instead, this information highlights some of the more important differences between the current versions of SOAP.

The changes to the SOAP 1.2 specification that are significant include the following updates: SOAP 1.1 is based on XML 1.0. SOAP 1.2 is based on XML Information Set (XML Infoset). The XML information set (infoset) provides a way to describe the XML document with XSD schema. However, the infoset does not necessarily serialize the document with XML 1.0 serialization on which SOAP 1.1 is based.. This new way to describe the XML document helps reveal other serialization formats, such as a binary protocol format. You can use the binary protocol format to compact the message into a compact format, where some of the verbose tagging information might not be required.

In SOAP 1.2 , you can use the specification of a binding to an underlying protocol to determine which XML serialization is used in the underlying protocol data units. The HTTP binding that is specified in SOAP 1.2 - Part 2 uses XML 1.0 as the serialization of the SOAP message infoset.

SOAP 1.2 provides the ability to officially define transport protocols, other than using HTTP, as long as the vendor conforms to the binding framework that is defined in SOAP 1.2. While HTTP is ubiquitous, it is not as reliable as other transports including TCP/IP and MQ. SOAP 1.2 provides a more specific definition of the SOAP processing model that removes many of the ambiguities that might lead to interoperability errors in the absence of the Web Services-Interoperability (WS-I) profiles. The goal is to significantly reduce the chances of interoperability issues between different vendors that use SOAP 1.2 implementations. SOAP with Attachments API for Java (SAAJ) can also stand alone as a simple mechanism to issue SOAP requests. A major change to the SAAJ specification is the ability to represent SOAP 1.1 messages and the additional SOAP 1.2 formatted messages. For example, SAAJ Version 1.3 introduces a new set of constants and methods that are more conducive to SOAP 1.2 (such as getRole(), getRelay()) on SOAP header elements. There are also additional methods on the factories for SAAJ to create appropriate SOAP 1.1 or SOAP 1.2 messages. The XML namespaces for the envelope and encoding schemas have changed for SOAP 1.2. These changes distinguish SOAP processors from SOAP 1.1 and SOAP 1.2 messages and supports changes in the SOAP schema, without affecting existing implementations. Java Architecture for XML Web Services (JAX-WS) introduces the ability to support both SOAP 1.1 and SOAP 1.2. Because JAX-RPC introduced a requirement to manipulate a SOAP message as it traversed through the run time, there became a need to represent this message in its appropriate SOAP context. In JAX-WS, a number of additional enhancements result from the support for SAAJ 1.3.

There is not difine POST AND GET method for particular android....but all here is differance

GET The GET method appends name/value pairs to the URL, allowing you to retrieve a resource representation. The big issue with this is that the length of a URL is limited (roughly 3000 char) resulting in data loss should you have to much stuff in the form on your page, so this method only works if there is a small number parameters.

What does this mean for me? Basically this renders the GET method worthless to most developers in most situations. Here is another way of looking at it: the URL could be truncated (and most likely will be give today's data-centric sites) if the form uses a large number of parameters, or if the parameters contain large amounts of data. Also, parameters passed on the URL are visible in the address field of the browser (YIKES!!!) not the best place for any kind of sensitive (or even non-sensitive) data to be shown because you are just begging the curious user to mess with it.

POST The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output, basically its a no-brainer on which one to use. POST is also more secure but certainly not safe. Although HTTP fully supports CRUD, HTML 4 only supports issuing GET and POST requests through its various elements. This limitation has held Web applications back from making full use of HTTP, and to work around it, most applications overload POST to take care of everything but resource retrieval.

Link to original IBM source

Rails.env vs RAILS_ENV

ENV['RAILS_ENV'] is now deprecated.

You should use Rails.env which is clearly much nicer.

What is the use of ByteBuffer in Java?

The ByteBuffer class is important because it forms a basis for the use of channels in Java. ByteBuffer class defines six categories of operations upon byte buffers, as stated in the Java 7 documentation:

  • Absolute and relative get and put methods that read and write single bytes;

  • Relative bulk get methods that transfer contiguous sequences of bytes from this buffer into an array;

  • Relative bulk put methods that transfer contiguous sequences of bytes from a byte array or some other byte buffer into this buffer;

  • Absolute and relative get and put methods that read and write values of other primitive types, translating them to and from sequences of bytes in a particular byte order;

  • Methods for creating view buffers, which allow a byte buffer to be viewed as a buffer containing values of some other primitive type; and

  • Methods for compacting, duplicating, and slicing a byte buffer.

Example code : Putting Bytes into a buffer.

    // Create an empty ByteBuffer with a 10 byte capacity
    ByteBuffer bbuf = ByteBuffer.allocate(10);

    // Get the buffer's capacity
    int capacity = bbuf.capacity(); // 10

    // Use the absolute put(int, byte).
    // This method does not affect the position.
    bbuf.put(0, (byte)0xFF); // position=0

    // Set the position
    bbuf.position(5);

    // Use the relative put(byte)
    bbuf.put((byte)0xFF);

    // Get the new position
    int pos = bbuf.position(); // 6

    // Get remaining byte count
    int rem = bbuf.remaining(); // 4

    // Set the limit
    bbuf.limit(7); // remaining=1

    // This convenience method sets the position to 0
    bbuf.rewind(); // remaining=7

Play a Sound with Python

pyMedia's sound example does just that. This should be all you need.

import time, wave, pymedia.audio.sound as sound
f= wave.open( 'YOUR FILE NAME', 'rb' )
sampleRate= f.getframerate()
channels= f.getnchannels()
format= sound.AFMT_S16_LE
snd= sound.Output( sampleRate, channels, format )
s= f.readframes( 300000 )
snd.play( s )

Submit a form in a popup, and then close the popup

The Solution on top won't work because a submit redirects the page to the endpoint of form and wait for response to redirect. I see that this is an old Question but Most Asked and even i came to know the answer.Still here is my solution what i am implementing. I tried to keep it secure with Nonce but if you don't care then not required.

Method 1: You need to Pop up the form.

document.getElementById('edit_info_button').addEventListener('click',function(){
        window.open('{% url "updateuserinfo" %}','newwindow', 'width=400,height=600,scrollbars=no');
    });

Then you have the form open.

Submit the form normally.

Then return an HTTPResponse in render to a template(HTML file) With a STRICT Content Security Policy. A Variable that contains the following script. Nonce contains a Base64 128bits or larger randomly generated string for every request made to server.

<script nonce="{{nonce}}">window.close()</script>

Method 2:

Or you can redirect to another Page which is suppose to close ... Which already Contains the window.close() script. This will close the pop up window.

Method 3:

Otherwise the simplest will be Use a Ajax call if you are comfortable with one.Use then() and check your condition to the httpresponse from the server.Close the window when success.

How do I connect to mongodb with node.js (and authenticate)?

Everyone should use this source link:

http://mongodb.github.com/node-mongodb-native/contents.html

Answer to the question:

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('integration_tests', new Server("127.0.0.1", 27017,
 {auto_reconnect: false, poolSize: 4}), {w:0, native_parser: false});

// Establish connection to db
db.open(function(err, db) {
  assert.equal(null, err);

  // Add a user to the database
  db.addUser('user', 'name', function(err, result) {
    assert.equal(null, err);

    // Authenticate
    db.authenticate('user', 'name', function(err, result) {
      assert.equal(true, result);

      db.close();
    });
  });
});

Delete a closed pull request from GitHub

5 step to do what you want if you made the pull request from a forked repository:

  1. reopen the pull request
  2. checkout to the branch which you made the pull request
  3. reset commit to the last master commit(that means remove all you new code)
  4. git push --force
  5. delete your forked repository which made the pull request

And everything is done, good luck!

json_encode/json_decode - returns stdClass instead of Array in PHP

To answer the actual question:

Why does PHP turn the JSON Object into a class?

Take a closer look at the output of the encoded JSON, I've extended the example the OP is giving a little bit:

$array = array(
    'stuff' => 'things',
    'things' => array(
        'controller', 'playing card', 'newspaper', 'sand paper', 'monitor', 'tree'
    )
);
$arrayEncoded = json_encode($array);
echo $arrayEncoded;
//prints - {"stuff":"things","things":["controller","playing card","newspaper","sand paper","monitor","tree"]}

The JSON format was derived from the same standard as JavaScript (ECMAScript Programming Language Standard) and if you would look at the format it looks like JavaScript. It is a JSON object ({} = object) having a property "stuff" with value "things" and has a property "things" with it's value being an array of strings ([] = array).

JSON (as JavaScript) doesn't know associative arrays only indexed arrays. So when JSON encoding a PHP associative array, this will result in a JSON string containing this array as an "object".

Now we're decoding the JSON again using json_decode($arrayEncoded). The decode function doesn't know where this JSON string originated from (a PHP array) so it is decoding into an unknown object, which is stdClass in PHP. As you will see, the "things" array of strings WILL decode into an indexed PHP array.

Also see:


Thanks to https://www.randomlists.com/things for the 'things'

Android - get children inside a View?

for(int index = 0; index < ((ViewGroup) viewGroup).getChildCount(); index++) {
    View nextChild = ((ViewGroup) viewGroup).getChildAt(index);
}

Will that do?

Regex Letters, Numbers, Dashes, and Underscores

You can indeed match all those characters, but it's safer to escape the - so that it is clear that it be taken literally.

If you are using a POSIX variant you can opt to use:

([[:alnum:]\-_]+)

But a since you are including the underscore I would simply use:

([\w\-]+)

(works in all variants)

Does overflow:hidden applied to <body> work on iPhone Safari?

For me this:

height: 100%; 
overflow: hidden; 
width: 100%; 
position: fixed;

Wasn't enough, i't didn't work on iOS on Safari. I also had to add:

top: 0;
left: 0;
right: 0;
bottom: 0;

To make it work good. Works fine now :)

numpy array TypeError: only integer scalar arrays can be converted to a scalar index

I ran into the problem when venturing to use numpy.concatenate to emulate a C++ like pushback for 2D-vectors; If A and B are two 2D numpy.arrays, then numpy.concatenate(A,B) yields the error.

The fix was to simply to add the missing brackets: numpy.concatenate( ( A,B ) ), which are required because the arrays to be concatenated constitute to a single argument

Access a JavaScript variable from PHP

Well the problem with the GET is that the user is able to change the value by himself if he has some knowledges. I wrote this so that PHP is able to retrive the timezone from Javascript:

// -- index.php

<?php
  if (!isset($_COOKIE['timezone'])) {
?>
<html>
<script language="javascript">  
  var d = new Date(); 
  var timezoneOffset = d.getTimezoneOffset() / 60;
  // the cookie expired in 3 hours
  d.setTime(d.getTime()+(3*60*60*1000));
  var expires = "; expires="+d.toGMTString();
  document.cookie = "timezone=" +  timezoneOffset + expires + "; path=/";
  document.location.href="index.php"
</script>
</html>
<?php
} else {
  ?>

  <html>
  <head>
  <body>

  <?php 
  if(isset($_COOKIE['timezone'])){ 
    dump_var($_COOKIE['timezone']); 
  } 
}
?>

Abort trap 6 error in C

You are writing to memory you do not own:

int board[2][50]; //make an array with 3 columns  (wrong)
                  //(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
    board[2][i] = 'O';
          ^

Change this line:

int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
          ^

To:

int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
          ^

When creating an array, the value used to initialize: [3] indicates array size.
However, when accessing existing array elements, index values are zero based.

For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]

EDIT To address bad output comment and initialization comment

add an additional "\n" for formatting output:

Change:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
 }

       ...

To:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
  printf("\n");//at the end of every row, print a new line
}
...  

Initialize board variable:

int board[3][50] = {0};//initialize all elements to zero

( array initialization discussion... )

What is 'Context' on Android?

Source


The topic of Context in Android seems to be confusing to many. People just know that Context is needed quite often to do basic things in Android. People sometimes panic because they try to do perform some operation that requires the Context and they don’t know how to “get” the right Context. I’m going to try to demystify the idea of Context in Android. A full treatment of the issue is beyond the scope of this post, but I’ll try to give a general overview so that you have a sense of what Context is and how to use it. To understand what Context is, let’s take a look at the source code:

https://github.com/android/platform_frameworks_base/blob/master/core/java/android/content/Context.java

What exactly is Context?

Well, the documentation itself provides a rather straightforward explanation: The Context class is an “Interface to global information about an application environment".

The Context class itself is declared as an abstract class, whose implementation is provided by the Android OS. The documentation further provides that Context “…allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc".

You can understand very well, now, why the name is Context. It’s because it’s just that. The Context provides the link or hook, if you will, for an Activity, Service, or any other component, thereby linking it to the system, enabling access to the global application environment. In other words: the Context provides the answer to the components question of “where the hell am I in relation to app generally and how do I access/communicate with the rest of the app?” If this all seems a bit confusing, a quick look at the methods exposed by the Context class provides some further clues about its true nature.

Here’s a random sampling of those methods:

  1. getAssets()
  2. getResources()
  3. getPackageManager()
  4. getString()
  5. getSharedPrefsFile()

What do all these methods have in common? They all enable whoever has access to the Context to be able to access application-wide resources.

Context, in other words, hooks the component that has a reference to it to the rest of the application environment. The assets (think ’/assets’ folder in your project), for example, are available across the application, provided that an Activity, Service, or whatever knows how to access those resources. The same goes for getResources() which allows us to do things like getResources().getColor() which will hook you into the colors.xml resource (nevermind that aapt enables access to resources via java code, that’s a separate issue).

The upshot is that Context is what enables access to system resources and its what hook components into the “greater app". Let’s look at the subclasses of Context, the classes that provide the implementation of the abstract Context class. The most obvious class is the Activity class. Activity inherits from ContextThemeWrapper, which inherits from ContextWrapper, which inherits from Context itself. Those classes are useful to look at to understand things at a deeper level, but for now, it’s sufficient to know that ContextThemeWrapper and ContextWrapper are pretty much what they sound like. They implement the abstract elements of the Context class itself by “wrapping” a context (the actual context) and delegating those functions to that context. An example is helpful - in the ContextWrapper class, the abstract method getAssets from the Context class is implemented as follows:

@Override
    public AssetManager getAssets() {
        return mBase.getAssets();
    }

mBase is simply a fieldset by the constructor to a specific context. So a context is wrapped and the ContextWrapper delegates its implementation of the getAssets method to that context. Let’s get back to examining the Activity class which ultimately inherits from Context to see how this all works.

You probably know what an Activity is, but to review - it’s basically 'a single thing the user can do. It takes care of providing a window in which to place the UI that the user interacts with'. Developers familiar with other APIs and even non-developers might think of it vernacularly as a “screen.” That’s technically inaccurate, but it doesn’t matter for our purposes. So how do Activity and Context interact and what exactly is going in their inheritance relationship?

Again, it’s helpful to look at specific examples. We all know how to launch Activities. Provided you have “the context” from which you are starting the Activity, you simply call startActivity(intent), where the Intent describes the context from which you are starting an Activity and the Activity you’d like to start. This is the familiar startActivity(this, SomeOtherActivity.class).

And what is this? this is your Activity because the Activity class inherits from Context. The full scoop is like this: When you call startActivity, ultimately the Activity class executes something like this:

Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode);

So it utilizes the execStartActivity from the Instrumentation class (actually from an inner class in Instrumentation called ActivityResult).

At this point, we are beginning to get a peek at the system internals.

This is where OS actually handles everything. So how does Instrumentation start the Activity exactly? Well, the param this in the execStartActivity method above is your Activity, i.e. the Context, and the execStartActivity makes use of this context.

A 30,000 overview is this: the Instrumentation class keeps tracks of a list of Activities that it’s monitoring in order to do its work. This list is used to coordinate all of the activities and make sure everything runs smoothly in managing the flow of activities.

There are some operations that I haven’t fully looked into which coordinate thread and process issues. Ultimately, the ActivityResult uses a native operation - ActivityManagerNative.getDefault().startActivity() which uses the Context that you passed in when you called startActivity. The context you passed in is used to assist in “intent resolution” if needed. Intent resolution is the process by which the system can determine the target of the intent if it is not supplied. (Check out the guide here for more details).

And in order for Android to do this, it needs access to information that is supplied by Context. Specifically, the system needs to access to a ContentResolver so it can “determine the MIME type of the intent’s data". This whole bit about how startActivity makes use of context was a bit complicated and I don’t fully understand the internals myself. My main point was just to illustrate how application-wide resources need to be accessed in order to perform many of the operations that are essential to an app. Context is what provides access to these resources. A simpler example might be Views. We all know what you create a custom View by extending RelativeLayout or some other View class, you must provide a constructor that takes a Context as an argument. When you instantiate your custom View you pass in the context. Why? Because the View needs to be able to have access to themes, resources, and other View configuration details. View configuration is actually a great example. Each Context has various parameters (fields in Context’s implementations) that are set by the OS itself for things like the dimension or density of the display. It’s easy to see why this information is important for setting up Views, etc.

One final word: For some reason, people new to Android (and even people not so new) seem to completely forget about object-oriented programming when it comes to Android. For some reason, people try to bend their Android development to pre-conceived paradigms or learned behaviors.

Android has it’s own paradigm and a certain pattern that is actually quite consistent if let go of your preconceived notions and simply read the documentation and dev guide. My real point, however, while “getting the right context” can sometimes be tricky, people unjustifiably panic because they run into a situation where they need the context and think they don’t have it. Once again, Java is an object-oriented language with an inheritance design.

You only “have” the context inside of your Activity because your activity itself inherits from Context. There’s no magic to it (except for all the stuff the OS does by itself to set various parameters and to correctly “configure” your context). So, putting memory/performance issues aside (e.g. holding references to context when you don’t need to or doing it in a way that has negative consequences on memory, etc), Context is an object like any other and it can be passed around just like any POJO (Plain Old Java Object). Sometimes you might need to do clever things to retrieve that context, but any regular Java class that extends from nothing other than Object itself can be written in a way that has access to context; simply expose a public method that takes a context and then uses it in that class as needed. This was not intended as an exhaustive treatment on Context or Android internals, but I hope it’s helpful in demystifying Context a little bit.

Generating an array of letters in the alphabet

C# 3.0 :

char[] az = Enumerable.Range('a', 'z' - 'a' + 1).Select(i => (Char)i).ToArray();
foreach (var c in az)
{
    Console.WriteLine(c);
}

yes it does work even if the only overload of Enumerable.Range accepts int parameters ;-)

GROUP BY and COUNT in PostgreSQL

I think you just need COUNT(DISTINCT post_id) FROM votes.

See "4.2.7. Aggregate Expressions" section in http://www.postgresql.org/docs/current/static/sql-expressions.html.

EDIT: Corrected my careless mistake per Erwin's comment.

Python way to clone a git repository

My solution is very simple and straight forward. It doesn't even need the manual entry of passphrase/password.

Here is my complete code:

import sys
import os

path  = "/path/to/store/your/cloned/project" 
clone = "git clone gitolite@<server_ip>:/your/project/name.git" 

os.system("sshpass -p your_password ssh user_name@your_localhost")
os.chdir(path) # Specifying the path where the cloned project needs to be copied
os.system(clone) # Cloning

jquery save json data object in cookie

Try this one: https://github.com/tantau-horia/jquery-SuperCookie

Quick Usage:

create - create cookie

check - check existance

verify - verify cookie value if JSON

check_index - verify if index exists in JSON

read_values - read cookie value as string

read_JSON - read cookie value as JSON object

read_value - read value of index stored in JSON object

replace_value - replace value from a specified index stored in JSON object

remove_value - remove value and index stored in JSON object

Just use:

$.super_cookie().create("name_of_the_cookie",name_field_1:"value1",name_field_2:"value2"});
$.super_cookie().read_json("name_of_the_cookie");

How to exclude particular class name in CSS selector?

In modern browsers you can do:

.reMode_hover:not(.reMode_selected):hover{}

Consult http://caniuse.com/css-sel3 for compatibility information.

How do I clone a specific Git branch?

Here is a really simple way to do it :)

Clone the repository

git clone <repository_url>

List all branches

git branch -a 

Checkout the branch that you want

git checkout <name_of_branch>

PHP convert date format dd/mm/yyyy => yyyy-mm-dd

Do this:

date('Y-m-d', strtotime('dd/mm/yyyy'));

But make sure 'dd/mm/yyyy' is the actual date.

How to access html form input from asp.net code behind

If you are accessing a plain HTML form, it has to be submitted to the server via a submit button (or via javascript post). This usually means that your form definition will look like this (I'm going off of memory, make sure you check the html elements are correct):

<form method="POST" action="page.aspx">

<input id="customerName" name="customerName" type="Text" />
<input id="customerPhone" name="customerPhone" type="Text" />
<input value="Save" type="Submit" />

</form>

You should be able to access the customerName and customerPhone data like this:

string n = String.Format("{0}", Request.Form["customerName"]);

If you have method="GET" in the form (not recommended, it messes up your URL space), you will have to access the form data like this:

string n = String.Format("{0}", Request.QueryString["customerName"]);

This of course will only work if the form was 'Posted', 'Submitted', or done via a 'Postback'. (i.e. somebody clicked the 'Save' button, or this was done programatically via javascript.)

Also, keep in mind that accessing these elements in this manner can only be done when you are not using server controls (i.e. runat="server"), with server controls the id and name are different.

Laravel - Pass more than one variable to view

Please try this,

$ms = Person::where('name', 'Foo Bar')->first();
$persons = Person::order_by('list_order', 'ASC')->get();
return View::make('viewname')->with(compact('persons','ms'));

Getting coordinates of marker in Google Maps API

One more alternative options

var map = new google.maps.Map(document.getElementById('map_canvas'), {
    zoom: 1,
    center: new google.maps.LatLng(35.137879, -82.836914),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});

var myMarker = new google.maps.Marker({
    position: new google.maps.LatLng(47.651968, 9.478485),
    draggable: true
});

google.maps.event.addListener(myMarker, 'dragend', function (evt) {
    document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});

google.maps.event.addListener(myMarker, 'dragstart', function (evt) {
    document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
});

map.setCenter(myMarker.position);
myMarker.setMap(map);

and html file

<body>
    <section>
        <div id='map_canvas'></div>
        <div id="current">Nothing yet...</div>
    </section>
</body>

NSAttributedString add text alignment

Swift 4.0+

let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .center

let titleFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
let title = NSMutableAttributedString(string: "You Are Registered", 
    attributes: [.font: titleFont,    
    .foregroundColor: UIColor.red, 
    .paragraphStyle: titleParagraphStyle])

Swift 3.0+

let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .center

let titleFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
let title = NSMutableAttributedString(string: "You Are Registered", 
    attributes: [NSFontAttributeName:titleFont,    
    NSForegroundColorAttributeName:UIColor.red, 
    NSParagraphStyleAttributeName: titleParagraphStyle])

(original answer below)

Swift 2.0+

let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .Center

let titleFont = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
let title = NSMutableAttributedString(string: "You Are Registered",
    attributes:[NSFontAttributeName:titleFont,   
    NSForegroundColorAttributeName:UIColor.redColor(), 
    NSParagraphStyleAttributeName: titleParagraphStyle])

GCC fatal error: stdio.h: No such file or directory

I had the same problem. I installed "XCode: development tools" from the app store and it fixed the problem for me.

I think this link will help: https://itunes.apple.com/us/app/xcode/id497799835?mt=12&ls=1

Credit to Yann Ramin for his advice. I think there is a better solution with links, but this was easy and fast.

Good luck!

How can I set a custom date time format in Oracle SQL Developer?

I stumbled on this post while trying to change the display format for dates in sql-developer. Just wanted to add to this what I found out:

  • To Change the default display format, I would use the steps provided by ousoo i.e Tools > Preferences > ...
  • But a lot of times, I just want to retain the DEFAULT_FORMAT while modifying the format only during a bunch of related queries. That's when I would change the format of the session with the following:

    alter SESSION set NLS_DATE_FORMAT = 'my_required_date_format'

Eg:

   alter SESSION set NLS_DATE_FORMAT = 'DD-MM-YYYY HH24:MI:SS' 

Specifying ssh key in ansible playbook file

If you run your playbook with ansible-playbook -vvv you'll see the actual command being run, so you can check whether the key is actually being included in the ssh command (and you might discover that the problem was the wrong username rather than the missing key).

I agree with Brian's comment above (and zigam's edit) that the vars section is too late. I also tested including the key in the on-the-fly definition of the host like this

# fails
- name: Add all instance public IPs to host group
  add_host: hostname={{ item.public_ip }} groups=ec2hosts ansible_ssh_private_key_file=~/.aws/dev_staging.pem
  loop: "{{ ec2.instances }}"

but that fails too.

So this is not an answer. Just some debugging help and things not to try.

How to insert blank lines in PDF?

You can add empty line ;

 Paragraph p = new Paragraph();
 // add one empty line
  addEmptyLine(p, 1);
 // add 3 empty line
  addEmptyLine(p, 3);


private static void addEmptyLine(Paragraph paragraph, int number) {
    for (int i = 0; i < number; i++) {
      paragraph.add(new Paragraph(" "));
    }
  }

Lambda expression to convert array/List of String to array/List of Integers

The helper methods from the accepted answer are not needed. Streams can be used with lambdas or usually shortened using Method References. Streams enable functional operations. map() converts the elements and collect(...) or toArray() wrap the stream back up into an array or collection.

Venkat Subramaniam's talk (video) explains it better than me.

1 Convert List<String> to List<Integer>

List<String> l1 = Arrays.asList("1", "2", "3");
List<Integer> r1 = l1.stream().map(Integer::parseInt).collect(Collectors.toList());

// the longer full lambda version:
List<Integer> r1 = l1.stream().map(s -> Integer.parseInt(s)).collect(Collectors.toList());

2 Convert List<String> to int[]

int[] r2 = l1.stream().mapToInt(Integer::parseInt).toArray();

3 Convert String[] to List<Integer>

String[] a1 = {"4", "5", "6"};
List<Integer> r3 = Stream.of(a1).map(Integer::parseInt).collect(Collectors.toList());

4 Convert String[] to int[]

int[] r4 = Stream.of(a1).mapToInt(Integer::parseInt).toArray();

5 Convert String[] to List<Double>

List<Double> r5 = Stream.of(a1).map(Double::parseDouble).collect(Collectors.toList());

6 (bonus) Convert int[] to String[]

int[] a2 = {7, 8, 9};
String[] r6 = Arrays.stream(a2).mapToObj(Integer::toString).toArray(String[]::new);

Lots more variations are possible of course.

Also see Ideone version of these examples. Can click fork and then run to run in the browser.

Is it possible to make a Tree View with Angular?

So many great solutions, but I feel they all in one way or another over-complicate things a bit.

I wanted to create something that recreated the simplicity of @Mark Lagendijk's awnser, but without it defining a template in the directive, but rather would let the "user" create the template in HTML...

With ideas taken from https://github.com/stackfull/angular-tree-repeat etc... I ended up with creating the project: https://github.com/dotJEM/angular-tree

Which allows you to build your tree like:

<ul dx-start-with="rootNode">
  <li ng-repeat="node in $dxPrior.nodes">
    {{ node.name }}
    <ul dx-connect="node"/>
  </li>
</ul>

Which to me is cleaner than having to create multiple directives for differently structured trees.... In essence calling the above a tree is a bit false, it picks much more off from @ganaraj's awnser of "recursive templates", but allows us to define the template where we need the tree.

(you could do that with a script tag based template, but it still has to sit right outside the actual tree node, and it still just feels a bit yuk...)

Left here for just another choice...

fatal: Not a git repository (or any of the parent directories): .git

The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo

  1. Are you in the right directory? Does typing ls show the right files?
  2. Have you initialized the repository yet? Typed git init? (git-init documentation)

Either of those would cause your error.

How do I check what version of Python is running my script?

The simplest way

Just type python in your terminal and you can see the version as like following

desktop:~$ python
Python 2.7.6 (default, Jun 22 2015, 18:00:18) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 

Obtain form input fields using jQuery?

All answers are good, but if there's a field that you like to ignore in that function? Easy, give the field a property, for example ignore_this:

<input type="text" name="some_name" ignore_this>

And in your Serialize Function:

if(!$(name).prop('ignorar')){
   do_your_thing;
}

That's the way you ignore some fields.

SQL DELETE with JOIN another table for WHERE condition

Try this sample SQL scripts for easy understanding,

CREATE TABLE TABLE1 (REFNO VARCHAR(10))
CREATE TABLE TABLE2 (REFNO VARCHAR(10))

--TRUNCATE TABLE TABLE1
--TRUNCATE TABLE TABLE2

INSERT INTO TABLE1 SELECT 'TEST_NAME'
INSERT INTO TABLE1 SELECT 'KUMAR'
INSERT INTO TABLE1 SELECT 'SIVA'
INSERT INTO TABLE1 SELECT 'SUSHANT'

INSERT INTO TABLE2 SELECT 'KUMAR'
INSERT INTO TABLE2 SELECT 'SIVA'
INSERT INTO TABLE2 SELECT 'SUSHANT'

SELECT * FROM TABLE1
SELECT * FROM TABLE2

DELETE T1 FROM TABLE1 T1 JOIN TABLE2 T2 ON T1.REFNO = T2.REFNO

Your case is:

   DELETE pgc
     FROM guide_category pgc 
LEFT JOIN guide g
       ON g.id_guide = gc.id_guide 
    WHERE g.id_guide IS NULL

Iterating through a List Object in JSP

Before teaching yourself Spring and Struts, you should probably learn Java. Output like this

org.classes.database.Employee@d9b02

is the result of the Object#toString() method which all objects inherit from the Object class, the superclass of all classes in Java.

The List sub classes implement this by iterating over all the elements and calling toString() on those. It seems, however, that you haven't implemented (overriden) the method in your Employee class.

Your JSTL here

<c:forEach items="${eList}" var="employee">
    <tr>
        <td>Employee ID: <c:out value="${employee.eid}"/></td>
        <td>Employee Pass: <c:out value="${employee.ename}"/></td>  
    </tr>
</c:forEach>

is fine except for the fact that you don't have a page, request, session, or application scoped attribute named eList.

You need to add it

<% List eList = (List)session.getAttribute("empList");
   request.setAttribute("eList", eList);
%>

Or use the attribute empList in the forEach.

<c:forEach items="${empList}" var="employee">
    <tr>
        <td>Employee ID: <c:out value="${employee.eid}"/></td>
        <td>Employee Pass: <c:out value="${employee.ename}"/></td>  
    </tr>
</c:forEach>

Using OR operator in a jquery if statement

Think about what

if ((state != 10) || (state != 15) || (state != 19) || (state != 22) || (state != 33) || (state != 39) || (state != 47) || (state != 48) || (state != 49) || (state != 51))

means. || means "or." The negation of this is (by DeMorgan's Laws):

state == 10 && state == 15 && state == 19...

In other words, the only way that this could be false if if a state equals 10, 15, and 19 (and the rest of the numbers in your or statement) at the same time, which is impossible.

Thus, this statement will always be true. State 15 will never equal state 10, for example, so it's always true that state will either not equal 10 or not equal 15.

Change || to &&.

Also, in most languages, the following:

if (x) {
  return true;
}
else {
  return false;
}

is not necessary. In this case, the method returns true exactly when x is true and false exactly when x is false. You can just do:

return x;

Perform curl request in javascript?

Yes, use getJSONP. It's the only way to make cross domain/server async calls. (*Or it will be in the near future). Something like

$.getJSON('your-api-url/validate.php?'+$(this).serialize+'callback=?', function(data){
if(data)console.log(data);
});

The callback parameter will be filled in automatically by the browser, so don't worry.

On the server side ('validate.php') you would have something like this

<?php
if(isset($_GET))
{
//if condition is met
echo $_GET['callback'] . '(' . "{'message' : 'success', 'userID':'69', 'serial' : 'XYZ99UAUGDVD&orwhatever'}". ')';
}
else echo json_encode(array('error'=>'failed'));
?>

How to correctly implement custom iterators and const_iterators?

There are plenty of good answers but I created a template header I use that is quite concise and easy to use.

To add an iterator to your class it is only necessary to write a small class to represent the state of the iterator with 7 small functions, of which 2 are optional:

#include <iostream>
#include <vector>
#include "iterator_tpl.h"

struct myClass {
  std::vector<float> vec;

  // Add some sane typedefs for STL compliance:
  STL_TYPEDEFS(float);

  struct it_state {
    int pos;
    inline void begin(const myClass* ref) { pos = 0; }
    inline void next(const myClass* ref) { ++pos; }
    inline void end(const myClass* ref) { pos = ref->vec.size(); }
    inline float& get(myClass* ref) { return ref->vec[pos]; }
    inline bool cmp(const it_state& s) const { return pos != s.pos; }

    // Optional to allow operator--() and reverse iterators:
    inline void prev(const myClass* ref) { --pos; }
    // Optional to allow `const_iterator`:
    inline const float& get(const myClass* ref) const { return ref->vec[pos]; }
  };
  // Declare typedef ... iterator;, begin() and end() functions:
  SETUP_ITERATORS(myClass, float&, it_state);
  // Declare typedef ... reverse_iterator;, rbegin() and rend() functions:
  SETUP_REVERSE_ITERATORS(myClass, float&, it_state);
};

Then you can use it as you would expect from an STL iterator:

int main() {
  myClass c1;
  c1.vec.push_back(1.0);
  c1.vec.push_back(2.0);
  c1.vec.push_back(3.0);

  std::cout << "iterator:" << std::endl;
  for (float& val : c1) {
    std::cout << val << " "; // 1.0 2.0 3.0
  }

  std::cout << "reverse iterator:" << std::endl;
  for (auto it = c1.rbegin(); it != c1.rend(); ++it) {
    std::cout << *it << " "; // 3.0 2.0 1.0
  }
}

I hope it helps.

How to escape special characters in building a JSON string?

Using template literals...

var json = `{"1440167924916":{"id":1440167924916,"type":"text","content":"It's a test!"}}`;

How to reverse a singly linked list using only two pointers?

#include <stdio.h>
#include <malloc.h>

tydef struct node
{
    int info;
    struct node *link;
} *start;

void main()
{
    rev();
}

void rev()
{
    struct node *p = start, *q = NULL, *r;
    while (p != NULL)
    {
        r = q;
        q = p;
        p = p->link;
        q->link = r;
    }

    start = q;
}

How to define unidirectional OneToMany relationship in JPA

My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany which explains how to do this with a @JoinColumn annotation. In your case, i think you would want:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;

I've used a Set rather than a List, because the data itself is not ordered.

The above is using a defaulted referencedColumnName, unlike the example in the wikibook. If that doesn't work, try an explicit one:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;

SQLException: No suitable Driver Found for jdbc:oracle:thin:@//localhost:1521/orcl

For me I did enter a invalid url like : orcl only instead of jdbc:oracle:thin:@//localhost:1521/orcl

jQuery remove selected option from this

This is a simpler one

$('#some_select_box').find('option:selected').remove().end();

How to use global variables in React Native?

Set up a flux container

simple example

import alt from './../../alt.js';

    class PostActions {
        constructor(){
        this.generateActions('setMessages');
        }

        setMessages(indexArray){
            this.actions.setMessages(indexArray);
        }
    }


export default alt.createActions(PostActions);

store looks like this

class PostStore{

    constructor(){

       this.messages = [];

       this.bindActions(MessageActions);
    }




    setMessages(messages){
        this.messages = messages;
    }
}

export default alt.createStore(PostStore);

Then every component that listens to the store can share this variable In your constructor is where you should grab it

constructor(props){
    super(props);

   //here is your data you get from the store, do what you want with it 
    var messageStore = MessageStore.getState();

}


    componentDidMount() {
      MessageStore.listen(this.onMessageChange.bind(this));
    }

    componentWillUnmount() {
      MessageStore.unlisten(this.onMessageChange.bind(this));
    }

    onMessageChange(state){ 
        //if the data ever changes each component listining will be notified and can do the proper processing. 
   }

This way, you can share you data across the app without every component having to communicate with each other.

What is Python Whitespace and how does it work?

Whitespace is used to denote blocks. In other languages curly brackets ({ and }) are common. When you indent, it becomes a child of the previous line. In addition to the indentation, the parent also has a colon following it.

im_a_parent:
    im_a_child:
        im_a_grandchild
    im_another_child:
        im_another_grand_child

Off the top of my head, def, if, elif, else, try, except, finally, with, for, while, and class all start blocks. To end a block, you simple outdent, and you will have siblings. In the above im_a_child and im_another_child are siblings.

Can I prevent text in a div block from overflowing?

Recommendations for how to catch which part of your CSS is causing the issue:

1) set style="height:auto;" on all the <div> elements and retry again.

2) Set style="border: 3px solid red;" on all the <div> elements to see how wide of an area your <div>'s box is taking up.

3) Take away all the css height:#px; properties from your CSS and start over.

So for example:

<div id="I" style="height:auto;border: 3px solid red;">I
    <div id="A" style="height:auto;border: 3px solid purple;">A
        <div id="1A" style="height:auto;border: 3px solid green;">1A
        </div>
        <div id="2A" style="height:auto;border: 3px solid green;">2A
        </div>
    </div>
    <div id="B" style="height:auto;border: 3px solid purple;">B
        <div id="1B" style="height:auto;border: 3px solid green;">1B
        </div>
        <div id="2B" style="height:auto;border: 3px solid green;">2B
        </div>
    </div>
</div>

Place a button right aligned

This solution depends on Bootstrap 3, as pointed out by @günther-jena

Try <a class="btn text-right">Call to Action</a>. This way you don't need extra markup or rules to clear out floated elements.

Default fetch type for one-to-one, many-to-one and one-to-many in Hibernate

I know the answers were correct at the time of asking the question - but since people (like me this minute) still happen to find them wondering why their WildFly 10 was behaving differently, I'd like to give an update for the current Hibernate 5.x version:

In the Hibernate 5.2 User Guide it is stated in chapter 11.2. Applying fetch strategies:

The Hibernate recommendation is to statically mark all associations lazy and to use dynamic fetching strategies for eagerness. This is unfortunately at odds with the JPA specification which defines that all one-to-one and many-to-one associations should be eagerly fetched by default. Hibernate, as a JPA provider, honors that default.

So Hibernate as well behaves like Ashish Agarwal stated above for JPA:

OneToMany: LAZY
ManyToOne: EAGER
ManyToMany: LAZY
OneToOne: EAGER

(see JPA 2.1 Spec)

Simplest way to merge ES6 Maps/Sets?

It does not make any sense to call new Set(...anArrayOrSet) when adding multiple elements (from either an array or another set) to an existing set.

I use this in a reduce function, and it is just plain silly. Even if you have the ...array spread operator available, you should not use it in this case, as it wastes processor, memory, and time resources.

// Add any Map or Set to another
function addAll(target, source) {
  if (target instanceof Map) {
    Array.from(source.entries()).forEach(it => target.set(it[0], it[1]))
  } else if (target instanceof Set) {
    source.forEach(it => target.add(it))
  }
}

Demo Snippet

_x000D_
_x000D_
// Add any Map or Set to another_x000D_
function addAll(target, source) {_x000D_
  if (target instanceof Map) {_x000D_
    Array.from(source.entries()).forEach(it => target.set(it[0], it[1]))_x000D_
  } else if (target instanceof Set) {_x000D_
    source.forEach(it => target.add(it))_x000D_
  }_x000D_
}_x000D_
_x000D_
const items1 = ['a', 'b', 'c']_x000D_
const items2 = ['a', 'b', 'c', 'd']_x000D_
const items3 = ['d', 'e']_x000D_
_x000D_
let set_x000D_
_x000D_
set = new Set(items1)_x000D_
addAll(set, items2)_x000D_
addAll(set, items3)_x000D_
console.log('adding array to set', Array.from(set))_x000D_
_x000D_
set = new Set(items1)_x000D_
addAll(set, new Set(items2))_x000D_
addAll(set, new Set(items3))_x000D_
console.log('adding set to set', Array.from(set))_x000D_
_x000D_
const map1 = [_x000D_
  ['a', 1],_x000D_
  ['b', 2],_x000D_
  ['c', 3]_x000D_
]_x000D_
const map2 = [_x000D_
  ['a', 1],_x000D_
  ['b', 2],_x000D_
  ['c', 3],_x000D_
  ['d', 4]_x000D_
]_x000D_
const map3 = [_x000D_
  ['d', 4],_x000D_
  ['e', 5]_x000D_
]_x000D_
_x000D_
const map = new Map(map1)_x000D_
addAll(map, new Map(map2))_x000D_
addAll(map, new Map(map3))_x000D_
console.log('adding map to map',_x000D_
  'keys', Array.from(map.keys()),_x000D_
  'values', Array.from(map.values()))
_x000D_
_x000D_
_x000D_

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

How I redirect to an area is add it as a parameter

@Html.Action("Action", "Controller", new { area = "AreaName" })

for the href portion of a link I use

@Url.Action("Action", "Controller", new { area = "AreaName" })

ios app maximum memory budget

Results of testing with the utility Split wrote (link is in his answer):

device: (crash amount/total amount/percentage of total)

  • iPad1: 127MB/256MB/49%
  • iPad2: 275MB/512MB/53%
  • iPad3: 645MB/1024MB/62%
  • iPad4: 585MB/1024MB/57% (iOS 8.1)
  • iPad Mini 1st Generation: 297MB/512MB/58%
  • iPad Mini retina: 696MB/1024MB/68% (iOS 7.1)
  • iPad Air: 697MB/1024MB/68%
  • iPad Air 2: 1383MB/2048MB/68% (iOS 10.2.1)
  • iPad Pro 9.7": 1395MB/1971MB/71% (iOS 10.0.2 (14A456))
  • iPad Pro 10.5”: 3057/4000/76% (iOS 11 beta4)
  • iPad Pro 12.9” (2015): 3058/3999/76% (iOS 11.2.1)
  • iPad Pro 12.9” (2017): 3057/3974/77% (iOS 11 beta4)
  • iPad Pro 11.0” (2018): 2858/3769/76% (iOS 12.1)
  • iPad Pro 12.9” (2018, 1TB): 4598/5650/81% (iOS 12.1)
  • iPad 10.2: 1844/2998/62% (iOS 13.2.3)
  • iPod touch 4th gen: 130MB/256MB/51% (iOS 6.1.1)
  • iPod touch 5th gen: 286MB/512MB/56% (iOS 7.0)
  • iPhone4: 325MB/512MB/63%
  • iPhone4s: 286MB/512MB/56%
  • iPhone5: 645MB/1024MB/62%
  • iPhone5s: 646MB/1024MB/63%
  • iPhone6: 645MB/1024MB/62% (iOS 8.x)
  • iPhone6+: 645MB/1024MB/62% (iOS 8.x)
  • iPhone6s: 1396MB/2048MB/68% (iOS 9.2)
  • iPhone6s+: 1392MB/2048MB/68% (iOS 10.2.1)
  • iPhoneSE: 1395MB/2048MB/69% (iOS 9.3)
  • iPhone7: 1395/2048MB/68% (iOS 10.2)
  • iPhone7+: 2040MB/3072MB/66% (iOS 10.2.1)
  • iPhone8: 1364/1990MB/70% (iOS 12.1)
  • iPhone X: 1392/2785/50% (iOS 11.2.1)
  • iPhone XS: 2040/3754/54% (iOS 12.1)
  • iPhone XS Max: 2039/3735/55% (iOS 12.1)
  • iPhone XR: 1792/2813/63% (iOS 12.1)
  • iPhone 11: 2068/3844/54% (iOS 13.1.3)
  • iPhone 11 Pro Max: 2067/3740/55% (iOS 13.2.3)

How to create and add users to a group in Jenkins for authentication?

You could use Role Strategy plugin for that purpose. It works like a charm, just setup some roles and assign them. Even on project-specific level.

How to save final model using keras?

You can use model.save(filepath) to save a Keras model into a single HDF5 file which will contain:

  • the architecture of the model, allowing to re-create the model.
  • the weights of the model.
  • the training configuration (loss, optimizer)
  • the state of the optimizer, allowing to resume training exactly where you left off.

In your Python code probable the last line should be:

model.save("m.hdf5")

This allows you to save the entirety of the state of a model in a single file. Saved models can be reinstantiated via keras.models.load_model().

The model returned by load_model() is a compiled model ready to be used (unless the saved model was never compiled in the first place).

model.save() arguments:

  • filepath: String, path to the file to save the weights to.
  • overwrite: Whether to silently overwrite any existing file at the target location, or provide the user with a manual prompt.
  • include_optimizer: If True, save optimizer's state together.

How do you print in Sublime Text 2

Still no print no native print function, but outside the installing the suggested package, you can go the autohotkey way, as the that app can actually help you run macros for other stuff as well. So you can do something like create a macro that with one click does:

  1. Select all the text
  2. Copies all the text
  3. Opens your other edit of choice
  4. pastes text
  5. Prints text

No the most glamorous of options but could also work if the receiving app has can accept code-formatting.

groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding

As pointed out by @Jayan in another post, the solution was to do the following

import jenkins.model.*
jenkins = Jenkins.instance

Then I was able to do the rest of my scripting the way it was.

auto create database in Entity Framework Core

For EF Core 2.0+ I had to take a different approach because they changed the API. As of March 2019 Microsoft recommends you put your database migration code in your application entry class but outside of the WebHost build code.

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args).Build();
        using (var serviceScope = host.Services.CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetRequiredService<PersonContext>();
            context.Database.Migrate();
        }
        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

'if' statement in jinja2 template

We need to remember that the {% endif %} comes after the {% else %}.

So this is an example:

{% if someTest %}
     <p> Something is True </p>
{% else %}
     <p> Something is False </p>
{% endif %}

Interview question: Check if one string is a rotation of other string

int rotation(char *s1,char *s2)
{
    int i,j,k,p=0,n;
    n=strlen(s1);
    k=strlen(s2);
    if (n!=k)
        return 0;
    for (i=0;i<n;i++)
    {
        if (s1[0]==s2[i])
        {
            for (j=i,k=0;k<n;k++,j++)
            {
                if (s1[k]==s2[j])
                    p++;
                if (j==n-1)
                    j=0;
            }
        }
    }
    if (n==p+1)
      return 1;
    else
      return 0;
}

Sass and combined child selector

Without the combined child selector you would probably do something similar to this:

foo {
  bar {
    baz {
      color: red;
    }
  }
}

If you want to reproduce the same syntax with >, you could to this:

foo {
  > bar {
    > baz {
      color: red;
    }
  }
}

This compiles to this:

foo > bar > baz {
  color: red;
}

Or in sass:

foo
  > bar
    > baz
      color: red

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

It seems to me that your Hibernate libraries are not found (NoClassDefFoundError: org/hibernate/boot/archive/scan/spi/ScanEnvironment as you can see above).

Try checking to see if Hibernate core is put in as dependency:

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>5.0.11.Final</version>
  <scope>compile</scope>
</dependency>

What is the difference between String and string in C#?

String : Represent a class

string : Represent an alias

It's just a coding convention from microsoft .

Notification bar icon turns white in Android 5 Lollipop

According to the Android design guidelines you must use a silhouette for builder.setSmallIcon(R.drawable.some_notification_icon); But if you still wants to show a colorful icon as a notification icon here is the trick for lollipop and above use below code. The largeIcon will act as a primary notification icon and you also need to provide a silhouette for smallIcon as it will be shown over the bottom right of the largeIcon.

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
     builder.setColor(context.getResources().getColor(R.color.red));
     builder.setSmallIcon(R.drawable.some_notification_icon);
     builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher));
}

And pre-lollipop use only .setSmallIcon(R.mipmap.ic_launcher) with your builder.

E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation

I faced the same issue:

E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation

I resolved by using the following commands:

apt-get update
apt-get install gnupg

Json.NET serialize object with root name

I found an easy way to render this out... simply declare a dynamic object and assign the first item within the dynamic object to be your collection class...This example assumes you're using Newtonsoft.Json

private class YourModelClass
{
    public string firstName { get; set; }
    public string lastName { get; set; }
}

var collection = new List<YourModelClass>();

var collectionWrapper = new {

    myRoot = collection

};

var output = JsonConvert.SerializeObject(collectionWrapper);

What you should end up with is something like this:

{"myRoot":[{"firstName":"John", "lastName": "Citizen"}, {...}]}

How to embed small icon in UILabel

In Swift 5, By using UILabel extensions to embed icon in leading as well as trailing side of the text as follows:-

extension UILabel {
    
    func addTrailing(image: UIImage, text:String) {
        let attachment = NSTextAttachment()
        attachment.image = image

        let attachmentString = NSAttributedString(attachment: attachment)
        let string = NSMutableAttributedString(string: text, attributes: [:])

        string.append(attachmentString)
        self.attributedText = string
    }
    
    func addLeading(image: UIImage, text:String) {
        let attachment = NSTextAttachment()
        attachment.image = image

        let attachmentString = NSAttributedString(attachment: attachment)
        let mutableAttributedString = NSMutableAttributedString()
        mutableAttributedString.append(attachmentString)
        
        let string = NSMutableAttributedString(string: text, attributes: [:])
        mutableAttributedString.append(string)
        self.attributedText = mutableAttributedString
    }
}

To use above mentioned code in your desired label as:-

Image in right of text then:-

statusLabel.addTrailing(image: UIImage(named: "rightTick") ?? UIImage(), text: " Verified ")

Image in left of text then:-

statusLabel.addLeading(image: UIImage(named: "rightTick") ?? UIImage(), text: " Verified ")

Output:-

enter image description here

enter image description here

how to convert from int to char*?

I would not typecast away the const in the last line since it is there for a reason. If you can't live with a const char* then you better copy the char array like:

char* char_type = new char[temp_str.length()];
strcpy(char_type, temp_str.c_str());

Real mouse position in canvas

The easiest way to compute the correct mouse click or mouse move position on a canvas event is to use this little equation:

canvas.addEventListener('click', event =>
{
    let bound = canvas.getBoundingClientRect();

    let x = event.clientX - bound.left - canvas.clientLeft;
    let y = event.clientY - bound.top - canvas.clientTop;

    context.fillRect(x, y, 16, 16);
});

If the canvas has padding-left or padding-top, subtract x and y via:

x -= parseFloat(style['padding-left'].replace('px'));
y -= parseFloat(style['padding-top'].replace('px'));

Can I write into the console in a unit test? If yes, why doesn't the console window open?

IMHO, output messages are relevant only for failed test cases in most cases. I made up the below format, and you can make your own too. This is displayed in the Visual Studio Test Explorer Window itself.

How can we throw this message in the Visual Studio Test Explorer Window?

Sample code like this should work:

if(test_condition_fails)
    Assert.Fail(@"Test Type: Positive/Negative.
                Mock Properties: someclass.propertyOne: True
                someclass.propertyTwo: True
                Test Properties: someclass.testPropertyOne: True
                someclass.testPropertyOne: False
                Reason for Failure: The Mail was not sent on Success Task completion.");

You can have a separate class dedicated to this for you.

MySQL query finding values in a comma separated string

select * from shirts where find_in_set('1',colors) <> 0

Works for me

Update Top 1 record in table sql server

UPDATE TX_Master_PCBA
SET TIMESTAMP2 = '2013-12-12 15:40:31.593',
G_FIELD='0000'
WHERE TIMESTAMP2 IN 
(
   SELECT TOP 1 TIMESTAMP2
   FROM TX_Master_PCBA WHERE SERIAL_NO='0500030309'
   ORDER BY TIMESTAMP2 DESC   -- You need to decide what column you want to sort on
)

Any way to clear python's IDLE window?

An extension for clearing the shell can be found in Issue6143 as a "feature request". This extension is included with IdleX.

.Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

Interestingly, the HttpWebResponse.GetResponseStream() that you get from the WebException.Response is not the same as the response stream that you would have received from server. In our environment, we're losing actual server responses when a 400 HTTP status code is returned back to the client using the HttpWebRequest/HttpWebResponse objects. From what we've seen, the response stream associated with the WebException's HttpWebResponse is generated at the client and does not include any of the response body from the server. Very frustrating, as we want to message back to the client the reason for the bad request.

jQuery: Uncheck other checkbox on one checked

Bind a change handler, then just uncheck all of the checkboxes, apart from the one checked:

$('input.example').on('change', function() {
    $('input.example').not(this).prop('checked', false);  
});

Here's a fiddle

Is there a limit on number of tcp/ip connections between machines on linux?

When looking for the max performance you run into a lot of issue and potential bottlenecks. Running a simple hello world test is not necessarily going to find them all.

Possible limitations include:

  • Kernel socket limitations: look in /proc/sys/net for lots of kernel tuning..
  • process limits: check out ulimit as others have stated here
  • as your application grows in complexity, it may not have enough CPU power to keep up with the number of connections coming in. Use top to see if your CPU is maxed
  • number of threads? I'm not experienced with threading, but this may come into play in conjunction with the previous items.

Define an alias in fish shell

For posterity, fish aliases are just functions:

$ alias foo="echo bar"
$ type foo
foo is a function with definition
function foo
    echo bar $argv; 
end

To remove it

$ unalias foo
/usr/bin/unalias: line 2: unalias: foo: not found
$ functions -e foo
$ type foo
type: Could not find “foo”

Make ABC Ordered List Items Have Bold Style

You could do something like this also:

<ol type="A" style="font-weight: bold;">

<li style="padding-bottom: 8px;">****</li>

It is simple code for the beginners.

This code is been tested in "Mozilla, chrome and edge..

select data up to a space?

You can use a combiation of LEFT and CHARINDEX to find the index of the first space, and then grab everything to the left of that.

 SELECT LEFT(YourColumn, charindex(' ', YourColumn) - 1) 

And in case any of your columns don't have a space in them:

SELECT LEFT(YourColumn, CASE WHEN charindex(' ', YourColumn) = 0 THEN 
    LEN(YourColumn) ELSE charindex(' ', YourColumn) - 1 END)

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

Instead of passing reference object passed the saved object, below is explanation which solve my issue:

//wrong
entityManager.persist(role);
user.setRole(role);
entityManager.persist(user)

//right
Role savedEntity= entityManager.persist(role);
user.setRole(savedEntity);
entityManager.persist(user)

What is the most "pythonic" way to iterate over a list in chunks?

The more-itertools package has chunked method which does exactly that:

import more_itertools
for s in more_itertools.chunked(range(9), 4):
    print(s)

Prints

[0, 1, 2, 3]
[4, 5, 6, 7]
[8]

chunked returns the items in a list. If you'd prefer iterables, use ichunked.

How do I check if a given string is a legal/valid file name under Windows?

Microsoft Windows: Windows kernel forbids the use of characters in range 1-31 (i.e., 0x01-0x1F) and characters " * : < > ? \ |. Although NTFS allows each path component (directory or filename) to be 255 characters long and paths up to about 32767 characters long, the Windows kernel only supports paths up to 259 characters long. Additionally, Windows forbids the use of the MS-DOS device names AUX, CLOCK$, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, CON, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9, NUL and PRN, as well as these names with any extension (for example, AUX.txt), except when using Long UNC paths (ex. \.\C:\nul.txt or \?\D:\aux\con). (In fact, CLOCK$ may be used if an extension is provided.) These restrictions only apply to Windows - Linux, for example, allows use of " * : < > ? \ | even in NTFS.

Source: http://en.wikipedia.org/wiki/Filename

Using Java 8's Optional with Stream::flatMap

A slightly shorter version using reduce:

things.stream()
  .map(this::resolve)
  .reduce(Optional.empty(), (a, b) -> a.isPresent() ? a : b );

You could also move the reduce function to a static utility method and then it becomes:

  .reduce(Optional.empty(), Util::firstPresent );

Is there a maximum number you can set Xmx to when trying to increase jvm memory?

I think a 32 bit JVM has a maximum of 2GB memory.This might be out of date though. If I understood correctly, you set the -Xmx on Eclipse launcher. If you want to increase the memory for the program you run from Eclipse, you should define -Xmx in the "Run->Run configurations..."(select your class and open the Arguments tab put it in the VM arguments area) menu, and NOT on Eclipse startup

Edit: details you asked for. in Eclipse 3.4

  1. Run->Run Configurations...

  2. if your class is not listed in the list on the left in the "Java Application" subtree, click on "New Launch configuration" in the upper left corner

  3. on the right, "Main" tab make sure the project and the class are the right ones

  4. select the "Arguments" tab on the right. this one has two text areas. one is for the program arguments that get in to the args[] array supplied to your main method. the other one is for the VM arguments. put into the one with the VM arguments(lower one iirc) the following:
    -Xmx2048m

    I think that 1024m should more than enough for what you need though!

  5. Click Apply, then Click Run

  6. Should work :)

jquery change class name

I think he wants to replace a class name.

Something like this would work:

$(document).ready(function(){
    $('.blue').removeClass('blue').addClass('green');
});

from http://monstertut.com/2012/06/use-jquery-to-change-css-class/

Angular ui-grid dynamically calculate height of the grid

I use ui-grid - v3.0.0-rc.20 because a scrolling issue is fixed when you go full height of container. Use the ui.grid.autoResize module will dynamically auto resize the grid to fit your data. To calculate the height of your grid use the function below. The ui-if is optional to wait until your data is set before rendering.

_x000D_
_x000D_
angular.module('app',['ui.grid','ui.grid.autoResize']).controller('AppController', ['uiGridConstants', function(uiGridConstants) {_x000D_
    ..._x000D_
    _x000D_
    $scope.gridData = {_x000D_
      rowHeight: 30, // set row height, this is default size_x000D_
      ..._x000D_
    };_x000D_
  _x000D_
    ..._x000D_
_x000D_
    $scope.getTableHeight = function() {_x000D_
       var rowHeight = 30; // your row height_x000D_
       var headerHeight = 30; // your header height_x000D_
       return {_x000D_
          height: ($scope.gridData.data.length * rowHeight + headerHeight) + "px"_x000D_
       };_x000D_
    };_x000D_
      _x000D_
    ...
_x000D_
<div ui-if="gridData.data.length>0" id="grid1" ui-grid="gridData" class="grid" ui-grid-auto-resize ng-style="getTableHeight()"></div>
_x000D_
_x000D_
_x000D_

HTML iframe - disable scroll

You can use the following CSS code:

margin-top: -145px; 
margin-left: -80px;
margin-bottom: -650px;

In order to limit the view of the iframe.

How can I show line numbers in Eclipse?

click on window tab and click on preferences

click on window tab

do this and check show line number

check show line number

Downloading and unzipping a .zip file without writing to disk

All of these answers appear too bulky and long. Use requests to shorten the code, e.g.:

import requests, zipfile, io
r = requests.get(zip_file_url)
z = zipfile.ZipFile(io.BytesIO(r.content))
z.extractall("/path/to/directory")

How do I set a cookie on HttpClient's HttpRequestMessage

I had a similar problem and for my AspNetCore 3.1 application the other answers to this question were not working. I found that configuring a named HttpClient in my Startup.cs and using header propagation of the Cookie header worked perfectly. It also avoids all the concerns about proper disposition of your handler and client. Note if propagation of the request cookies is not what you need (sorry Op) you can set your own cookies when configuring the client factory.

Configure Services with IServiceCollection

services.AddHttpClient("MyNamedClient").AddHeaderPropagation();
services.AddHeaderPropagation(options =>
{
    options.Headers.Add("Cookie");
});

Configure with IApplicationBuilder

builder.UseHeaderPropagation();
  • Inject the IHttpClientFactory into your controller or middleware.
  • Create your client using var client = clientFactory.CreateClient("MyNamedClient");

Python error message io.UnsupportedOperation: not readable

There are few modes to open file (read, write etc..)

If you want to read from file you should type file = open("File.txt","r"), if write than file = open("File.txt","w"). You need to give the right permission regarding your usage.

more modes:

  • r. Opens a file for reading only.
  • rb. Opens a file for reading only in binary format.
  • r+ Opens a file for both reading and writing.
  • rb+ Opens a file for both reading and writing in binary format.
  • w. Opens a file for writing only.
  • you can find more modes in here

How do I deal with special characters like \^$.?*|+()[{ in my regex?

I think the easiest way to match the characters like

\^$.?*|+()[

are using character classes from within R. Consider the following to clean column headers from a data file, which could contain spaces, and punctuation characters:

> library(stringr)
> colnames(order_table) <- str_replace_all(colnames(order_table),"[:punct:]|[:space:]","")

This approach allows us to string character classes to match punctation characters, in addition to whitespace characters, something you would normally have to escape with \\ to detect. You can learn more about the character classes at this cheatsheet below, and you can also type in ?regexp to see more info about this.

https://www.rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf

What is a deadlock?

Deadlock is a common problem in multiprocessing/multiprogramming problems in OS. Say there are two processes P1, P2 and two globally shareable resource R1, R2 and in critical section both resources need to be accessed

Initially, the OS assigns R1 to process P1 and R2 to process P2. As both processes are running concurrently they may start executing their code but the PROBLEM arises when a process hits the critical section. So process R1 will wait for process P2 to release R2 and vice versa... So they will wait for forever (DEADLOCK CONDITION).

A small ANALOGY...

Your Mother(OS),
You(P1),
Your brother(P2),
Apple(R1),
Knife(R2),
critical section(cutting apple with knife).

Your mother gives you the apple and the knife to your brother in the beginning.
Both are happy and playing(Executing their codes).
Anyone of you wants to cut the apple(critical section) at some point.
You don't want to give the apple to your brother.
Your brother doesn't want to give the knife to you.
So both of you are going to wait for a long very long time :)

How to hide Soft Keyboard when activity starts

Use SOFT_INPUT_STATE_ALWAYS_HIDDEN instead of SOFT_INPUT_STATE_HIDDEN

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

When to use React setState callback

The 1. usecase which comes into my mind, is an api call, which should't go into the render, because it will run for each state change. And the API call should be only performed on special state change, and not on every render.

changeSearchParams = (params) => {
  this.setState({ params }, this.performSearch)
} 

performSearch = () => {
  API.search(this.state.params, (result) => {
    this.setState({ result })
  });
}

Hence for any state change, an action can be performed in the render methods body.

Very bad practice, because the render-method should be pure, it means no actions, state changes, api calls, should be performed, just composite your view and return it. Actions should be performed on some events only. Render is not an event, but componentDidMount for example.

'Incomplete final line' warning when trying to read a .csv file into R

I realized that several answers have been provided but no real fix yet.

The reason, as mentioned above, is a "End of line" missing at the end of the CSV file.

While the real Fix should come from Microsoft, the walk around is to open the CSV file with a Text-editor and add a line at the end of the file (aka press return key). I use ATOM software as a text/code editor but virtually all basic text editor would do.

In the meanwhile, please report the bug to Microsoft.

Question: It seems to me that it is a office 2016 problem. Does anyone have the issue on a PC?

Function not defined javascript

The actual problem is with your

showList function.

There is an extra ')' after 'visible'.

Remove that and it will work fine.

function showList()
{
  if (document.getElementById("favSports").style.visibility == "hidden") 
    {
       // document.getElementById("favSports").style.visibility = "visible");  
       // your code
       document.getElementById("favSports").style.visibility = "visible";
       // corrected code
    }
}

Removing empty lines in Notepad++

  1. notepad++
  2. Ctrl-H
  3. Select Regular Expression
  4. Enter ^[ \t]*$\r?\n into find what, leave replace empty. This will match all lines starting with white space and ending with carriage return (in this case a windows crlf)
  5. Click the Find Next button to see for yourself how it matches only empty lines.

Case-insensitive search

You can make everything lowercase:

var string="Stackoverflow is the BEST";
var searchstring="best";
var result= (string.toLowerCase()).search((searchstring.toLowerCase()));
alert(result);

Remove all multiple spaces in Javascript and replace with single space

You can also replace without a regular expression.

while(str.indexOf('  ')!=-1)str.replace('  ',' ');

Hyphen, underscore, or camelCase as word delimiter in URIs?

Whilst I recommend hyphens, I shall also postulate an answer that isn't on your list:

Nothing At All

  • My company's API has URIs like /quotationrequests/, /purchaseorders/ and so on.
  • Despite you saying it was an intranet app, you listed SEO as a benefit. Google does match the pattern /foobar/ in a URL for a query of ?q=foo+bar
  • I really hope you do not consider executing a PHP call to any arbitrary string the user passes in to the address bar, as @ServAce85 suggests!

How can I convert NSDictionary to NSData and vice versa?

NSDictionary -> NSData:

NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];

NSData -> NSDictionary:

NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];

Eclipse: How do you change the highlight color of the currently selected method/expression?

1 - right click the highlight whose color you want to change

2 - select "Properties" in the popup menu

3 - choose the new color (as coobird suggested)

This solution is easy because you dont have to search for the highlight by its name ("Ocurrence" or "Write Ocurrence" etc), just right click and the appropriate window is shown.

Timeout a command in bash without unnecessary delay

The timeout command itself has a --foreground option. This lets the command interact with the user "when not running timeout directly from a shell prompt".

timeout --foreground the_command its_options

I think the questioner must have been aware of the very obvious solution of the timeout command, but asked for an alternate solution for this reason. timeout did not work for me when I called it using popen, i.e. 'not directly from the shell'. However, let me not assume that this may have been the reason in the questioner's case. Take a look at its man page.

Creating a data frame from two vectors using cbind

Using data.frame instead of cbind should be helpful

x <- data.frame(col1=c(10, 20), col2=c("[]", "[]"), col3=c("[[1,2]]","[[1,3]]"))
x
  col1 col2    col3
1   10   [] [[1,2]]
2   20   [] [[1,3]]

sapply(x, class) # looking into x to see the class of each element
     col1      col2      col3 
"numeric"  "factor"  "factor" 

As you can see elements from col1 are numeric as you wish.

data.frame can have variables of different class: numeric, factor and character but matrix doesn't, once you put a character element into a matrix all the other will become into this class no matter what clase they were before.

Reordering Chart Data Series

This function gets the series names, puts them into an array, sorts the array and based on that defines the plotting order which will give the desired output.

Function Increasing_Legend_Sort(mychart As Chart)


    Dim Arr()
    ReDim Arr(1 To mychart.FullSeriesCollection.Count)

        'Assigning Series names to an array
        For i = LBound(Arr) To UBound(Arr)
        Arr(i) = mychart.FullSeriesCollection(i).Name
        Next i

        'Bubble-Sort (Sort the array in increasing order)
        For r1 = LBound(Arr) To UBound(Arr)
            rval = Arr(r1)
                For r2 = LBound(Arr) To UBound(Arr)
                    If Arr(r2) > rval Then 'Change ">" to "<" to make it decreasing
                        Arr(r1) = Arr(r2)
                        Arr(r2) = rval
                        rval = Arr(r1)
                    End If
                Next r2
        Next r1

    'Defining the PlotOrder
    For i = LBound(Arr) To UBound(Arr)
    mychart.FullSeriesCollection(Arr(i)).PlotOrder = i
    Next i

End Function

Is there a simple way to delete a list element by value?

As stated by numerous other answers, list.remove() will work, but throw a ValueError if the item wasn't in the list. With python 3.4+, there's an interesting approach to handling this, using the suppress contextmanager:

from contextlib import suppress
with suppress(ValueError):
    a.remove('b')

How to send Basic Auth with axios

The solution given by luschn and pillravi works fine unless you receive a Strict-Transport-Security header in the response.

Adding withCredentials: true will solve that issue.

  axios.post(session_url, {
    withCredentials: true,
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/json"
    }
  },{
    auth: {
      username: "USERNAME",
      password: "PASSWORD"
  }}).then(function(response) {
    console.log('Authenticated');
  }).catch(function(error) {
    console.log('Error on Authentication');
  });

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

The first line of a paragraph is indented by default, thus whether or not you have \indent there won't make a difference. \indent and \noindent can be used to override default behavior. You can see this by replacing your line with the following:

Now we are engaged in a great civil war.\\
\indent this is indented\\
this isn't indented


\noindent override default indentation (not indented)\\
asdf 

undefined offset PHP error

If preg_match did not find a match, $matches is an empty array. So you should check if preg_match found an match before accessing $matches[0], for example:

function get_match($regex,$content)
{
    if (preg_match($regex,$content,$matches)) {
        return $matches[0];
    } else {
        return null;
    }
}

How to declare a inline object with inline variables without a parent class

yes, there is:

object[] x = new object[2];

x[0] = new { firstName = "john", lastName = "walter" };
x[1] = new { brand = "BMW" };

you were practically there, just the declaration of the anonymous types was a little off.

Pass by Reference / Value in C++

When passing by value:

void func(Object o);

and then calling

func(a);

you will construct an Object on the stack, and within the implementation of func it will be referenced by o. This might still be a shallow copy (the internals of a and o might point to the same data), so a might be changed. However if o is a deep copy of a, then a will not change.

When passing by reference:

void func2(Object& o);

and then calling

func2(a);

you will only be giving a new way to reference a. "a" and "o" are two names for the same object. Changing o inside func2 will make those changes visible to the caller, who knows the object by the name "a".

How to use a filter in a controller?

First of all inject $filter to your controller, making sure ngSanitize is loaded within your app, later within the controller usage is as follows:

$filter('linky')(text, target, attributes)

Always check out the angularjs docs

Can't access object property, even though it shows up in a console log

I've just had the same issue with a document loaded from MongoDB using Mongoose.

Turned out that i'm using the property find() to return just one object, so i changed find() to findOne() and everything worked for me.

Solution (if you're using Mongoose): Make sure to return one object only, so you can parse its object.id or it will be treated as an array so you need to acces it like that object[0].id.

Disable dragging an image from an HTML page

Great solution, had one small issue with conflicts, If anyone else has conflict from other js library simply enable no conflict like so.

var $j = jQuery.noConflict();$j('img').bind('dragstart', function(event) { event.preventDefault(); });

Hope this helps someone out.

javascript regex for special characters

You can be specific by testing for not valid characters. This will return true for anything not alphanumeric and space:

var specials = /[^A-Za-z 0-9]/g;
return specials.test(input.val());

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

Your Button2Click and Button3Click functions pass klad.xls and smimime.txt. These files most likely aren't actual executables indeed.

In order to open arbitrary files using the application associated with them, use ShellExecute

ASP MVC in IIS 7 results in: HTTP Error 403.14 - Forbidden

After trying every solution suggested here, I found yet another possible solution: URLScan

The IIS had WebDAV disabled, even in the web.config of my application, WebDAV's handler and module was removed. PUTs still returned a 403 - Forbidden without any log entries in the IIS logs. (GET / POST worked fine).

Turns out the IIS had an active ISAPI Filter (the URLScan) enabled which prevented all PUTs. After removing URLScan, it worked for me.

LINQ query to select top five

This can also be achieved using the Lambda based approach of Linq;

var list = ctn.Items
.Where(t=> t.DeliverySelection == true && t.Delivery.SentForDelivery == null)
.OrderBy(t => t.Delivery.SubmissionDate)
.Take(5);

select from one table, insert into another table oracle sql query

try this query below:

Insert into tab1 (tab1.column1,tab1.column2) 
select tab2.column1, 'hard coded  value' 
from tab2 
where tab2.column='value';

Repeat each row of data.frame the number of times specified in a column

in fact. use the methods of vector and index. we can also achieve the same result, and more easier to understand:

rawdata <- data.frame('time' = 1:3, 
           'x1' = 4:6,
           'x2' = 7:9,
           'x3' = 10:12)

rawdata[rep(1, time=2), ] %>% remove_rownames()
#  time x1 x2 x3
# 1    1  4  7 10
# 2    1  4  7 10


linux execute command remotely

If you don't want to deal with security and want to make it as exposed (aka "convenient") as possible for short term, and|or don't have ssh/telnet or key generation on all your hosts, you can can hack a one-liner together with netcat. Write a command to your target computer's port over the network and it will run it. Then you can block access to that port to a few "trusted" users or wrap it in a script that only allows certain commands to run. And use a low privilege user.

on the server

mkfifo /tmp/netfifo; nc -lk 4201 0</tmp/netfifo | bash -e &>/tmp/netfifo

This one liner reads whatever string you send into that port and pipes it into bash to be executed. stderr & stdout are dumped back into netfifo and sent back to the connecting host via nc.

on the client

To run a command remotely: echo "ls" | nc HOST 4201

Can I position an element fixed relative to parent?

With multiple divs I managed to get a fixed-y and absolute-x divs. In my case I needed a div on left and right sides, aligned to a centered 1180px width div.

    <div class="parentdiv" style="
        background: transparent;
        margin: auto;
        width: 100%;
        max-width: 1220px;
        height: 10px;
        text-align: center;">
        <div style="
            position: fixed;
            width: 100%;
            max-width: 1220px;">
            <div style="
                position: absolute;
                background: black;
                height: 20px;
                width: 20px;
                left: 0;">
            </div>
            <div style="
                width: 20px;
                height: 20px;
                background: blue;
                position: absolute;                                           
                right: 0;">
            </div>
        </div>
    </div>

How to enable file upload on React's Material UI simple input?

If you're using React function components, and you don't like to work with labels or IDs, you can also use a reference.

const uploadInputRef = useRef(null);

return (
  <Fragment>
    <input
      ref={uploadInputRef}
      type="file"
      accept="image/*"
      style={{ display: "none" }}
      onChange={onChange}
    />
    <Button
      onClick={() => uploadInputRef.current && uploadInputRef.current.click()}
      variant="contained"
    >
      Upload
    </Button>
  </Fragment>
);

Jenkins - How to access BUILD_NUMBER environment variable

To Answer your first question, Jenkins variables are case sensitive. However, if you are writing a windows batch script, they are case insensitive, because Windows doesn't care about the case.

Since you are not very clear about your setup, let's make the assumption that you are using an ant build step to fire up your ant task. Have a look at the Jenkins documentation (same page that Adarsh gave you, but different chapter) for an example on how to make Jenkins variables available to your ant task.

EDIT:

Hence, I will need to access the environmental variable ${BUILD_NUMBER} to construct the URL.

Why don't you use $BUILD_URL then? Isn't it available in the extended email plugin?

Cross-platform way of getting temp directory in Python

This should do what you want:

print tempfile.gettempdir()

For me on my Windows box, I get:

c:\temp

and on my Linux box I get:

/tmp

Move all files except one

I would go with the traditional find & xargs way:

find ~/Linux/Old -maxdepth 1 -mindepth 1 -not -name Tux.png -print0 | 
    xargs -0 mv -t ~/Linux/New

-maxdepth 1 makes it not search recursively. If you only care about files, you can say -type f. -mindepth 1 makes it not include the ~/Linux/Old path itself into the result. Works with any filenames, including with those that contain embedded newlines.

One comment notes that the mv -t option is a probably GNU extension. For systems that don't have it

find ~/Linux/Old -maxdepth 1 -mindepth 1 -not -name Tux.png \
    -exec mv '{}' ~/Linux/New \;

Validate select box

For starters, you can "disable" the option from being selected accidentally by users:

<option value="" disabled="disabled">Choose an option</option>

Then, inside your JavaScript event (doesn't matter whether it is jQuery or JavaScript), for your form to validate whether it is set, do:

select = document.getElementById('select'); // or in jQuery use: select = this;
if (select.value) {
  // value is set to a valid option, so submit form
  return true;
}
return false;

Or something to that effect.

IllegalMonitorStateException on wait() call

Those who are using Java 7.0 or below version can refer the code which I used here and it works.

public class WaitTest {

    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    public void waitHere(long waitTime) {
        System.out.println("wait started...");
        lock.lock();
        try {
            condition.await(waitTime, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        lock.unlock();
        System.out.println("wait ends here...");
    }

    public static void main(String[] args) {
        //Your Code
        new WaitTest().waitHere(10);
        //Your Code
    }

}

How can I limit ngFor repeat to some number of items in Angular?

In addition to @Gunter's answer, you can use trackBy to improve the performance. trackBy takes a function that has two arguments: index and item. You can return a unique value in the object from the function. It will stop re-rendering already displayed items in ngFor. In your html add trackBy as below.

<li *ngFor="let item of list; trackBy: trackByFn;let i=index" class="dropdown-item" (click)="onClick(item)">
  <template [ngIf]="i<11">{{item.text}}</template>
</li>

And write a function like this in your .ts file.

trackByfn(index, item) { 
  return item.uniqueValue;
}

HTML5 input type range show range value

version with editable input:

<form>
    <input type="range" name="amountRange" min="0" max="20" value="0" oninput="this.form.amountInput.value=this.value" />
    <input type="number" name="amountInput" min="0" max="20" value="0" oninput="this.form.amountRange.value=this.value" />
</form>

http://jsfiddle.net/Xjxe6/

Execute combine multiple Linux commands in one line

If you want to execute all the commands, whether the previous one executes or not, you can use semicolon (;) to separate the commands.

cd /my_folder; rm *.jar; svn co path to repo; mvn compile package install

If you want to execute the next command only if the previous command succeeds, then you can use && to separate the commands.

cd /my_folder && rm *.jar && svn co path to repo && mvn compile package install

In your case, the execution of consecutive commands seems to depend upon the previous commands, so use the second example i.e. use && to join the commands.

What is the difference between Collection and List in Java?

Collection is the Super interface of List so every Java list is as well an instance of collection. Collections are only iterable sequentially (and in no particular order) whereas a List allows access to an element at a certain position via the get(int index) method.

Check if bash variable equals 0

Double parenthesis (( ... )) is used for arithmetic operations.

Double square brackets [[ ... ]] can be used to compare and examine numbers (only integers are supported), with the following operators:

· NUM1 -eq NUM2 returns true if NUM1 and NUM2 are numerically equal.

· NUM1 -ne NUM2 returns true if NUM1 and NUM2 are not numerically equal.

· NUM1 -gt NUM2 returns true if NUM1 is greater than NUM2.

· NUM1 -ge NUM2 returns true if NUM1 is greater than or equal to NUM2.

· NUM1 -lt NUM2 returns true if NUM1 is less than NUM2.

· NUM1 -le NUM2 returns true if NUM1 is less than or equal to NUM2.

For example

if [[ $age > 21 ]] # bad, > is a string comparison operator

if [ $age > 21 ] # bad, > is a redirection operator

if [[ $age -gt 21 ]] # okay, but fails if $age is not numeric

if (( $age > 21 )) # best, $ on age is optional

Java Immutable Collections

Now java 9 has factory Methods for Immutable List, Set, Map and Map.Entry .

In Java SE 8 and earlier versions, We can use Collections class utility methods like unmodifiableXXX to create Immutable Collection objects.

However these Collections.unmodifiableXXX methods are very tedious and verbose approach. To overcome those shortcomings, Oracle corp has added couple of utility methods to List, Set and Map interfaces.

Now in java 9 :- List and Set interfaces have “of()” methods to create an empty or no-empty Immutable List or Set objects as shown below:

Empty List Example

List immutableList = List.of();

Non-Empty List Example

List immutableList = List.of("one","two","three");

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

In my case, I use Xamarin with Visual Studio 2013. I create Blank App (Android) then deploy without any code update.

You can try:

  • Make sure that icon.png (or whatever files mentioned in the application android:icon tag) is present in the drawable-hdpi folder inside res folder of Android project.

  • If it shows the error even if the icon.png is present,then remove the statement application android:icon from the AndroidManifest.xml and add it again.

  • Check your project folder's path. If it is too long, or contains space, or contains any unicode character, try to relocated.

How to use function srand() with time.h?

You need to call srand() once, to randomize the seed, and then call rand() in your loop:

#include <stdlib.h>
#include <time.h>

#define size 10

srand(time(NULL)); // randomize seed

for(i=0;i<size;i++)
    Arr[i] = rand()%size;

Querying Datatable with where condition

You can do it with Linq, as mamoo showed, but the oldies are good too:

var filteredDataTable = dt.Select(@"EmpId > 2
    AND (EmpName <> 'abc' OR EmpName <> 'xyz')
    AND EmpName like '%il%'" );

How to convert interface{} to string?

You don't need to use a type assertion, instead just use the %v format specifier with Sprintf:

hostAndPort := fmt.Sprintf("%v:%v", arguments["<host>"], arguments["<port>"])

SQL Server AS statement aliased column within WHERE statement

This would work on your edited question !

SELECT * FROM (SELECT <Column_List>,  
( 6371*1000 * acos( cos( radians(42.3936868308) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(-72.5277256966) ) + sin( radians(42.3936868308) ) * sin( radians( lat ) ) ) )  
AS distance 
FROM poi_table) TMP
WHERE distance < 500; 

python location on mac osx

which python3 simply result in a path in which the interpreter settles down.

How to properly highlight selected item on RecyclerView?

Just adding android:background="?attr/selectableItemBackgroundBorderless" should work if you don't have background color, but don't forget to use setSelected method. If you have different background color, I just used this (I'm using data-binding);

Set isSelected at onClick function

b.setIsSelected(true);

And add this to xml;

android:background="@{ isSelected ? @color/{color selected} : @color/{color not selected} }"

iTerm2 keyboard shortcut - split pane navigation

Cmd+opt+?/?/?/? navigate similarly to vim's C-w hjkl.

Which is faster: Stack allocation or Heap allocation

Usually stack allocation just consists of subtracting from the stack pointer register. This is tons faster than searching a heap.

Sometimes stack allocation requires adding a page(s) of virtual memory. Adding a new page of zeroed memory doesn't require reading a page from disk, so usually this is still going to be tons faster than searching a heap (especially if part of the heap was paged out too). In a rare situation, and you could construct such an example, enough space just happens to be available in part of the heap which is already in RAM, but allocating a new page for the stack has to wait for some other page to get written out to disk. In that rare situation, the heap is faster.

What could cause java.lang.reflect.InvocationTargetException?

This will print the exact line of code in the specific method, which when invoked, raised the exception:

try {

    // try code
    ..
    m.invoke(testObject);
    ..

} catch (InvocationTargetException e) {

    // Answer:
    e.getCause().printStackTrace();
} catch (Exception e) {

    // generic exception handling
    e.printStackTrace();
}

How to write the Fibonacci Sequence?

Using for loop and print just the result

def fib(n:'upto n number')->int:
    if n==0:
        return 0
    elif n==1:
        return 1
    a=0
    b=1
    for i in range(0,n-1):
        b=a+b
        a=b-a
    return b

Result

>>>fib(50)
12586269025
>>>>
>>> fib(100)
354224848179261915075
>>> 

Print the list containing all the numbers

def fib(n:'upto n number')->int:
    l=[0,1]
    if n==0:
        return l[0]
    elif n==1:
        return l
    a=0
    b=1
    for i in range(0,n-1):
        b=a+b
        a=b-a
        l.append(b)
    return l

Result

>>> fib(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

Convert java.util.Date to String

Commons-lang DateFormatUtils is full of goodies (if you have commons-lang in your classpath)

//Formats a date/time into a specific pattern
 DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");

How to install python3 version of package via pip on Ubuntu?

Firstly, you need to install pip for the Python 3 installation that you want. Then you run that pip to install packages for that Python version.

Since you have both pip and python 3 in /usr/bin, I assume they are both installed with a package manager of some sort. That package manager should also have a Python 3 pip. That's the one you should install.

Felix' recommendation of virtualenv is a good one. If you are only testing, or you are doing development, then you shouldn't install the package in the system python. Using virtualenv, or even building your own Pythons for development, is better in those cases.

But if you actually do want to install this package in the system python, installing pip for Python 3 is the way to go.

How to programmatically modify WCF app.config endpoint address setting?

You can do it like this:

  • Keep your settings in a separate xml file and read through it when you create a proxy for your service.

For example , i want to modify my service endpoint address at runtime so i have the following ServiceEndpoint.xml file.

     <?xml version="1.0" encoding="utf-8" ?>
     <Services>
        <Service name="FileTransferService">
           <Endpoints>
              <Endpoint name="ep1" address="http://localhost:8080/FileTransferService.svc" />
           </Endpoints>
        </Service>
     </Services>
  • For reading your xml :

     var doc = new XmlDocument();
     doc.Load(FileTransferConstants.Constants.SERVICE_ENDPOINTS_XMLPATH);
     XmlNodeList endPoints = doc.SelectNodes("/Services/Service/Endpoints");  
     foreach (XmlNode endPoint in endPoints)
     {
        foreach (XmlNode child in endPoint)
        {
            if (child.Attributes["name"].Value.Equals("ep1"))
            {
                var adressAttribute = child.Attributes["address"];
                if (!ReferenceEquals(null, adressAttribute))
                {
                    address = adressAttribute.Value;
                }
           }
       }
    }  
    
  • Then get your web.config file of your client at runtime and assign the service endpoint address as:

        Configuration wConfig = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = @"C:\FileTransferWebsite\web.config" }, ConfigurationUserLevel.None);
        ServiceModelSectionGroup wServiceSection = ServiceModelSectionGroup.GetSectionGroup(wConfig);
    
        ClientSection wClientSection = wServiceSection.Client;
        wClientSection.Endpoints[0].Address = new Uri(address);
        wConfig.Save();
    

Why doesn't RecyclerView have onItemClickListener()?

Here is a way to implement it quite easily if you have a list of POJOs and want to retrieve one on click from outside the adapter.

In your adapter, create a listener for the click events and a method to set it:

public class MyAdapter extends RecyclerView.Adapter<SitesListAdapter.ViewHolder> {
...
private List<MyPojo> mMyPojos;
private static OnItemClickListener mOnItemClickListener;

...
public interface OnItemClickListener {
    public void onItemClick(MyPojo pojo);
}

...
public void setOnItemClickListener(OnItemClickListener onItemClickListener){
    mOnItemClickListener = onItemClickListener;
}
...

}

In your ViewHolder, implement onClickListener and create a class member to temporarily store the POJO the view is presenting, that way (this is an example, creating a setter would be better):

public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    public MyPojo mCurrentPojo;
    ...
    public ViewHolder(View view) {
        super(v);
        ...
        view.setOnClickListener(this); //You could set this on part of the layout too
    }

    ...
    @Override
    public void onClick(View view) {
        if(mOnItemClickListener != null && mCurrentPojo != null){
            mOnItemClickListener.onItemClick(mCurrentPojo);
        }
    }

Back in your adapter, set the current POJO when the ViewHolder is bound (or to null if the current view doesn't have one):

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    final MyPojo currentPojo = mMyPojos.get(position); 
    holder.mCurrentPojo = currentPojo;
    ...

That's it, now you can use it like this from your fragment/activity:

    mMyAdapter.setOnItemClickListener(new mMyAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(MyPojo pojo) {
            //Do whatever you want with your pojo here
        }
    });

Download a file by jQuery.Ajax

That's it works so fine in any browser (I'm using asp.net core)

_x000D_
_x000D_
            function onDownload() {_x000D_
_x000D_
  const api = '@Url.Action("myaction", "mycontroller")'; _x000D_
  var form = new FormData(document.getElementById('form1'));_x000D_
_x000D_
  fetch(api, { body: form, method: "POST"})_x000D_
      .then(resp => resp.blob())_x000D_
      .then(blob => {_x000D_
          const url = window.URL.createObjectURL(blob);_x000D_
        $('#linkdownload').attr('download', 'Attachement.zip');_x000D_
          $('#linkdownload').attr("href", url);_x000D_
          $('#linkdownload')_x000D_
              .fadeIn(3000,_x000D_
                  function() { });_x000D_
_x000D_
      })_x000D_
      .catch(() => alert('An error occurred'));_x000D_
_x000D_
_x000D_
_x000D_
}
_x000D_
 _x000D_
 <button type="button" onclick="onDownload()" class="btn btn-primary btn-sm">Click to Process Files</button>_x000D_
 _x000D_
 _x000D_
 _x000D_
 <a role="button" href="#" style="display: none" class="btn btn-sm btn-secondary" id="linkdownload">Click to download Attachments</a>_x000D_
 _x000D_
 _x000D_
 <form asp-controller="mycontroller" asp-action="myaction" id="form1"></form>_x000D_
 _x000D_
 
_x000D_
_x000D_
_x000D_

        function onDownload() {
            const api = '@Url.Action("myaction", "mycontroller")'; 
            //form1 is your id form, and to get data content of form
            var form = new FormData(document.getElementById('form1'));

            fetch(api, { body: form, method: "POST"})
                .then(resp => resp.blob())
                .then(blob => {
                    const url = window.URL.createObjectURL(blob);
                    $('#linkdownload').attr('download', 'Attachments.zip');
                    $('#linkdownload').attr("href", url);
                    $('#linkdownload')
                        .fadeIn(3000,
                            function() {

                            });
                })
                .catch(() => alert('An error occurred'));                 

        }

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag

FIXED

Give initial height of div and specify height in percentage in your style;

#map {
   height: 100%;
}

<div id="map" style="clear:both; height:200px;"></div> 

How can I use Python to get the system hostname?

If I'm correct, you're looking for the socket.gethostname function:

>> import socket
>> socket.gethostname()
'terminus'

Programmatically create a UIView with color gradient

Simple swift view based on Yuchen's version

class GradientView: UIView {
    override class func layerClass() -> AnyClass { return CAGradientLayer.self }

    lazy var gradientLayer: CAGradientLayer = {
        return self.layer as! CAGradientLayer
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

}

Then you can use gradientLayer after initialization like this...

someView.gradientLayer.colors = [UIColor.whiteColor().CGColor, UIColor.blackColor().CGColor]

Cleanest way to toggle a boolean variable in Java?

theBoolean ^= true;

Fewer keystrokes if your variable is longer than four letters

Edit: code tends to return useful results when used as Google search terms. The code above doesn't. For those who need it, it's bitwise XOR as described here.

Writing an Excel file in EPPlus

Have you looked at the samples provided with EPPlus?

This one shows you how to create a file http://epplus.codeplex.com/wikipage?title=ContentSheetExample

This one shows you how to use it to stream back a file http://epplus.codeplex.com/wikipage?title=WebapplicationExample

This is how we use the package to generate a file.

var newFile = new FileInfo(ExportFileName);
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{                       
    // do work here                            
    xlPackage.Save();
}