Programs & Examples On #Composite index

Composite index: An index that contains more than one column.

Check for a substring in a string in Oracle without LIKE

Databases are heavily optimized for common usage scenarios (and LIKE is one of those).

You won't find a faster way of doing your search if you want to stay on the DB-level.

Bootstrap 3: how to make head of dropdown link clickable in navbar

Here is my solution which uses JQuery in your header, and works on Mobile.

On mobile the top links require two taps: one to dropdown the menu and one to go to its link.

_x000D_
_x000D_
$(function(){_x000D_
  $('.dropdown-toggle').click(_x000D_
    function(){_x000D_
      if ($(this).next().is(':visible')) {_x000D_
        location.href = $(this).attr('href');;_x000D_
      }_x000D_
     });_x000D_
  });_x000D_
});
_x000D_
_x000D_
_x000D_

Debug vs Release in CMake

// CMakeLists.txt : release

set(CMAKE_CONFIGURATION_TYPES "Release" CACHE STRING "" FORCE)

// CMakeLists.txt : debug

set(CMAKE_CONFIGURATION_TYPES "Debug" CACHE STRING "" FORCE)

Showing all errors and warnings

PHP errors can be displayed by any of below methods:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

For more details:

Displaying PHP errors

How do I check out a remote Git branch?

git checkout -b "Branch_name" [ B means Create local branch]

git branch --all

git checkout -b "Your Branch name"

git branch

successfully checkout from the master branch to dev branch

enter image description here

Visual Studio Code - Convert spaces to tabs

To change tab settings, click the text area right to the Ln/Col text in the status bar on the bottom right of vscode window.

The name can be Tab Size or Spaces.

A menu will pop up with all available actions and settings.

enter image description here

Update rows in one table with data from another table based on one column in each being equal

update 
  table1 t1
set
  (
    t1.column1, 
    t1.column2
      ) = (
    select
      t2.column1, 
      t2.column2
    from
      table2  t2
    where
      t2.column1 = t1.column1
     )
    where exists (
      select 
        null
      from 
        table2 t2
      where 
        t2.column1 = t1.column1
      );

Or this (if t2.column1 <=> t1.column1 are many to one and anyone of them is good):

update 
  table1 t1
set
  (
    t1.column1, 
    t1.column2
      ) = (
    select
      t2.column1, 
      t2.column2
    from
      table2  t2
    where
      t2.column1 = t1.column1
    and
      rownum = 1    
     )
    where exists (
      select 
        null
      from 
        table2 t2
      where 
        t2.column1 = t1.column1
      ); 

How to have a drop down <select> field in a rails form?

In your model,

class Contact
  self.email_providers = %w[Gmail Yahoo MSN]
  validates :email_provider, :inclusion => email_providers
end

In your form,

<%= f.select :email_provider, 
    options_for_select(Contact.email_providers, @contact.email_provider) %>

the second arg of the options_for_select will have any current email_provider selected.

Serializing/deserializing with memory stream

This code works for me:

public void Run()
{
    Dog myDog = new Dog();
    myDog.Name= "Foo";
    myDog.Color = DogColor.Brown;

    System.Console.WriteLine("{0}", myDog.ToString());

    MemoryStream stream = SerializeToStream(myDog);

    Dog newDog = (Dog)DeserializeFromStream(stream);

    System.Console.WriteLine("{0}", newDog.ToString());
}

Where the types are like this:

[Serializable]
public enum DogColor
{
    Brown,
    Black,
    Mottled
}

[Serializable]
public class Dog
{
    public String Name
    {
        get; set;
    }

    public DogColor Color
    {
        get;set;
    }

    public override String ToString()
    {
        return String.Format("Dog: {0}/{1}", Name, Color);
    }
}

and the utility methods are:

public static MemoryStream SerializeToStream(object o)
{
    MemoryStream stream = new MemoryStream();
    IFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, o);
    return stream;
}

public static object DeserializeFromStream(MemoryStream stream)
{
    IFormatter formatter = new BinaryFormatter();
    stream.Seek(0, SeekOrigin.Begin);
    object o = formatter.Deserialize(stream);
    return o;
}

System.BadImageFormatException: Could not load file or assembly

Try to configure the setting of your projects, it is usually due to x86/x64 architecture problems:

Go and set your choice as shown:

Make WPF Application Fullscreen (Cover startmenu)

<Window x:Class="HTA.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    mc:Ignorable="d" 
    ResizeMode="NoResize"
    WindowStartupLocation="CenterScreen" 
    Width="1024" Height="768"
    WindowState="Maximized" WindowStyle="None">

Window state to Maximized and window style to None

adb remount permission denied, but able to access super user in shell -- android

In case anyone has the same problem in the future:

$ adb shell
$ su
# mount -o rw,remount /system

Both adb remount and adb root don't work on a production build without altering ro.secure, but you can still remount /system by opening a shell, asking for root permissions and typing the mount command.

java.sql.SQLException: Fail to convert to internal representation

Your data types are mismatched when you are retrieving the field values. Check your code and ensure that for each field that you are retrieving that the java object matches that type. For example, retrieving a date into and int. If you are doing a select * then it is possible a change in the fields of the table has happened causing this error to occur. Your SQL should only select the fields you specifically want in order to avoid this error.

Hope this helps.

disable a hyperlink using jQuery

Try:

$(this).prop( "disabled", true );

How do I get the list of keys in a Dictionary?

To get list of all keys

using System.Linq;
List<String> myKeys = myDict.Keys.ToList();

System.Linq is supported in .Net framework 3.5 or above. See the below links if you face any issue in using System.Linq

Visual Studio Does not recognize System.Linq

System.Linq Namespace

Stored procedure with default parameters

I'd do this one of two ways. Since you're setting your start and end dates in your t-sql code, i wouldn't ask for parameters in the stored proc

Option 1

Create Procedure [Test] AS
    DECLARE @StartDate varchar(10)
    DECLARE @EndDate varchar(10)
    Set @StartDate = '201620' --Define start YearWeek
    Set @EndDate  = (SELECT CAST(DATEPART(YEAR,getdate()) AS varchar(4)) + CAST(DATEPART(WEEK,getdate())-1 AS varchar(2)))

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Option 2

Create Procedure [Test] @StartDate varchar(10),@EndDate varchar(10) AS

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Then run exec test '2016-01-01','2016-01-25'

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

I've found a solution for me with Spring and jackson

First specify the filter name in the entity

@Entity
@Table(name = "SECTEUR")
@JsonFilter(ModelJsonFilters.SECTEUR_FILTER)
public class Secteur implements Serializable {

/** Serial UID */
private static final long serialVersionUID = 5697181222899184767L;

/**
 * Unique ID
 */
@Id
@JsonView(View.SecteurWithoutChildrens.class)
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

@JsonView(View.SecteurWithoutChildrens.class)
@Column(name = "code", nullable = false, length = 35)
private String code;

/**
 * Identifiant du secteur parent
 */
@JsonView(View.SecteurWithoutChildrens.class)
@Column(name = "id_parent")
private Long idParent;

@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "id_parent")
private List<Secteur> secteursEnfants = new ArrayList<>(0);

}

Then you can see the constants filters names class with the default FilterProvider used in spring configuration

public class ModelJsonFilters {

public final static String SECTEUR_FILTER = "SecteurFilter";
public final static String APPLICATION_FILTER = "ApplicationFilter";
public final static String SERVICE_FILTER = "ServiceFilter";
public final static String UTILISATEUR_FILTER = "UtilisateurFilter";

public static SimpleFilterProvider getDefaultFilters() {
    SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAll();
    return new SimpleFilterProvider().setDefaultFilter(theFilter);
}

}

Spring configuration :

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "fr.sodebo")

public class ApiRootConfiguration extends WebMvcConfigurerAdapter {

@Autowired
private EntityManagerFactory entityManagerFactory;


/**
 * config qui permet d'éviter les "Lazy loading Error" au moment de la
 * conversion json par jackson pour les retours des services REST<br>
 * on permet à jackson d'acceder à sessionFactory pour charger ce dont il a
 * besoin
 */
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

    super.configureMessageConverters(converters);
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    ObjectMapper mapper = new ObjectMapper();

    // config d'hibernate pour la conversion json
    mapper.registerModule(getConfiguredHibernateModule());//

    // inscrit les filtres json
    subscribeFiltersInMapper(mapper);

    // config du comportement de json views
    mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);

    converter.setObjectMapper(mapper);
    converters.add(converter);
}

/**
 * config d'hibernate pour la conversion json
 * 
 * @return Hibernate5Module
 */
private Hibernate5Module getConfiguredHibernateModule() {
    SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
    Hibernate5Module module = new Hibernate5Module(sessionFactory);
    module.configure(Hibernate5Module.Feature.FORCE_LAZY_LOADING, true);

    return module;

}

/**
 * inscrit les filtres json
 * 
 * @param mapper
 */
private void subscribeFiltersInMapper(ObjectMapper mapper) {

    mapper.setFilterProvider(ModelJsonFilters.getDefaultFilters());

}

}

Endly I can specify a specific filter in restConstoller when i need....

@RequestMapping(value = "/{id}/droits/", method = RequestMethod.GET)
public MappingJacksonValue getListDroits(@PathVariable long id) {

    LOGGER.debug("Get all droits of user with id {}", id);

    List<Droit> droits = utilisateurService.findDroitsDeUtilisateur(id);

    MappingJacksonValue value;

    UtilisateurWithSecteurs utilisateurWithSecteurs = droitsUtilisateur.fillLists(droits).get(id);

    value = new MappingJacksonValue(utilisateurWithSecteurs);

    FilterProvider filters = ModelJsonFilters.getDefaultFilters().addFilter(ModelJsonFilters.SECTEUR_FILTER, SimpleBeanPropertyFilter.serializeAllExcept("secteursEnfants")).addFilter(ModelJsonFilters.APPLICATION_FILTER,
            SimpleBeanPropertyFilter.serializeAllExcept("services"));

    value.setFilters(filters);
    return value;

}

How can I use JQuery to post JSON data?

You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param to serialize the object into name-value pairs.

If you pass the data as a string, it won't be serialized:

$.ajax({
    type: 'POST',
    url: '/form/',
    data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
    success: function(data) { alert('data: ' + data); },
    contentType: "application/json",
    dataType: 'json'
});

.htaccess redirect http to https

This makes sure that redirects work for all combinations of intransparent proxies.

This includes the case client <http> proxy <https> webserver.

# behind proxy
RewriteCond %{HTTP:X-FORWARDED-PROTO} ^http$
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]

# plain
RewriteCond %{HTTP:X-FORWARDED-PROTO} ^$
RewriteCond %{REQUEST_SCHEME} ^http$ [NC,OR]
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]

Find p-value (significance) in scikit-learn LinearRegression

For a one-liner you can use the pingouin.linear_regression function (disclaimer: I am the creator of Pingouin), which works with uni/multi-variate regression using NumPy arrays or Pandas DataFrame, e.g:

import pingouin as pg
# Using a Pandas DataFrame `df`:
lm = pg.linear_regression(df[['x', 'z']], df['y'])
# Using a NumPy array:
lm = pg.linear_regression(X, y)

The output is a dataframe with the beta coefficients, standard errors, T-values, p-values and confidence intervals for each predictor, as well as the R^2 and adjusted R^2 of the fit.

How can I obfuscate (protect) JavaScript?

As a JavaScript/HTML/CSS obfuscator/compressor you can also try Patu Digua.

How to get cell value from DataGridView in VB.Net?

This helped me get close to what I needed and I will throw this out there for anyone else who needs it.

If you are looking for the value in the first cell in the selected column, you can try this. (I chose the first column, since you are asking for it to return "3", but you can change the number after Cells to get whichever column you need. Remember it is zero-based.)

This will copy the result to the clipboard: Clipboard.SetDataObject(Me.DataGridView1.CurrentRow.Cells(0).Value)

Fastest way to find second (third...) highest/lowest value in vector or column

This will find the index of the N'th smallest or largest value in the input numeric vector x. Set bottom=TRUE in the arguments if you want the N'th from the bottom, or bottom=FALSE if you want the N'th from the top. N=1 and bottom=TRUE is equivalent to which.min, N=1 and bottom=FALSE is equivalent to which.max.

FindIndicesBottomTopN <- function(x=c(4,-2,5,-77,99),N=1,bottom=FALSE)
{

  k1 <- rank(x)
  if(bottom==TRUE){
    Nindex <- which(k1==N)
    Nindex <- Nindex[1]
  }

  if(bottom==FALSE){
    Nindex <- which(k1==(length(x)+1-N))
    Nindex <- Nindex[1]
  }

  return(Nindex)
}

How to set textColor of UILabel in Swift

I think most people want their placeholder text to be in grey and appear only once, so this is what I did:

  1. Set your color in viewDidLoad() (not in IB)

    commentsTextView.textColor = UIColor.darkGray
    
  2. Implement UITextViewDelegate to your controller

  3. add function to your controller

    func textViewDidBeginEditing(_ textView: UITextView) {
        if (commentsTextView.textColor == UIColor.darkGray) {
           commentsTextView.text = ""
           commentsTextView.textColor = UIColor.black
        }
    }
    

This solution is simple.

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

"401 Unauthorized" on a directory

In our case it was Windows-integrated authentication specified in the app's web.config

BUT the windows-auth module was not installed on the IIS machine at all.

Just adding another possible reason.

Hide div if screen is smaller than a certain width

