Programs & Examples On #Hdfs

Hadoop Distributed File System (HDFS) is the primary storage system used by Hadoop applications. HDFS creates multiple replicas of data blocks and distributes them on compute nodes throughout a cluster to enable reliable, extremely rapid computations.

Hive load CSV with commas in quoted fields

As of Hive 0.14, the CSV SerDe is a standard part of the Hive install

ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'

(See: https://cwiki.apache.org/confluence/display/Hive/CSV+Serde)

Permission denied at hdfs

Start a shell as hduser (from root) and run your command

sudo -u hduser bash
hadoop fs -put /usr/local/input-data/ /input

[update] Also note that the hdfs user is the super user and has all r/w privileges.

Namenode not getting started

Open a new terminal and start the namenode using path-to-your-hadoop-install/bin/hadoop namenode

The check using jps and namenode should be running

How to fix corrupt HDFS FIles

the solution here worked for me : https://community.hortonworks.com/articles/4427/fix-under-replicated-blocks-in-hdfs-manually.html

su - <$hdfs_user>

bash-4.1$ hdfs fsck / | grep 'Under replicated' | awk -F':' '{print $1}' >> /tmp/under_replicated_files 

-bash-4.1$ for hdfsfile in `cat /tmp/under_replicated_files`; do echo "Fixing $hdfsfile :" ;  hadoop fs -setrep 3 $hdfsfile; done

What are the pros and cons of parquet format compared to other formats?

Tom's answer is quite detailed and exhaustive but you may also be interested in this simple study about Parquet vs Avro done at Allstate Insurance, summarized here:

"Overall, Parquet showed either similar or better results on every test [than Avro]. The query-performance differences on the larger datasets in Parquet’s favor are partly due to the compression results; when querying the wide dataset, Spark had to read 3.5x less data for Parquet than Avro. Avro did not perform well when processing the entire dataset, as suspected."

Name node is in safe mode. Not able to leave

If you use Hadoop version 2.6.1 above, while the command works, it complains that its depreciated. I actually could not use the hadoop dfsadmin -safemode leave because I was running Hadoop in a Docker container and that command magically fails when run in the container, so what I did was this. I checked doc and found dfs.safemode.threshold.pct in documentation that says

Specifies the percentage of blocks that should satisfy the minimal replication requirement defined by dfs.replication.min. Values less than or equal to 0 mean not to wait for any particular percentage of blocks before exiting safemode. Values greater than 1 will make safe mode permanent.

so I changed the hdfs-site.xml into the following (In older Hadoop versions, apparently you need to do it in hdfs-default.xml:

<configuration>
    <property>
        <name>dfs.safemode.threshold.pct</name>
        <value>0</value>
    </property>
</configuration>

hadoop copy a local file system folder to HDFS

Navigate to your "/install/hadoop/datanode/bin" folder or path where you could execute your hadoop commands:

To place the files in HDFS: Format: hadoop fs -put "Local system path"/filename.csv "HDFS destination path"

eg)./hadoop fs -put /opt/csv/load.csv /user/load

Here the /opt/csv/load.csv is source file path from my local linux system.

/user/load means HDFS cluster destination path in "hdfs://hacluster/user/load"

To get the files from HDFS to local system: Format : hadoop fs -get "/HDFSsourcefilepath" "/localpath"

eg)hadoop fs -get /user/load/a.csv /opt/csv/

After executing the above command, a.csv from HDFS would be downloaded to /opt/csv folder in local linux system.

This uploaded files could also be seen through HDFS NameNode web UI.

How to copy data from one HDFS to another HDFS?

DistCp (distributed copy) is a tool used for copying data between clusters. It uses MapReduce to effect its distribution, error handling and recovery, and reporting. It expands a list of files and directories into input to map tasks, each of which will copy a partition of the files specified in the source list.

Usage: $ hadoop distcp <src> <dst>

example: $ hadoop distcp hdfs://nn1:8020/file1 hdfs://nn2:8020/file2

file1 from nn1 is copied to nn2 with filename file2

Distcp is the best tool as of now. Sqoop is used to copy data from relational database to HDFS and vice versa, but not between HDFS to HDFS.

More info:

There are two versions available - runtime performance in distcp2 is more compared to distcp

How to copy file from HDFS to the local file system

In Hadoop 2.0,

hdfs dfs -copyToLocal <hdfs_input_file_path> <output_path>

where,

  • hdfs_input_file_path maybe obtained from http://<<name_node_ip>>:50070/explorer.html

  • output_path is the local path of the file, where the file is to be copied to.

  • you may also use get in place of copyToLocal.

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

Some of the data processing requirements doesn't need sort at all. Syncsort had made the sorting in Hadoop pluggable. Here is a nice blog from them on sorting. The process of moving the data from the mappers to the reducers is called shuffling, check this article for more information on the same.

How to list all files in a directory and its subdirectories in hadoop hdfs

Now, one can use Spark to do the same and its way faster than other approaches (such as Hadoop MR). Here is the code snippet.

def traverseDirectory(filePath:String,recursiveTraverse:Boolean,filePaths:ListBuffer[String]) {
    val files = FileSystem.get( sparkContext.hadoopConfiguration ).listStatus(new Path(filePath))
            files.foreach { fileStatus => {
                if(!fileStatus.isDirectory() && fileStatus.getPath().getName().endsWith(".xml")) {                
                    filePaths+=fileStatus.getPath().toString()      
                }
                else if(fileStatus.isDirectory()) {
                    traverseDirectory(fileStatus.getPath().toString(), recursiveTraverse, filePaths)
                }
            }
    }   
}

Spark - load CSV file as DataFrame?

With Spark 2.4+, if you want to load a csv from a local directory, then you can use 2 sessions and load that into hive. The first session should be created with master() config as "local[*]" and the second session with "yarn" and Hive enabled.

The below one worked for me.

import org.apache.log4j.{Level, Logger}
import org.apache.spark._
import org.apache.spark.rdd._
import org.apache.spark.sql._

object testCSV { 

  def main(args: Array[String]) {
    Logger.getLogger("org").setLevel(Level.ERROR)
    val spark_local = SparkSession.builder().appName("CSV local files reader").master("local[*]").getOrCreate()

    import spark_local.implicits._
    spark_local.sql("SET").show(100,false)
    val local_path="/tmp/data/spend_diversity.csv"  // Local file
    val df_local = spark_local.read.format("csv").option("inferSchema","true").load("file://"+local_path) // "file://" is mandatory
    df_local.show(false)

    val spark = SparkSession.builder().appName("CSV HDFS").config("spark.sql.warehouse.dir", "/apps/hive/warehouse").enableHiveSupport().getOrCreate()

    import spark.implicits._
    spark.sql("SET").show(100,false)
    val df = df_local
    df.createOrReplaceTempView("lcsv")
    spark.sql(" drop table if exists work.local_csv ")
    spark.sql(" create table work.local_csv as select * from lcsv ")

   }

When ran with spark2-submit --master "yarn" --conf spark.ui.enabled=false testCSV.jar it went fine and created the table in hive.

Where does Hive store files in HDFS?

In Hive terminal type:

hive> set hive.metastore.warehouse.dir;

(it will print the path)

The way to check a HDFS directory's size?

% of used space on Hadoop cluster
sudo -u hdfs hadoop fs –df

Capacity under specific folder:
sudo -u hdfs hadoop fs -du -h /user

Select from one table matching criteria in another?

I have a similar problem (at least I think it is similar). In one of the replies here the solution is as follows:

select
    A.*
from
    table_A A
inner join table_B B
    on A.id = B.id
where
    B.tag = 'chair'

That WHERE clause I would like to be:

WHERE B.tag = A.<col_name>

or, in my specific case:

WHERE B.val BETWEEN A.val1 AND A.val2

More detailed:

Table A carries status information of a fleet of equipment. Each status record carries with it a start and stop time of that status. Table B carries regularly recorded, timestamped data about the equipment, which I want to extract for the duration of the period indicated in table A.

deleting folder from java

The javadoc for File.delete()

public boolean delete()

Deletes the file or directory denoted by this abstract pathname. If this pathname >denotes a directory, then the directory must be empty in order to be deleted.

So a folder has to be empty or deleting it will fail. Your code currently fills the folder list with the top most folder first, followed by its sub folders. Since you iterrate through the list in the same way it will try to delete the top most folder before deleting its subfolders, this will fail.

Changing these line

    for(String filePath : folderList) {
        File tempFile = new File(filePath);
        tempFile.delete();
    }

to this

    for(int i = folderList.size()-1;i>=0;i--) {
        File tempFile = new File(folderList.get(i));
        tempFile.delete();
    }

should cause your code to delete the sub folders first.

The delete operation also returns false when it fails, so you can check this value to do some error handling if necessary.

Undefined reference to static class member

The C++ standard requires a definition for your static const member if the definition is somehow needed.

The definition is required, for example if it's address is used. push_back takes its parameter by const reference, and so strictly the compiler needs the address of your member and you need to define it in the namespace.

When you explicitly cast the constant, you're creating a temporary and it's this temporary which is bound to the reference (under special rules in the standard).

This is a really interesting case, and I actually think it's worth raising an issue so that the std be changed to have the same behaviour for your constant member!

Although, in a weird kind of way this could be seen as a legitimate use of the unary '+' operator. Basically the result of the unary + is an rvalue and so the rules for binding of rvalues to const references apply and we don't use the address of our static const member:

v.push_back( +Foo::MEMBER );

How can I declare a two dimensional string array?

string[,] Tablero = new string[3,3];

You can also instantiate it in the same line with array initializer syntax as follows:

string[,] Tablero = new string[3, 3] {{"a","b","c"},
                                      {"d","e","f"}, 
                                      {"g","h","i"} };

How do I get my Maven Integration tests to run

I have done EXACTLY what you want to do and it works great. Unit tests "*Tests" always run, and "*IntegrationTests" only run when you do a mvn verify or mvn install. Here it the snippet from my POM. serg10 almost had it right....but not quite.