The problem I was having is my css media queries and my IF statement in Jquery clashing. They were both set to 700px but one would think it's hit 700px before the other.

To get around this I created a empty Div right at the top of my HTML(outside my main container)

<div id="max-width"></div>

In css I set this div to display none

 #max-width {
        display: none;
    }

In my JS created a function

var hasSwitched = function () {
    var maxWidth = parseInt($('#max-width').css('max-width'), 10);
    return !isNaN(maxWidth);
};

So in my IF statement instead of saying if (hasSwitched<700) perform the following code, I did the following

if (!hasSwitched()) { Your code

}

else{ your code

}

By doing this CSS tells Jquery when it's hit 700px. So css and jquery are both synchronized... rather than having a couple of pixels difference. Do give this a try peeps it shall definitely not disappoint.

To get this same logic working for IE8 I used the Respond.js plugin(which also definitely works) It lets you use media queries for IE8. Only thing that wasn't supported was the viewport width and viewport height... hence my reason to try get my css and JS working together. Hope this helps you guys

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

You can use geom_col() directly. See the differences between geom_bar() and geom_col() in this link https://ggplot2.tidyverse.org/reference/geom_bar.html

geom_bar() makes the height of the bar proportional to the number of cases in each group If you want the heights of the bars to represent values in the data, use geom_col() instead.

ggplot(data_country)+aes(x=country,y = conversion_rate)+geom_col()

jQuery or Javascript - how to disable window scroll without overflow:hidden;

Try to handler 'mousewheel' event on all nodes except one

$('body').on({
    'mousewheel': function(e) {
        if (e.target.id == 'el') return;
        e.preventDefault();
        e.stopPropagation();
    }
})

Demo: http://jsfiddle.net/DHz77/1/

jQuery set radio button

Try this:

$("#" + newcol).attr("checked", "checked");

I've had issues with attr("checked", true), so I tend to use the above instead.

Also, if you have the ID then you don't need that other stuff for selection. An ID is unique.

How to add footnotes to GitHub-flavoured Markdown?

I used a variant of Mateo's solution. I'm using this in Rmd files written in github flavored markdown (gfm) for a Jekyll powered website but the same Rmd files are being used to produce pdfs in various contexts. The Rmd files are math heavy and the math is displayed with MathJax on the website. So I needed a solution that works with gfm that is processed via Jekyll, works with pandoc->pdflatex, and is compatible with MathJax.

snippet from Rmd file (which is gfm)