  <plugin>
    <!-- Separates the unit tests from the integration tests. -->
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
       <!-- Skip the default running of this plug-in (or everything is run twice...see below) -->
       <skip>true</skip>
       <!-- Show 100% of the lines from the stack trace (doesn't work) -->
       <trimStackTrace>false</trimStackTrace>
    </configuration>
    <executions>
       <execution>
          <id>unit-tests</id>
          <phase>test</phase>
          <goals>
             <goal>test</goal>
          </goals>
          <configuration>
                <!-- Never skip running the tests when the test phase is invoked -->
                <skip>false</skip>
             <includes>
                   <!-- Include unit tests within integration-test phase. -->
                <include>**/*Tests.java</include>
             </includes>
             <excludes>
               <!-- Exclude integration tests within (unit) test phase. -->
                <exclude>**/*IntegrationTests.java</exclude>
            </excludes>
          </configuration>
       </execution>
       <execution>
          <id>integration-tests</id>
          <phase>integration-test</phase>
          <goals>
             <goal>test</goal>
          </goals>
          <configuration>
            <!-- Never skip running the tests when the integration-test phase is invoked -->
             <skip>false</skip>
             <includes>
               <!-- Include integration tests within integration-test phase. -->
               <include>**/*IntegrationTests.java</include>
             </includes>
          </configuration>
       </execution>
    </executions>
  </plugin>

Good luck!

Android : Check whether the phone is dual SIM

Tips:

You can try to use

ctx.getSystemService("phone_msim")

instead of

ctx.getSystemService(Context.TELEPHONY_SERVICE)

If you have already tried Vaibhav's answer and telephony.getClass().getMethod() fails, above is what works for my Qualcomm mobile.

I need to learn Web Services in Java. What are the different types in it?

Q1) Here are couple things to read or google more :

Main differences between SOAP and RESTful web services in java http://www.ajaxonomy.com/2008/xml/web-services-part-1-soap-vs-rest

It's up to you what do you want to learn first. I'd recommend you take a look at the CXF framework. You can build both rest/soap services.

Q2) Here are couple of good tutorials for soap (I had them bookmarked) :

http://united-coders.com/phillip-steffensen/developing-a-simple-soap-webservice-using-spring-301-and-apache-cxf-226

http://www.benmccann.com/blog/web-services-tutorial-with-apache-cxf/

http://www.mastertheboss.com/web-interfaces/337-apache-cxf-interceptors.html

Best way to learn is not just reading tutorials. But you would first go trough tutorials to get a basic idea so you can see that you're able to produce something(or not) and that would get you motivated.

SO is great way to learn particular technology (or more), people ask lot of wierd questions, and there are ever weirder answers. But overall you'll learn about ways to solve issues on other way. Maybe you didn't know of that way, maybe you couldn't thought of it by yourself.

Subscribe to couple of tags that are interesting to you and be persistent, ask good questions and try to give good answers and I guarantee you that you'll learn this as time passes (if you're persistent that is).

Q3) You will have to answer this one yourself. First by deciding what you're going to build, after all you will need to think of some mini project or something and take it from there.

If you decide to use CXF as your framework for building either REST/SOAP services I'd recommend you look up this book Apache CXF Web Service Development. It's fantastic, not hard to read and not too big either (win win).

Java TreeMap Comparator

you can swipe the key and the value. For example

        String[] k = {"Elena", "Thomas", "Hamilton", "Suzie", "Phil"};
        int[] v = {341, 273, 278, 329, 445};
        TreeMap<Integer,String>a=new TreeMap();
        for (int i = 0; i < k.length; i++) 
           a.put(v[i],k[i]);            
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
        a.remove(a.firstEntry().getKey());
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());

What is the use of adding a null key or value to a HashMap in Java?

Another example : I use it to group Data by date. But some data don't have date. I can group it with the header "NoDate"

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

Make sure your Gradle version is 3.*.* or higher before using "implementation".

Open the project level Gradle file under dependencies:

dependencies{
    classpath 'com.android.tools.build:gradle:3.1.2'
}

Open the 'gradle-wrapper.properties' file and set the distributionUrl:

distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

or latest version.

Sync the project. I Hope this solves your problem.

Clear History and Reload Page on Login/Logout Using Ionic Framework

As pointed out by @ezain reload controllers only when its necessary. Another cleaner way of updating data when changing states rather than reloading the controller is using broadcast events and listening to such events in controllers that need to update data on views.

Example: in your login/logout functions you can do something like so:

$scope.login = function(){
    //After login logic then send a broadcast
    $rootScope.$broadcast("user-logged-in");
    $state.go("mainPage");
};
$scope.logout = function(){
   //After logout logic then send a broadcast
   $rootScope.$broadcast("user-logged-out");
   $state.go("mainPage");
};

Now in your mainPage controller trigger the changes in the view by using the $on function to listen to broadcast within the mainPage Controller like so:

$scope.$on("user-logged-in", function(){
     //update mainPage view data here eg. $scope.username = 'John';
});

$scope.$on("user-logged-out", function(){
    //update mainPage view data here eg. $scope.username = '';
});

ASP.NET Core configuration for .NET Core console application

Install these packages:

  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.Binder
  • Microsoft.Extensions.Configuration.EnvironmentVariables
  • Microsoft.Extensions.Configuration.FileExtensions
  • Microsoft.Extensions.Configuration.Json

Code:

static void Main(string[] args)
    {
        var environmentName = Environment.GetEnvironmentVariable("ENVIRONMENT");
        Console.WriteLine("ENVIRONMENT: " + environmentName);

        var builder = new ConfigurationBuilder()
           .SetBasePath(Directory.GetCurrentDirectory())
           .AddJsonFile("appsettings.json", false)
           .AddJsonFile($"appsettings.{environmentName}.json", true)
           .AddEnvironmentVariables();

        IConfigurationRoot configuration = builder.Build();
        var mySettingsConfig = configuration.Get<MySettingsConfig>();

        Console.WriteLine("URL: " + mySettingsConfig.Url);
        Console.WriteLine("NAME: " + mySettingsConfig.Name);

        Console.ReadKey();
    }

MySettingsConfig Class:

public class MySettingsConfig
{
    public string Url { get; set; }
    public string Name { get; set; }
}

Your appsettings can be as simple as this: enter image description here

Also, set the appsettings files to Content / Copy if newer: content

How do I convert a decimal to an int in C#?

Use Convert.ToInt32 from mscorlib as in

decimal value = 3.14m;
int n = Convert.ToInt32(value);

See MSDN. You can also use Decimal.ToInt32. Again, see MSDN. Finally, you can do a direct cast as in

decimal value = 3.14m;
int n = (int) value;

which uses the explicit cast operator. See MSDN.

How to check if an email address is real or valid using PHP

You should check with SMTP.

That means you have to connect to that email's SMTP server.

After connecting to the SMTP server you should send these commands:

HELO somehostname.com
MAIL FROM: <[email protected]>
RCPT TO: <[email protected]>

If you get "<[email protected]> Relay access denied" that means this email is Invalid.

There is a simple PHP class. You can use it:

http://www.phpclasses.org/package/6650-PHP-Check-if-an-e-mail-is-valid-using-SMTP.html

How do I make a stored procedure in MS Access?

Access 2010 has both stored procedures, and also has table triggers. And, both features are available even when you not using a server (so, in 100% file based mode).

If you using SQL Server with Access, then of course the stored procedures are built using SQL Server and not Access.

For Access 2010, you open up the table (non-design view), and then choose the table tab. You see options there to create store procedures and table triggers.

For example:

screenshot

Note that the stored procedure language is its own flavor just like Oracle or SQL Server (T-SQL). Here is example code to update an inventory of fruits as a result of an update in the fruit order table alt text

Keep in mind these are true engine-level table triggers. In fact if you open up that table with VB6, VB.NET, FoxPro or even modify the table on a computer WITHOUT Access having been installed, the procedural code and the trigger at the table level will execute. So, this is a new feature of the data engine jet (now called ACE) for Access 2010. As noted, this is procedural code that runs, not just a single statement.

What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?

Send params from View to an other View, from Sender View to Receiver View use viewParam and includeViewParams=true

In Sender

  1. Declare params to be sent. We can send String, Object,…

Sender.xhtml

<f:metadata>
      <f:viewParam name="ID" value="#{senderMB._strID}" />
</f:metadata>
  1. We’re going send param ID, it will be included with “includeViewParams=true” in return String of click button event Click button fire senderMB.clickBtnDetail(dto) with dto from senderMB._arrData

Sender.xhtml

<p:dataTable rowIndexVar="index" id="dataTale"value="#{senderMB._arrData}" var="dto">
      <p:commandButton action="#{senderMB.clickBtnDetail(dto)}" value="??" 
      ajax="false"/>
</p:dataTable>

In senderMB.clickBtnDetail(dto) we assign _strID with argument we got from button event (dto), here this is Sender_DTO and assign to senderMB._strID

Sender_MB.java
    public String clickBtnDetail(sender_DTO sender_dto) {
        this._strID = sender_dto.getStrID();
        return "Receiver?faces-redirect=true&includeViewParams=true";
    }

The link when clicked will become http://localhost:8080/my_project/view/Receiver.xhtml?*ID=12345*

In Recever

  1. Get viewParam Receiver.xhtml In Receiver we declare f:viewParam to get param from get request (receive), the name of param of receiver must be the same with sender (page)

Receiver.xhtml

<f:metadata><f:viewParam name="ID" value="#{receiver_MB._strID}"/></f:metadata>

It will get param ID from sender View and assign to receiver_MB._strID

  1. Use viewParam In Receiver, we want to use this param in sql query before the page render, so that we use preRenderView event. We are not going to use constructor because constructor will be invoked before viewParam is received So that we add

Receiver.xhtml

<f:event listener="#{receiver_MB.preRenderView}" type="preRenderView" />

into f:metadata tag

Receiver.xhtml

<f:metadata>
<f:viewParam name="ID" value="#{receiver_MB._strID}" />
<f:event listener="#{receiver_MB.preRenderView}"
            type="preRenderView" />
</f:metadata>

Now we want to use this param in our read database method, it is available to use

Receiver_MB.java
public void preRenderView(ComponentSystemEvent event) throws Exception {
        if (FacesContext.getCurrentInstance().isPostback()) {
            return;
        }
        readFromDatabase();
    }
private void readFromDatabase() {
//use _strID to read and set property   
}

AWS Lambda import module error in python

Please add below one after Import requests

import boto3

What I can see that is missing in your code.

How to insert the current timestamp into MySQL database using a PHP insert query

Instead of NOW() you can use UNIX_TIMESTAMP() also:

$update_query = "UPDATE db.tablename 
                 SET insert_time=UNIX_TIMESTAMP()
                 WHERE username='$somename'";

Difference between UNIX_TIMESTAMP and NOW() in MySQL

Unsupported major.minor version 52.0

I ran into this issue in Eclipse on Mac OS X v10.9 (Mavericks). I tried many answers on Stack Overflow ... finally, after a full day I *installed a fresh version of the Android SDK (and updated Eclipse, menu Project ? Properties ? Android to use the new path)*.

I had to get SDK updates, but only pulling down those updates I thought were necessary, avoiding APIs I were not working with (like Wear and TV) .. and that did the trick. Apparently, it seems I had corrupted my SDK somewhere along the way.

BTW .. I did see the error re-surface with one project in my workspace, but it seemed related to an import of appcompat-7, which I was not using. After rm-ing that project, so far haven't seen the issue resurface.

A variable modified inside a while loop is not remembered

I use stderr to store within a loop, and read from it outside. Here var i is initially set and read inside the loop as 1.

# reading lines of content from 2 files concatenated
# inside loop: write value of var i to stderr (before iteration)
# outside: read var i from stderr, has last iterative value

f=/tmp/file1
g=/tmp/file2
i=1
cat $f $g | \
while read -r s;
do
  echo $s > /dev/null;  # some work
  echo $i > 2
  let i++
done;
read -r i < 2
echo $i

Or use the heredoc method to reduce the amount of code in a subshell. Note the iterative i value can be read outside the while loop.

i=1
while read -r s;
do
  echo $s > /dev/null
  let i++
done <<EOT
$(cat $f $g)
EOT
let i--
echo $i

In C/C++ what's the simplest way to reverse the order of bits in a byte?

a slower but simpler implementation:

static int swap_bit(unsigned char unit)
{
    /*
     * swap bit[7] and bit[0]
     */
    unit = (((((unit & 0x80) >> 7) ^ (unit & 0x01)) << 7) | (unit & 0x7f));
    unit = (((((unit & 0x80) >> 7) ^ (unit & 0x01))) | (unit & 0xfe));
    unit = (((((unit & 0x80) >> 7) ^ (unit & 0x01)) << 7) | (unit & 0x7f));

    /*
     * swap bit[6] and bit[1]
     */
    unit = (((((unit & 0x40) >> 5) ^ (unit & 0x02)) << 5) | (unit & 0xbf));
    unit = (((((unit & 0x40) >> 5) ^ (unit & 0x02))) | (unit & 0xfd));
    unit = (((((unit & 0x40) >> 5) ^ (unit & 0x02)) << 5) | (unit & 0xbf));

    /*
     * swap bit[5] and bit[2]
     */
    unit = (((((unit & 0x20) >> 3) ^ (unit & 0x04)) << 3) | (unit & 0xdf));
    unit = (((((unit & 0x20) >> 3) ^ (unit & 0x04))) | (unit & 0xfb));
    unit = (((((unit & 0x20) >> 3) ^ (unit & 0x04)) << 3) | (unit & 0xdf));

    /*
     * swap bit[4] and bit[3]
     */
    unit = (((((unit & 0x10) >> 1) ^ (unit & 0x08)) << 1) | (unit & 0xef));
    unit = (((((unit & 0x10) >> 1) ^ (unit & 0x08))) | (unit & 0xf7));
    unit = (((((unit & 0x10) >> 1) ^ (unit & 0x08)) << 1) | (unit & 0xef));

    return unit;
}

Convert named list to vector with values only

purrr::flatten_*() is also a good option. the flatten_* functions add thin sanity checks and ensure type safety.

myList <- list('A'=1, 'B'=2, 'C'=3)

purrr::flatten_dbl(myList)
## [1] 1 2 3

Algorithm to randomly generate an aesthetically-pleasing color palette

David Crow's method in an R two-liner:

GetRandomColours <- function(num.of.colours, color.to.mix=c(1,1,1)) {
  return(rgb((matrix(runif(num.of.colours*3), nrow=num.of.colours)*color.to.mix)/2))
}

How to submit an HTML form without redirection

You need Ajax to make it happen. Something like this:

$(document).ready(function(){
    $("#myform").on('submit', function(){
        var name = $("#name").val();
        var email = $("#email").val();
        var password = $("#password").val();
        var contact = $("#contact").val();

        var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;
        if(name=='' || email=='' || password=='' || contact=='')
        {
            alert("Please fill in all fields");
        }
        else
        {
            // Ajax code to submit form.
            $.ajax({
                type: "POST",
                url: "ajaxsubmit.php",
                data: dataString,
                cache: false,
                success: function(result){
                    alert(result);
                }
           });
        }
        return false;
    });
});

How can a query multiply 2 cell for each row MySQL?

I'm assuming this should work. This will actually put it in the column in your database

UPDATE yourTable yt SET yt.Total = (yt.Pieces * yt.Price)

If you want to retrieve the 2 values from the database and put your multiplication in the third column of the result only, then

SELECT yt.Pieces, yt.Price, (yt.Pieces * yt.Price) as 'Total' FROM yourTable yt

will be your friend

AngularJS : The correct way of binding to a service properties

Late to the party, but for future Googlers - don't use the provided answer.

JavaScript has a mechanism of passing objects by reference, while it only passes a shallow copy for values "numbers, strings etc".

In above example, instead of binding attributes of a service, why don't we expose the service to the scope?

$scope.hello = HelloService;

This simple approach will make angular able to do two-way binding and all the magical things you need. Don't hack your controller with watchers or unneeded markup.

And if you are worried about your view accidentally overwriting your service attributes, use defineProperty to make it readable, enumerable, configurable, or define getters and setters. You can gain lots of control by making your service more solid.

Final tip: if you spend your time working on your controller more than your services then you are doing it wrong :(.

In that particular demo code you supplied I would recommend you do:

 function TimerCtrl1($scope, Timer) {
   $scope.timer = Timer;
 }
///Inside view
{{ timer.time_updated }}
{{ timer.other_property }}
etc...

Edit:

As I mentioned above, you can control the behaviour of your service attributes using defineProperty

Example:

// Lets expose a property named "propertyWithSetter" on our service
// and hook a setter function that automatically saves new value to db !
Object.defineProperty(self, 'propertyWithSetter', {
  get: function() { return self.data.variable; },
  set: function(newValue) { 
         self.data.variable = newValue; 
         // let's update the database too to reflect changes in data-model !
         self.updateDatabaseWithNewData(data);
       },
  enumerable: true,
  configurable: true
});

Now in our controller if we do

$scope.hello = HelloService;
$scope.hello.propertyWithSetter = 'NEW VALUE';

our service will change the value of propertyWithSetter and also post the new value to database somehow!

Or we can take any approach we want.

Refer to the MDN documentation for defineProperty.

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

Best-for-now Legacy Browser Frame Breaking Script

The other solutions did not worked for me. This one works on all browsers:

One way to defend against clickjacking is to include a "frame-breaker" script in each page that should not be framed. The following methodology will prevent a webpage from being framed even in legacy browsers, that do not support the X-Frame-Options-Header.

In the document HEAD element, add the following:

<style id="antiClickjack">body{display:none !important;}</style>

First apply an ID to the style element itself:

<script type="text/javascript">
   if (self === top) {
       var antiClickjack = document.getElementById("antiClickjack");
       antiClickjack.parentNode.removeChild(antiClickjack);
   } else {
       top.location = self.location;
   }
</script>

This way, everything can be in the document HEAD and you only need one method/taglib in your API.

Reference: https://www.codemagi.com/blog/post/194

Is there a way to split a widescreen monitor in to two or more virtual monitors?

It seems a window manager is what you want. The problem is finding one that works.

I use a tiling window manager in Linux (dwm) and it seems to do exactly what you are after, PLUS it has multiple workspaces which is what I thought you were going for at first.

A tiling window manager has no concept of "maximized" windows. All windows take up the full amount of space that they are allotted, and they never overlap. When you only have one window up on the screen, it gets the full screen. Open up another window, and it opens next to the first, while the first re-sizes automatically to take up only part of the screen. In dwm, the split between them is adjustable with keystrokes. Additional windows each take up their own allotted space on the screen, and any existing windows re-size to accommodate them depending on the particular layout you have chosen.

Workspaces use "tags"; any window can have one or more tags, and you can choose to see any windows that have one or more of a certain set of tags at a time. Thus you can hide windows that you don't want to see, and let the other windows take up more space.

Unfortunately, the few tiling add-ons I've tried for Windows don't work anywhere near as well. Although dwm has a few quirks with certain apps that use an SDI-style interface like Gimp or Pidgin (you can set windows as "floating" above the tiled layout to work around this), I've never had it get confused about where my windows are or shove windows off the screen like some of the window managers I've tried on Windows. If anyone knows of something with equivalent functionality that actually WORKS on Windows, I would love to know about it.

How to move screen without moving cursor in Vim?

Enter vim and type:

:help z

z is the vim command for redraw, so it will redraw the file relative to where you position the cursor. The options you have are as follows:

z+ - Redraws the file with the cursor at top of the window and at first non-blank character of your line.

z- - Redraws the file with the cursor at bottom of the window and at first non-blank character of your line.

z. - Redraws the file with the cursor at centre of the window and at first non-blank character of your line.

zt - Redraws file with the cursor at top of the window.

zb - Redraws file with the cursor at bottom of the window.

zz - Redraws file with the cursor at centre of the window.

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Try using SCP on Windows to transfer files, you can download SCP from Putty's website. Then try running:

pscp.exe filename.extension [email protected]:directory/subdirectory

There is a full length guide here.

How to filter empty or NULL names in a QuerySet?

Name.objects.filter(alias__gt='',alias__isnull=False)

Android Canvas: drawing too large bitmap

This solution worked for me.

Add these lines in your Manifest application tag

android:largeHeap="true"
android:hardwareAccelerated="false"

    

BeautifulSoup: extract text from anchor tag

All the above answers really help me to construct my answer, because of this I voted for all the answers that other users put it out: But I finally put together my own answer to exact problem I was dealing with:

As question clearly defined I had to access some of the siblings and its children in a dom structure: This solution will iterate over the images in the dom structure and construct image name using product title and save the image to the local directory.

import urlparse
from urllib2 import urlopen
from urllib import urlretrieve
from BeautifulSoup import BeautifulSoup as bs
import requests

def getImages(url):
    #Download the images
    r = requests.get(url)
    html = r.text
    soup = bs(html)
    output_folder = '~/amazon'
    #extracting the images that in div(s)
    for div in soup.findAll('div', attrs={'class':'image'}):
        modified_file_name = None
        try:
            #getting the data div using findNext
            nextDiv =  div.findNext('div', attrs={'class':'data'})
            #use findNext again on previous object to get to the anchor tag
            fileName = nextDiv.findNext('a').text
            modified_file_name = fileName.replace(' ','-') + '.jpg'
        except TypeError:
            print 'skip'
        imageUrl = div.find('img')['src']
        outputPath = os.path.join(output_folder, modified_file_name)
        urlretrieve(imageUrl, outputPath)

if __name__=='__main__':
    url = r'http://www.amazon.com/s/ref=sr_pg_1?rh=n%3A172282%2Ck%3Adigital+camera&keywords=digital+camera&ie=UTF8&qid=1343600585'
    getImages(url)

how to pass data in an hidden field from one jsp page to another?

The code from Alex works great. Just note that when you use request.getParameter you must use a request dispatcher

//Pass results back to the client
RequestDispatcher dispatcher =   getServletContext().getRequestDispatcher("TestPages/ServiceServlet.jsp");
dispatcher.forward(request, response);

git pull error "The requested URL returned error: 503 while accessing"

Every one please avoid modifying post buffer and advising it to others. It may help in some cases but it breaks others. If you have modified your post buffer for pushing your large project. Undo it using following command. git config --global --unset http.postBuffer git config --local --unset http.postBuffer

I modified my post buffer to fix one of the issues I had with git but it was the reason for my future problems with git.

Cleanest way to toggle a boolean variable in Java?

Before:

boolean result = isresult();
if (result) {
    result = false;
} else {
    result = true;
}

After:

boolean result = isresult();
result ^= true;

What is the best way to ensure only one instance of a Bash script is running?

first test example

[[ $(lsof -t $0| wc -l) > 1 ]] && echo "At least one of $0 is running"

second test example

currsh=$0
currpid=$$
runpid=$(lsof -t $currsh| paste -s -d " ")
if [[ $runpid == $currpid ]]
then
  sleep 11111111111111111
else
  echo -e "\nPID($runpid)($currpid) ::: At least one of \"$currsh\" is running !!!\n"
  false
  exit 1
fi

explanation

"lsof -t" to list all pids of current running scripts named "$0".

Command "lsof" will do two advantages.

  1. Ignore pids which is editing by editor such as vim, because vim edit its mapping file such as ".file.swp".
  2. Ignore pids forked by current running shell scripts, which most "grep" derivative command can't achieve it. Use "pstree -pH pidnum" command to see details about current process forking status.

Android webview & localStorage

I've also had problem with data being lost after application is restarted. Adding this helped:

webView.getSettings().setDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/databases/");

How to Get JSON Array Within JSON Object?

Solved, use array list of string to get name from Ingredients. Use below code:

JSONObject jsonObj = new JSONObject(jsonStr);

//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = ja_data.length();

//loop to get all json objects from data json array
for(int i=0; i<length; i++){
    JSONObject jObj = ja_data.getJSONObject(i);
    Toast.makeText(this, jObj.getString("Name"), Toast.LENGTH_LONG).show();
    // getting inner array Ingredients
    JSONArray ja = jObj.getJSONArray("Ingredients");
    int len = ja.length();
    ArrayList<String> Ingredients_names = new ArrayList<>();
    for(int j=0; j<len; j++){
        JSONObject json = ja.getJSONObject(j);
        Ingredients_names.add(json.getString("name"));
    }
}

How to compile .c file with OpenSSL includes?

You need to include the library path (-L/usr/local/lib/)

gcc -o Opentest Opentest.c -L/usr/local/lib/ -lssl -lcrypto

It works for me.

Pandas concat: ValueError: Shape of passed values is blah, indices imply blah2

To drop duplicate indices, use df = df.loc[df.index.drop_duplicates()]. C.f. pandas.pydata.org/pandas-docs/stable/generated/… – BallpointBen Apr 18 at 15:25

This is wrong but I can't reply directly to BallpointBen's comment due to low reputation. The reason its wrong is that df.index.drop_duplicates() returns a list of unique indices, but when you index back into the dataframe using those the unique indices it still returns all records. I think this is likely because indexing using one of the duplicated indices will return all instances of the index.

Instead, use df.index.duplicated(), which returns a boolean list (add the ~ to get the not-duplicated records):

df = df.loc[~df.index.duplicated()]

Action Image MVC3 Razor

To add to all the Awesome work started by Luke I am posting one more that takes a css class value and treats class and alt as optional parameters (valid under ASP.NET 3.5+). This will allow more functionality but reduct the number of overloaded methods needed.

// Extension method
    public static MvcHtmlString ActionImage(this HtmlHelper html, string action,
        string controllerName, object routeValues, string imagePath, string alt = null, string cssClass = null)
    {
        var url = new UrlHelper(html.ViewContext.RequestContext);

        // build the <img> tag
        var imgBuilder = new TagBuilder("img");
        imgBuilder.MergeAttribute("src", url.Content(imagePath));
        if(alt != null)
            imgBuilder.MergeAttribute("alt", alt);
        if (cssClass != null)
            imgBuilder.MergeAttribute("class", cssClass);

        string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

        // build the <a> tag
        var anchorBuilder = new TagBuilder("a");

        anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
        anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
        string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

        return MvcHtmlString.Create(anchorHtml);
    }

updating Google play services in Emulator

My answer is not to update the Google play service but work around. Get the play service version of the emulator by using the following code

getPackageManager().getPackageInfo("com.google.android.gms", 0 ).versionName);

For example if the value is "9.8.79" then use the nearest lesser version available com.google.android.gms:play-services:9.8.0'

This will resolve your problem. Get the release history from https://developers.google.com/android/guides/releases#november_2016_-_v100

SET NOCOUNT ON usage

Ok now I've done my research, here is the deal:

In TDS protocol, SET NOCOUNT ON only saves 9-bytes per query while the text "SET NOCOUNT ON" itself is a whopping 14 bytes. I used to think that 123 row(s) affected was returned from server in plain text in a separate network packet but that's not the case. It's in fact a small structure called DONE_IN_PROC embedded in the response. It's not a separate network packet so no roundtrips are wasted.

I think you can stick to default counting behavior almost always without worrying about the performance. There are some cases though, where calculating the number of rows beforehand would impact the performance, such as a forward-only cursor. In that case NOCOUNT might be a necessity. Other than that, there is absolutely no need to follow "use NOCOUNT wherever possible" motto.

Here is a very detailed analysis about insignificance of SET NOCOUNT setting: http://daleburnett.com/2014/01/everything-ever-wanted-know-set-nocount/

Excel - Sum column if condition is met by checking other column in same table

This should work, but there is a little trick. After you enter the formula, you need to hold down Ctrl+Shift while you press Enter. When you do, you'll see that the formula bar has curly-braces around your formula. This is called an array formula.

For example, if the Months are in cells A2:A100 and the amounts are in cells B2:B100, your formula would look like {=SUM(If(A2:A100="January",B2:B100))}. You don't actually type the curly-braces though.

You could also do something like =SUM((A2:A100="January")*B2:B100). You'd still need to use the trick to get it to work correctly.

How to horizontally center an element

HTML:

<div id="outer">
  <div id="inner">
  </div>
</div>

CSS:

#outer{
  width: 500px;
  background-color: #000;
  height: 500px
}
#inner{
  background-color: #333;
  margin: 0 auto;
  width: 50%;
  height: 250px;
}