Here is a paragraph with an footnote <span id="a1">[[1]](#f1)</span>.

Footnotes
=========

1. <span id="f1"></span> This is a footnote. [$\hookleftarrow$](#a1)

$\hookleftarrow$ is latex, which works for me since I always have MathJax enabled. I use that to make sure it shows up correctly in my pdfs. I put my footnotes in square brackets because superscript is confusing if I am putting a footnote on some inline math.

Here it is in action: https://eeholmes.github.io/posts/2016-5-18-FI-recursion-1/

These notes can be put anywhere in the Rmd. I am putting in a list at the end so they are technically endnotes.

Google Maps: Auto close open InfoWindows?

There is a close() function for InfoWindows. Just keep track of the last opened window, and call the close function on it when a new window is created.

How can I get the named parameters from a URL using Flask?

You can also use brackets <> on the URL of the view definition and this input will go into your view function arguments

@app.route('/<name>')
def my_view_func(name):
    return name

Is there a way to delete all the data from a topic or delete the topic before every run?

Don't think it is supported yet. Take a look at this JIRA issue "Add delete topic support".

To delete manually:

  1. Shutdown the cluster
  2. Clean kafka log dir (specified by the log.dir attribute in kafka config file ) as well the zookeeper data
  3. Restart the cluster

For any given topic what you can do is

  1. Stop kafka
  2. Clean kafka log specific to partition, kafka stores its log file in a format of "logDir/topic-partition" so for a topic named "MyTopic" the log for partition id 0 will be stored in /tmp/kafka-logs/MyTopic-0 where /tmp/kafka-logs is specified by the log.dir attribute
  3. Restart kafka

This is NOT a good and recommended approach but it should work. In the Kafka broker config file the log.retention.hours.per.topic attribute is used to define The number of hours to keep a log file before deleting it for some specific topic

Also, is there a way the messages gets deleted as soon as the consumer reads it?

From the Kafka Documentation :

The Kafka cluster retains all published messages—whether or not they have been consumed—for a configurable period of time. For example if the log retention is set to two days, then for the two days after a message is published it is available for consumption, after which it will be discarded to free up space. Kafka's performance is effectively constant with respect to data size so retaining lots of data is not a problem.

In fact the only metadata retained on a per-consumer basis is the position of the consumer in in the log, called the "offset". This offset is controlled by the consumer: normally a consumer will advance its offset linearly as it reads messages, but in fact the position is controlled by the consumer and it can consume messages in any order it likes. For example a consumer can reset to an older offset to reprocess.

For finding the start offset to read in Kafka 0.8 Simple Consumer example they say

Kafka includes two constants to help, kafka.api.OffsetRequest.EarliestTime() finds the beginning of the data in the logs and starts streaming from there, kafka.api.OffsetRequest.LatestTime() will only stream new messages.

You can also find the example code there for managing the offset at your consumer end.

    public static long getLastOffset(SimpleConsumer consumer, String topic, int partition,
                                 long whichTime, String clientName) {
    TopicAndPartition topicAndPartition = new TopicAndPartition(topic, partition);
    Map<TopicAndPartition, PartitionOffsetRequestInfo> requestInfo = new HashMap<TopicAndPartition, PartitionOffsetRequestInfo>();
    requestInfo.put(topicAndPartition, new PartitionOffsetRequestInfo(whichTime, 1));
    kafka.javaapi.OffsetRequest request = new kafka.javaapi.OffsetRequest(requestInfo, kafka.api.OffsetRequest.CurrentVersion(),clientName);
    OffsetResponse response = consumer.getOffsetsBefore(request);

    if (response.hasError()) {
        System.out.println("Error fetching data Offset Data the Broker. Reason: " + response.errorCode(topic, partition) );
        return 0;
    }
    long[] offsets = response.offsets(topic, partition);
    return offsets[0];
}

Convert character to Date in R

library(lubridate) if your date format is like this '04/24/2017 05:35:00'then change it like below prods.all$Date2<-gsub("/","-",prods.all$Date2) then change the date format parse_date_time(prods.all$Date2, orders="mdy hms")

Twitter Bootstrap 3.0 how do I "badge badge-important" now

Well, this is a terribly late answer but I think I'll still put my two cents in... I could have posted this as a comment because this answer doesn't essentially add any new solution but it does add value to the post as yet another alternative. But in a comment I wouldn't be able to give all the details because of character limit.

NOTE: This needs an edit to bootstrap CSS file - move style definitions for .badge above .label-default. Couldn't find any practical side effects due to the change in my limited testing.

While broc.seib's solution is probably the best way to achieve the requirement of OP with minimal addition to CSS, it is possible to achieve the same effect without any extra CSS at all just like Jens A. Koch's solution or by using .label-xxx contextual classes because they are easy to remember compared to progress-bar-xxx classes. I don't think that .alert-xxx classes give the same effect.

All you have to do is just use .badge and .label-xxx classes together (but in this order). Don't forget to make the changes mentioned in NOTE above.

<a href="#">Inbox <span class="badge label-warning">42</span></a> looks like this:

Badge with warning bg

IMPORTANT: This solution may break your styles if you decide to upgrade and forget to make the changes in your new local CSS file. My solution for this challenge was to copy all .label-xxx styles in my custom CSS file and load it after all other CSS files. This approach also helps when I use a CDN for loading BS3.

**P.S: ** Both the top rated answers have their pros and cons. It's just the way you prefer to do your CSS because there is no "only correct way" to do it.

How to set IntelliJ IDEA Project SDK

For IntelliJ IDEA 2017.2 I did the following to fix this issue: Go to your project structure enter image description here Now go to SDKs under platform settings and click the green add button. Add your JDK path. In my case it was this path C:\Program Files\Java\jdk1.8.0_144 enter image description here Now Just go Project under Project settings and select the project SDK. enter image description here

What is HEAD in Git?

HEAD is just a special pointer that points to the local branch you’re currently on.

From the Pro Git book, chapter 3.1 Git Branching - Branches in a Nutshell, in the section Creating a New Branch:

What happens if you create a new branch? Well, doing so creates a new pointer for you to move around. Let’s say you create a new branch called testing. You do this with the git branch command:

$ git branch testing 

This creates a new pointer at the same commit you’re currently on

enter image description here

How does Git know what branch you’re currently on? It keeps a special pointer called HEAD. Note that this is a lot different than the concept of HEAD in other VCSs you may be used to, such as Subversion or CVS. In Git, this is a pointer to the local branch you’re currently on. In this case, you’re still on master. The git branch command only created a new branch — it didn’t switch to that branch.

enter image description here

Finding rows containing a value (or values) in any column

Here's a dplyr option:

library(dplyr)

# across all columns:
df %>% filter_all(any_vars(. %in% c('M017', 'M018')))

# or in only select columns:
df %>% filter_at(vars(col1, col2), any_vars(. %in% c('M017', 'M018')))                                                                                                     

Using the GET parameter of a URL in JavaScript

You can get the "search" part of the location object - and then parse it out.

var matches = /param1=([^&#=]*)/.exec(window.location.search);
var param1 = matches[1];

How to align center the text in html table row?

<td align="center" valign="center">textgoeshere</td>

Is the only correct answer imho, since your working with tables which is old functionality most common used for e-mail formatting. So your best bet is to not use just style but inline style and known table tags.

What is the difference between 'protected' and 'protected internal'?

In practice, about methods:

protected - accessible for inherited classes, otherwise private.

internal - public only for classes inside the assembly, otherwise private.

protected internal - means protected or internal - methods become accessible for inherited classes and for any classes inside the assembly.

In Oracle SQL: How do you insert the current date + time into a table?

It only seems to because that is what it is printing out. But actually, you shouldn't write the logic this way. This is equivalent:

insert into errortable (dateupdated, table1id)
    values (sysdate, 1083);

It seems silly to convert the system date to a string just to convert it back to a date.

If you want to see the full date, then you can do:

select TO_CHAR(dateupdated, 'YYYY-MM-DD HH24:MI:SS'), table1id
from errortable;

What is offsetHeight, clientHeight, scrollHeight?

My descriptions for the three:

  • offsetHeight: How much of the parent's "relative positioning" space is taken up by the element. (ie. it ignores the element's position: absolute descendents)
  • clientHeight: Same as offset-height, except it excludes the element's own border, margin, and the height of its horizontal scroll-bar (if it has one).
  • scrollHeight: How much space is needed to see all of the element's content/descendents (including position: absolute ones) without scrolling.

Then there is also:

How to save username and password in Git?

Check official git documentation:

If you use the SSH transport for connecting to remotes, it’s possible for you to have a key without a passphrase, which allows you to securely transfer data without typing in your username and password. However, this isn’t possible with the HTTP protocols – every connection needs a username and password. This gets even harder for systems with two-factor authentication, where the token you use for a password is randomly generated and unpronounceable.

Fortunately, Git has a credentials system that can help with this. Git has a few options provided in the box:

  • The default is not to cache at all. Every connection will prompt you for your username and password.

  • The “cache” mode keeps credentials in memory for a certain period of time. None of the passwords are ever stored on disk, and they are purged from the cache after 15 minutes.

  • The “store” mode saves the credentials to a plain-text file on disk, and they never expire. This means that until you change your password for the Git host, you won’t ever have to type in your credentials again. The downside of this approach is that your passwords are stored in cleartext in a plain file in your home directory.

  • If you’re using a Mac, Git comes with an “osxkeychain” mode, which caches credentials in the secure keychain that’s attached to your system account. This method stores the credentials on disk, and they never expire, but they’re encrypted with the same system that stores HTTPS certificates and Safari auto-fills.

  • If you’re using Windows, you can install a helper called “Git Credential Manager for Windows.” This is similar to the “osxkeychain” helper described above, but uses the Windows Credential Store to control sensitive information. It can be found at https://github.com/Microsoft/Git-Credential-Manager-for-Windows.

You can choose one of these methods by setting a Git configuration value:

$ git config --global credential.helper cache

$ git config --global credential.helper store

https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage

How to remove symbols from a string with Python?

Sometimes it takes longer to figure out the regex than to just write it out in python:

import string
s = "how much for the maple syrup? $20.99? That's ricidulous!!!"
for char in string.punctuation:
    s = s.replace(char, ' ')

If you need other characters you can change it to use a white-list or extend your black-list.

Sample white-list:

whitelist = string.letters + string.digits + ' '
new_s = ''
for char in s:
    if char in whitelist:
        new_s += char
    else:
        new_s += ' '

Sample white-list using a generator-expression:

whitelist = string.letters + string.digits + ' '
new_s = ''.join(c for c in s if c in whitelist)

How can I apply a function to every row/column of a matrix in MATLAB?

Building on Alex's answer, here is a more generic function:

applyToGivenRow = @(func, matrix) @(row) func(matrix(row, :));
newApplyToRows = @(func, matrix) arrayfun(applyToGivenRow(func, matrix), 1:size(matrix,1), 'UniformOutput', false)';
takeAll = @(x) reshape([x{:}], size(x{1},2), size(x,1))';
genericApplyToRows = @(func, matrix) takeAll(newApplyToRows(func, matrix));

Here is a comparison between the two functions:

>> % Example
myMx = [1 2 3; 4 5 6; 7 8 9];
myFunc = @(x) [mean(x), std(x), sum(x), length(x)];
>> genericApplyToRows(myFunc, myMx)

ans =

     2     1     6     3
     5     1    15     3
     8     1    24     3

>> applyToRows(myFunc, myMx)
??? Error using ==> arrayfun
Non-scalar in Uniform output, at index 1, output 1.
Set 'UniformOutput' to false.

Error in ==> @(func,matrix)arrayfun(applyToGivenRow(func,matrix),1:size(matrix,1))'

How can I add raw data body to an axios request?

Here is my solution:

axios({
  method: "POST",
  url: "https://URL.com/api/services/fetchQuizList",
  headers: {
    "x-access-key": data,
    "x-access-token": token,
  },
  data: {
    quiz_name: quizname,
  },
})
.then(res => {
  console.log("res", res.data.message);
})
.catch(err => {
  console.log("error in request", err);
});

This should help

Get first and last day of month using threeten, LocalDate

Jon Skeets answer is right and has deserved my upvote, just adding this slightly different solution for completeness:

import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;

LocalDate initial = LocalDate.of(2014, 2, 13);
LocalDate start = initial.withDayOfMonth(1);
LocalDate end = initial.with(lastDayOfMonth());

Recommendations of Python REST (web services) framework?

Something to be careful about when designing a RESTful API is the conflation of GET and POST, as if they were the same thing. It's easy to make this mistake with Django's function-based views and CherryPy's default dispatcher, although both frameworks now provide a way around this problem (class-based views and MethodDispatcher, respectively).

HTTP-verbs are very important in REST, and unless you're very careful about this, you'll end up falling into a REST anti-pattern.

Some frameworks that get it right are web.py, Flask and Bottle. When combined with the mimerender library (full disclosure: I wrote it), they allow you to write nice RESTful webservices:

import web
import json
from mimerender import mimerender

render_xml = lambda message: '<message>%s</message>'%message
render_json = lambda **args: json.dumps(args)
render_html = lambda message: '<html><body>%s</body></html>'%message
render_txt = lambda message: message

urls = (
    '/(.*)', 'greet'
)
app = web.application(urls, globals())

class greet:
    @mimerender(
        default = 'html',
        html = render_html,
        xml  = render_xml,
        json = render_json,
        txt  = render_txt
    )
    def GET(self, name):
        if not name: 
            name = 'world'
        return {'message': 'Hello, ' + name + '!'}

if __name__ == "__main__":
    app.run()

The service's logic is implemented only once, and the correct representation selection (Accept header) + dispatch to the proper render function (or template) is done in a tidy, transparent way.

$ curl localhost:8080/x
<html><body>Hello, x!</body></html>

$ curl -H "Accept: application/html" localhost:8080/x
<html><body>Hello, x!</body></html>

$ curl -H "Accept: application/xml" localhost:8080/x
<message>Hello, x!</message>

$ curl -H "Accept: application/json" localhost:8080/x
{'message':'Hello, x!'}

$ curl -H "Accept: text/plain" localhost:8080/x
Hello, x!

Update (April 2012): added information about Django's class-based views, CherryPy's MethodDispatcher and Flask and Bottle frameworks. Neither existed back when the question was asked.

Regex for Mobile Number Validation

Try this regex:

^(\+?\d{1,4}[\s-])?(?!0+\s+,?$)\d{10}\s*,?$

Explanation of the regex using Perl's YAPE is as below:

NODE                     EXPLANATION
----------------------------------------------------------------------
(?-imsx:                 group, but do not capture (case-sensitive)
                         (with ^ and $ matching normally) (with . not
                         matching \n) (matching whitespace and #
                         normally):
----------------------------------------------------------------------
  ^                        the beginning of the string
----------------------------------------------------------------------
  (                        group and capture to \1 (optional
                           (matching the most amount possible)):
----------------------------------------------------------------------
    \+?                      '+' (optional (matching the most amount
                             possible))
----------------------------------------------------------------------
    \d{1,4}                  digits (0-9) (between 1 and 4 times
                             (matching the most amount possible))
----------------------------------------------------------------------
    [\s-]                    any character of: whitespace (\n, \r,
                             \t, \f, and " "), '-'
----------------------------------------------------------------------
  )?                       end of \1 (NOTE: because you are using a
                           quantifier on this capture, only the LAST
                           repetition of the captured pattern will be
                           stored in \1)
----------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
----------------------------------------------------------------------
    0+                       '0' (1 or more times (matching the most
                             amount possible))
----------------------------------------------------------------------
    \s+                      whitespace (\n, \r, \t, \f, and " ") (1
                             or more times (matching the most amount
                             possible))
----------------------------------------------------------------------
    ,?                       ',' (optional (matching the most amount
                             possible))
----------------------------------------------------------------------
    $                        before an optional \n, and the end of
                             the string
----------------------------------------------------------------------
  )                        end of look-ahead
----------------------------------------------------------------------
  \d{10}                   digits (0-9) (10 times)
----------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
----------------------------------------------------------------------
  ,?                       ',' (optional (matching the most amount
                           possible))
----------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

To remove spaces from left/right, use LTRIM/RTRIM. What you had

UPDATE *tablename*
   SET *columnname* = LTRIM(RTRIM(*columnname*));

would have worked on ALL the rows. To minimize updates if you don't need to update, the update code is unchanged, but the LIKE expression in the WHERE clause would have been

UPDATE [tablename]
   SET [columnname] = LTRIM(RTRIM([columnname]))
 WHERE 32 in (ASCII([columname]), ASCII(REVERSE([columname])));

Note: 32 is the ascii code for the space character.

The program can't start because cygwin1.dll is missing... in Eclipse CDT

You can compile with either Cygwin's g++ or MinGW (via stand-alone or using Cygwin package). However, in order to run it, you need to add the Cygwin1.dll (and others) PATH to the system Windows PATH, before any cygwin style paths.

Thus add: ;C:\cygwin64\bin to the end of your Windows system PATH variable.

Also, to compile for use in CMD or PowerShell, you may need to use:

x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe

(This invokes the cross-compiler, if installed.)

How do I cancel a build that is in progress in Visual Studio?

The "pause" command was a function button underneath my right shift key, so the below combination of keys did the trick for me.

Ctrl + Fn + Shift

GROUP BY with MAX(DATE)

I know I'm late to the party, but try this...

SELECT 
    `Train`, 
    `Dest`,
    SUBSTRING_INDEX(GROUP_CONCAT(`Time` ORDER BY `Time` DESC), ",", 1) AS `Time`
FROM TrainTable
GROUP BY Train;

Src: Group Concat Documentation

Edit: fixed sql syntax

Excel VBA - Delete empty rows

How about

sub foo()
  dim r As Range, rows As Long, i As Long
  Set r = ActiveSheet.Range("A1:Z50")
  rows = r.rows.Count
  For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
  Next
End Sub

Try this

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Range("A" & i & ":" & "Z" & i)
            Else
                Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

IF you want to delete the entire row then use this code

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Rows(i)
            Else
                Set DelRange = Union(DelRange, Rows(i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

How to permanently remove few commits from remote branch

 git reset --soft commit_id
 git stash save "message"
 git reset --hard commit_id
 git stash apply stash stash@{0}
 git push --force

How to make a drop down list in yii2?

In ActiveForm just use:

<?=
    $form->field($model, 'state_id')
         ->dropDownList(['prompt' => '---- Select State ----'])
         ->label('State')
?>

How to Find App Pool Recycles in Event Log

It seemed quite hard to find this information, but eventually, I came across this question
You have to look at the 'System' event log, and filter by the WAS source.
Here is more info about the WAS (Windows Process Activation Service)

Each GROUP BY expression must contain at least one column that is not an outer reference

I just found this error., while using GETDATE() [i.e outer reference] in the group by clause in a select query.

When replaced it with date column from the respective table it cleared.

Thought to share as a simple example. cheers ;)

How to append multiple items in one line in Python

No. The method for appending an entire sequence is list.extend().

>>> L = [1, 2]
>>> L.extend((3, 4, 5))
>>> L
[1, 2, 3, 4, 5]

Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?

This function found here, works fine for me

function jsonRemoveUnicodeSequences($struct) {
   return preg_replace("/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($struct));
}

How to get the response of XMLHttpRequest?

You can get it by XMLHttpRequest.responseText in XMLHttpRequest.onreadystatechange when XMLHttpRequest.readyState equals to XMLHttpRequest.DONE.

Here's an example (not compatible with IE6/7).

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);

For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.

$.get('http://example.com', function(responseText) {
    alert(responseText);
});

Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.

I want to exception handle 'list index out of range.'

You have two options; either handle the exception or test the length:

if len(dlist) > 1:
    newlist.append(dlist[1])
    continue

or

try:
    newlist.append(dlist[1])
except IndexError:
    pass
continue

Use the first if there often is no second item, the second if there sometimes is no second item.

How to comment and uncomment blocks of code in the Office VBA Editor

  1. Right-click on the toolbar and select Customize...
  2. Select the Commands tab.
  3. Under Categories click on Edit, then select Comment Block in the Commands listbox.
  4. Drag the Comment Block entry onto the Menu Bar (yep! the menu bar)
    Note: You should now see a new icon on the menu bar.
  5. Make sure that the new icon is highlighted (it will have a black square around it) then
    click Modify Selection button on the Customize dialog box.
  6. An interesting menu will popup.
    Under name, add an ampersand (&) to the beginning of the entry.
    So now instead of "Comment Block" it should read &Comment Block.
    Press Enter to save the change.
  7. Click on Modify Selection again and select Image and Text.
  8. Dismiss the Customize dialog box.
  9. Highlight any block of code and press Alt-C. Voila.
  10. Do the same thing for the Uncomment Block or
    any other commands that you find yourself using often.

Scanner is skipping nextLine() after using next() or nextFoo()?

Why not use a new Scanner for every reading? Like below. With this approach you will not confront your problem.

int i = new Scanner(System.in).nextInt();

How do I format date in jQuery datetimepicker?

Here you go.

$('#timePicker').datetimepicker({
   // dateFormat: 'dd-mm-yy',
   format:'DD/MM/YYYY HH:mm:ss',
    minDate: getFormattedDate(new Date())
});

function getFormattedDate(date) {
    var day = date.getDate();
    var month = date.getMonth() + 1;
    var year = date.getFullYear().toString().slice(2);
    return day + '-' + month + '-' + year;
}

You need to pass datepicker() the date formatted correctly.

How do I create a folder in a GitHub repository?

To add a new directory all you have to do is create a new folder in your local repository. Create a new folder, and add a file in it.

Now go to your terminal and add it like you add the normal files in Git. Push them into the repository, and check the status to make sure you have created a directory.

node.js - request - How to "emitter.setMaxListeners()"?

I use the code to increase the default limit globally: require('events').EventEmitter.prototype._maxListeners = 100;

trace a particular IP and port

You can use the default traceroute command for this purpose, then there will be nothing to install.

traceroute -T -p 9100 <IP address/hostname>

The -T argument is required so that the TCP protocol is used instead of UDP.

In the rare case when traceroute isn't available, you can also use ncat.

nc -Czvw 5 <IP address/hostname> 9100

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

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

SQL Developer Version 4.1.0.19

Step 1: Go to Tools -> Preferences

Step 2: Select Database -> NLS

Step 3: Go to Date Format and Enter DD-MON-RR HH24: MI: SS

Step 4: Click OK.

enable or disable checkbox in html

If you specify the disabled attribute then the value you give it must be disabled. (In HTML 5 you may leave off everything except the attribute value. In HTML 4 you may leave off everything except the attribute name.)

If you do not want the control to be disabled then do not specify the attribute at all.

Disabled:

<input type="checkbox" disabled>
<input type="checkbox" disabled="disabled">

Enabled:

<input type="checkbox">

Invalid (but usually error recovered to be treated as disabled):

<input type="checkbox" disabled="1">
<input type="checkbox" disabled="true">
<input type="checkbox" disabled="false">

So, without knowing your template language, I guess you are looking for:

<td><input type="checkbox" name="repriseCheckBox" {checkStat == 1 ? disabled : }/></td>

Where do alpha testers download Google Play Android apps?

You need to publish the app before it becomes available for testing.

if you publish the app and the apk is only in "alpha testing" section then it is NOT available to general public, only for activated testers in the alpha section.

EDIT: One additional note: "normal" users will not find your app on Google Play, but also the activated tester can not find the application by using the search box.

Only the direct link to the application package will work. (only for the activated testers).

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

I feel the performance characteristics change from one DBMS to another. It's all on how they choose to implement it. Since I have worked extensively on Oracle, I'll tell from that perspective.

COUNT(*) - Fetches entire row into result set before passing on to the count function, count function will aggregate 1 if the row is not null

COUNT(1) - Will not fetch any row, instead count is called with a constant value of 1 for each row in the table when the WHERE matches.

COUNT(PK) - The PK in Oracle is indexed. This means Oracle has to read only the index. Normally one row in the index B+ tree is many times smaller than the actual row. So considering the disk IOPS rate, Oracle can fetch many times more rows from Index with a single block transfer as compared to entire row. This leads to higher throughput of the query.

From this you can see the first count is the slowest and the last count is the fastest in Oracle.

How to execute powershell commands from a batch file?

This solution is similar to walid2mi (thank you for inspiration), but allows the standard console input by the Read-Host cmdlet.

pros:

  • can be run like standard .cmd file
  • only one file for batch and powershell script
  • powershell script may be multi-line (easy to read script)
  • allows the standard console input (use the Read-Host cmdlet by standard way)

cons:

  • requires powershell version 2.0+

Commented and runable example of batch-ps-script.cmd:

<# : Begin batch (batch script is in commentary of powershell v2.0+)
@echo off
: Use local variables
setlocal
: Change current directory to script location - useful for including .ps1 files
cd %~dp0
: Invoke this file as powershell expression
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
: Restore environment variables present before setlocal and restore current directory
endlocal
: End batch - go to end of file
goto:eof
#>
# here start your powershell script

# example: include another .ps1 scripts (commented, for quick copy-paste and test run)
#. ".\anotherScript.ps1"

# example: standard input from console
$variableInput = Read-Host "Continue? [Y/N]"
if ($variableInput -ne "Y") {
    Write-Host "Exit script..."
    break
}

# example: call standard powershell command
Get-Item .

Snippet for .cmd file:

<# : batch script
@echo off
setlocal
cd %~dp0
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
endlocal
goto:eof
#>
# here write your powershell commands...

How to use BeginInvoke C#

Action is a Type of Delegate provided by the .NET framework. The Action points to a method with no parameters and does not return a value.

() => is lambda expression syntax. Lambda expressions are not of Type Delegate. Invoke requires Delegate so Action can be used to wrap the lambda expression and provide the expected Type to Invoke()

Invoke causes said Action to execute on the thread that created the Control's window handle. Changing threads is often necessary to avoid Exceptions. For example, if one tries to set the Rtf property on a RichTextBox when an Invoke is necessary, without first calling Invoke, then a Cross-thread operation not valid exception will be thrown. Check Control.InvokeRequired before calling Invoke.

BeginInvoke is the Asynchronous version of Invoke. Asynchronous means the thread will not block the caller as opposed to a synchronous call which is blocking.

$ is not a function - jQuery error

As RPM1984 refers to, this is mostly likely caused by the fact that your script is loading before jQuery is loaded.

Evaluate if list is empty JSTL

There's also the function tags, a bit more flexible:

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(list) > 0}">

And here's the tag documentation.

How to remove error about glyphicons-halflings-regular.woff2 not found

Add this one to your html if you only have access to the html:

<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">

C - reading command line parameters

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {
  int i, parameter = 0;
  if (argc >= 2) {
    /* there is 1 parameter (or more) in the command line used */
    /* argv[0] may point to the program name */
    /* argv[1] points to the 1st parameter */
    /* argv[argc] is NULL */
    parameter = atoi(argv[1]); /* better to use strtol */
    if (parameter > 0) {
      for (i = 0; i < parameter; i++) printf("%d ", i);
    } else {
      fprintf(stderr, "Please use a positive integer.\n");
    }
  }
  return 0;
}

How to replace ${} placeholders in a text file?

here's my solution with perl based on former answer, replaces environment variables:

perl -p -e 's/\$\{(\w+)\}/(exists $ENV{$1}?$ENV{$1}:"missing variable $1")/eg' < infile > outfile

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

I don't like all the solutions that use magic numbers like 97 or 36.

const A = 'A'.charCodeAt(0);

let numberToCharacter = number => String.fromCharCode(A + number);

let characterToNumber = character => character.charCodeAt(0) - A;

this assumes uppercase letters and starts 'A' at 0.

Changing the space between each item in Bootstrap navbar

As of Bootstrap 4, you can use the spacing utilities.

Add for instance px-2 in the classes of the nav-item to increase the padding.

Convert floating point number to a certain precision, and then copy to string

It's not print that does the formatting, It's a property of strings, so you can just use

newstring = "%.9f" % numvar

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

I used the Visual Studio 2008 Uninstall tool and it worked fine for me.

You can use this tool to uninstall Visual Studio 2008 official release and Visual Studio 2008 Release candidate (Only English version).

Found here, on the MSDN Forum: MSDN forum topic.

I found this answer here

Be sure you run the tool with admin-rights.

How to find server name of SQL Server Management Studio

Please Install SQL Server Data Tools from link (SSDT)

You can also Install it when you are installing Visual Studio there is Option "Data Storage and Processing" you must be select while installing Visual Studio enter image description here

Codeigniter how to create PDF

I have used mpdf in my project. In Codeigniter-3, putted mpdf files under application/third_party and then used in this way:

 /**
 * This function is used to display data in PDF file.
 * function is using mpdf api to generate pdf.
 * @param number $id : This is unique id of table.
 */
function generatePDF($id){
    require APPPATH . '/third_party/mpdf/vendor/autoload.php';
    //$mpdf=new mPDF();
    $mpdf = new mPDF('utf-8', 'Letter', 0, '', 0, 0, 7, 0, 0, 0);

    $checkRecords =  $this->user_model->getCheckInfo($id);      
    foreach ($checkRecords as $key => $value) {
        $data['info'] = $value;
        $filename = $this->load->view(CHEQUE_VIEWS.'index',$data,TRUE);
        $mpdf->WriteHTML($filename); 
    }

    $mpdf->Output(); //output pdf document.
    //$content = $mpdf->Output('', 'S'); //get pdf document content's as variable. 

}

How to compare if two structs, slices or maps are equal?

reflect.DeepEqual is often incorrectly used to compare two like structs, as in your question.

cmp.Equal is a better tool for comparing structs.

To see why reflection is ill-advised, let's look at the documentation:

Struct values are deeply equal if their corresponding fields, both exported and unexported, are deeply equal.

....

numbers, bools, strings, and channels - are deeply equal if they are equal using Go's == operator.

If we compare two time.Time values of the same UTC time, t1 == t2 will be false if their metadata timezone is different.

go-cmp looks for the Equal() method and uses that to correctly compare times.

Example:

m1 := map[string]int{
    "a": 1,
    "b": 2,
}
m2 := map[string]int{
    "a": 1,
    "b": 2,
}
fmt.Println(cmp.Equal(m1, m2)) // will result in true

Get values from other sheet using VBA

SomeVal=ActiveWorkbook.worksheets("Sheet2").cells(aRow,aCol).Value

did not work. However the following code only worked for me.

SomeVal = ThisWorkbook.Sheets(2).cells(aRow,aCol).Value

Colors in JavaScript console

I wrote template-colors-web https://github.com/icodeforlove/Console.js to allow us to do this a bit easier

console.log(c`red ${c`green ${'blue'.bold}.blue`}.green`.red);

The above would be extremely hard to do with the default console.log.

For a live interactive demo click here.

enter image description here

How to skip the first n rows in sql query

For SQL Server 2012 and later versions, the best method is @MajidBasirati's answer.

I also loved @CarlosToledo's answer, it's not limited to any SQL Server version but it's missing Order By Clauses. Without them, it may return wrong results.

For SQL Server 2008 and later I would use Common Table Expressions for better performance.

-- This example omits first 10 records and select next 5 records
;WITH MyCTE(Id) as
(
    SELECT TOP (10) Id 
    FROM MY_TABLE
    ORDER BY Id
)
SELECT TOP (5) * 
FROM MY_TABLE
    INNER JOIN MyCTE ON (MyCTE.Id <> MY_TABLE.Id) 
ORDER BY Id

How to read from a file or STDIN in Bash?

More accurately...

while IFS= read -r line ; do
    printf "%s\n" "$line"
done < file

How to execute an .SQL script file using c#

I managed to work out the answer by reading the manual :)

This extract from the MSDN

The code example avoids a deadlock condition by calling p.StandardOutput.ReadToEnd before p.WaitForExit. A deadlock condition can result if the parent process calls p.WaitForExit before p.StandardOutput.ReadToEnd and the child process writes enough text to fill the redirected stream. The parent process would wait indefinitely for the child process to exit. The child process would wait indefinitely for the parent to read from the full StandardOutput stream.

There is a similar issue when you read all text from both the standard output and standard error streams. For example, the following C# code performs a read operation on both streams.

Turns the code into this;

Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "sqlplus";
p.StartInfo.Arguments = string.Format("xxx/xxx@{0} @{1}", in_database, s);

bool started = p.Start();
// important ... read stream input before waiting for exit.
// this avoids deadlock.
string output = p.StandardOutput.ReadToEnd();

p.WaitForExit();

Console.WriteLine(output);

if (p.ExitCode != 0)
{
    Console.WriteLine( string.Format("*** Failed : {0} - {1}",s,p.ExitCode));
    break;
}

Which now exits correctly.

JPA : How to convert a native query result set to POJO class collection

Old style using ResultSet

@Transactional(readOnly=true)
public void accessUser() {
    EntityManager em = this.getEntityManager();
    org.hibernate.Session session = em.unwrap(org.hibernate.Session.class);
    session.doWork(new Work() {
        @Override
        public void execute(Connection con) throws SQLException {
            try (PreparedStatement stmt = con.prepareStatement(
                    "SELECT u.username, u.name, u.email, 'blabla' as passe, login_type as loginType FROM users u")) {
                ResultSet rs = stmt.executeQuery();
                ResultSetMetaData rsmd = rs.getMetaData();
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    System.out.print(rsmd.getColumnName(i) + " (" + rsmd.getColumnTypeName(i) + ") / ");
                }
                System.out.println("");
                while (rs.next()) {
                    System.out.println("Found username " + rs.getString("USERNAME") + " name " + rs.getString("NAME") + " email " + rs.getString("EMAIL") + " passe " + rs.getString("PASSE") + " email " + rs.getInt("LOGIN_TYPE"));
                }
            }
        }
    });
}

unique object identifier in javascript

For the purpose of comparing two objects, the simplest way to do this would be to add a unique property to one of the objects at the time you need to compare the objects, check if the property exists in the other and then remove it again. This saves overriding prototypes.

function isSameObject(objectA, objectB) {
   unique_ref = "unique_id_" + performance.now();
   objectA[unique_ref] = true;
   isSame = objectB.hasOwnProperty(unique_ref);
   delete objectA[unique_ref];
   return isSame;
}

object1 = {something:true};
object2 = {something:true};
object3 = object1;

console.log(isSameObject(object1, object2)); //false
console.log(isSameObject(object1, object3)); //true

Allow user to select camera or gallery for image

I also had this issue and what I did was create an AlertDialog and use the setItems() method along with the DialogInterface listener:

AlertDialog.Builder getImageFrom = new AlertDialog.Builder(Fotos.this);
getImageFrom.setTitle("Select:");
final CharSequence[] opsChars = {getResources().getString(R.string.takepic), getResources().getString(R.string.opengallery)};
getImageFrom.setItems(opsChars, new android.content.DialogInterface.OnClickListener(){

    @Override
    public void onClick(DialogInterface dialog, int which) {
        if(which == 0){
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
        }else
            if(which == 1){
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,
                    getResources().getString(R.string.pickgallery)), SELECT_PICTURE);
            }
        dialog.dismiss();
    }
});