Fiddle.

How to reset / remove chrome's input highlighting / focus border?

You should be able to remove it using

outline: none;

but keep in mind this is potentially bad for usability: It will be hard to tell whether an element is focused, which can suck when you walk through all a form's elements using the Tab key - you should reflect somehow when an element is focused.

How to create a folder with name as current date in batch (.bat) files

You need to get rid of the '/' characters in the date before you can use it in mkdir like this:

setlocal enableextensions
set name=%DATE:/=_%
mkdir %name%

Is it possible to deserialize XML into List<T>?

If you decorate the User class with the XmlType to match the required capitalization:

[XmlType("user")]
public class User
{
   ...
}

Then the XmlRootAttribute on the XmlSerializer ctor can provide the desired root and allow direct reading into List<>:

    // e.g. my test to create a file
    using (var writer = new FileStream("users.xml", FileMode.Create))
    {
        XmlSerializer ser = new XmlSerializer(typeof(List<User>),  
            new XmlRootAttribute("user_list"));
        List<User> list = new List<User>();
        list.Add(new User { Id = 1, Name = "Joe" });
        list.Add(new User { Id = 2, Name = "John" });
        list.Add(new User { Id = 3, Name = "June" });
        ser.Serialize(writer, list);
    }

...

    // read file
    List<User> users;
    using (var reader = new StreamReader("users.xml"))
    {
        XmlSerializer deserializer = new XmlSerializer(typeof(List<User>),  
            new XmlRootAttribute("user_list"));
        users = (List<User>)deserializer.Deserialize(reader);
    }

Credit: based on answer from YK1.

Convert UTC Epoch to local date

 function ToLocalDate (inDate) {
    var date = new Date();
    date.setTime(inDate.valueOf() - 60000 * inDate.getTimezoneOffset());
    return date;
}

git recover deleted file where no commit was made after the delete

Use git ls-files to checkout deleted(-d) or modified(-m) files.

git checkout $(git ls-files -d)

see How can I restore only the modified files on a git checkout?

Disable building workspace process in Eclipse

if needed programmatic from a PDE or JDT code:

public static void setWorkspaceAutoBuild(boolean flag) throws CoreException 
{
IWorkspace workspace = ResourcesPlugin.getWorkspace();
final IWorkspaceDescription description = workspace.getDescription();
description.setAutoBuilding(flag);
workspace.setDescription(description);
}

Capturing a form submit with jquery and .submit

try this:

Use ´return false´ for to cut the flow of the event:

$('#login_form').submit(function() {
    var data = $("#login_form :input").serializeArray();
    alert('Handler for .submit() called.');
    return false;  // <- cancel event
});

Edit

corroborate if the form element with the 'length' of jQuery:

alert($('#login_form').length) // if is == 0, not found form
$('#login_form').submit(function() {
    var data = $("#login_form :input").serializeArray();
    alert('Handler for .submit() called.');
    return false;  // <- cancel event
});

OR:

it waits for the DOM is ready:

jQuery(function() {

    alert($('#login_form').length) // if is == 0, not found form
    $('#login_form').submit(function() {
        var data = $("#login_form :input").serializeArray();
        alert('Handler for .submit() called.');
        return false;  // <- cancel event
    });

});

Do you put your code inside the event "ready" the document or after the DOM is ready?

How to fix "unable to open stdio.h in Turbo C" error?

If you have problems like that, first of all your TC folder put in to the C:..drive. after completing installation open turbo c blue screen. there is a OPTIONS > Directories ..in that you can see for option to set up path..

  1. include directories..you can set path there now.. C:\TC\INCUDE
  2. libraries Directories..you can set path there...C:\TC\LIB
  3. if you want to store your output in BIN then you can set..C:\TC\BIN..otherwise you can set another path where you want to store your output..

Finally you can give OK and finished processes.. It will now work properly

Twitter API - Display all tweets with a certain hashtag?

This answer was written in 2010. The API it uses has since been retired. It is kept for historical interest only.


Search for it.

Make sure include_entities is set to true to get hashtag results. See Tweet Entities

Returns 5 mixed results with Twitter.com user IDs plus entities for the term "blue angels":

GET http://search.twitter.com/search.json?q=blue%20angels&rpp=5&include_entities=true&with_twitter_user_id=true&result_type=mixed

Java: splitting a comma-separated string but ignoring commas in quotes

The simplest approach is not to match delimiters, i.e. commas, with a complex additional logic to match what is actually intended (the data which might be quoted strings), just to exclude false delimiters, but rather match the intended data in the first place.

The pattern consists of two alternatives, a quoted string ("[^"]*" or ".*?") or everything up to the next comma ([^,]+). To support empty cells, we have to allow the unquoted item to be empty and to consume the next comma, if any, and use the \\G anchor:

Pattern p = Pattern.compile("\\G\"(.*?)\",?|([^,]*),?");

The pattern also contains two capturing groups to get either, the quoted string’s content or the plain content.

Then, with Java 9, we can get an array as

String[] a = p.matcher(input).results()
    .map(m -> m.group(m.start(1)<0? 2: 1))
    .toArray(String[]::new);

whereas older Java versions need a loop like

for(Matcher m = p.matcher(input); m.find(); ) {
    String token = m.group(m.start(1)<0? 2: 1);
    System.out.println("found: "+token);
}

Adding the items to a List or an array is left as an excise to the reader.

For Java 8, you can use the results() implementation of this answer, to do it like the Java 9 solution.

For mixed content with embedded strings, like in the question, you can simply use

Pattern p = Pattern.compile("\\G((\"(.*?)\"|[^,])*),?");

But then, the strings are kept in their quoted form.

How do I auto-resize an image to fit a 'div' container?

Or you can simply use:

background-position:center;
background-size:cover;

Now the image will take all the space of the div.

How to create an empty matrix in R?

The default for matrix is to have 1 column. To explicitly have 0 columns, you need to write

matrix(, nrow = 15, ncol = 0)

A better way would be to preallocate the entire matrix and then fill it in

mat <- matrix(, nrow = 15, ncol = n.columns)
for(column in 1:n.columns){
  mat[, column] <- vector
}

Editing in the Chrome debugger

You can use "Overrides" in Chrome to persist javascript changes between page loads, even where you aren't hosting the original source.

  1. Create a folder under Developer Tools > Sources > Overrides
  2. Chrome will ask for permission to the folder, click Allow
  3. Edit the file in Sources>Page then save (ctrl-s). A purple dot will indicate the file is saved locally.

The Overrides sub tab in Chrome Developer Tools

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Your code is in the <head> => runs before the elements are rendered, so document.getElementById('compute'); returns null, as MDN promise...

element = document.getElementById(id);
element is a reference to an Element object, or null if an element with the specified ID is not in the document.

MDN

Solutions:

  1. Put the scripts in the bottom of the page.
  2. Call the attach code in the load event.
  3. Use jQuery library and it's DOM ready event.

What is the jQuery ready event and why is it needed?
(why no just JavaScript's load event):

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers...
...

ready docs

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

Reading and writing to serial port in C on Linux

1) I'd add a /n after init. i.e. write( USB, "init\n", 5);

2) Double check the serial port configuration. Odds are something is incorrect in there. Just because you don't use ^Q/^S or hardware flow control doesn't mean the other side isn't expecting it.

3) Most likely: Add a "usleep(100000); after the write(). The file-descriptor is set not to block or wait, right? How long does it take to get a response back before you can call read? (It has to be received and buffered by the kernel, through system hardware interrupts, before you can read() it.) Have you considered using select() to wait for something to read()? Perhaps with a timeout?

Edited to Add:

Do you need the DTR/RTS lines? Hardware flow control that tells the other side to send the computer data? e.g.

int tmp, serialLines;

cout << "Dropping Reading DTR and RTS\n";
ioctl ( readFd, TIOCMGET, & serialLines );
serialLines &= ~TIOCM_DTR;
serialLines &= ~TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
usleep(100000);
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
sleep (2);

cout << "Setting Reading DTR and RTS\n";
serialLines |= TIOCM_DTR;
serialLines |= TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;

What are the dark corners of Vim your mom never told you about?

Let's see some pretty little IDE editor do column transposition.

:%s/\(.*\)^I\(.*\)/\2^I\1/

Explanation

\( and \) is how to remember stuff in regex-land. And \1, \2 etc is how to retrieve the remembered stuff.

>>> \(.*\)^I\(.*\)

Remember everything followed by ^I (tab) followed by everything.

>>> \2^I\1

Replace the above stuff with "2nd stuff you remembered" followed by "1st stuff you remembered" - essentially doing a transpose.

JSON character encoding

The symptoms indicate that the JSON string which was originally in UTF-8 encoding was written to the HTTP response using ISO-8859-1 encoding and the webbrowser was instructed to display it as UTF-8. If it was written using UTF-8 and displayed as ISO-8859-1, then you would have seen aériennes. If it was written and displayed using ISO-8859-1, then you would have seen a�riennes.

To fix the problem of the JSON string incorrectly been written as ISO-8859-1, you need to configure your webapp / Spring to use UTF-8 as HTTP response encoding. Basically, it should be doing the following under the covers:

response.setCharacterEncoding("UTF-8");

Don't change your content type header. It's perfectly fine for JSON and it is been displayed as UTF-8.

TypeError: can't use a string pattern on a bytes-like object in re.findall()

You want to convert html (a byte-like object) into a string using .decode, e.g. html = response.read().decode('utf-8').

See Convert bytes to a Python String

StringBuilder vs String concatenation in toString() in Java

In Java 9 the version 1 should be faster because it is converted to invokedynamic call. More details can be found in JEP-280:

The idea is to replace the entire StringBuilder append dance with a simple invokedynamic call to java.lang.invoke.StringConcatFactory, that will accept the values in the need of concatenation.

How to convert WebResponse.GetResponseStream return into a string?