python modify item in list, save back in list

For Python 3:

ListOfStrings = []
ListOfStrings.append('foo')
ListOfStrings.append('oof')
for idx, item in enumerate(ListOfStrings):
if 'foo' in item:
    ListOfStrings[idx] = "bar"

Matplotlib/pyplot: How to enforce axis range?

Calling p.plot after setting the limits is why it is rescaling. You are correct in that turning autoscaling off will get the right answer, but so will calling xlim() or ylim() after your plot command.

I use this quite a lot to invert the x axis, I work in astronomy and we use a magnitude system which is backwards (ie. brighter stars have a smaller magnitude) so I usually swap the limits with

lims = xlim()
xlim([lims[1], lims[0]]) 

How to select all columns, except one column in pandas?

Here is another way:

df[[i for i in list(df.columns) if i != '<your column>']]

You just pass all columns to be shown except of the one you do not want.

Combine two or more columns in a dataframe into a new column with a new name

We can use paste0:

df$combField <- paste0(df$x, df$y)

If you do not want any padding space introduced in the concatenated field. This is more useful if you are planning to use the combined field as a unique id that represents combinations of two fields.

How to create a sticky left sidebar menu using bootstrap 3?

You can also try to use a Polyfill like Fixed-Sticky. Especially when you are using Bootstrap4 the affix component is no longer included:

Dropped the Affix jQuery plugin. We recommend using a position: sticky polyfill instead.

php Replacing multiple spaces with a single space

preg_replace("/[[:blank:]]+/"," ",$input)

Copy directory to another directory using ADD command

ADD go /usr/local/

will copy the contents of your local go directory in the /usr/local/ directory of your docker image.

To copy the go directory itself in /usr/local/ use:

ADD go /usr/local/go

or

COPY go /usr/local/go

JAVA_HOME does not point to the JDK

You installed java...

apt-get install default-jre

But not the JDK...

apt-get install default-jdk

shuffling/permutating a DataFrame in pandas

Sampling randomizes, so just sample the entire data frame.

df.sample(frac=1)

How to unpack and pack pkg file?

Here is a bash script inspired by abarnert's answer which will unpack a package named MyPackage.pkg into a subfolder named MyPackage_pkg and then open the folder in Finder.

    #!/usr/bin/env bash
    filename="$*"
    dirname="${filename/\./_}"
    pkgutil --expand "$filename" "$dirname"
    cd "$dirname"
    tar xvf Payload
    open .

Usage:

    pkg-upack.sh MyPackage.pkg

Warning: This will not work in all cases, and will fail with certain files, e.g. the PKGs inside the OSX system installer. If you want to peek inside the pkg file and see what's inside, you can try SuspiciousPackage (free app), and if you need more options such as selectively unpacking specific files, then have a look at Pacifist (nagware).

How can query string parameters be forwarded through a proxy_pass with nginx?

I modified @kolbyjack code to make it work for

http://website1/service
http://website1/service/

with parameters

location ~ ^/service/?(.*) {
    return 301 http://service_url/$1$is_args$args;
}

Google Maps API v3: How do I dynamically change the marker icon?

The GMaps Utility Library has a plugin called MapIconMaker that makes it easy to generate different marker styles on the fly. It uses Google Charts to draw the markers.

There's a good demo here that shows what kind of markers you can make with it.

In Java, should I escape a single quotation mark (') in String (double quoted)?

You don't need to escape the ' character in a String (wrapped in "), and you don't have to escape a " character in a char (wrapped in ').

Programmatically Install Certificate into Mozilla

Here is an alternative way that doesn't override the existing certificates: [bash fragment for linux systems]

certificateFile="MyCa.cert.pem"
certificateName="MyCA Name" 
for certDB in $(find  ~/.mozilla* ~/.thunderbird -name "cert8.db")
do
  certDir=$(dirname ${certDB});
  #log "mozilla certificate" "install '${certificateName}' in ${certDir}"
  certutil -A -n "${certificateName}" -t "TCu,Cuw,Tuw" -i ${certificateFile} -d ${certDir}
done

You may find certutil in the libnss3-tools package (debian/ubuntu).

Source:
http://web.archive.org/web/20150622023251/http://www.computer42.org:80/xwiki-static/exported/DevNotes/xwiki.DevNotes.Firefox.html

See also:
https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/tools/NSS_Tools_certutil

How to auto-format code in Eclipse?

Update your IDE with the latest PDT version for better code formatting. On the main menu click Help -> Install New Software and then add the following URL in the Work with field:

http://download.eclipse.org/tools/pdt/updates/4.0.1 

When asked for the name, give it PDT4.0.1 and then move along with the update or install.

It will see if the appropriate PDT is already installed or if it is a lower version, which then would be updated.

After restarting or applying the changes go to Windows -> Preferences on the side bar and expand PHP -> Code Style. Here you will see an item named Formatter. Select it and choose the active profile for the code formating. Thats it.

The next time you format it, it will choose a format according to the chosen active profile.

Hope it helps.

PHP parse/syntax errors; and how to solve them

Unexpected [

These days, the unexpected [ array bracket is commonly seen on outdated PHP versions. The short array syntax is available since PHP >= 5.4. Older installations only support array().

$php53 = array(1, 2, 3);
$php54 = [1, 2, 3];
         ?

Array function result dereferencing is likewise not available for older PHP versions:

$result = get_whatever()["key"];
                      ?

Reference - What does this error mean in PHP? - "Syntax error, unexpected \[" shows the most common and practical workarounds.

Though, you're always better off just upgrading your PHP installation. For shared webhosting plans, first research if e.g. SetHandler php56-fcgi can be used to enable a newer runtime.

See also:

BTW, there are also preprocessors and PHP 5.4 syntax down-converters if you're really clingy with older + slower PHP versions.

Other causes for Unexpected [ syntax errors

If it's not the PHP version mismatch, then it's oftentimes a plain typo or newcomer syntax mistake:

  • You can't use array property declarations/expressions in classes, not even in PHP 7.

    protected $var["x"] = "Nope";
                  ?
    
  • Confusing [ with opening curly braces { or parentheses ( is a common oversight.

    foreach [$a as $b)
            ?
    

    Or even:

    function foobar[$a, $b, $c] {
                   ?
    
  • Or trying to dereference constants (before PHP 5.6) as arrays:

    $var = const[123];
           ?
    

    At least PHP interprets that const as a constant name.

    If you meant to access an array variable (which is the typical cause here), then add the leading $ sigil - so it becomes a $varname.

  • You are trying to use the global keyword on a member of an associative array. This is not valid syntax:

    global $var['key'];
    


Unexpected ] closing square bracket

This is somewhat rarer, but there are also syntax accidents with the terminating array ] bracket.

  • Again mismatches with ) parentheses or } curly braces are common:

    function foobar($a, $b, $c] {
                              ?
    
  • Or trying to end an array where there isn't one:

    $var = 2];
    

    Which often occurs in multi-line and nested array declarations.

    $array = [1,[2,3],4,[5,6[7,[8],[9,10]],11],12]],15];
                                                 ?
    

    If so, use your IDE for bracket matching to find any premature ] array closure. At the very least use more spacing and newlines to narrow it down.

React-router urls don't work when refreshing or writing manually

Solution for Preact with preact-router

Works with refresh and direct access

For those discovering this via Google, here's a demo of preact-router + hash history:

const { h, Component, render } = preact; /** @jsx h */
const { Router } = preactRouter;
const { createHashHistory } = History;
const App = () => (
    <div>
        <AddressBar />

        <Router history={createHashHistory()}>
            <div path="/">
                <p>
                    all paths in preact-router are still /normal/urls.
                    using hash history rewrites them to /#/hash/urls
                </p>
                Example: <a href="/page2">page 2</a>
            </div>
            <div path="/page2">
                <p>Page Two</p>
                <a href="/">back to home</a><br/>
            </div>
        </Router>
    </div>
);

jsfiddle

Objective C - Assign, Copy, Retain

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"First",@"Second", nil];
NSMutableArray *copiedArray = [array mutableCopy];
NSMutableArray *retainedArray = [array retain];

[retainedArray addObject:@"Retained Third"];
[copiedArray addObject:@"Copied Third"];

NSLog(@"array = %@",array);
NSLog(@"Retained Array = %@",retainedArray);
NSLog(@"Copied Array = %@",copiedArray);

array = (
    First,
    Second,
    "Retained Third"
)
Retained Array = (
    First,
    Second,
    "Retained Third"
)
Copied Array = (
    First,
    Second,
    "Copied Third"
)

Using multiprocessing.Process with a maximum number of simultaneous processes

I think Semaphore is what you are looking for, it will block the main process after counting down to 0. Sample code:

from multiprocessing import Process
from multiprocessing import Semaphore
import time

def f(name, sema):
    print('process {} starting doing business'.format(name))
    # simulate a time-consuming task by sleeping
    time.sleep(5)
    # `release` will add 1 to `sema`, allowing other 
    # processes blocked on it to continue
    sema.release()

if __name__ == '__main__':
    concurrency = 20
    total_task_num = 1000
    sema = Semaphore(concurrency)
    all_processes = []
    for i in range(total_task_num):
        # once 20 processes are running, the following `acquire` call
        # will block the main process since `sema` has been reduced
        # to 0. This loop will continue only after one or more 
        # previously created processes complete.
        sema.acquire()
        p = Process(target=f, args=(i, sema))
        all_processes.append(p)
        p.start()

    # inside main process, wait for all processes to finish
    for p in all_processes:
        p.join()

The following code is more structured since it acquires and releases sema in the same function. However, it will consume too much resources if total_task_num is very large:

from multiprocessing import Process
from multiprocessing import Semaphore
import time

def f(name, sema):
    print('process {} starting doing business'.format(name))
    # `sema` is acquired and released in the same
    # block of code here, making code more readable,
    # but may lead to problem.
    sema.acquire()
    time.sleep(5)
    sema.release()

if __name__ == '__main__':
    concurrency = 20
    total_task_num = 1000
    sema = Semaphore(concurrency)
    all_processes = []
    for i in range(total_task_num):
        p = Process(target=f, args=(i, sema))
        all_processes.append(p)
        # the following line won't block after 20 processes
        # have been created and running, instead it will carry 
        # on until all 1000 processes are created.
        p.start()

    # inside main process, wait for all processes to finish
    for p in all_processes:
        p.join()

The above code will create total_task_num processes but only concurrency processes will be running while other processes are blocked, consuming precious system resources.

Pandas - replacing column values

Can try this too!
Create a dictionary of replacement values.

import pandas as pd
data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

enter image description here

replace_dict= {0:'Female',1:'Male'}
print(replace_dict)

enter image description here

Use the map function for replacing values

data['sex']=data['sex'].map(replace_dict)

Output after replacing
enter image description here

What is uintptr_t data type

There are already many good answers to the part "what is uintptr_t data type". I will try to address the "what it can be used for?" part in this post.

Primarily for bitwise operations on pointers. Remember that in C++ one cannot perform bitwise operations on pointers. For reasons see Why can't you do bitwise operations on pointer in C, and is there a way around this?

Thus in order to do bitwise operations on pointers one would need to cast pointers to type unitpr_t and then perform bitwise operations.

Here is an example of a function that I just wrote to do bitwise exclusive or of 2 pointers to store in a XOR linked list so that we can traverse in both directions like a doubly linked list but without the penalty of storing 2 pointers in each node.

 template <typename T>
 T* xor_ptrs(T* t1, T* t2)
 {
     return reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(t1)^reinterpret_cast<uintptr_t>(t2));
  }

How to obtain values of request variables using Python and Flask

If you want to retrieve POST data:

first_name = request.form.get("firstname")

If you want to retrieve GET (query string) data:

first_name = request.args.get("firstname")

Or if you don't care/know whether the value is in the query string or in the post data:

first_name = request.values.get("firstname") 

request.values is a CombinedMultiDict that combines Dicts from request.form and request.args.

Difference between HashMap and Map in Java..?

Map is an interface; HashMap is a particular implementation of that interface.

HashMap uses a collection of hashed key values to do its lookup. TreeMap will use a red-black tree as its underlying data store.

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

This is specific for each site. So if you type that once, you will only get through that site and all other sites will need a similar type-through.

It is also remembered for that site and you have to click on the padlock to reset it (so you can type it again):

enter image description here

Needless to say use of this "feature" is a bad idea and is unsafe - hence the name.

You should find out why the site is showing the error and/or stop using it until they fix it. HSTS specifically adds protections for bad certs to prevent you clicking through them. The fact it's needed suggests there is something wrong with the https connection - like the site or your connection to it has been hacked.

The chrome developers also do change this periodically. They changed it recently from badidea to thisisunsafe so everyone using badidea, suddenly stopped being able to use it. You should not depend on it. As Steffen pointed out in the comments below, it is available in the code should it change again though they now base64 encode it to make it more obscure. The last time they changed they put this comment in the commit:

Rotate the interstitial bypass keyword

The security interstitial bypass keyword hasn't changed in two years and awareness of the bypass has been increased in blogs and social media. Rotate the keyword to help prevent misuse.

I think the message from the Chrome team is clear - you should not use it. It would not surprise me if they removed it completely in future.

If you are using this when using a self-signed certificate for local testing then why not just add your self-signed certificate certificate to your computer's certificate store so you get a green padlock and do not have to type this? Note Chrome insists on a SAN field in certificates now so if just using the old subject field then even adding it to the certificate store will not result in a green padlock.

If you leave the certificate untrusted then certain things do not work. Caching for example is completely ignored for untrusted certificates. As is HTTP/2 Push.

HTTPS is here to stay and we need to get used to using it properly - and not bypassing the warnings with a hack that is liable to change and doesn't work the same as a full HTTPS solution.

Convert java.util.Date to String

If you only need the time from the date, you can just use the feature of String.

Date test = new Date();
String dayString = test.toString();
String timeString = dayString.substring( 11 , 19 );

This will automatically cut the time part of the String and save it inside the timeString.

How to print Two-Dimensional Array like table

You could write a method to print a 2d array like this:

//Displays a 2d array in the console, one line per row.
static void printMatrix(int[][] grid) {
    for(int r=0; r<grid.length; r++) {
       for(int c=0; c<grid[r].length; c++)
           System.out.print(grid[r][c] + " ");
       System.out.println();
    }
}

Where to place JavaScript in an HTML file?

The Yahoo! Exceptional Performance team recommend placing scripts at the bottom of your page because of the way browsers download components.

Of course Levi's comment "just before you need it and no sooner" is really the correct answer, i.e. "it depends".

Run PowerShell scripts on remote PC

After further investigating on PSExec tool, I think I got the answer. I need to add -i option to tell PSExec to launch process on remote in interactive mode:

PSExec \\RPC001 -i -u myID -p myPWD PowerShell C:\script\StartPS.ps1 par1 par2

Without -i, powershell.exe is running on the remote in waiting mode. Interesting point is that if I run a simple bat (without PS in bat), it works fine. Maybe this is something special for PS case? Welcome comments and explanations.

Relative path in HTML

The relative pathing is based on the document level of the client side i.e. the URL level of the document as seen in the browser.

If the URL of your website is: http://www.example.com/mywebsite/ then starting at the root level starts above the "mywebsite" folder path.

What character represents a new line in a text area

It seems that, according to the HTML5 spec, the value property of the textarea element should return '\r\n' for a newline:

The element's value is defined to be the element's raw value with the following transformation applied:

Replace every occurrence of a "CR" (U+000D) character not followed by a "LF" (U+000A) character, and every occurrence of a "LF" (U+000A) character not preceded by a "CR" (U+000D) character, by a two-character string consisting of a U+000D CARRIAGE RETURN "CRLF" (U+000A) character pair.

Following the link to 'value' makes it clear that it refers to the value property accessed in javascript:

Form controls have a value and a checkedness. (The latter is only used by input elements.) These are used to describe how the user interacts with the control.

However, in all five major browsers (using Windows, 11/27/2015), if '\r\n' is written to a textarea, the '\r' is stripped. (To test: var e=document.createElement('textarea'); e.value='\r\n'; alert(e.value=='\n');) This is true of IE since v9. Before that, IE was returning '\r\n' and converting both '\r' and '\n' to '\r\n' (which is the HTML5 spec). So... I'm confused.

To be safe, it's usually enough to use '\r?\n' in regular expressions instead of just '\n', but if the newline sequence must be known, a test like the above can be performed in the app.

g++ ld: symbol(s) not found for architecture x86_64

I had a similar warning/error/failure when I was simply trying to make an executable from two different object files (main.o and add.o). I was using the command:

gcc -o exec main.o add.o

But my program is a C++ program. Using the g++ compiler solved my issue:

g++ -o exec main.o add.o

I was always under the impression that gcc could figure these things out on its own. Apparently not. I hope this helps someone else searching for this error.

How to install a package inside virtualenv?

To use the environment virtualenv has created, you first need to source env/bin/activate. After that, just install packages using pip install package-name.

form action with javascript

I always include the js files in the head of the html document and them in the action just call the javascript function. Something like this:

action="javascript:checkout()"

You try this?

Don't forget include the script reference in the html head.

I don't know cause of that works in firefox. Regards.

Why won't bundler install JSON gem?

So after a half day on this and almost immediately after posting my question I found the answer. Bundler 1.5.0 has a bug where it doesn't recognize default gems as referenced here

The solution was to update to bundler 1.5.1 using gem install bundler -v '= 1.5.1'

What is http multipart request?

I have found an excellent and relatively short explanation here.

A multipart request is a REST request containing several packed REST requests inside its entity.

How can I combine multiple nested Substitute functions in Excel?

=SUBSTITUTE(text, old_text, new_text)

if: a=!, b=@, c=#,... x=>, y=?, z=~, " "="     "
then: abcdefghijklmnopqrstuvwxyz ... try this out
equals: !@#$%^&*()-=+[]\{}|;:/<>?~     ...     ;}?     ;*(|     ]:;

RULES:

(1) text to substitute is in cell A1
(2) max 64 substitution levels (the formula below only has 27 levels [alphabet + space])
(2) "old_text" cannot also be a "new_text" (ie: if a=z .: z cannot be "old text")

---so if a=z,b=y,...y=b,z=a, then the result is 
---abcdefghijklmnopqrstuvwxyz = zyxwvutsrqponnopqrstuvwxyz (and z changes to a then changes back to z) ... (pattern starts to fail after m=n, n=m... and n becomes n)

The formula is:

=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"a","!"),"b","@"),"c","#"),"d","$"),"e","%"),"f","^"),"g","&"),"h","*"),"i","("),"j",")"),"k","-"),"l","="),"m","+"),"n","["),"o","]"),"p","\"),"q","{"),"r","}"),"s","|"),"t",";"),"u",":"),"v","/"),"w","<"),"x",">"),"y","?"),"z","~")," ","     ")