You should create a StreamReader around the stream, then call ReadToEnd.

You should consider calling WebClient.DownloadString instead.

How to change values in a tuple?

based on Jon's Idea and dear Trufa

def modifyTuple(tup, oldval, newval):
    lst=list(tup)
    for i in range(tup.count(oldval)):
        index = lst.index(oldval)
        lst[index]=newval

    return tuple(lst)

print modTupByIndex((1, 1, 3), 1, "a")

it changes all of your old values occurrences

How do I delete unpushed git commits?

I wonder why the best answer that I've found is only in the comments! (by Daenyth with 86 up votes)

git reset --hard origin

This command will sync the local repository with the remote repository getting rid of every change you have made on your local. You can also do the following to fetch the exact branch that you have in the origin.

git reset --hard origin/<branch>

How can I save application settings in a Windows Forms application?

If you work with Visual Studio then it is pretty easy to get persistable settings. Right click on the project in Solution Explorer and choose Properties. Select the Settings tab and click on the hyperlink if settings doesn't exist.

Use the Settings tab to create application settings. Visual Studio creates the files Settings.settings and Settings.Designer.settings that contain the singleton class Settings inherited from ApplicationSettingsBase. You can access this class from your code to read/write application settings:

Properties.Settings.Default["SomeProperty"] = "Some Value";
Properties.Settings.Default.Save(); // Saves settings in application configuration file

This technique is applicable both for console, Windows Forms, and other project types.

Note that you need to set the scope property of your settings. If you select Application scope then Settings.Default.<your property> will be read-only.

Reference: How To: Write User Settings at Run Time with C# - Microsoft Docs

JSONObject - How to get a value?

You can try the below function to get value from JSON string,

public static String GetJSONValue(String JSONString, String Field)
{
       return JSONString.substring(JSONString.indexOf(Field), JSONString.indexOf("\n", JSONString.indexOf(Field))).replace(Field+"\": \"", "").replace("\"", "").replace(",","");   
}

Why can't I change my input value in React even with the onChange listener

In React, the component will re-render (or update) only if the state or the prop changes.

In your case you have to update the state immediately after the change so that the component will re-render with the updates state value.

onTodoChange(event) {
        // update the state
    this.setState({name: event.target.value});
}

How do I turn off the mysql password validation?

On some installations, you cannot execute this command until you have reset the root password. You cannot reset the root password, until you execute this command. Classic Catch-22.

One solution not mention by other responders is to temporarily disable the plugin via mysql configuration. In any my.cnf, in the [mysqld] section, add:

skip-validate_password=1

and restart the server. Change the password, and set the value back to 0, and restart again.

how to move elasticsearch data from one server to another

You can take a snapshot of the complete status of your cluster (including all data indices) and restore them (using the restore API) in the new cluster or server.

Opening a folder in explorer and selecting a file

Samuel Yang answer tripped me up, here is my 3 cents worth.

Adrian Hum is right, make sure you put quotes around your filename. Not because it can't handle spaces as zourtney pointed out, but because it will recognize the commas (and possibly other characters) in filenames as separate arguments. So it should look as Adrian Hum suggested.

string argument = "/select, \"" + filePath +"\"";

Force page scroll position to top at page refresh in HTML

You can use location.replace instead of location.reload:

location.replace(location.href);

This way page will reload with scroll on top.

How do I include a file over 2 directories back?

I saw your answers and I used include path with syntax

require_once '../file.php'; // server internal error 500

and http server (Apache 2.4.3) returned internal error 500.

When I changed the path to

require_once '/../file.php'; // OK

everything is fine.

How can I set a DateTimePicker control to a specific date?

Can't figure out why, but in some circumstances if you have bound DataTimePicker and BindingSource contol is postioned to a new record, setting to Value property doesn't affect to bound field, so when you try to commit changes via EndEdit() method of BindingSource, you receive Null value doesn't allowed error. I managed this problem setting direct DataRow field.

How do I get the backtrace for all the threads in GDB?

Is there a command that does?

thread apply all where

How to display image with JavaScript?

You could make use of the Javascript DOM API. In particular, look at the createElement() method.

You could create a re-usable function that will create an image like so...

function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;

    // This next line will just add it to the <body> tag
    document.body.appendChild(img);
}

Then you could use it like this...

<button onclick=
    "show_image('http://google.com/images/logo.gif', 
                 276, 
                 110, 
                 'Google Logo');">Add Google Logo</button> 

See a working example on jsFiddle: http://jsfiddle.net/Bc6Et/

@Media min-width & max-width

If website on small devices behavior like desktop screen then you have to put this meta tag into header before

<meta name="viewport" content="width=device-width, initial-scale=1">

For media queries you can set this as

this will cover your all mobile/cellphone widths

 @media only screen and (min-width: 200px) and (max-width: 767px)  {
    //Put your CSS here for 200px to 767px width devices (cover all width between 200px to 767px //
   
    }

For iPad and iPad pro you have to use

  @media only screen and (min-width: 768px) and (max-width: 1024px)  {
        //Put your CSS here for 768px to 1024px width devices(covers all width between 768px to 1024px //   
  }

If you want to add css for Landscape mode you can add this

and (orientation : landscape)

  @media only screen and (min-width: 200px) and (max-width: 767px) and (orientation : portrait) {
        //Put your CSS here for 200px to 767px width devices (cover all mobile portrait width //        
  }

Why do I get a warning icon when I add a reference to an MEF plugin project?

Based on the answer from @AljohnYamaro (sorry, couldn't comment on your answer, new account without enough reputation yet, but upvotaded you), I've checked the .csproj file.

On my file, besides the standard project reference:

<ProjectReference Include="..\ProjectA\ProjectA.csproj">
    <Private>true</Private>
    <CopyLocalSatelliteAssemblies>true</CopyLocalSatelliteAssemblies>
</ProjectReference>

There were also a directy link to the compiled dll from the referenced project:

<ItemGroup>
    <Reference Include="ProjectA">
    <HintPath>..\ProjectA\bin\Debug\netcoreapp3.1\ProjectA.dll</HintPath>
    </Reference>
</ItemGroup>

Removing this second reference solved the issue.

How to send a JSON object over Request with Android?

HttpPost is deprecated by Android Api Level 22. So, Use HttpUrlConnection for further.

public static String makeRequest(String uri, String json) {
    HttpURLConnection urlConnection;
    String url;
    String data = json;
    String result = null;
    try {
        //Connect 
        urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestMethod("POST");
        urlConnection.connect();

        //Write
        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(data);
        writer.close();
        outputStream.close();

        //Read
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));

        String line = null;
        StringBuilder sb = new StringBuilder();

        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }

        bufferedReader.close();
        result = sb.toString();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

SQL ROWNUM how to return rows between a specific range

I was looking for a solution for this and found this great article explaining the solution Relevant excerpt

My all-time-favorite use of ROWNUM is pagination. In this case, I use ROWNUM to get rows N through M of a result set. The general form is as follows:

select * enter code here
  from ( select /*+ FIRST_ROWS(n) */ 
  a.*, ROWNUM rnum 
      from ( your_query_goes_here, 
      with order by ) a 
      where ROWNUM <= 
      :MAX_ROW_TO_FETCH ) 
where rnum  >= :MIN_ROW_TO_FETCH;

Now with a real example (gets rows 148, 149 and 150):

select *
    from
  (select a.*, rownum rnum
     from
  (select id, data
     from t
   order by id, rowid) a
   where rownum <= 150
  )
   where rnum >= 148;

Command-line svn for Windows?

I've used sliksvn and it works great for me

Binary Search Tree - Java Implementation

Here is a sample implementation:

import java.util.*;

public class MyBSTree<K,V> implements MyTree<K,V>{
    private BSTNode<K,V> _root;
    private int _size;
    private Comparator<K> _comparator;
    private int mod = 0;

    public MyBSTree(Comparator<K> comparator){
        _comparator = comparator;
    }

    public Node<K,V> root(){
        return _root;
    }

    public int size(){
        return _size;
    }

    public boolean containsKey(K key){
        if(_root == null){
            return false;
        }

        BSTNode<K,V> node = _root;

        while (node != null){
            int comparison = compare(key, node.key());

            if(comparison == 0){
                return true;
            }else if(comparison <= 0){
                node = node._left;
            }else {
                node = node._right;
            }
        }

        return false;
    }

    private int compare(K k1, K k2){
        if(_comparator != null){
            return _comparator.compare(k1,k2);
        }
        else {
            Comparable<K> comparable = (Comparable<K>)k1;
            return comparable.compareTo(k2);
        }
    }


    public V get(K key){
        Node<K,V> node = node(key);

        return node != null ? node.value() : null;
    }

    private BSTNode<K,V> node(K key){
        if(_root != null){
            BSTNode<K,V> node = _root;

            while (node != null){
                int comparison = compare(key, node.key());

                if(comparison == 0){
                    return node;
                }else if(comparison <= 0){
                    node = node._left;
                }else {
                    node = node._right;
                }
            }
        }

        return null;
    }

    public void add(K key, V value){
        if(key == null){
            throw new IllegalArgumentException("key");
        }

        if(_root == null){
            _root = new BSTNode<K, V>(key, value);
        }

        BSTNode<K,V> prev = null, curr = _root;
        boolean lastChildLeft = false;
        while(curr != null){
            int comparison = compare(key, curr.key());
            prev = curr;

            if(comparison == 0){
                curr._value = value;
                return;
            }else if(comparison < 0){
                curr = curr._left;
                lastChildLeft = true;
            }
            else{
                curr = curr._right;
                lastChildLeft = false;
            }
        }

        mod++;
        if(lastChildLeft){
            prev._left = new BSTNode<K, V>(key, value);
        }else {
            prev._right = new BSTNode<K, V>(key, value);
        }
    }

    private void removeNode(BSTNode<K,V> curr){
        if(curr.left() == null && curr.right() == null){
            if(curr == _root){
                _root = null;
            }else{
                if(curr.isLeft()) curr._parent._left = null;
                else curr._parent._right = null;
            }
        }
        else if(curr._left == null && curr._right != null){
            curr._key = curr._right._key;
            curr._value = curr._right._value;
            curr._left = curr._right._left;
            curr._right = curr._right._right;
        }
        else if(curr._left != null && curr._right == null){
            curr._key = curr._left._key;
            curr._value = curr._left._value;
            curr._right = curr._left._right;
            curr._left = curr._left._left;
        }
        else { // both left & right exist
            BSTNode<K,V> x = curr._left;
            // find right-most node of left sub-tree
            while (x._right != null){ 
                x = x._right;
            }
            // move that to current
            curr._key = x._key;
            curr._value = x._value;
            // delete duplicate data
            removeNode(x);
        }
    }


    public V remove(K key){
        BSTNode<K,V> curr = _root;
        V val = null;
        while(curr != null){
            int comparison = compare(key, curr.key());
            if(comparison == 0){
                val = curr._value;
                removeNode(curr);
                mod++;
                break;
            }else if(comparison < 0){
                curr = curr._left;
            }
            else{
                curr = curr._right;
            }
        }

        return val;
    }

    public Iterator<MyTree.Node<K,V>> iterator(){
        return new MyIterator();
    }

    private class MyIterator implements Iterator<Node<K,V>>{
        int _startMod;
        Stack<BSTNode<K,V>> _stack;

        public MyIterator(){
            _startMod = MyBSTree.this.mod;
            _stack = new Stack<BSTNode<K, V>>();

            BSTNode<K,V> node = MyBSTree.this._root;
            while (node != null){
                _stack.push(node);
                node = node._left;
            }
        }

        public void remove(){
            throw new UnsupportedOperationException();
        }

        public boolean hasNext(){
            if(MyBSTree.this.mod != _startMod){
                throw new ConcurrentModificationException();
            }

            return !_stack.empty();
        }

        public Node<K,V> next(){
            if(MyBSTree.this.mod != _startMod){
                throw new ConcurrentModificationException();
            }

            if(!hasNext()){
                throw new NoSuchElementException();
            }

            BSTNode<K,V> node = _stack.pop();
            BSTNode<K,V> x = node._right;
            while (x != null){
                _stack.push(x);
                x = x._left;
            }

            return node;
        }
    }

    @Override
    public String toString(){
        if(_root == null) return "[]";

        return _root.toString();
    }

    private static class BSTNode<K,V> implements Node<K,V>{
        K _key;
        V _value;
        BSTNode<K,V> _left, _right, _parent;

        public BSTNode(K key, V value){
            if(key == null){
                throw new IllegalArgumentException("key");
            }

            _key = key;
            _value = value;
        }

        public K key(){
            return _key;
        }

        public V value(){
            return _value;
        }

        public Node<K,V> left(){
            return _left;
        }

        public Node<K,V> right(){
            return _right;
        }

        public Node<K,V> parent(){
            return _parent;
        }

        boolean isLeft(){
            if(_parent == null) return false;

            return _parent._left == this;
        }

        boolean isRight(){
            if(_parent == null) return false;

            return _parent._right == this;
        }

        @Override
        public boolean equals(Object o){
            if(o == null){
                return false;
            }

            try{
                BSTNode<K,V> node = (BSTNode<K,V>)o;
                return node._key.equals(_key) && ((_value == null && node._value == null) || (_value != null && _value.equals(node._value)));
            }catch (ClassCastException ex){
                return false;
            }
        }

        @Override
        public int hashCode(){
            int hashCode = _key.hashCode();

            if(_value != null){
                hashCode ^= _value.hashCode();
            }

            return hashCode;
        }

        @Override
        public String toString(){
            String leftStr = _left != null ? _left.toString() : "";
            String rightStr = _right != null ? _right.toString() : "";
            return "["+leftStr+" "+_key+" "+rightStr+"]";
        }
    }
}

java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

This is an issue with the jdbc Driver version. I had this issue when I was using mysql-connector-java-commercial-5.0.3-bin.jar but when I changed to a later driver version mysql-connector-java-5.1.22.jar, the issue was fixed.

Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

If you can use shell, try

psql -U postgres -c 'select 1' -d $DB &>dev/null || psql -U postgres -tc 'create database $DB'

I think psql -U postgres -c "select 1" -d $DB is easier than SELECT 1 FROM pg_database WHERE datname = 'my_db',and only need one type of quote, easier to combine with sh -c.

I use this in my ansible task

- name: create service database
  shell: docker exec postgres sh -c '{ psql -U postgres -tc "SELECT 1" -d {{service_name}} &> /dev/null && echo -n 1; } || { psql -U postgres -c "CREATE DATABASE {{service_name}}"}'
  register: shell_result
  changed_when: "shell_result.stdout != '1'"

Set initial focus in an Android application

android:focusedByDefault="true"

How to export html table to excel or pdf in php

<script src="jquery.min.js"></script>
<table border="1" id="ReportTable" class="myClass">
    <tr bgcolor="#CCC">
      <td width="100">xxxxx</td>
      <td width="700">xxxxxx</td>
      <td width="170">xxxxxx</td>
      <td width="30">xxxxxx</td>
    </tr>
    <tr bgcolor="#FFFFFF">
      <td><?php                 
            $date = date_create($row_Recordset3['fecha']);
            echo date_format($date, 'd-m-Y');
            ?></td>
      <td><?php echo $row_Recordset3['descripcion']; ?></td>
      <td><?php echo $row_Recordset3['producto']; ?></td>
      <td><img src="borrar.png" width="14" height="14" class="clickable" onClick="eliminarSeguimiento(<?php echo $row_Recordset3['idSeguimiento']; ?>)" title="borrar"></td>
    </tr>
  </table>

  <input type="hidden" id="datatodisplay" name="datatodisplay">  
    <input type="submit" value="Export to Excel"> 

exporttable.php

<?php
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=export.xls');
// Fix for crappy IE bug in download.
header("Pragma: ");
header("Cache-Control: ");
echo $_REQUEST['datatodisplay'];
?>

How do I ignore files in Subversion?