Format cell color based on value in another sheet and cell

I'm using Excel 2003 -

The problem with using conditional formatting here is that you can't reference another worksheet or workbook in your conditions. What you can to do is set some column on sheet 1 equal to the appropriate column on sheet 2 (in your example =Sheet2!B6). I used Column F in my example below. Then you can use conditional formatting. Select the cell at Sheet 1, row , column 1 and then go to the conditional formatting menu. Choose "Formula Is" from the drop down and set the condition to "=$F$6=4". Click on the format button and then choose the Patterns tab. Choose the color you want and you're done.

You can use the format painter tool to apply conditional formatting to other cells, but be aware that by default Excel uses absolute references in the conditions. If you want them to be relative you'll need to remove the dollar signs from the condition.

You can have up to 3 conditions applied to a cell (use the add >> button at the bottom of the Conditional formatting dialog) so if the last row is fixed (for example, you know that it will always be row 10) you can use it as a condition to set the background color to none. Assuming that the last value you care about is in row 10 then (still assuming that you've set column F on sheet1 to the corresponding cells on sheet 2) then set the 1st condition to Formula Is =$F$10="" and the pattern to None. Make it the first condition and it will override any following conflicting statements.

Netbeans installation doesn't find JDK

I also had the same problem. So I tried by installing a lesser version say jdk1.5 and running the netbeans installation from command prompt as: Linux: netbeans-5_5-linux.bin -is:javahome /usr/jdk/jdk1.5.0_06 Windows: netbeans-5_5-windows.exe -is:javahome "C:\Program Files\Java\jdk1.5.0_06"

Hope it helps

PHP - Indirect modification of overloaded property

Nice you gave me something to play around with

Run

class Sample extends Creator {

}

$a = new Sample ();
$a->role->rolename = 'test';
echo  $a->role->rolename , PHP_EOL;
$a->role->rolename->am->love->php = 'w00';
echo  $a->role->rolename  , PHP_EOL;
echo  $a->role->rolename->am->love->php   , PHP_EOL;

Output

test
test
w00

Class Used

abstract class Creator {
    public function __get($name) {
        if (! isset ( $this->{$name} )) {
            $this->{$name} = new Value ( $name, null );
        }
        return $this->{$name};
    }

    public function __set($name, $value) {
        $this->{$name} = new Value ( $name, $value );
    }



}

class Value extends Creator {
    private $name;
    private $value;
    function __construct($name, $value) {
        $this->name = $name;
        $this->value = $value;
    }

    function __toString()
    {
        return (string) $this->value ;
    }
}      

Edit : New Array Support as requested

class Sample extends Creator {

}

$a = new Sample ();
$a->role = array (
        "A",
        "B",
        "C" 
);


$a->role[0]->nice = "OK" ;

print ($a->role[0]->nice  . PHP_EOL);

$a->role[1]->nice->ok = array("foo","bar","die");

print ($a->role[1]->nice->ok[2]  . PHP_EOL);


$a->role[2]->nice->raw = new stdClass();
$a->role[2]->nice->raw->name = "baba" ;

print ($a->role[2]->nice->raw->name. PHP_EOL);

Output

 Ok die baba

Modified Class

abstract class Creator {
    public function __get($name) {
        if (! isset ( $this->{$name} )) {
            $this->{$name} = new Value ( $name, null );
        }
        return $this->{$name};
    }

    public function __set($name, $value) {
        if (is_array ( $value )) {
            array_walk ( $value, function (&$item, $key) {
                $item = new Value ( $key, $item );
            } );
        }
        $this->{$name} = $value;

    }

}

class Value {
    private $name ;
    function __construct($name, $value) {
        $this->{$name} = $value;
        $this->name = $value ;
    }

    public function __get($name) {
        if (! isset ( $this->{$name} )) {
            $this->{$name} = new Value ( $name, null );
        }

        if ($name == $this->name) {
            return $this->value;
        }

        return $this->{$name};
    }

    public function __set($name, $value) {
        if (is_array ( $value )) {
            array_walk ( $value, function (&$item, $key) {
                $item = new Value ( $key, $item );
            } );
        }
        $this->{$name} = $value;
    }

    public function __toString() {
        return (string) $this->name ;
    }   
}

Convert JSON String to Pretty Print JSON output using Jackson

This looks like it might be the answer to your question. It says it's using Spring, but I think that should still help you in your case. Let me inline the code here so it's more convenient:

import java.io.FileReader;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    ObjectMapper mapper = new ObjectMapper();
    MyClass myObject = mapper.readValue(new FileReader("input.json"), MyClass.class);
    // this is Jackson 1.x API only: 
    ObjectWriter writer = mapper.defaultPrettyPrintingWriter();
    // ***IMPORTANT!!!*** for Jackson 2.x use the line below instead of the one above: 
    // ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
    System.out.println(writer.writeValueAsString(myObject));
  }
}

class MyClass
{
  String one;
  String[] two;
  MyOtherClass three;

  public String getOne() {return one;}
  void setOne(String one) {this.one = one;}
  public String[] getTwo() {return two;}
  void setTwo(String[] two) {this.two = two;}
  public MyOtherClass getThree() {return three;}
  void setThree(MyOtherClass three) {this.three = three;}
}

class MyOtherClass
{
  String four;
  String[] five;

  public String getFour() {return four;}
  void setFour(String four) {this.four = four;}
  public String[] getFive() {return five;}
  void setFive(String[] five) {this.five = five;}
}

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

You need to install opencv-contrib

pip install opencv-contrib-python

It should work after that.

How do I use Apache tomcat 7 built in Host Manager gui?

To access "Host Manager" you have to configure "admin-gui" user inside the tomcat-users.xml

Just add the below lines[change username & pwd] :

<role rolename="admin-gui"/>
<user username="admin" password="password" roles="admin-gui"/>

Restart tomcat 7 server and you are done.

What is the best way to iterate over multiple lists at once?

The usual way is to use zip():

for x, y in zip(a, b):
    # x is from a, y is from b

This will stop when the shorter of the two iterables a and b is exhausted. Also worth noting: itertools.izip() (Python 2 only) and itertools.izip_longest() (itertools.zip_longest() in Python 3).

Function to calculate R2 (R-squared) in R

It is not something obvious, but the caret package has a function postResample() that will calculate "A vector of performance estimates" according to the documentation. The "performance estimates" are

  • RMSE
  • Rsquared
  • mean absolute error (MAE)

and have to be accessed from the vector like this

library(caret)
vect1 <- c(1, 2, 3)
vect2 <- c(3, 2, 2)
res <- caret::postResample(vect1, vect2)
rsq <- res[2]

However, this is using the correlation squared approximation for r-squared as mentioned in another answer. I'm not sure why Max Kuhn didn't just use the conventional 1-SSE/SST.

caret also has an R2() method, although it's hard to find in the documentation.

The way to implement the normal coefficient of determination equation is:

preds <- c(1, 2, 3)
actual <- c(2, 2, 4)
rss <- sum((preds - actual) ^ 2)
tss <- sum((actual - mean(actual)) ^ 2)
rsq <- 1 - rss/tss

Not too bad to code by hand of course, but why isn't there a function for it in a language primarily made for statistics? I'm thinking I must be missing the implementation of R^2 somewhere, or no one cares enough about it to implement it. Most of the implementations, like this one, seem to be for generalized linear models.

Store a closure as a variable in Swift

The compiler complains on

var completionHandler: (Float)->Void = {}

because the right-hand side is not a closure of the appropriate signature, i.e. a closure taking a float argument. The following would assign a "do nothing" closure to the completion handler:

var completionHandler: (Float)->Void = {
    (arg: Float) -> Void in
}

and this can be shortened to

var completionHandler: (Float)->Void = { arg in }

due to the automatic type inference.

But what you probably want is that the completion handler is initialized to nil in the same way that an Objective-C instance variable is inititialized to nil. In Swift this can be realized with an optional:

var completionHandler: ((Float)->Void)?

Now the property is automatically initialized to nil ("no value"). In Swift you would use optional binding to check of a the completion handler has a value

if let handler = completionHandler {
    handler(result)
}

or optional chaining:

completionHandler?(result)

Removing a list of characters in string

I am thinking about a solution for this. First I would make the string input as a list. Then I would replace the items of list. Then through using join command, I will return list as a string. The code can be like this:

def the_replacer(text):
    test = []    
    for m in range(len(text)):
        test.append(text[m])
        if test[m]==','\
        or test[m]=='!'\
        or test[m]=='.'\
        or test[m]=='\''\
        or test[m]==';':
    #....
            test[n]=''
    return ''.join(test)

This would remove anything from the string. What do you think about that?

SQLAlchemy IN clause

Just wanted to share my solution using sqlalchemy and pandas in python 3. Perhaps, one would find it useful.

import sqlalchemy as sa
import pandas as pd
engine = sa.create_engine("postgresql://postgres:my_password@my_host:my_port/my_db")
values = [val1,val2,val3]   
query = sa.text(""" 
                SELECT *
                FROM my_table
                WHERE col1 IN :values; 
""")
query = query.bindparams(values=tuple(values))
df = pd.read_sql(query, engine)

Google Maps: how to get country, state/province/region, city given a lat/long value?

You have a basic answer here: Get city name using geolocation

But for what you are looking for, i'd recommend this way.

Only if you also need administrative_area_level_1,to store different things for Paris, Texas, US and Paris, Ile-de-France, France and provide a manual fallback:

--

There is a problem in Michal's way, in that it takes the first result, not a particular one. He uses results[0]. The way I see fit (I just modified his code) is to take ONLY the result whose type is "locality", which is always present, even in an eventual manual fallback in case the browser does not support geolocation.

His way: fetched results are different from using http://maps.googleapis.com/maps/api/geocode/json?address=bucharest&sensor=false than from using http://maps.googleapis.com/maps/api/geocode/json?latlng=44.42514,26.10540&sensor=false (searching by name / searching by lat&lng)

This way: same fetched results.

<!DOCTYPE html> 
<html> 
<head> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
<title>Reverse Geocoding</title> 

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript"> 
  var geocoder;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} 
//Get the latitude and the longitude;
function successFunction(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    codeLatLng(lat, lng)
}