(This answer has been updated to match SVN 1.8 and 1.9's behaviour)

You have 2 questions:

Marking files as ignored:

By "ignored file" I mean the file won't appear in lists even as "unversioned": your SVN client will pretend the file doesn't exist at all in the filesystem.

Ignored files are specified by a "file pattern". The syntax and format of file patterns is explained in SVN's online documentation: http://svnbook.red-bean.com/nightly/en/svn.advanced.props.special.ignore.html "File Patterns in Subversion".

Subversion, as of version 1.8 (June 2013) and later, supports 3 different ways of specifying file patterns. Here's a summary with examples:

1 - Runtime Configuration Area - global-ignores option:

  • This is a client-side only setting, so your global-ignores list won't be shared by other users, and it applies to all repos you checkout onto your computer.
  • This setting is defined in your Runtime Configuration Area file:
    • Windows (file-based) - C:\Users\{you}\AppData\Roaming\Subversion\config
    • Windows (registry-based) - Software\Tigris.org\Subversion\Config\Miscellany\global-ignores in both HKLM and HKCU.
    • Linux/Unix - ~/.subversion/config

2 - The svn:ignore property, which is set on directories (not files):

  • This is stored within the repo, so other users will have the same ignore files. Similar to how .gitignore works.
  • svn:ignore is applied to directories and is non-recursive or inherited. Any file or immediate subdirectory of the parent directory that matches the File Pattern will be excluded.
  • While SVN 1.8 adds the concept of "inherited properties", the svn:ignore property itself is ignored in non-immediate descendant directories:

    cd ~/myRepoRoot                             # Open an existing repo.
    echo "foo" > "ignoreThis.txt"                # Create a file called "ignoreThis.txt".
    
    svn status                                  # Check to see if the file is ignored or not.
    > ?    ./ignoreThis.txt
    > 1 unversioned file                        # ...it is NOT currently ignored.
    
    svn propset svn:ignore "ignoreThis.txt" .   # Apply the svn:ignore property to the "myRepoRoot" directory.
    svn status
    > 0 unversioned files                       # ...but now the file is ignored!
    
    cd subdirectory                             # now open a subdirectory.
    echo "foo" > "ignoreThis.txt"                # create another file named "ignoreThis.txt".
    
    svn status
    > ?    ./subdirectory/ignoreThis.txt        # ...and is is NOT ignored!
    > 1 unversioned file
    

    (So the file ./subdirectory/ignoreThis is not ignored, even though "ignoreThis.txt" is applied on the . repo root).

  • Therefore, to apply an ignore list recursively you must use svn propset svn:ignore <filePattern> . --recursive.

    • This will create a copy of the property on every subdirectory.
    • If the <filePattern> value is different in a child directory then the child's value completely overrides the parents, so there is no "additive" effect.
    • So if you change the <filePattern> on the root ., then you must change it with --recursive to overwrite it on the child and descendant directories.
  • I note that the command-line syntax is counter-intuitive.

    • I started-off assuming that you would ignore a file in SVN by typing something like svn ignore pathToFileToIgnore.txt however this is not how SVN's ignore feature works.

3- The svn:global-ignores property. Requires SVN 1.8 (June 2013):

  • This is similar to svn:ignore, except it makes use of SVN 1.8's "inherited properties" feature.
  • Compare to svn:ignore, the file pattern is automatically applied in every descendant directory (not just immediate children).
    • This means that is unnecessary to set svn:global-ignores with the --recursive flag, as inherited ignore file patterns are automatically applied as they're inherited.
  • Running the same set of commands as in the previous example, but using svn:global-ignores instead:

    cd ~/myRepoRoot                                    # Open an existing repo
    echo "foo" > "ignoreThis.txt"                       # Create a file called "ignoreThis.txt"
    svn status                                         # Check to see if the file is ignored or not
    > ?    ./ignoreThis.txt
    > 1 unversioned file                               # ...it is NOT currently ignored
    
    svn propset svn:global-ignores "ignoreThis.txt" .
    svn status
    > 0 unversioned files                              # ...but now the file is ignored!
    
    cd subdirectory                                    # now open a subdirectory
    echo "foo" > "ignoreThis.txt"                       # create another file named "ignoreThis.txt"
    svn status
    > 0 unversioned files                              # the file is ignored here too!
    

For TortoiseSVN users:

This whole arrangement was confusing for me, because TortoiseSVN's terminology (as used in their Windows Explorer menu system) was initially misleading to me - I was unsure what the significance of the Ignore menu's "Add recursively", "Add *" and "Add " options. I hope this post explains how the Ignore feature ties-in to the SVN Properties feature. That said, I suggest using the command-line to set ignored files so you get a feel for how it works instead of using the GUI, and only using the GUI to manipulate properties after you're comfortable with the command-line.

Listing files that are ignored:

The command svn status will hide ignored files (that is, files that match an RGA global-ignores pattern, or match an immediate parent directory's svn:ignore pattern or match any ancesor directory's svn:global-ignores pattern.

Use the --no-ignore option to see those files listed. Ignored files have a status of I, then pipe the output to grep to only show lines starting with "I".

The command is:

svn status --no-ignore | grep "^I"

For example:

svn status
> ? foo                             # An unversioned file
> M modifiedFile.txt                # A versioned file that has been modified

svn status --no-ignore
> ? foo                             # An unversioned file
> I ignoreThis.txt                  # A file matching an svn:ignore pattern
> M modifiedFile.txt                # A versioned file that has been modified

svn status --no-ignore | grep "^I"
> I ignoreThis.txt                  # A file matching an svn:ignore pattern

ta-da!

Link entire table row?

I feel like the simplest solution is sans javascript and simply putting the link in each cell (provided you don't have massive gullies between your cells or really think border lines). Have your css:

.tableClass td a{
   display: block;
}

and then add a link per cell:

<table class="tableClass">
    <tr>
        <td><a href="#link">Link name</a></td>
        <td><a href="#link">Link description</a></td>
        <td><a href="#link">Link somthing else</a></td>
    </tr>
</table>

boring but clean.

Sum of two input value by jquery

Because at least one value is a string the + operator is being interpreted as a string concatenation operator. The simplest fix for this is to indicate that you intend for the values to be interpreted as numbers.

var total = +a + +b;

and

$('#total_price').val(+a + +b);

Or, better, just pull them out as numbers to begin with:

var a = +$('input[name=service_price]').val();
var b = +$('input[name=modem_price]').val();
var total = a+b;
$('#total_price').val(a+b);

See Mozilla's Unary + documentation.

Note that this is only a good idea if you know the value is going to be a number anyway. If this is user input you must be more careful and probably want to use parseInt and other validation as other answers suggest.

Remove CSS from a Div using JQuery

Set the default value, for example:

$(this).css("height", "auto");

or in the case of other CSS features

$(this).css("height", "inherit");

How to compile and run C/C++ in a Unix console/Mac terminal?

just enter in the directory in which your c/cpp file is.

for compiling and running c code.

$gcc filename.c
$./a.out filename.c

for compiling and running c++ code.

$g++ filename.cpp
$./a.out filename.cpp

"$" is default mac terminal symbol

Is it possible to ping a server from Javascript?

I don't know what version of Ruby you're running, but have you tried implementing ping for ruby instead of javascript? http://raa.ruby-lang.org/project/net-ping/

Visual Studio popup: "the operation could not be completed"

Run eventvwr from the command line to see if it has recorded any Application errors.

This might give you an actual error message that is more useful.

How do I block or restrict special characters from input fields with jquery?

this is an example that prevent the user from typing the character "a"

$(function() {
$('input:text').keydown(function(e) {
if(e.keyCode==65)
    return false;

});
});

key codes refrence here:
http://www.expandinghead.net/keycode.html

Makefile If-Then Else and Loops

Conditional Forms

Simple

conditional-directive
text-if-true
endif

Moderately Complex

conditional-directive
text-if-true
else
text-if-false
endif

More Complex

conditional-directive
text-if-one-is-true
else
conditional-directive
text-if-true
else
text-if-false
endif
endif

Conditional Directives

If Equal Syntax

ifeq (arg1, arg2)
ifeq 'arg1' 'arg2'
ifeq "arg1" "arg2"
ifeq "arg1" 'arg2'
ifeq 'arg1' "arg2"

If Not Equal Syntax

ifneq (arg1, arg2)
ifneq 'arg1' 'arg2'
ifneq "arg1" "arg2"
ifneq "arg1" 'arg2'
ifneq 'arg1' "arg2"

If Defined Syntax

ifdef variable-name

If Not Defined Syntax

ifndef variable-name  

foreach Function

foreach Function Syntax

$(foreach var, list, text)  

foreach Semantics
For each whitespace separated word in "list", the variable named by "var" is set to that word and text is executed.

How can I find whitespace in a String?

You can use charAt() function to find out spaces in string.

 public class Test {
  public static void main(String args[]) {
   String fav="Hi Testing  12 3";
   int counter=0;
   for( int i=0; i<fav.length(); i++ ) {
    if(fav.charAt(i) == ' ' ) {
     counter++;
      }
     }
    System.out.println("Number of spaces "+ counter);
    //This will print Number of spaces 4
   }
  }

SVN: Is there a way to mark a file as "do not commit"?

I came to this thread looking for a way to make an "atomic" commit of just some files and instead of ignoring some files on commit I went the other way and only commited the files I wanted:

svn ci filename1 filename2

Maybe, it will help someone.

Removing spaces from string

Try this:

String urle = HOST + url + value;

Then return the values from:

urle.replace(" ", "%20").trim();

How to redirect to logon page when session State time out is completed in asp.net mvc

There is a generic solution:

Lets say you have a controller named Admin where you put content for authorized users.

Then, you can override the Initialize or OnAuthorization methods of Admin controller and write redirect to login page logic on session timeout in these methods as described:

protected override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
    {
        //lets say you set session value to a positive integer
        AdminLoginType = Convert.ToInt32(filterContext.HttpContext.Session["AdminLoginType"]);
        if (AdminLoginType == 0)
        {
            filterContext.HttpContext.Response.Redirect("~/login");
        }

        base.OnAuthorization(filterContext);
    }

SQL query with avg and group by

If I understand what you need, try this:

SELECT id, pass, AVG(val) AS val_1 
FROM data_r1 
GROUP BY id, pass;

Or, if you want just one row for every id, this:

SELECT d1.id,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 1) as val_1,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 2) as val_2,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 3) as val_3,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 4) as val_4,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 5) as val_5,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 6) as val_6,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 7) as val_7
from data_r1 d1
GROUP BY d1.id

Do Git tags only apply to the current branch?

Tags and branch are completely unrelated, since tags refer to a specific commit, and branch is a moving reference to the last commit of a history. Branches go, tags stay.

So when you tag a commit, git doesn't care which commit or branch is checked out, if you provide him the SHA1 of what you want to tag.

I can even tag by refering to a branch (it will then tag the tip of the branch), and later say that the branch's tip is elsewhere (with git reset --hard for example), or delete the branch. The tag I created however won't move.

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

This explains better: Postman docs

Request body

While constructing requests, you would be dealing with the request body editor a lot. Postman lets you send almost any kind of HTTP request (If you can't send something, let us know!). The body editor is divided into 4 areas and has different controls depending on the body type.

form-data

multipart/form-data is the default encoding a web form uses to transfer data. This simulates filling a form on a website, and submitting it. The form-data editor lets you set key/value pairs (using the key-value editor) for your data. You can attach files to a key as well. Do note that due to restrictions of the HTML5 spec, files are not stored in history or collections. You would have to select the file again at the time of sending a request.

urlencoded

This encoding is the same as the one used in URL parameters. You just need to enter key/value pairs and Postman will encode the keys and values properly. Note that you can not upload files through this encoding mode. There might be some confusion between form-data and urlencoded so make sure to check with your API first.

raw

A raw request can contain anything. Postman doesn't touch the string entered in the raw editor except replacing environment variables. Whatever you put in the text area gets sent with the request. The raw editor lets you set the formatting type along with the correct header that you should send with the raw body. You can set the Content-Type header manually as well. Normally, you would be sending XML or JSON data here.

binary

binary data allows you to send things which you can not enter in Postman. For example, image, audio or video files. You can send text files as well. As mentioned earlier in the form-data section, you would have to reattach a file if you are loading a request through the history or the collection.

UPDATE

As pointed out by VKK, the WHATWG spec say urlencoded is the default encoding type for forms.

The invalid value default for these attributes is the application/x-www-form-urlencoded state. The missing value default for the enctype attribute is also the application/x-www-form-urlencoded state.

validate natural input number with ngpattern

<label>Mobile Number(*)</label>
<input id="txtMobile" ng-maxlength="10" maxlength="10" Validate-phone  required  name='strMobileNo' ng-model="formModel.strMobileNo" type="text"  placeholder="Enter Mobile Number">
<span style="color:red" ng-show="regForm.strMobileNo.$dirty && regForm.strMobileNo.$invalid"><span ng-show="regForm.strMobileNo.$error.required">Phone is required.</span>

the following code will help for phone number validation and the respected directive is

app.directive('validatePhone', function() {
var PHONE_REGEXP = /^[789]\d{9}$/;
  return {
    link: function(scope, elm) {
      elm.on("keyup",function(){
            var isMatchRegex = PHONE_REGEXP.test(elm.val());
            if( isMatchRegex&& elm.hasClass('warning') || elm.val() == ''){
              elm.removeClass('warning');
            }else if(isMatchRegex == false && !elm.hasClass('warning')){
              elm.addClass('warning');
            }
      });
    }
  }
});

Can I serve multiple clients using just Flask app.run() as standalone?

Tips from 2020:

From Flask 1.0, it defaults to enable multiple threads (source), you don't need to do anything, just upgrade it with:

$ pip install -U flask

If you are using flask run instead of app.run() with older versions, you can control the threaded behavior with a command option (--with-threads/--without-threads):

$ flask run --with-threads

It's same as app.run(threaded=True)

How to store an output of shell script to a variable in Unix?

You need to start the script with a preceding dot, this will put the exported variables in the current environment.

#!/bin/bash
...
export output="SUCCESS"

Then execute it like so

chmod +x /tmp/test.sh
. /tmp/test.sh

When you need the entire output and not just a single value, just put the output in a variable like the other answers indicate

How-to turn off all SSL checks for postman for a specific site

enter image description here

This steps are used in spring boot with self signed ssl certificate implementation

if SSL turns off then HTTPS call will be worked as expected.

https://localhost:8443/test/hello

These are the steps we have to follow,

  1. Generate self signed ssl certificate
keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650

after key generation has done then copy that file in to the resource foder in your project

  1. add key store properties in applicaiton.properties
server.port: 8443
server.ssl.key-store:classpath:keystore.p12
server.ssl.key-store-password: test123
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat
  1. change your postman ssl verification settings to turn OFF

now verify the url: https://localhost:8443/test/hello

Using Laravel Homestead: 'no input file specified'

I was just struggling with same situation. Following solved the issue:

If you have directory structure like this:

folders:
    - map: /Users/me/code/exampleproject
      to: /home/vagrant/code/exampleproject

Just create 'public' folder within exampleproject on your host machine.

What is the best way to search the Long datatype within an Oracle database?

Don't use LONGs, use CLOB instead. You can index and search CLOBs like VARCHAR2.

Additionally, querying with a leading wildcard(%) will ALWAYS result in a full-table-scan. Look into Oracle Text indexes instead.

Nginx serves .php files as downloads, instead of executing them

For me it was the line: fastcgi_pass unix:/var/run/php5-fpm.sock;

which had to be just: fastcgi_pass unix:/run/php5-fpm.sock;

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

In my case i have included jdbc api dependencies in the project so the "Hello World" not printed. After removing the below dependency it works like a charm.

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

log4j configuration via JVM argument(s)?

The solution is using of the following JVM argument:

-Dlog4j.configuration={path to file}

If the file is NOT in the classpath (in WEB-INF/classes in case of Tomcat) but somewhere on you disk, use file:, like

-Dlog4j.configuration=file:C:\Users\me\log4j.xml

More information and examples here: http://logging.apache.org/log4j/1.2/manual.html

Spring Maven clean error - The requested profile "pom.xml" could not be activated because it does not exist

The warning message

[WARNING] The requested profile "pom.xml" could not be activated because it does not exist.

means that you somehow passed -P pom.xml to Maven which means "there is a profile called pom.xml; find it and activate it". Check your environment and your settings.xml for this flag and also look at all <profile> elements inside the various XML files.

Usually, mvn help:effective-pom is also useful to see what the real POM would look like.

Now the error means that you tried to configure Maven to build Java 8 code but you're not using a Java 8 runtime. Solutions:

  1. Install Java 8
  2. Make sure Maven uses Java 8 if you have it installed. JAVA_HOME is your friend
  3. Configure the Java compiler in your pom.xml to a Java version which you actually have.

Related:

Is mongodb running?

To check current running status of mongodb use: sudo service mongodb status

What is the difference between Class.getResource() and ClassLoader.getResource()?

The first call searches relative to the .class file while the latter searches relative to the classpath root.

To debug issues like that, I print the URL:

System.out.println( getClass().getResource(getClass().getSimpleName() + ".class") );

How do I parse a URL into hostname and path in javascript?

You can also use parse_url() function from Locutus project (former php.js).

Code:

parse_url('http://username:password@hostname/path?arg=value#anchor');

Result:

{
  scheme: 'http',
  host: 'hostname',
  user: 'username',
  pass: 'password',
  path: '/path',
  query: 'arg=value',
  fragment: 'anchor'
}

Spring boot - Not a managed type

never forget to add @Entity on domain class

Server configuration by allow_url_fopen=0 in

Using relative instead of absolute file path solved the problem for me. I had the same issue and setting allow_url_fopen=on did not help. This means for instance :

use $file="folder/file.ext"; instead of $file="https://website.com/folder/file.ext"; in

$f=fopen($file,"r+");

How can I make a list of lists in R?

You can easily make lists of lists

list1 <- list(a = 2, b = 3)
list2 <- list(c = "a", d = "b")
mylist <- list(list1, list2)

mylist is now a list that contains two lists. To access list1 you can use mylist[[1]]. If you want to be able to something like mylist$list1 then you need to do somethingl like

mylist <- list(list1 = list1, list2 = list2)
# Now you can do the following
mylist$list1

Edit: To reply to your edit. Just use double bracket indexing

a <- list_all[[1]]
a[[1]]
#[1] 1
a[[2]]
#[1] 2

How to capitalize first letter of each word, like a 2-word city?

function convertCase(str) {
  var lower = String(str).toLowerCase();
  return lower.replace(/(^| )(\w)/g, function(x) {
    return x.toUpperCase();
  });
}

XAMPP - MySQL shutdown unexpectedly

Guys just make sure you dont have MySql Server installed. Because I have MySql server pre-installed and when I start mysql from xampp control panel some port conflicts are happening and its not working.. SO before starting the mysql from xampp control panel make sure mysql server is not installed. I use .net so I have installed mysql server in the Past. Uninstalling it solved my Problem....

How to split one string into multiple strings separated by at least one space in bash shell?

Did you try just passing the string variable to a for loop? Bash, for one, will split on whitespace automatically.

sentence="This is   a sentence."
for word in $sentence
do
    echo $word
done

 

This
is
a
sentence.

Use space as a delimiter with cut command

You can't do it easily with cut if the data has for example multiple spaces. I have found it useful to normalize input for easier processing. One trick is to use sed for normalization as below.

echo -e "foor\t \t bar" | sed 's:\s\+:\t:g' | cut -f2  #bar

Installing ADB on macOS

  1. You must download Android SDK from this link.

  2. You can really put it anywhere, but the best place at least for me was right in the YOUR USERNAME folder root.

  3. Then you need to set the path by copying the below text, but edit your username into the path, copy the text into Terminal by hitting command+spacebar type terminal. export PATH = ${PATH}:/Users/**YOURUSERNAME**/android-sdk/platform-tools/

  4. Verify ADB works by hitting command+spacebar and type terminal, and type ADB.

There you go. You have ADB setup on MAC OS X. It works on latest MAC OS X 10.10.3.

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

java_home environment variable should point to the location of the proper version of java installation directory, so that tomcat starts with the right version. for example it you built the project with java 1.7 , then make sure that JAVA_HOME environment variable points to the jdk 1.7 installation directory in your machine.

I had same problem , when i deploy the war in tomcat and run, the link throws the error. But pointing the variable - JAVA_HOME to jdk 1.7 resolved the issue, as my war file was built in java 1.7 environment.

Why am I getting "Thread was being aborted" in ASP.NET?

If you spawn threads in Application_Start, they will still be executing in the application pool's AppDomain.

If an application is idle for some time (meaning that no requests are coming in), or certain other conditions are met, ASP.NET will recycle the entire AppDomain.

When that happens, any threads that you started from that AppDomain, including those from Application_Start, will be aborted.

Lots more on application pools and recycling in this question: What exactly is Appdomain recycling

If you are trying to run a long-running process within IIS/ASP.NET, the short answer is usually "Don't". That's what Windows Services are for.

How do you serialize a model instance in Django?

ville = UneVille.objects.get(nom='lihlihlihlih')
....
blablablab
.......

return HttpResponse(simplejson.dumps(ville.__dict__))

I return the dict of my instance

so it return something like {'field1':value,"field2":value,....}

Custom HTTP Authorization Header

No, that is not a valid production according to the "credentials" definition in RFC 2617. You give a valid auth-scheme, but auth-param values must be of the form token "=" ( token | quoted-string ) (see section 1.2), and your example doesn't use "=" that way.

Differences between unique_ptr and shared_ptr

Both of these classes are smart pointers, which means that they automatically (in most cases) will deallocate the object that they point at when that object can no longer be referenced. The difference between the two is how many different pointers of each type can refer to a resource.

When using unique_ptr, there can be at most one unique_ptr pointing at any one resource. When that unique_ptr is destroyed, the resource is automatically reclaimed. Because there can only be one unique_ptr to any resource, any attempt to make a copy of a unique_ptr will cause a compile-time error. For example, this code is illegal:

unique_ptr<T> myPtr(new T);       // Okay
unique_ptr<T> myOtherPtr = myPtr; // Error: Can't copy unique_ptr

However, unique_ptr can be moved using the new move semantics:

unique_ptr<T> myPtr(new T);                  // Okay
unique_ptr<T> myOtherPtr = std::move(myPtr); // Okay, resource now stored in myOtherPtr

Similarly, you can do something like this:

unique_ptr<T> MyFunction() {
    unique_ptr<T> myPtr(/* ... */);

    /* ... */

    return myPtr;
}

This idiom means "I'm returning a managed resource to you. If you don't explicitly capture the return value, then the resource will be cleaned up. If you do, then you now have exclusive ownership of that resource." In this way, you can think of unique_ptr as a safer, better replacement for auto_ptr.

shared_ptr, on the other hand, allows for multiple pointers to point at a given resource. When the very last shared_ptr to a resource is destroyed, the resource will be deallocated. For example, this code is perfectly legal:

shared_ptr<T> myPtr(new T);       // Okay
shared_ptr<T> myOtherPtr = myPtr; // Sure!  Now have two pointers to the resource.

Internally, shared_ptr uses reference counting to track how many pointers refer to a resource, so you need to be careful not to introduce any reference cycles.

In short:

  1. Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed.
  2. Use shared_ptr when you want multiple pointers to the same resource.

Hope this helps!

How to get city name from latitude and longitude coordinates in Google Maps?

You can use this if you have a list:

Address address = list.get(0);
String cityname = address.getLocality();

Remove last character from C++ string

With C++11, you don't even need the length/size. As long as the string is not empty, you can do the following:

if (!st.empty())
  st.erase(std::prev(st.end())); // Erase element referred to by iterator one
                                 // before the end

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

For those using newer versions of java: jhat has been removed since Java 9. Source: https://www.infoq.com/news/2015/12/OpenJDK-9-removal-of-HPROF-jhat/

That same article recommends using Java VisualVM instead.

jquery ajax function not working

Try this

    $("#postcontent").submit(function() {
  return false;
};

$('#postsubmit').click(function(){

// your ajax request here
});

How to store a command in a variable in a shell script?

var=$(echo "asdf")
echo $var
# => asdf

Using this method, the command is immediately evaluated and it's return value is stored.

stored_date=$(date)
echo $stored_date
# => Thu Jan 15 10:57:16 EST 2015
# (wait a few seconds)
echo $stored_date
# => Thu Jan 15 10:57:16 EST 2015

Same with backtick

stored_date=`date`
echo $stored_date
# => Thu Jan 15 11:02:19 EST 2015
# (wait a few seconds)
echo $stored_date
# => Thu Jan 15 11:02:19 EST 2015

Using eval in the $(...) will not make it evaluated later

stored_date=$(eval "date")
echo $stored_date
# => Thu Jan 15 11:05:30 EST 2015
# (wait a few seconds)
echo $stored_date
# => Thu Jan 15 11:05:30 EST 2015

Using eval, it is evaluated when eval is used

stored_date="date" # < storing the command itself
echo $(eval "$stored_date")
# => Thu Jan 15 11:07:05 EST 2015
# (wait a few seconds)
echo $(eval "$stored_date")
# => Thu Jan 15 11:07:16 EST 2015
#                     ^^ Time changed

In the above example, if you need to run a command with arguments, put them in the string you are storing

stored_date="date -u"
# ...

For bash scripts this is rarely relevant, but one last note. Be careful with eval. Eval only strings you control, never strings coming from an untrusted user or built from untrusted user input.

  • Thanks to @CharlesDuffy for reminding me to quote the command!

What is the difference between a hash join and a merge join (Oracle RDBMS )?

I just want to edit this for posterity that the tags for oracle weren't added when I answered this question. My response was more applicable to MS SQL.

Merge join is the best possible as it exploits the ordering, resulting in a single pass down the tables to do the join. IF you have two tables (or covering indexes) that have their ordering the same such as a primary key and an index of a table on that key then a merge join would result if you performed that action.

Hash join is the next best, as it's usually done when one table has a small number (relatively) of items, its effectively creating a temp table with hashes for each row which is then searched continuously to create the join.

Worst case is nested loop which is order (n * m) which means there is no ordering or size to exploit and the join is simply, for each row in table x, search table y for joins to do.

How to represent a DateTime in Excel

Excel expects dates and times to be stored as a floating point number whose value depends on the Date1904 setting of the workbook, plus a number format such as "mm/dd/yyyy" or "hh:mm:ss" or "mm/dd/yyyy hh:mm:ss" so that the number is displayed to the user as a date / time.

Using SpreadsheetGear for .NET you can do this: worksheet.Cells["A1"].Value = DateTime.Now;

This will convert the DateTime to a double which is the underlying type which Excel uses for a Date / Time, and then format the cell with a default date and / or time number format automatically depending on the value.

SpreadsheetGear also has IWorkbook.DateTimeToNumber(DateTime) and NumberToDateTime(double) methods which convert from .NET DateTime objects to a double which Excel can use.

I would expect XlsIO to have something similar.

Disclaimer: I own SpreadsheetGear LLC

Creating object with dynamic keys

You can't define an object literal with a dynamic key. Do this :

var o = {};
o[key] = value;
return o;

There's no shortcut (edit: there's one now, with ES6, see the other answer).

What's the scope of a variable initialized in an if statement?

Unlike languages such as C, a Python variable is in scope for the whole of the function (or class, or module) where it appears, not just in the innermost "block". It is as though you declared int x at the top of the function (or class, or module), except that in Python you don't have to declare variables.

Note that the existence of the variable x is checked only at runtime -- that is, when you get to the print x statement. If __name__ didn't equal "__main__" then you would get an exception: NameError: name 'x' is not defined.

Reading Xml with XmlReader in C#

The following example navigates through the stream to determine the current node type, and then uses XmlWriter to output the XmlReader content.

    StringBuilder output = new StringBuilder();

    String xmlString =
            @"<?xml version='1.0'?>
            <!-- This is a sample XML document -->
            <Items>
              <Item>test with a child element <more/> stuff</Item>
            </Items>";
    // Create an XmlReader
    using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
    {
        XmlWriterSettings ws = new XmlWriterSettings();
        ws.Indent = true;
        using (XmlWriter writer = XmlWriter.Create(output, ws))
        {

            // Parse the file and display each of the nodes.
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        writer.WriteStartElement(reader.Name);
                        break;
                    case XmlNodeType.Text:
                        writer.WriteString(reader.Value);
                        break;
                    case XmlNodeType.XmlDeclaration:
                    case XmlNodeType.ProcessingInstruction:
                        writer.WriteProcessingInstruction(reader.Name, reader.Value);
                        break;
                    case XmlNodeType.Comment:
                        writer.WriteComment(reader.Value);
                        break;
                    case XmlNodeType.EndElement:
                        writer.WriteFullEndElement();
                        break;
                }
            }

        }
    }
    OutputTextBlock.Text = output.ToString();

The following example uses the XmlReader methods to read the content of elements and attributes.

StringBuilder output = new StringBuilder();

String xmlString =
    @"<bookstore>
        <book genre='autobiography' publicationdate='1981-03-22' ISBN='1-861003-11-0'>
            <title>The Autobiography of Benjamin Franklin</title>
            <author>
                <first-name>Benjamin</first-name>
                <last-name>Franklin</last-name>
            </author>
            <price>8.99</price>
        </book>
    </bookstore>";

// Create an XmlReader
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
    reader.ReadToFollowing("book");
    reader.MoveToFirstAttribute();
    string genre = reader.Value;
    output.AppendLine("The genre value: " + genre);

    reader.ReadToFollowing("title");
    output.AppendLine("Content of the title element: " + reader.ReadElementContentAsString());
}

OutputTextBlock.Text = output.ToString();

How to prevent background scrolling when Bootstrap 3 modal open on mobile browsers?

The above answers did not help so what I did was:

.modal {
  -webkit-overflow-scrolling: touch; 
}

My particular problem was when I increased the modal size after loading.

It's a known iOS issue, see here. Since it does not break anything else the above solution was enough for my needs.

How to get the current time in Google spreadsheet using script editor?

use the JavaScript Date() object. There are a number of ways to get the time, date, timestamps, etc from the object. (Reference)

function myFunction() {
  var d = new Date();
  var timeStamp = d.getTime();  // Number of ms since Jan 1, 1970

  // OR:

  var currentTime = d.toLocaleTimeString(); // "12:35 PM", for instance
}

Python append() vs. + operator on lists, why do these give different results?

append is appending an element to a list. if you want to extend the list with the new list you need to use extend.

>>> c = [1, 2, 3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]

Forgot Oracle username and password, how to retrieve?

if you are on Windows

  1. Start the Oracle service if it is not started (most probably it starts automatically when Windows starts)
  2. Start CMD.exe
  3. in the cmd (black window) type: sqlplus / as sysdba

Now you are logged with SYS user and you can do anything you want (query DBA_USERS to find out your username, or change any user password). You can not see the old password, you can only change it.

How can I mock the JavaScript window object using Jest?

There are a couple of ways to mock globals in Jest:

  1. Use the mockImplementation approach (the most Jest-like way), but it will work only for those variables which has some default implementation provided by jsdom. window.open is one of them:

    test('it works', () => {
      // Setup
      const mockedOpen = jest.fn();
      // Without making a copy, you will have a circular dependency problem
      const originalWindow = { ...window };
      const windowSpy = jest.spyOn(global, "window", "get");
      windowSpy.mockImplementation(() => ({
        ...originalWindow, // In case you need other window properties to be in place
        open: mockedOpen
      }));
    
      // Tests
      statementService.openStatementsReport(111)
      expect(mockedOpen).toBeCalled();
    
      // Cleanup
      windowSpy.mockRestore();
    });
    
  2. Assign the value directly to the global property. It is the most straightforward, but it may trigger error messages for some window variables, e.g. window.href.

    test('it works', () => {
      // Setup
      const mockedOpen = jest.fn();
      const originalOpen = window.open;
      window.open = mockedOpen;
    
      // Tests
      statementService.openStatementsReport(111)
      expect(mockedOpen).toBeCalled();
    
      // Cleanup
      window.open = originalOpen;
    });
    
  3. Don't use globals directly (requires a bit of refactoring)

    Instead of using the global value directly, it might be cleaner to import it from another file, so mocking will became trivial with Jest.