function errorFunction(){
    alert("Geocoder failed");
}

  function initialize() {
    geocoder = new google.maps.Geocoder();



  }

  function codeLatLng(lat, lng) {

    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
      //console.log(results);
        if (results[1]) {
        var indice=0;
        for (var j=0; j<results.length; j++)
        {
            if (results[j].types[0]=='locality')
                {
                    indice=j;
                    break;
                }
            }
        alert('The good number is: '+j);
        console.log(results[j]);
        for (var i=0; i<results[j].address_components.length; i++)
            {
                if (results[j].address_components[i].types[0] == "locality") {
                        //this is the object you are looking for City
                        city = results[j].address_components[i];
                    }
                if (results[j].address_components[i].types[0] == "administrative_area_level_1") {
                        //this is the object you are looking for State
                        region = results[j].address_components[i];
                    }
                if (results[j].address_components[i].types[0] == "country") {
                        //this is the object you are looking for
                        country = results[j].address_components[i];
                    }
            }

            //city data
            alert(city.long_name + " || " + region.long_name + " || " + country.short_name)


            } else {
              alert("No results found");
            }
        //}
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });
  }
</script> 
</head> 
<body onload="initialize()"> 

</body> 
</html> 

how to use JSON.stringify and json_decode() properly

When you save some data using JSON.stringify() and then need to read that in php. The following code worked for me.

json_decode( html_entity_decode( stripslashes ($jsonString ) ) );

Thanks to @Thisguyhastwothumbs

PHP how to get value from array if key is in a variable

$value = ( array_key_exists($key, $array) && !empty($array[$key]) ) 
         ? $array[$key] 
         : 'non-existant or empty value key';

How to highlight text using javascript

None of the other solutions really fit my needs, and although Stefan Steiger's solution worked as I expected I found it a bit too verbose.

Following is my attempt:

_x000D_
_x000D_
/**_x000D_
 * Highlight keywords inside a DOM element_x000D_
 * @param {string} elem Element to search for keywords in_x000D_
 * @param {string[]} keywords Keywords to highlight_x000D_
 * @param {boolean} caseSensitive Differenciate between capital and lowercase letters_x000D_
 * @param {string} cls Class to apply to the highlighted keyword_x000D_
 */_x000D_
function highlight(elem, keywords, caseSensitive = false, cls = 'highlight') {_x000D_
  const flags = caseSensitive ? 'gi' : 'g';_x000D_
  // Sort longer matches first to avoid_x000D_
  // highlighting keywords within keywords._x000D_
  keywords.sort((a, b) => b.length - a.length);_x000D_
  Array.from(elem.childNodes).forEach(child => {_x000D_
    const keywordRegex = RegExp(keywords.join('|'), flags);_x000D_
    if (child.nodeType !== 3) { // not a text node_x000D_
      highlight(child, keywords, caseSensitive, cls);_x000D_
    } else if (keywordRegex.test(child.textContent)) {_x000D_
      const frag = document.createDocumentFragment();_x000D_
      let lastIdx = 0;_x000D_
      child.textContent.replace(keywordRegex, (match, idx) => {_x000D_
        const part = document.createTextNode(child.textContent.slice(lastIdx, idx));_x000D_
        const highlighted = document.createElement('span');_x000D_
        highlighted.textContent = match;_x000D_
        highlighted.classList.add(cls);_x000D_
        frag.appendChild(part);_x000D_
        frag.appendChild(highlighted);_x000D_
        lastIdx = idx + match.length;_x000D_
      });_x000D_
      const end = document.createTextNode(child.textContent.slice(lastIdx));_x000D_
      frag.appendChild(end);_x000D_
      child.parentNode.replaceChild(frag, child);_x000D_
    }_x000D_
  });_x000D_
}_x000D_
_x000D_
// Highlight all keywords found in the page_x000D_
highlight(document.body, ['lorem', 'amet', 'autem']);
_x000D_
.highlight {_x000D_
  background: lightpink;_x000D_
}
_x000D_
<p>Hello world lorem ipsum dolor sit amet, consectetur adipisicing elit. Est vel accusantium totam, ipsum delectus et dignissimos mollitia!</p>_x000D_
<p>_x000D_
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Numquam, corporis._x000D_
  <small>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium autem voluptas perferendis dolores ducimus velit error voluptatem, qui rerum modi?</small>_x000D_
</p>
_x000D_
_x000D_
_x000D_

I would also recommend using something like escape-string-regexp if your keywords can have special characters that would need to be escaped in regexes:

const keywordRegex = RegExp(keywords.map(escapeRegexp).join('|')), flags);

Hide text using css

If the point is simply to make the text inside the element invisible, set the color attribute to have 0 opacity using a rgba value such as color:rgba(0,0,0,0); clean and simple.

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

You can do it using group by:

c_maxes = df.groupby(['A', 'B']).C.transform(max)
df = df.loc[df.C == c_maxes]

c_maxes is a Series of the maximum values of C in each group but which is of the same length and with the same index as df. If you haven't used .transform then printing c_maxes might be a good idea to see how it works.

Another approach using drop_duplicates would be

df.sort('C').drop_duplicates(subset=['A', 'B'], take_last=True)

Not sure which is more efficient but I guess the first approach as it doesn't involve sorting.

EDIT: From pandas 0.18 up the second solution would be

df.sort_values('C').drop_duplicates(subset=['A', 'B'], keep='last')

or, alternatively,

df.sort_values('C', ascending=False).drop_duplicates(subset=['A', 'B'])

In any case, the groupby solution seems to be significantly more performing:

%timeit -n 10 df.loc[df.groupby(['A', 'B']).C.max == df.C]
10 loops, best of 3: 25.7 ms per loop

%timeit -n 10 df.sort_values('C').drop_duplicates(subset=['A', 'B'], keep='last')
10 loops, best of 3: 101 ms per loop

Select element based on multiple classes

You mean two classes? "Chain" the selectors (no spaces between them):

.class1.class2 {
    /* style here */
}

This selects all elements with class1 that also have class2.

In your case:

li.left.ui-class-selector {

}

Official documentation : CSS2 class selectors.


As akamike points out a problem with this method in Internet Explorer 6 you might want to read this: Use double classes in IE6 CSS?

How can I find the first occurrence of a sub-string in a python string?

to implement this in algorithmic way, by not using any python inbuilt function . This can be implemented as

def find_pos(string,word):

    for i in range(len(string) - len(word)+1):
        if string[i:i+len(word)] == word:
            return i
    return 'Not Found'

string = "the dude is a cool dude"
word = 'dude1'
print(find_pos(string,word))
# output 4

Windows command prompt log to a file

First method

For Windows 7 and above users, Windows PowerShell give you this option. Users with windows version less than 7 can download PowerShell online and install it.

Steps:

  1. type PowerShell in search area and click on "Windows PowerShell"

  2. If you have a .bat (batch) file go to step 3 OR copy your commands to a file and save it with .bat extension (e.g. file.bat)

  3. run the .bat file with following command

    PS (location)> <path to bat file>/file.bat | Tee-Object -file log.txt

This will generate a log.txt file with all command prompt output in it. Advantage is that you can also the output on command prompt.

Second method

You can use file redirection (>, >>) as suggest by Bali C above.

I will recommend first method if you have lots of commands to run or a script to run. I will recommend last method if there is only few commands to run.

std::string to char*

Here is one more robust version from Protocol Buffer

char* string_as_array(string* str)
{
    return str->empty() ? NULL : &*str->begin();
}

// test codes
std::string mystr("you are here");
char* pstr = string_as_array(&mystr);
cout << pstr << endl; // you are here

Creating a JSON dynamically with each input value using jquery

same from above example - if you are just looking for json (not an array of object) just use

function getJsonDetails() {
      item = {}
      item ["token1"] = token1val;
      item ["token2"] = token1val;
      return item;
}
console.log(JSON.stringify(getJsonDetails()))

this output ll print as (a valid json)

{ 
   "token1":"samplevalue1",
   "token2":"samplevalue2"
}

Min width in window resizing

You can set min-width property of CSS for body tag. Since this property is not supported by IE6, you can write like:

body{
   min-width:1000px;        /* Suppose you want minimum width of 1000px */
   width: auto !important;  /* Firefox will set width as auto */
   width:1000px;            /* As IE6 ignores !important it will set width as 1000px; */
}

Or:

body{
   min-width:1000px; // Suppose you want minimum width of 1000px
   _width: expression( document.body.clientWidth > 1000 ? "1000px" : "auto" ); /* sets max-width for IE6 */
}

Android: ScrollView vs NestedScrollView

NestedScrollView is just like ScrollView, but in NestedScrollView we can put other scrolling views as child of it, e.g. RecyclerView.

But if we put RecyclerView inside NestedScrollView, RecyclerView's smooth scrolling is disturbed. So to bring back smooth scrolling there's trick:

ViewCompat.setNestedScrollingEnabled(recyclerView, false);

put above line after setting adapter for recyclerView.

How to view instagram profile picture in full-size?

replace "150x150" with 720x720 and remove /vp/ from the link.it should work.

MySQL: @variable vs. variable. What's the difference?

@variable is very useful if calling stored procedures from an application written in Java , Python etc. There are ocassions where variable values are created in the first call and needed in functions of subsequent calls.

Side-note on PL/SQL (Oracle)

The advantage can be seen in Oracle PL/SQL where these variables have 3 different scopes:

  • Function variable for which the scope ends when function exits.
  • Package body variables defined at the top of package and outside all functions whose scope is the session and visibility is package.
  • Package variable whose variable is session and visibility is global.

My Experience in PL/SQL

I have developed an architecture in which the complete code is written in PL/SQL. These are called from a middle-ware written in Java. There are two types of middle-ware. One to cater calls from a client which is also written in Java. The other other one to cater for calls from a browser. The client facility is implemented 100 percent in JavaScript. A command set is used instead of HTML and JavaScript for writing application in PL/SQL.

I have been looking for the same facility to port the codes written in PL/SQL to another database. The nearest one I have found is Postgres. But all the variables have function scope.

Opinion towards @ in MySQL

I am happy to see that at least this @ facility is there in MySQL. I don't think Oracle will build same facility available in PL/SQL to MySQL stored procedures since it may affect the sales of Oracle database.

jQuery datepicker set selected date, on the fly

In Html you can add your input field with a date picker like this

<input class="form-control date-picker fromDates" id="myDate" type="text">

and then in java script, initialize your datepicker and set your value to the date like this,

$('.fromDates').datepicker({
                maxDate: '0',
                dateFormat: "dd/mm/yy",
                changeYear: true,
                changeMonth: true,
                yearRange: "-100:+0"
            });

var myDateVal = moment('${value}').format('DD/MM/YYYY');
$('#myDate').datepicker().datepicker('setDate', myDateVal );

(In here fromdate attribute shows the previous dates of the current date)

Adobe Acrobat Pro make all pages the same dimension

The above works,(having an original document with mixed pages of 11' and 16' wide). However auto rotate needs to be off otherwise landscape pages are saved with page white top and bottom, so dont work in full screen view.

Solution is to re open the new PDF in acrobat and crop the first image (carefully to avoid white border), then select page range i.e. all, this then applies to all pages. job done !

Boto3 to download all files from a S3 Bucket

I have the same needs and created the following function that download recursively the files.

The directories are created locally only if they contain files.

import boto3
import os

def download_dir(client, resource, dist, local='/tmp', bucket='your_bucket'):
    paginator = client.get_paginator('list_objects')
    for result in paginator.paginate(Bucket=bucket, Delimiter='/', Prefix=dist):
        if result.get('CommonPrefixes') is not None:
            for subdir in result.get('CommonPrefixes'):
                download_dir(client, resource, subdir.get('Prefix'), local, bucket)
        for file in result.get('Contents', []):
            dest_pathname = os.path.join(local, file.get('Key'))
            if not os.path.exists(os.path.dirname(dest_pathname)):
                os.makedirs(os.path.dirname(dest_pathname))
            resource.meta.client.download_file(bucket, file.get('Key'), dest_pathname)

The function is called that way:

def _start():
    client = boto3.client('s3')
    resource = boto3.resource('s3')
    download_dir(client, resource, 'clientconf/', '/tmp', bucket='my-bucket')

A good Sorted List for Java

Depending on how you're using the list, it may be worth it to use a TreeSet and then use the toArray() method at the end. I had a case where I needed a sorted list, and I found that the TreeSet + toArray() was much faster than adding to an array and merge sorting at the end.

Installing Java 7 (Oracle) in Debian via apt-get

Managed to get answer after do some google..

echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer

Where does Console.WriteLine go in ASP.NET?

The TraceContext object in ASP.NET writes to the DefaultTraceListener which outputs to the host process’ standard output. Rather than using Console.Write(), if you use Trace.Write, output will go to the standard output of the process.

You could use the System.Diagnostics.Process object to get the ASP.NET process for your site and monitor standard output using the OutputDataRecieved event.

How can I combine flexbox and vertical scroll in a full-height app?

The current spec says this regarding flex: 1 1 auto:

Sizes the item based on the width/height properties, but makes them fully flexible, so that they absorb any free space along the main axis. If all items are either flex: auto, flex: initial, or flex: none, any positive free space after the items have been sized will be distributed evenly to the items with flex: auto.

http://www.w3.org/TR/2012/CR-css3-flexbox-20120918/#flex-common

It sounds to me like if you say an element is 100px tall, it is treated more like a "suggested" size, not an absolute. Because it is allowed to shrink and grow, it takes up as much space as its allowed to. That's why adding this line to your "main" element works: height: 0 (or any other smallish number).

plot legends without border and with white background

As documented in ?legend you do this like so:

plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")
points(1:10,1:10)

enter image description here