File ./test.js

jest.mock('./fileWithGlobalValueExported.js');
import { windowOpen } from './fileWithGlobalValueExported.js';
import { statementService } from './testedFile.js';

// Tests
test('it works', () => {
  statementService.openStatementsReport(111)
  expect(windowOpen).toBeCalled();
});

File ./fileWithGlobalValueExported.js

export const windowOpen = window.open;

File ./testedFile.js

import { windowOpen } from './fileWithGlobalValueExported.js';
export const statementService = {
  openStatementsReport(contactIds) {
    windowOpen(`a_url_${contactIds}`);
  }
}

How to select option in drop down using Capybara

none of the answers worked for me in 2017 with capybara 2.7. I got "ArgumentError: wrong number of arguments (given 2, expected 0)"

But this did:

find('#organizationSelect').all(:css, 'option').find { |o| o.value == 'option_name_here' }.select_option

Print in new line, java

System.out.println("hello"+"\n"+"world");

How can I replace non-printable Unicode characters in Java?

Based on the answers by Op De Cirkel and noackjr, the following is what I do for general string cleaning: 1. trimming leading or trailing whitespaces, 2. dos2unix, 3. mac2unix, 4. removing all "invisible Unicode characters" except whitespaces:

myString.trim.replaceAll("\r\n", "\n").replaceAll("\r", "\n").replaceAll("[\\p{Cc}\\p{Cf}\\p{Co}\\p{Cn}&&[^\\s]]", "")

Tested with Scala REPL.

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..

How do I install Python 3 on an AWS EC2 instance?

Note: This may be obsolete for current versions of Amazon Linux 2 since late 2018 (see comments), you can now directly install it via yum install python3.

In Amazon Linux 2, there isn't a python3[4-6] in the default yum repos, instead there's the Amazon Extras Library.

sudo amazon-linux-extras install python3

If you want to set up isolated virtual environments with it; using yum install'd virtualenv tools don't seem to reliably work.

virtualenv --python=python3 my_venv

Calling the venv module/tool is less finicky, and you could double check it's what you want/expect with python3 --version beforehand.

python3 -m venv my_venv

Other things it can install (versions as of 18 Jan 18):

[ec2-user@x ~]$ amazon-linux-extras list
  0  ansible2   disabled  [ =2.4.2 ]
  1  emacs   disabled  [ =25.3 ]
  2  memcached1.5   disabled  [ =1.5.1 ]
  3  nginx1.12   disabled  [ =1.12.2 ]
  4  postgresql9.6   disabled  [ =9.6.6 ]
  5  python3=latest  enabled  [ =3.6.2 ]
  6  redis4.0   disabled  [ =4.0.5 ]
  7  R3.4   disabled  [ =3.4.3 ]
  8  rust1   disabled  [ =1.22.1 ]
  9  vim   disabled  [ =8.0 ]
 10  golang1.9   disabled  [ =1.9.2 ]
 11  ruby2.4   disabled  [ =2.4.2 ]
 12  nano   disabled  [ =2.9.1 ]
 13  php7.2   disabled  [ =7.2.0 ]
 14  lamp-mariadb10.2-php7.2   disabled  [ =10.2.10_7.2.0 ]

Remove Project from Android Studio

The location of SDK is incorrect, the name of one filer is with place this is creating an issue. By removing that space issue will be resolved. old SDK location:

C:\Users\At Tech\AppData\Local\Android\Sdk

new SDK location:

F:\AndroidSDK\Sdk

Visual Studio 64 bit?

No! There is no 64-bit version of Visual Studio.

How to know it is not 64-bit: Once you download Visual Studio and click the install button, you will see that the initialization folder it selects automatically is C:\Program Files (x86)\Microsoft Visual Studio 14.0

As per my understanding, all 64-bit programs/applications goes to C:\Program Files and all 32-bit applications goes to C:\Program Files (x86) from Windows 7 onwards.

Powershell v3 Invoke-WebRequest HTTPS error

The following worked worked for me (and uses the latest non deprecated means to interact with the SSL Certs/callback functionality), and doesn't attempt to load the same code multiple times within the same powershell session:

if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type)
{
$certCallback=@"
    using System;
    using System.Net;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;
    public class ServerCertificateValidationCallback
    {
        public static void Ignore()
        {
            if(ServicePointManager.ServerCertificateValidationCallback ==null)
            {
                ServicePointManager.ServerCertificateValidationCallback += 
                    delegate
                    (
                        Object obj, 
                        X509Certificate certificate, 
                        X509Chain chain, 
                        SslPolicyErrors errors
                    )
                    {
                        return true;
                    };
            }
        }
    }
"@
    Add-Type $certCallback
 }
[ServerCertificateValidationCallback]::Ignore();

This was adapted from the following article https://d-fens.ch/2013/12/20/nobrainer-ssl-connection-error-when-using-powershell/

Calculate difference between two datetimes in MySQL

my two cents about logic:

syntax is "old date" - :"new date", so:

SELECT TIMESTAMPDIFF(SECOND, '2018-11-15 15:00:00', '2018-11-15 15:00:30')

gives 30,

SELECT TIMESTAMPDIFF(SECOND, '2018-11-15 15:00:55', '2018-11-15 15:00:15')

gives: -40

What is the equivalent of the C# 'var' keyword in Java?

JEP - JDK Enhancement-Proposal

http://openjdk.java.net/jeps/286

JEP 286: Local-Variable Type Inference

Author Brian Goetz

// Goals:
var list = new ArrayList<String>();  // infers ArrayList<String>
var stream = list.stream();          // infers Stream<String>

PostgreSQL visual interface similar to phpMyAdmin?

I would also highly recommend Adminer - http://www.adminer.org/

It is much faster than phpMyAdmin, does less funky iframe stuff, and supports both MySQL and PostgreSQL.

jQuery scroll() detect when user stops scrolling

ES6 style with checking scrolling start also.

function onScrollHandler(params: {
  onStart: () => void,
  onStop: () => void,
  timeout: number
}) {
  const {onStart, onStop, timeout = 200} = params
  let timer = null

  return (event) => {
    if (timer) {
      clearTimeout(timer)
    } else {
      onStart && onStart(event)
    }
    timer = setTimeout(() => {
      timer = null
      onStop && onStop(event)
    }, timeout)
  }
}

Usage:

yourScrollableElement.addEventListener('scroll', onScrollHandler({
  onStart: (event) => {
    console.log('Scrolling has started')
  },
  onStop: (event) => {
    console.log('Scrolling has stopped')
  },
  timeout: 123 // Remove to use default value
}))

Search an array for matching attribute

Must be too late now, but the right version would be:

for(var i = 0; i < restaurants.restaurant.length; i++)
{
  if(restaurants.restaurant[i].food == 'chicken')
  {
    return restaurants.restaurant[i].name;
  }
}

Scrolling to element using webdriver?

This can be done using driver.execute_script():-

driver.execute_script("document.getElementById('myelementid').scrollIntoView();")

Compare two folders which has many files inside contents

I used

diff -rqyl folder1 folder2 --exclude=node_modules

in my nodejs apps.

Python3 project remove __pycache__ folders and .pyc files

I found the answer myself when I mistyped pyclean as pycclean:

    No command 'pycclean' found, did you mean:
     Command 'py3clean' from package 'python3-minimal' (main)
     Command 'pyclean' from package 'python-minimal' (main)
    pycclean: command not found

Running py3clean . cleaned it up very nicely.

PyTorch: How to get the shape of a Tensor as a list of int

If you're a fan of NumPyish syntax, then there's tensor.shape.

In [3]: ar = torch.rand(3, 3)

In [4]: ar.shape
Out[4]: torch.Size([3, 3])

# method-1
In [7]: list(ar.shape)
Out[7]: [3, 3]

# method-2
In [8]: [*ar.shape]
Out[8]: [3, 3]

# method-3
In [9]: [*ar.size()]
Out[9]: [3, 3]

P.S.: Note that tensor.shape is an alias to tensor.size(), though tensor.shape is an attribute of the tensor in question whereas tensor.size() is a function.

Changing the page title with Jquery

Html code:

Change Title:
<input type="text" id="changeTitle" placeholder="Enter title tag">
<button id="changeTitle1">Click!</button>

Jquery code:

$(document).ready(function(){   
    $("#changeTitle1").click(function() {
        $(document).prop('title',$("#changeTitle").val()); 
    });
});

Converting Stream to String and back...what are we missing?

In usecase where you want to serialize/deserialize POCOs, Newtonsoft's JSON library is really good. I use it to persist POCOs within SQL Server as JSON strings in an nvarchar field. Caveat is that since its not true de/serialization, it will not preserve private/protected members and class hierarchy.

Load local javascript file in chrome for testing?

To load local resources in Chrome when just using your local computer and not using a webserver you need to add the --allow-file-access-from-files flag.

You can have a shortcut to Chrome that allows files access and one that does not.

Create a shortcut for Chrome on the desktop, right click on shortcut, select properties. In the dialog box that opens find the target for the short cut and add the parameter after chrome.exe leaving a space

eg C:\PATH TO\chrome.exe --allow-file-access-from-files

This shortcut will allow access to files without affecting any other shortcut to Chrome you have.

When you open Chrome with this shortcut it should allow local resources to be loaded using HTML5 and the filesystem api

Check if a temporary table exists and delete if it exists before creating a temporary table

Yes, "invalid column" this error raised from the line "select company, stepid, fieldid, NewColumn from #Results".

There are two phases of runing t-sql,

first, parsing, in this phase the sql server check the correction of you submited sql string, including column of table, and optimized your query for fastest retreival.

second, running, retreiving the datas.

If table #Results exists then parsing process will check the columns you specified are valid or not, else (table doesn't exist) parsing will be by passsed the checking columns as you specified.

Node.js + Nginx - What now?

answering your question 2:

I would use option b simply because it consumes much less resources. with option 'a', every client will cause the server to consume a lot of memory, loading all the files you need (even though i like php, this is one of the problems with it). With option 'b' you can load your libraries (reusable code) and share them among all client requests.

But be ware that if you have multiple cores you should tweak node.js to use all of them.

Change values on matplotlib imshow() graph axis

I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.

Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.

Here is an attempt at this with your data:

import matplotlib.pyplot as plt

# ... define 2D array hist as you did

plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case

android EditText - finished typing event

I had the same problem when trying to implement 'now typing' on chat app. try to extend EditText as follows:

public class TypingEditText extends EditText implements TextWatcher {

private static final int TypingInterval = 2000;


public interface OnTypingChanged {
    public void onTyping(EditText view, boolean isTyping);
}
private OnTypingChanged t;
private Handler handler;
{
    handler = new Handler();
}
public TypingEditText(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    this.addTextChangedListener(this);
}

public TypingEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.addTextChangedListener(this);
}

public TypingEditText(Context context) {
    super(context);
    this.addTextChangedListener(this);
}

public void setOnTypingChanged(OnTypingChanged t) {
    this.t = t;
}

@Override
public void afterTextChanged(Editable s) {
    if(t != null){
        t.onTyping(this, true);
        handler.removeCallbacks(notifier);
        handler.postDelayed(notifier, TypingInterval);
    }

}

private Runnable notifier = new Runnable() {

    @Override
    public void run() {
        if(t != null)
            t.onTyping(TypingEditText.this, false);
    }
};

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }


@Override
public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { }

}

What is the difference between ( for... in ) and ( for... of ) statements?

When I first started out learning the for in and of loop, I was confused with my output too, but with a couple of research and understanding you can think of the individual loop like the following : The

  1. for...in loop returns the indexes of the individual property and has no effect of impact on the property's value, it loops and returns information on the property and not the value. E.g

let profile = { name : "Naphtali", age : 24, favCar : "Mustang", favDrink : "Baileys" }

The above code is just creating an object called profile, we'll use it for both our examples, so, don't be confused when you see the profile object on an example, just know it was created.

So now let us use the for...in loop below

for(let myIndex in profile){
    console.log(`The index of my object property is ${myIndex}`)
}
 // Outputs : 
        The index of my object property is 0
        The index of my object property is 1
        The index of my object property is 2
        The index of my object property is 3

Now Reason for the output being that we have Four(4) properties in our profile object and indexing as we all know starts from 0...n, so, we get the index of properties 0,1,2,3 since we are working with the for..in loop.

  1. for...of loop* can return either the property, value or both, Let's take a look at how. In javaScript, we can't loop through objects normally as we would on arrays, so, there are a few elements we can use to access either of our choices from an object.

    • Object.keys(object-name-goes-here) >>> Returns the keys or properties of an object.

    • Object.values(object-name-goes-here) >>> Returns the values of an object.

    • Object.entries(object-name-goes-here) >>> Returns both the keys and values of an object.

Below are examples of their usage, pay attention to Object.entries() :

Step One: Convert the object to get either its key, value, or both.
Step Two: loop through.


// Getting the keys/property

   Step One: let myKeys = ***Object.keys(profile)***
   Step Two: for(let keys of myKeys){
             console.log(`The key of my object property is ${keys}`)
           }

// Getting the values of the property

    Step One: let myValues = ***Object.values(profile)***
    Step Two : for(let values of myValues){
                 console.log(`The value of my object property is ${values}`)
               }

When using Object.entries() have it that you are calling two entries on the object, i.e the keys and values. You can call both by either of the entry. Example Below.

Step One: Convert the object to entries, using ***Object.entries(object-name)***
Step Two: **Destructure** the ***entries object which carries the keys and values*** 
like so **[keys, values]**, by so doing, you have access to either or both content.


    // Getting the keys/property

       Step One: let myKeysEntry = ***Object.entries(profile)***
       Step Two: for(let [keys, values] of myKeysEntry){
                 console.log(`The key of my object property is ${keys}`)
               }

    // Getting the values of the property

        Step One: let myValuesEntry = ***Object.entries(profile)***
        Step Two : for(let [keys, values] of myValuesEntry){
                     console.log(`The value of my object property is ${values}`)
                   }

    // Getting both keys and values

        Step One: let myBothEntry = ***Object.entries(profile)***
        Step Two : for(let [keys, values] of myBothEntry){
                     console.log(`The keys of my object is ${keys} and its value 
is ${values}`)
                   }

Make comments on unclear parts section(s).

Mongoose delete array element in document and save

You can also do the update directly in MongoDB without having to load the document and modify it using code. Use the $pull or $pullAll operators to remove the item from the array :

Favorite.updateOne( {cn: req.params.name}, { $pullAll: {uid: [req.params.deleteUid] } } )

(you can also use updateMany for multiple documents)

http://docs.mongodb.org/manual/reference/operator/update/pullAll/

Pythonic way to check if a list is sorted or not

A solution using assignment expressions (added in Python 3.8):

def is_sorted(seq):
    seq_iter = iter(seq)
    cur = next(seq_iter, None)
    return all((prev := cur) <= (cur := nxt) for nxt in seq_iter)

z = list(range(10))
print(z)
print(is_sorted(z))

import random
random.shuffle(z)
print(z)
print(is_sorted(z))

z = []
print(z)
print(is_sorted(z))

Gives:

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

using stored procedure in entity framework

You need to create a model class that contains all stored procedure properties like below. Also because Entity Framework model class needs primary key, you can create a fake key by using Guid.

public class GetFunctionByID
{
    [Key]
    public Guid? GetFunctionByID { get; set; }

    // All the other properties.
}

then register the GetFunctionByID model class in your DbContext.

public class FunctionsContext : BaseContext<FunctionsContext>
{
    public DbSet<App_Functions> Functions { get; set; }
    public DbSet<GetFunctionByID> GetFunctionByIds {get;set;}
}

When you call your stored procedure, just see below:

var functionId = yourIdParameter;
var result =  db.Database.SqlQuery<GetFunctionByID>("GetFunctionByID @FunctionId", new SqlParameter("@FunctionId", functionId)).ToList());

How can I load the contents of a text file into a batch file variable?

Create a file called "SetFile.bat" that contains the following line with no carriage return at the end of it...

set FileContents=

Then in your batch file do something like this...

   @echo off
   copy SetFile.bat + %1 $tmp$.bat > nul
   call $tmp$.bat
   del $tmp$.bat

%1 is the name of your input file and %FileContents% will contain the contents of the input file after the call. This will only work on a one line file though (i.e. a file containing no carriage returns). You could strip out/replace carriage returns from the file before calling the %tmp%.bat if needed.

Replace all whitespace with a line break/paragraph mark to make a word list

  1. option 1

    echo $(cat testfile)
    
  2. Option 2

    tr ' ' '\n' < testfile
    

Twig: in_array or similar possible within if statement?

It should help you.

{% for user in users if user.active and user.id not 1 %}
   {{ user.name }}
{% endfor %}

More info: http://twig.sensiolabs.org/doc/tags/for.html

How to reload current page?

Not really refreshing the page but thought it would help someone else out there looking for something simple

ngOnInit(){
    startUp()
}

startUp(){
    // Codes
}

refresh(){
    // Code to destroy child component
    startUp()
}

Copy entire contents of a directory to another using php

My pruned version of @Kzoty answer. Thank you Kzoty.

Usage

Helper::copy($sourcePath, $targetPath);

class Helper {

    static function copy($source, $target) {
        if (!is_dir($source)) {//it is a file, do a normal copy
            copy($source, $target);
            return;
        }

        //it is a folder, copy its files & sub-folders
        @mkdir($target);
        $d = dir($source);
        $navFolders = array('.', '..');
        while (false !== ($fileEntry=$d->read() )) {//copy one by one
            //skip if it is navigation folder . or ..
            if (in_array($fileEntry, $navFolders) ) {
                continue;
            }

            //do copy
            $s = "$source/$fileEntry";
            $t = "$target/$fileEntry";
            self::copy($s, $t);
        }
        $d->close();
    }

}

Watch multiple $scope attributes

A slightly safer solution to combine values might be to use the following as your $watch function:

function() { return angular.toJson([item1, item2]) }

or

$scope.$watch(
  function() {
    return angular.toJson([item1, item2]);
  },
  function() {
    // Stuff to do after either value changes
  });

Adding a column to a data.frame

If I understand the question correctly, you want to detect when the h_no doesn't increase and then increment the class. (I'm going to walk through how I solved this problem, there is a self-contained function at the end.)

Working

We only care about the h_no column for the moment, so we can extract that from the data frame:

> h_no <- data$h_no

We want to detect when h_no doesn't go up, which we can do by working out when the difference between successive elements is either negative or zero. R provides the diff function which gives us the vector of differences:

> d.h_no <- diff(h_no)
> d.h_no
 [1]  1  1  1 -3  1  1  1  1  1  1 -6  1  1  1

Once we have that, it is a simple matter to find the ones that are non-positive:

> nonpos <- d.h_no <= 0
> nonpos
 [1] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE
[13] FALSE FALSE

In R, TRUE and FALSE are basically the same as 1 and 0, so if we get the cumulative sum of nonpos, it will increase by 1 in (almost) the appropriate spots. The cumsum function (which is basically the opposite of diff) can do this.

> cumsum(nonpos)
 [1] 0 0 0 1 1 1 1 1 1 1 2 2 2 2

But, there are two problems: the numbers are one too small; and, we are missing the first element (there should be four in the first class).

The first problem is simply solved: 1+cumsum(nonpos). And the second just requires adding a 1 to the front of the vector, since the first element is always in class 1:

 > classes <- c(1, 1 + cumsum(nonpos))
 > classes
  [1] 1 1 1 1 2 2 2 2 2 2 2 3 3 3 3

Now, we can attach it back onto our data frame with cbind (by using the class= syntax, we can give the column the class heading):

 > data_w_classes <- cbind(data, class=classes)

And data_w_classes now contains the result.

Final result

We can compress the lines together and wrap it all up into a function to make it easier to use:

classify <- function(data) {
   cbind(data, class=c(1, 1 + cumsum(diff(data$h_no) <= 0)))
}

Or, since it makes sense for the class to be a factor:

classify <- function(data) {
   cbind(data, class=factor(c(1, 1 + cumsum(diff(data$h_no) <= 0))))
}

You use either function like:

> classified <- classify(data) # doesn't overwrite data
> data <- classify(data) # data now has the "class" column

(This method of solving this problem is good because it avoids explicit iteration, which is generally recommend for R, and avoids generating lots of intermediate vectors and list etc. And also it's kinda neat how it can be written on one line :) )

Remove HTML Tags from an NSString on the iPhone

I've extended the answer by m.kocikowski and tried to make it a bit more efficient by using an NSMutableString. I've also structured it for use in a static Utils class (I know a Category is probably the best design though), and removed the autorelease so it compiles in an ARC project.

Included here in case anybody finds it useful.

.h

+ (NSString *)stringByStrippingHTML:(NSString *)inputString;

.m

+ (NSString *)stringByStrippingHTML:(NSString *)inputString 
{
  NSMutableString *outString;

  if (inputString)
  {
    outString = [[NSMutableString alloc] initWithString:inputString];

    if ([inputString length] > 0)
    {
      NSRange r;

      while ((r = [outString rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
      {
        [outString deleteCharactersInRange:r];
      }      
    }
  }

  return outString; 
}

How best to read a File into List<string>

string inLine = reader.ReadToEnd();
myList = inLine.Split(new string[] { "\r\n" }, StringSplitOptions.None).ToList();

This answer misses the original point, which was that they were getting an OutOfMemory error. If you proceed with the above version, you are sure to hit it if your system does not have the appropriate CONTIGUOUS available ram to load the file.

You simply must break it into parts, and either store as List or String[] either way.

How to ping multiple servers and return IP address and Hostnames using batch script?

This works for spanish operation system.

Script accepts two parameters:

  • a file with the list of IP or domains
  • output file

script.bat listofurls.txt output.txt

@echo off
setlocal enabledelayedexpansion
set OUTPUT_FILE=%2
>nul copy nul %OUTPUT_FILE%
for /f %%i in (%1) do (
    set SERVER_ADDRESS=No se pudo resolver el host
    for /f "tokens=1,2,3,4,5" %%v in ('ping -a -n 1 %%i ^&^& echo SERVER_IS_UP') 
    do (
        if %%v==Haciendo set SERVER_ADDRESS=%%z
        if %%v==Respuesta set SERVER_ADDRESS=%%x
        if %%v==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
    )
    echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE! >>%OUTPUT_FILE%
    echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE!
)

How to delete specific columns with VBA?

You say you want to delete any column with the title "Percent Margin of Error" so let's try to make this dynamic instead of naming columns directly.

Sub deleteCol()

On Error Resume Next

Dim wbCurrent As Workbook
Dim wsCurrent As Worksheet
Dim nLastCol, i As Integer

Set wbCurrent = ActiveWorkbook
Set wsCurrent = wbCurrent.ActiveSheet
'This next variable will get the column number of the very last column that has data in it, so we can use it in a loop later
nLastCol = wsCurrent.Cells.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

'This loop will go through each column header and delete the column if the header contains "Percent Margin of Error"
For i = nLastCol To 1 Step -1
    If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) > 0 Then
        wsCurrent.Columns(i).Delete Shift:=xlShiftToLeft
    End If
Next i

End Sub

With this you won't need to worry about where you data is pasted/imported to, as long as the column headers are in the first row.

EDIT: And if your headers aren't in the first row, it would be a really simple change. In this part of the code: If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) change the "1" in Cells(1, i) to whatever row your headers are in.

EDIT 2: Changed the For section of the code to account for completely empty columns.

How to create a MySQL hierarchical recursive query?

From the blog Managing Hierarchical Data in MySQL

Table structure

+-------------+----------------------+--------+
| category_id | name                 | parent |
+-------------+----------------------+--------+
|           1 | ELECTRONICS          |   NULL |
|           2 | TELEVISIONS          |      1 |
|           3 | TUBE                 |      2 |
|           4 | LCD                  |      2 |
|           5 | PLASMA               |      2 |
|           6 | PORTABLE ELECTRONICS |      1 |
|           7 | MP3 PLAYERS          |      6 |
|           8 | FLASH                |      7 |
|           9 | CD PLAYERS           |      6 |
|          10 | 2 WAY RADIOS         |      6 |
+-------------+----------------------+--------+

Query:

SELECT t1.name AS lev1, t2.name as lev2, t3.name as lev3, t4.name as lev4
FROM category AS t1
LEFT JOIN category AS t2 ON t2.parent = t1.category_id
LEFT JOIN category AS t3 ON t3.parent = t2.category_id
LEFT JOIN category AS t4 ON t4.parent = t3.category_id
WHERE t1.name = 'ELECTRONICS';

Output

+-------------+----------------------+--------------+-------+
| lev1        | lev2                 | lev3         | lev4  |
+-------------+----------------------+--------------+-------+
| ELECTRONICS | TELEVISIONS          | TUBE         | NULL  |
| ELECTRONICS | TELEVISIONS          | LCD          | NULL  |
| ELECTRONICS | TELEVISIONS          | PLASMA       | NULL  |
| ELECTRONICS | PORTABLE ELECTRONICS | MP3 PLAYERS  | FLASH |
| ELECTRONICS | PORTABLE ELECTRONICS | CD PLAYERS   | NULL  |
| ELECTRONICS | PORTABLE ELECTRONICS | 2 WAY RADIOS | NULL  |
+-------------+----------------------+--------------+-------+

Most users at one time or another have dealt with hierarchical data in a SQL database and no doubt learned that the management of hierarchical data is not what a relational database is intended for. The tables of a relational database are not hierarchical (like XML), but are simply a flat list. Hierarchical data has a parent-child relationship that is not naturally represented in a relational database table. Read more

Refer the blog for more details.

EDIT:

select @pv:=category_id as category_id, name, parent from category
join
(select @pv:=19)tmp
where parent=@pv

Output:

category_id name    parent
19  category1   0
20  category2   19
21  category3   20
22  category4   21

Reference: How to do the Recursive SELECT query in Mysql?

What is the difference between persist() and merge() in JPA and Hibernate?

The most important difference is this:

  • In case of persist method, if the entity that is to be managed in the persistence context, already exists in persistence context, the new one is ignored. (NOTHING happened)

  • But in case of merge method, the entity that is already managed in persistence context will be replaced by the new entity (updated) and a copy of this updated entity will return back. (from now on any changes should be made on this returned entity if you want to reflect your changes in persistence context)

How to convert an xml string to a dictionary?

I have modified one of the answers to my taste and to work with multiple values with the same tag for example consider the following xml code saved in XML.xml file

     <A>
        <B>
            <BB>inAB</BB>
            <C>
                <D>
                    <E>
                        inABCDE
                    </E>
                    <E>value2</E>
                    <E>value3</E>
                </D>
                <inCout-ofD>123</inCout-ofD>
            </C>
        </B>
        <B>abc</B>
        <F>F</F>
    </A>

and in python

import xml.etree.ElementTree as ET




class XMLToDictionary(dict):
    def __init__(self, parentElement):
        self.parentElement = parentElement
        for child in list(parentElement):
            child.text = child.text if (child.text != None) else  ' '
            if len(child) == 0:
                self.update(self._addToDict(key= child.tag, value = child.text.strip(), dict = self))
            else:
                innerChild = XMLToDictionary(parentElement=child)
                self.update(self._addToDict(key=innerChild.parentElement.tag, value=innerChild, dict=self))

    def getDict(self):
        return {self.parentElement.tag: self}

    class _addToDict(dict):
        def __init__(self, key, value, dict):
            if not key in dict:
                self.update({key: value})
            else:
                identical = dict[key] if type(dict[key]) == list else [dict[key]]
                self.update({key: identical + [value]})


tree = ET.parse('./XML.xml')
root = tree.getroot()
parseredDict = XMLToDictionary(root).getDict()
print(parseredDict)

the output is

{'A': {'B': [{'BB': 'inAB', 'C': {'D': {'E': ['inABCDE', 'value2', 'value3']}, 'inCout-ofD': '123'}}, 'abc'], 'F': 'F'}}

How to programmatically empty browser cache?

You can now use Cache.delete()

Example:

let id = "your-cache-id";
// you can find the id by going to 
// application>storage>cache storage 
// (minus the page url at the end)
// in your chrome developer console 

caches.open(id)
.then(cache => cache.keys()
  .then(keys => {
    for (let key of keys) {
      cache.delete(key)
    }
  }));

Works on Chrome 40+, Firefox 39+, Opera 27+ and Edge.

keytool error bash: keytool: command not found

In Windows 10, you need to add a double slash

./keytool -genkey -v -keystore c:\\Users\\USERNAME\\youralias.jks -storetype JKS -keyalg RSA -keysize 2048 -validity 10000 -alias youralias

Running Python in PowerShell?

Go to Python Website/dowloads/windows. Download Windows x86-64 embeddable zip file. 2. Open Windows Explorer

open zipped folder python-3.7.0 In the windows toolbar with the Red flair saying “Compressed Folder Tool” Press “Extract” button on the tool bar with “File” “Home “Share” “View” Select Extract all Extraction process is not covered yet Once extracted save onto SDD or fastest memory device. Not usb. HDD is fine. SDD Users/butte/ProgramFiles blah blah ooooor D:\Python Or Hook up to your cloud 3. Click your User Icon in the Windows tool bar.

Search environment variable Proceed with progressing with “Environment Variables” button press Under the “user variables” table select “New..” After the Canvas of Information Add Python in Variable Name Select the “D:\Python\python-3.7.0-embed-amd64\python.exe;” click ok Under the “System Variables” label and in the Canvas the first row has a value marked “Path” Select “Edit” when “Path” is highlighted. Select “New” Enter D:\Python\python-3.7.0-embed-amd click ok Ok Save and double check Open Power Shell python --help

python --version

Source to tutorial https://thedishbunnybitch.com/2018/08/11/installing-python-on-windows-10-for-powershell/

Best way to find if an item is in a JavaScript array?

A robust way to check if an object is an array in javascript is detailed here:

Here are two functions from the xa.js framework which I attach to a utils = {} ‘container’. These should help you properly detect arrays.

var utils = {};

/**
 * utils.isArray
 *
 * Best guess if object is an array.
 */
utils.isArray = function(obj) {
     // do an instanceof check first
     if (obj instanceof Array) {
         return true;
     }
     // then check for obvious falses
     if (typeof obj !== 'object') {
         return false;
     }
     if (utils.type(obj) === 'array') {
         return true;
     }
     return false;
 };

/**
 * utils.type
 *
 * Attempt to ascertain actual object type.
 */
utils.type = function(obj) {
    if (obj === null || typeof obj === 'undefined') {
        return String (obj);
    }
    return Object.prototype.toString.call(obj)
        .replace(/\[object ([a-zA-Z]+)\]/, '$1').toLowerCase();
};

If you then want to check if an object is in an array, I would also include this code:

/**
 * Adding hasOwnProperty method if needed.
 */
if (typeof Object.prototype.hasOwnProperty !== 'function') {
    Object.prototype.hasOwnProperty = function (prop) {
        var type = utils.type(this);
        type = type.charAt(0).toUpperCase() + type.substr(1);
        return this[prop] !== undefined
            && this[prop] !== window[type].prototype[prop];
    };
}

And finally this in_array function:

function in_array (needle, haystack, strict) {
    var key;

    if (strict) {
        for (key in haystack) {
            if (!haystack.hasOwnProperty[key]) continue;

            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (!haystack.hasOwnProperty[key]) continue;

            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}

Adobe Reader Command Line Reference

Call this after the print job has returned:

oShell.AppActivate "Adobe Reader"
oShell.SendKeys "%FX"

Convert hex string to int

It's simply too big for an int (which is 4 bytes and signed).

Use

Long.parseLong("AA0F245C", 16);

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.