Line breaks are achieved with the new line character \n. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.

Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).

How to convert current date into string in java?

// On the form: dow mon dd hh:mm:ss zzz yyyy
new Date().toString();

How to get two or more commands together into a batch file

To get a user Input :

set /p pathName=Enter The Value:%=%
@echo %pathName%

enter image description here

p.s. this is also valid :

set /p pathName=Enter The Value:

Why use @PostConstruct?

If your class performs all of its initialization in the constructor, then @PostConstruct is indeed redundant.

However, if your class has its dependencies injected using setter methods, then the class's constructor cannot fully initialize the object, and sometimes some initialization needs to be performed after all the setter methods have been called, hence the use case of @PostConstruct.

Is Task.Result the same as .GetAwaiter.GetResult()?

As already mentioned if you can use await. If you need to run the code synchronously like you mention .GetAwaiter().GetResult(), .Result or .Wait() is a risk for deadlocks as many have said in comments/answers. Since most of us like oneliners you can use these for .Net 4.5<

Acquiring a value via an async method:

var result = Task.Run(() => asyncGetValue()).Result;

Syncronously calling an async method

Task.Run(() => asyncMethod()).Wait();

No deadlock issues will occur due to the use of Task.Run.

Source:

https://stackoverflow.com/a/32429753/3850405

Update:

Could cause a deadlock if the calling thread is from the threadpool. The following happens: A new task is queued to the end of the queue, and the threadpool thread which would eventually execute the Task is blocked until the Task is executed.

Source:

https://medium.com/rubrikkgroup/understanding-async-avoiding-deadlocks-e41f8f2c6f5d

How to enable external request in IIS Express?

As a sidenote to this:

netsh http add urlacl url=http://vaidesg:8080/ user=everyone

This will only work on English versions of Windows. If you are using a localized version you have to replace "everyone" with something else, for example:

  • "Iedereen" when using a Dutch version
  • "Jeder" when using a German version
  • "Mindenki" when using a Hungarian version

Otherwise you will get an error (Create SDDL failed, Error: 1332)

Best way to encode text data for XML

If this is an ASP.NET app why not use Server.HtmlEncode() ?

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

Try to add like this:

<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>

instead of having

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

Stop setInterval call in JavaScript

If you set the return value of setInterval to a variable, you can use clearInterval to stop it.

var myTimer = setInterval(...);
clearInterval(myTimer);

How do I format a date with Dart?

This will work too:

DateTime today = new DateTime.now();
String dateSlug ="${today.year.toString()}-${today.month.toString().padLeft(2,'0')}-${today.day.toString().padLeft(2,'0')}";
print(dateSlug);

How to echo JSON in PHP

if you want to encode or decode an array from or to JSON you can use these functions

$myJSONString = json_encode($myArray);
$myArray = json_decode($myString);

json_encode will result in a JSON string, built from an (multi-dimensional) array. json_decode will result in an Array, built from a well formed JSON string

with json_decode you can take the results from the API and only output what you want, for example:

echo $myArray['payload']['ign'];

C# : "A first chance exception of type 'System.InvalidOperationException'"

The problem here is that your timer starts a thread and when it runs the callback function, the callback function ( updatelistview) is accessing controls on UI thread so this can not be done becuase of this

Height of an HTML select box (dropdown)

You can change the height of one. Don't use height="500"(Just an example number). Use the style. You can use <style>tag or just use this:

<!DOCTYPE html>
<html>
<body>
  <select id="option" style="height: 100px;">
    <option value="1">Option 1
    <option value="2">Option 2
  </select>
</body>
</html>

I spotlight the change:

  <select id="option" style="height: 100px;">

And even better...

style="height: 100px;">

You see that?

Please up vote if it's helpful!

Make a DIV fill an entire table cell

you can do it like that:

<td>
  <div style="width: 100%; position: relative; float: left;">inner div</div>
</td>

How can I find the last element in a List<>?

To get the last item of a collection use LastOrDefault() and Last() extension methods

var lastItem = integerList.LastOrDefault();

OR

var lastItem = integerList.Last();

Remeber to add using System.Linq;, or this method won't be available.

How to convert any date format to yyyy-MM-dd

Try this code:

 lblUDate.Text = DateTime.Parse(ds.Tables[0].Rows[0]["AppMstRealPaidTime"].ToString()).ToString("yyyy-MM-dd");

UIView with rounded corners and drop shadow?

I make some changes to the code of daniel.gindi

This is all you need to make it work.

+ (void)putView:(UIView*)view insideShadowWithColor:(UIColor*)color andBlur:         (CGFloat)blur andOffset:(CGSize)shadowOffset andOpacity:(CGFloat)shadowOpacity
{
    CGRect shadowFrame = view.frame;
    UIView * shadow = [[UIView alloc] initWithFrame:shadowFrame];
    shadow.backgroundColor = [UIColor redColor];
    shadow.userInteractionEnabled = YES; // Modify this if needed
    shadow.layer.shadowColor = color.CGColor;
    shadow.layer.shadowOffset = shadowOffset;
    shadow.layer.shadowRadius = blur;
    shadow.layer.cornerRadius = view.layer.cornerRadius;
    shadow.layer.masksToBounds = NO;
    shadow.clipsToBounds = NO;
    shadow.layer.shadowOpacity = shadowOpacity;
    [view.superview insertSubview:shadow belowSubview:view];
}

How do I Convert DateTime.now to UTC in Ruby?

Unfortunately, the DateTime class doesn't have the convenience methods available in the Time class to do this. You can convert any DateTime object into UTC like this:

d = DateTime.now
d.new_offset(Rational(0, 24))

You can switch back from UTC to localtime using:

d.new_offset(DateTime.now.offset)

where d is a DateTime object in UTC time. If you'd like these as convenience methods, then you can create them like this:

class DateTime
  def localtime
    new_offset(DateTime.now.offset)
  end

  def utc
    new_offset(Rational(0, 24))
  end
end

You can see this in action in the following irb session:

d = DateTime.now.new_offset(Rational(-4, 24))
 => #<DateTime: 106105391484260677/43200000000,-1/6,2299161> 
1.8.7 :185 > d.to_s
 => "2012-08-03T15:42:48-04:00" 
1.8.7 :186 > d.localtime.to_s
 => "2012-08-03T12:42:48-07:00" 
1.8.7 :187 > d.utc.to_s
 => "2012-08-03T19:42:48+00:00" 

As you can see above, the initial DateTime object has a -04:00 offset (Eastern Time). I'm in Pacific Time with a -07:00 offset. Calling localtime as described previously properly converts the DateTime object into local time. Calling utc on the object properly converts it to a UTC offset.

Drop all tables command

I don't think you can drop all tables in one hit but you can do the following to get the commands:

select 'drop table ' || name || ';' from sqlite_master
    where type = 'table';

The output of this is a script that will drop the tables for you. For indexes, just replace table with index.

You can use other clauses in the where section to limit which tables or indexes are selected (such as "and name glob 'pax_*'" for those starting with "pax_").

You could combine the creation of this script with the running of it in a simple bash (or cmd.exe) script so there's only one command to run.

If you don't care about any of the information in the DB, I think you can just delete the file it's stored in off the hard disk - that's probably faster. I've never tested this but I can't see why it wouldn't work.

Linux command to translate DomainName to IP

You can use:

nslookup www.example.com

How to check if a database exists in SQL Server?

I like @Eduardo's answer and I liked the accepted answer. I like to get back a boolean from something like this, so I wrote it up for you guys.

CREATE FUNCTION dbo.DatabaseExists(@dbname nvarchar(128))
RETURNS bit
AS
BEGIN
    declare @result bit = 0 
    SELECT @result = CAST(
        CASE WHEN db_id(@dbname) is not null THEN 1 
        ELSE 0 
        END 
    AS BIT)
    return @result
END
GO

Now you can use it like this:

select [dbo].[DatabaseExists]('master') --returns 1
select [dbo].[DatabaseExists]('slave') --returns 0

What's causing my java.net.SocketException: Connection reset?

The javadoc for SocketException states that it is

Thrown to indicate that there is an error in the underlying protocol such as a TCP error

In your case it seems that the connection has been closed by the server end of the connection. This could be an issue with the request you are sending or an issue at their end.

To aid debugging you could look at using a tool such as Wireshark to view the actual network packets. Also, is there an alternative client to your Java code that you could use to test the web service? If this was successful it could indicate a bug in the Java code.

As you are using Commons HTTP Client have a look at the Common HTTP Client Logging Guide. This will tell you how to log the request at the HTTP level.

Centering brand logo in Bootstrap Navbar

The simplest way is css transform:

.navbar-brand {
  transform: translateX(-50%);
  left: 50%;
  position: absolute;
}

DEMO: http://codepen.io/candid/pen/dGPZvR

centered background logo bootstrap 3


This way also works with dynamically sized background images for the logo and allows us to utilize the text-hide class:

CSS:

.navbar-brand {
  background: url(http://disputebills.com/site/uploads/2015/10/dispute.png) center / contain no-repeat;
  transform: translateX(-50%);
  left: 50%;
  position: absolute;
  width: 200px; /* no height needed ... image will resize automagically */
}

HTML:

<a class="navbar-brand text-hide" href="http://disputebills.com">Brand Text
        </a>

We can also use flexbox though. However, using this method we'd have to move navbar-brand outside of navbar-header. This way is great though because we can now have image and text side by side:

bootstrap 3 logo centered

.brand-centered {
  display: flex;
  justify-content: center;
  position: absolute;
  width: 100%;
  left: 0;
  top: 0;
}
.navbar-brand {
  display: flex;
  align-items: center;
}

Demo: http://codepen.io/candid/pen/yeLZax

To only achieve these results on mobile simply wrap the above css inside a media query:

@media (max-width: 768px) {

}

Submit form with Enter key without submit button?

@JayGuilford's answer is a good one, but if you don't want a JS dependency, you could use a submit element and simply hide it using display: none;.

Ruby 'require' error: cannot load such file

you need to give the path. Atleast you should give the path from the current directory. It will work for sure. ./filename

Google Maps API: open url by clicking on marker

the previous answers didn't work out for me well. I had persisting problems by setting the marker. So i changed the code slightly.

   <!DOCTYPE html>
   <html>
   <head>
     <meta http-equiv="content-type" content="text/html; charset=ANSI" />
     <title>Google Maps Multiple Markers</title>
     <script src="http://maps.google.com/maps/api/js?sensor=false"
      type="text/javascript"></script>
   </head>
   <body>
     <div id="map" style="width: 1500px; height: 1000px;"></div>

     <script type="text/javascript">
       var locations = [
         ['Goettingen',  51.54128040000001,  9.915803500000038, 'http://www.google.de'],
         ['Kassel', 51.31271139999999,  9.479746100000057,0, 'http://www.stackoverflow.com'],
         ['Witzenhausen', 51.33996819999999,  9.855564299999969,0, 'www.http://developer.mozilla.org.de']

 ];

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 10,
 center: new google.maps.LatLng(51.54376, 9.910419999999931),
 mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();

var marker, i;

for (i = 0; i < locations.length; i++) {
  marker = new google.maps.Marker({
   position: new google.maps.LatLng(locations[i][1], locations[i][2]),
   map: map,
   url: locations[i][4]
  });

 google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
   return function() {
     infowindow.setContent(locations[i][0]);
     infowindow.open(map, marker);
   }
 })(marker, i));

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
   return function() {
     infowindow.setContent(locations[i][0]);
     infowindow.open(map, marker);
     window.location.href = this.url;
   }
 })(marker, i));

    }

     </script>
   </body>
   </html>

This way worked out for me! You can create Google Maps routing links from your Datebase to to use it as an interactive routing map.

import android packages cannot be resolved

May be you are using this checking :

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
}

To resolve this you need to import android.provider.DocumentsContract class.

To resolve this issue you'll need to set the build SDK version to 19 (4.4) or higher to have API level 19 symbols available while compiling.

First, use the SDK Manager to download API 19 if you don't have it yet. Then, configure your project to use API 19:

  • In Android Studio: File -> Project Structure -> General Settings -> Project SDK.
  • In Eclipse ADT: Project Properties -> Android -> Project Build Target

I found this answer from here

Thanks .

Close Form Button Event

Try this:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    // You may decide to prompt to user else just kill.
    Process.GetCurrentProcess().Goose();
} 

Minimum rights required to run a windows service as a domain account

Thanks for the links, Chris. I've often wondered about the specific effects of privileges like "BypassTraverseChecking" but never bothered to look them up.

I was having interesting problems getting a service to run and discovered that it didn't have access to it's files after the initial installation had been done by the administrator. I was thinking it needed something in addition to Logon As A Service until I found the file issue.

  1. Disabled simple file sharing.
  2. Temporarily made my service account an administrator.
  3. Used the service account to take ownership of the files.
  4. Remove service account from the administrators group.
  5. Reboot.

During Take Ownership, it was necessary to disable inheritance of permissions from the parent directories and apply permissions recursively down the tree.

Wasn't able to find a "give ownership" option to avoid making the service account an administrator temporarily, though.

Anyway, thought I'd post this in case anyone else was going down the same road I was looking for security policy issues when it was really just filesystem rights.

Javascript: Fetch DELETE and PUT requests

Ok, here is a fetch DELETE example too:

fetch('https://example.com/delete-item/' + id, {
  method: 'DELETE',
})
.then(res => res.text()) // or res.json()
.then(res => console.log(res))