Programs & Examples On #Web architecture

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

The query below will result in dd/mm/yy format.

select  LEFT(convert(varchar(10), @date, 103),6) + Right(Year(@date)+ 1,2)

Close Window from ViewModel

My proffered way is Declare event in ViewModel and use blend InvokeMethodAction as below.

Sample ViewModel

public class MainWindowViewModel : BindableBase, ICloseable
{
    public DelegateCommand SomeCommand { get; private set; }
    #region ICloseable Implementation
    public event EventHandler CloseRequested;        

    public void RaiseCloseNotification()
    {
        var handler = CloseRequested;
        if (handler != null)
        {
            handler.Invoke(this, EventArgs.Empty);
        }
    }
    #endregion

    public MainWindowViewModel()
    {
        SomeCommand = new DelegateCommand(() =>
        {
            //when you decide to close window
            RaiseCloseNotification();
        });
    }
}

I Closeable interface is as below but don't require to perform this action. ICloseable will help in creating generic view service, so if you construct view and ViewModel by dependency injection then what you can do is

internal interface ICloseable
{
    event EventHandler CloseRequested;
}

Use of ICloseable

var viewModel = new MainWindowViewModel();
        // As service is generic and don't know whether it can request close event
        var window = new Window() { Content = new MainView() };
        var closeable = viewModel as ICloseable;
        if (closeable != null)
        {
            closeable.CloseRequested += (s, e) => window.Close();
        }

And Below is Xaml, You can use this xaml even if you don't implement interface, it will only need your view model to raise CloseRquested.

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPFRx"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" 
xmlns:ViewModels="clr-namespace:WPFRx.ViewModels" x:Name="window" x:Class="WPFRx.MainWindow"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525" 
d:DataContext="{d:DesignInstance {x:Type ViewModels:MainWindowViewModel}}">

<i:Interaction.Triggers>
    <i:EventTrigger SourceObject="{Binding Mode=OneWay}" EventName="CloseRequested" >
        <ei:CallMethodAction TargetObject="{Binding ElementName=window}" MethodName="Close"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

<Grid>
    <Button Content="Some Content" Command="{Binding SomeCommand}" Width="100" Height="25"/>
</Grid>

PHP "pretty print" json_encode

PHP has JSON_PRETTY_PRINT option since 5.4.0 (release date 01-Mar-2012).

This should do the job:

$json = json_decode($string);
echo json_encode($json, JSON_PRETTY_PRINT);

See http://www.php.net/manual/en/function.json-encode.php

Note: Don't forget to echo "<pre>" before and "</pre>" after, if you're printing it in HTML to preserve formatting ;)

Does C# support multiple inheritance?

Multiple inheritance allows programmers to create classes that combine aspects of multiple classes and their corresponding hierarchies. For ex. the C++ allows you to inherit from more than one class

In C#, the classes are only allowed to inherit from a single parent class, which is called single inheritance. But you can use interfaces or a combination of one class and interface(s), where interface(s) should be followed by class name in the signature.

Ex:

Class FirstClass { }
Class SecondClass { }

interface X { }
interface Y { }

You can inherit like the following:

class NewClass : X, Y { } In the above code, the class "NewClass" is created from multiple interfaces.

class NewClass : FirstClass, X { } In the above code, the class "NewClass" is created from interface X and class "FirstClass".

How to insert multiple rows from array using CodeIgniter framework?

I have created this simple function which you guys can use easily. You will need to pass the table-name ($tbl), table-field ($insertFieldsArr) against your inserting data, data array ($arr).

insert_batch('table',array('field1','field2'),$dataArray);

    function insert_batch($tbl,$insertFieldsArr,$arr){ $sql = array(); 
    foreach( $arr as $row ) {
        $strVals='';
        $cnt=0;
        foreach($insertFieldsArr as $key=>$val){
            if(is_array($row)){
                $strVals.="'".mysql_real_escape_string($row[$cnt]).'\',';
            }
            else{
                $strVals.="'".mysql_real_escape_string($row).'\',';
            }
            $cnt++;
        }
        $strVals=rtrim($strVals,',');
        $sql[] = '('.$strVals.')';
    }

    $fields=implode(',',$insertFieldsArr);
    mysql_query('INSERT INTO `'.$tbl.'` ('.$fields.') VALUES '.implode(',', $sql));
}

How to update a single library with Composer?

You can use the following command to update any module with its dependencies

composer update vendor-name/module-name --with-dependencies

Xpath for href element

have you tried:

//a[@id='oldcontent']/u[text()='Re-Call']

Can I use return value of INSERT...RETURNING in another INSERT?

The best practice for this situation. Use RETURNING … INTO.

INSERT INTO teams VALUES (...) RETURNING id INTO last_id;

Note this is for PLPGSQL

JSON library for C#

To answer your first question, Microsoft does ship a DataContractJsonSerializer: see msdn How to: Serialize and Deserialize JSON Data

Table border left and bottom

Give a class .border-lb and give this CSS

.border-lb {border: 1px solid #ccc; border-width: 0 0 1px 1px;}

And the HTML

<table width="770">
  <tr>
    <td class="border-lb">picture (border only to the left and bottom ) </td>
    <td>text</td>
  </tr>
  <tr>
    <td>text</td>
    <td class="border-lb">picture (border only to the left and bottom) </td>
  </tr>
</table>

Screenshot

Fiddle: http://jsfiddle.net/FXMVL/

Using SQL LIKE and IN together

I tried another way

Say the table has values


    1   M510
    2   M615
    3   M515
    4   M612
    5   M510MM
    6   M615NN
    7   M515OO
    8   M612PP
    9   A
    10  B
    11  C
    12  D

Here cols 1 to 8 are valid while the rest of them are invalid


  SELECT COL_VAL
    FROM SO_LIKE_TABLE SLT
   WHERE (SELECT DECODE(SUM(CASE
                              WHEN INSTR(SLT.COL_VAL, COLUMN_VALUE) > 0 THEN
                               1
                              ELSE
                               0
                            END),
                        0,
                        'FALSE',
                        'TRUE')
            FROM TABLE(SYS.DBMS_DEBUG_VC2COLl('M510', 'M615', 'M515', 'M612'))) =
         'TRUE'

What I have done is using the INSTR function, I have tried to find is the value in table matches with any of the values as input. In case it does, it will return it's index, i.e. greater than ZERO. In case the table's value does not match with any of the input, then it will return ZERO. This index I have added up, to indicate successful match.

It seems to be working.

Hope it helps.

json_decode to array

According to the PHP Documentation json_decode function has a parameter named assoc which convert the returned objects into associative arrays

 mixed json_decode ( string $json [, bool $assoc = FALSE ] )

Since assoc parameter is FALSE by default, You have to set this value to TRUE in order to retrieve an array.

Examine the below code for an example implication:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));

which outputs:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

Service has zero application (non-infrastructure) endpoints

As another clue, that indeed fixed this issue in my case.

I'm migrating some WCF services from a console application (that configures in code few WCF services) to an Azure WebRole to publish them in Azure. Every time I add a new service VS edits my web.config and adds this line:

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true">

Well, with all the advices and answers above I couldn't make it work until I removed all the attributes in the serviceHostingEnvironment element. As you can see I'm not a WCF rockstar but I made it to work with the first Service just by configuring it as:

<service name="FirstService" behaviorConfiguration="metadataBehavior">
                <endpoint address=""
                 binding="wsHttpBinding"
                 bindingConfiguration="WSHttpBinding_WcfServicesBinding"
                 contract="IFirstService" />

            </service>

but when I added the second Service it stoped working and I realized that those attributes where there again.

I hope it saves you time.

Retrieve CPU usage and memory usage of a single process on Linux?

As commented in caf's answer above, ps and in some cases pidstat will give you the lifetime average of the pCPU. To get more accurate results use top. If you need to run top once you can run:

top -b -n 1 -p <PID>

or for process only data and header:

top -b -n 1 -p <PID> | tail -3 | head -2

without headers:

top -b -n 1 -p <PID> | tail -2 | head -1

Prevent Caching in ASP.NET MVC for specific actions using an attribute

For MVC6 (DNX), there is no System.Web.OutputCacheAttribute

Note: when you set NoStore Duration parameter is not considered. It is possible to set an initial duration for first registration and override this with custom attributes.

But we have Microsoft.AspNet.Mvc.Filters.ResponseCacheFilter

 public void ConfigureServices(IServiceCollection services)
        ...
        services.AddMvc(config=>
        {
            config.Filters.Add(
                 new ResponseCacheFilter(
                    new CacheProfile() { 
                      NoStore=true
                     }));
        }
        ...
       )

It is possible to override initial filter with a custom attribute

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public sealed class NoCacheAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            var filter=filterContext.Filters.Where(t => t.GetType() == typeof(ResponseCacheFilter)).FirstOrDefault();
            if (filter != null)
            {
                ResponseCacheFilter f = (ResponseCacheFilter)filter;
                f.NoStore = true;
                //f.Duration = 0;
            }

            base.OnResultExecuting(filterContext);
        }
    }

Here is a use case

    [NoCache]
    [HttpGet]
    public JsonResult Get()
    {            
        return Json(new DateTime());
    }

MySQL, Concatenate two columns

In query, CONCAT_WS() function.

This function not only add multiple string values and makes them a single string value. It also let you define separator ( ” “, ” , “, ” – “,” _ “, etc.).

Syntax –

CONCAT_WS( SEPERATOR, column1, column2, ... )

Example

SELECT 
topic, 
CONCAT_WS( " ", subject, year ) AS subject_year 
FROM table

How can I write maven build to add resources to classpath?

A cleaner alternative of putting your config file into a subfolder of src/main/resources would be to enhance your classpath locations. This is extremely easy to do with Maven.

For instance, place your property file in a new folder src/main/config, and add the following to your pom:

 <build>
    <resources>
        <resource>
            <directory>src/main/config</directory>
        </resource>
    </resources>
 </build>

From now, every files files under src/main/config is considered as part of your classpath (note that you can exclude some of them from the final jar if needed: just add in the build section:

    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>my-config.properties</exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>

so that my-config.properties can be found in your classpath when you run your app from your IDE, but will remain external from your jar in your final distribution).

How to "select distinct" across multiple data frame columns in pandas?

You can use the drop_duplicates method to get the unique rows in a DataFrame:

In [29]: df = pd.DataFrame({'a':[1,2,1,2], 'b':[3,4,3,5]})

In [30]: df
Out[30]:
   a  b
0  1  3
1  2  4
2  1  3
3  2  5

In [32]: df.drop_duplicates()
Out[32]:
   a  b
0  1  3
1  2  4
3  2  5

You can also provide the subset keyword argument if you only want to use certain columns to determine uniqueness. See the docstring.

How to read Excel cell having Date with Apache POI?

NOTE: HSSFDateUtil is deprecated

If you know which cell i.e. column position say 0 in each row is going to be a date, you can go for row.getCell(0).getDateCellValue() directly.
http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFCell.html#getDateCellValue()

UPDATE: Here is an example - you can apply this in your switch case code above. I am checking and printing the Numeric as well as Date value. In this case the first column in my sheet has dates, hence I use row.getCell(0).

You can use the if (HSSFDateUtil.isCellDateFormatted .. code block directly in your switch case.

if (row.getCell(0).getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
    System.out.println ("Row No.: " + row.getRowNum ()+ " " +
        row.getCell(0).getNumericCellValue());

    if (HSSFDateUtil.isCellDateFormatted(row.getCell(0))) {
        System.out.println ("Row No.: " + row.getRowNum ()+ " " + 
            row.getCell(0).getDateCellValue());
    }
}

The output is

Row No.: 0 39281.0
Row No.: 0 Wed Jul 18 00:00:00 IST 2007
Row No.: 1 39491.0
Row No.: 1 Wed Feb 13 00:00:00 IST 2008
Row No.: 2 39311.0
Row No.: 2 Fri Aug 17 00:00:00 IST 2007

Array.sort() doesn't sort numbers correctly

try this:

a = new Array();
a.push(10);
a.push(60);
a.push(20);
a.push(30);
a.push(100);
a.sort(Test)

document.write(a);


function Test(a,b)
{
    return a > b ? true : false;
}

What does numpy.random.seed(0) do?

As noted, numpy.random.seed(0) sets the random seed to 0, so the pseudo random numbers you get from random will start from the same point. This can be good for debuging in some cases. HOWEVER, after some reading, this seems to be the wrong way to go at it, if you have threads because it is not thread safe.

from differences-between-numpy-random-and-random-random-in-python:

For numpy.random.seed(), the main difficulty is that it is not thread-safe - that is, it's not safe to use if you have many different threads of execution, because it's not guaranteed to work if two different threads are executing the function at the same time. If you're not using threads, and if you can reasonably expect that you won't need to rewrite your program this way in the future, numpy.random.seed() should be fine for testing purposes. If there's any reason to suspect that you may need threads in the future, it's much safer in the long run to do as suggested, and to make a local instance of the numpy.random.Random class. As far as I can tell, random.random.seed() is thread-safe (or at least, I haven't found any evidence to the contrary).

example of how to go about this:

from numpy.random import RandomState
prng = RandomState()
print prng.permutation(10)
prng = RandomState()
print prng.permutation(10)
prng = RandomState(42)
print prng.permutation(10)
prng = RandomState(42)
print prng.permutation(10)

may give:

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

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

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

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

Lastly, note that there might be cases where initializing to 0 (as opposed to a seed that has not all bits 0) may result to non-uniform distributions for some few first iterations because of the way xor works, but this depends on the algorithm, and is beyond my current worries and the scope of this question.

implement time delay in c

system("timeout /t 60"); // waits 60s. this is only for windows vista,7,8
system("ping -n 60 127.0.0.1 >nul"); // waits 60s. for all windows

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

For Single valued associations, i.e.-One-to-One and Many-to-One:-
Default Lazy=proxy
Proxy lazy loading:- This implies a proxy object of your associated entity is loaded. This means that only the id connecting the two entities is loaded for the proxy object of associated entity.
Eg: A and B are two entities with Many to one association. ie: There may be multiple A's for every B. Every object of A will contain a reference of B.
`

public class A{
    int aid;
    //some other A parameters;
    B b;
}
public class B{
    int bid;
     //some other B parameters;
}

`
The relation A will contain columns(aid,bid,...other columns of entity A).
The relation B will contain columns(bid,...other columns of entity B)

Proxy implies when A is fetched, only id is fetched for B and stored into a proxy object of B which contains only id. Proxy object of B is a an object of a proxy-class which is a subclass of B with only minimal fields. Since bid is already part of relation A, it is not necessary to fire a query to get bid from the relation B. Other attributes of entity B are lazily loaded only when a field other than bid is accessed.

For Collections, i.e.-Many-to-Many and One-to-Many:-
Default Lazy=true


Please also note that the fetch strategy(select,join etc) can override lazy. ie: If lazy='true' and fetch='join', fetching of A will also fetch B or Bs(In case of collections). You can get the reason if you think about it.
Default fetch for single valued association is "join".
Default fetch for collections is "select". Please verify the last two lines. I have deduced that logically.

Setting size for icon in CSS

Funnily enough, adjusting the padding seems to do it.

_x000D_
_x000D_
.arrow {
  border: solid rgb(2, 0, 0);
  border-width: 0 3px 3px 0;
  display: inline-block;
}

.first{
  padding: 2vh;
}

.second{
  padding: 4vh;
}

.left {
    transform: rotate(135deg);
    -webkit-transform: rotate(135deg);
 }
_x000D_
<i class="arrow first left"></i>
<i class="arrow second left"></i>
_x000D_
_x000D_
_x000D_

Splitting a continuous variable into equal sized groups

equal_freq from funModeling takes a vector and the number of bins (based on equal frequency):

das <- data.frame(anim=1:15,
                  wt=c(181,179,180.5,201,201.5,245,246.4,
                       189.3,301,354,369,205,199,394,231.3))

das$wt_bin=funModeling::equal_freq(das$wt, 3)

table(das$wt_bin)

#[179,201) [201,246) [246,394] 
#        5         5         5 

Check folder size in Bash

if you just want to see the folder size and not the sub-folders, you can use:

du -hs /path/to/directory

Update:

You should know that du shows the used disk space; and not the file size.

You can use --apparent-size if u want to see sum of actual file sizes.

--apparent-size
      print  apparent  sizes,  rather  than  disk  usage; although the apparent size is usually smaller, it may be larger due to holes in ('sparse')
      files, internal fragmentation, indirect blocks, and the like

And of course theres no need for -h (Human readable) option inside a script.

Instead You can use -b for easier comparison inside script.

But You should Note that -b applies --apparent-size by itself. And it might not be what you need.

-b, --bytes
      equivalent to '--apparent-size --block-size=1'

so I think, you should use --block-size or -B

#!/bin/bash
SIZE=$(du -B 1 /path/to/directory | cut -f 1 -d "   ")    
# 2GB = 2147483648 bytes
# 10GB = 10737418240 bytes
if [[ $SIZE -gt 2147483648 && $SIZE -lt 10737418240 ]]; then
    echo 'Condition returned True'
fi

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

I had met a similar problem, after i add a scope property of servlet dependency in pom.xml

 <dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

Then it was ok . maybe that will help you.

Set Focus After Last Character in Text Box

You should code like this.

var num = $('#Number').val();        
$('#Number').focus().val('').val(num);    

Making text bold using attributed string in swift

Super easy way to do this.

    let text = "This string is having multiple font"
    let attributedText = 
    NSMutableAttributedString.getAttributedString(fromString: text)

    attributedText.apply(font: UIFont.boldSystemFont(ofSize: 24), subString: 
    "This")

    attributedText.apply(font: UIFont.boldSystemFont(ofSize: 24), onRange: 
    NSMakeRange(5, 6))

For more detail click here: https://github.com/iOSTechHub/AttributedString

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

The issue is related to the DockerFile creation procedure.

In order to work, open cmd, cd to the directory of interest and type:

abc>DockerFile

This will create a file called DockerFile inside your folder.

Now type:

notepad DockerFile 

This will open the DockerFile file in notepad and you will have to copy/paste the standard code provided.

Save the file and now, finally, build your image with Docker typing:

docker build -t docker-whale . 

This is working for me and I hope it helps others

Get Request and Session Parameters and Attributes from JSF pages

You can get a request parameter id using the expression:

<h:outputText value="#{param['id']}" />
  • param—An immutable Map of the request parameters for this request, keyed by parameter name. Only the first value for each parameter name is included.
  • sessionScope—A Map of the session attributes for this request, keyed by attribute name.

Section 5.3.1.2 of the JSF 1.0 specification defines the objects that must be resolved by the variable resolver.

getting the screen density programmatically in android?

Blundell's answer as a static helper method:

private static String getDensityName(Context context) {
    float density = context.getResources().getDisplayMetrics().density;
    if (density >= 4.0) {
        return "xxxhdpi";
    }
    if (density >= 3.0) {
        return "xxhdpi";
    }
    if (density >= 2.0) {
        return "xhdpi";
    }
    if (density >= 1.5) {
        return "hdpi";
    }
    if (density >= 1.0) {
        return "mdpi";
    }
    return "ldpi";
}

Jquery - How to make $.post() use contentType=application/json?

we can change Content-type like this in $.post

$.post(url,data, function (data, status, xhr) { xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");});

Split string into string array of single characters

Simple!!
one line:

 var res = test.Select(x => new string(x, 1)).ToArray();

Can HTTP POST be limitless?

Quite amazing how all answers talk about IIS, as if that were the only web server that mattered. Even back in 2010 when the question was asked, Apache had between 60% and 70% of the market share. Anyway,

  • The HTTP protocol does not specify a limit.
  • The POST method allows sending far more data than the GET method, which is limited by the URL length - about 2KB.
  • The maximum POST request body size is configured on the HTTP server and typically ranges from
    1MB to 2GB
  • The HTTP client (browser or other user agent) can have its own limitations. Therefore, the maximum POST body request size is min(serverMaximumSize, clientMaximumSize).

Here are the POST body sizes for some of the more popular HTTP servers:

How to make a machine trust a self-signed Java application

I had the same problem, but i solved it from Java Control Panel-->Security-->SecurityLevel:MEDIUM. Just so, no Manage certificates, imports ,exports etc..

How can I import data into mysql database via mysql workbench?

  1. Open Connetion
  2. Select "Administration" tab
  3. Click on Data import

Upload sql file

enter image description here

Make sure to select your database in this award winning GUI:

enter image description here

MVC which submit button has been pressed

// Buttons
<input name="submit" type="submit" id="submit" value="Save" />
<input name="process" type="submit" id="process" value="Process" />

// Controller
[HttpPost]
public ActionResult index(FormCollection collection)
{
    string submitType = "unknown";

    if(collection["submit"] != null)
    {
        submitType = "submit";
    }
    else if (collection["process"] != null)
    {
        submitType = "process";
    }

} // End of the index method

Output (echo/print) everything from a PHP Array

This is a little function I use all the time its handy if you are debugging arrays. Its pretty much the same thing Darryl and Karim posted. I just added a parameter title so you have some debug info as what array you are printing. it also checks if you have supplied it with a valid array and lets you know if you didn't.

function print_array($title,$array){

        if(is_array($array)){

            echo $title."<br/>".
            "||---------------------------------||<br/>".
            "<pre>";
            print_r($array); 
            echo "</pre>".
            "END ".$title."<br/>".
            "||---------------------------------||<br/>";

        }else{
             echo $title." is not an array.";
        }
}

Basic usage:

//your array
$array = array('cat','dog','bird','mouse','fish','gerbil');
//usage
print_array("PETS", $array);

Results:

PETS
||---------------------------------||

Array
(
    [0] => cat
    [1] => dog
    [2] => bird
    [3] => mouse
    [4] => fish
    [5] => gerbil
)

END PETS
||---------------------------------||

How to change file encoding in NetBeans?

In NetBeans model all project files should have the same encoding. The answer is that you can't do that in Netbeans.

If you are working in Netbeans you should consider to convert all files to a single encoding using other tools.

My httpd.conf is empty

The /etc/apache2/httpd.conf is empty in Ubuntu, because the Apache configuration resides in /etc/apache2/apache2.conf!

“httpd.conf is for user options.” No it isn't, it's there for historic reasons.

Using Apache server, all user options should go into a new *.conf-file inside /etc/apache2/conf.d/. This method should be "update-safe", as httpd.conf or apache2.conf may get overwritten on the next server update.

Inside /etc/apache2/apache2.conf, you will find the following line, which includes those files:

# Include generic snippets of statements
Include conf.d/

As of Apache 2.4+ the user configuration directory is /etc/apache2/conf-available/. Use a2enconf FILENAME_WITHOUT_SUFFIX to enable the new configuration file or manually create a symlink in /etc/apache2/conf-enabled/. Be aware that as of Apache 2.4 the configuration files must have the suffix .conf (e.g. conf-available/my-settings.conf);

How to merge many PDF files into a single one?

You can use http://www.mergepdf.net/ for example

Or:

PDFTK http://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/

If you are NOT on Ubuntu and you have the same problem (and you wanted to start a new topic on SO and SO suggested to have a look at this question) you can also do it like this:

Things You'll Need:

* Full Version of Adobe Acrobat
  1. Open all the .pdf files you wish to merge. These can be minimized on your desktop as individual tabs.

  2. Pull up what you wish to be the first page of your merged document.

  3. Click the 'Combine Files' icon on the top left portion of the screen.

  4. The 'Combine Files' window that pops up is divided into three sections. The first section is titled, 'Choose the files you wish to combine'. Select the 'Add Open Files' option.

  5. Select the other open .pdf documents on your desktop when prompted.

  6. Rearrange the documents as you wish in the second window, titled, 'Arrange the files in the order you want them to appear in the new PDF'

  7. The final window, titled, 'Choose a file size and conversion setting' allows you to control the size of your merged PDF document. Consider the purpose of your new document. If its to be sent as an e-mail attachment, use a low size setting. If the PDF contains images or is to be used for presentation, choose a high setting. When finished, select 'Next'.

  8. A final choice: choose between either a single PDF document, or a PDF package, which comes with the option of creating a specialized cover sheet. When finished, hit 'Create', and save to your preferred location.

    • Tips & Warnings

Double check the PDF documents prior to merging to make sure all pertinent information is included. Its much easier to re-create a single PDF page than a multi-page document.

Style jQuery autocomplete in a Bootstrap input field

The gap between the (bootstrap) input field and jquery-ui autocompleter seem to occur only in jQuery versions >= 3.2

When using jQuery version 3.1.1 it seem to not happen.

Possible reason is the notable update in v3.2.0 related to a bug fix on .width() and .height(). Check out the jQuery release notes for further details: v3.2.0 / v3.1.1

Bootstrap version 3.4.1 and jquery-ui version 1.12.0 used

MySQL: Get column name or alias from query

I think this should do what you need (builds on the answer above) . I am sure theres a more pythony way to write it, but you should get the general idea.

cursor.execute(query)
columns = cursor.description
result = []
for value in cursor.fetchall():
    tmp = {}
    for (index,column) in enumerate(value):
        tmp[columns[index][0]] = column
    result.append(tmp)
pprint.pprint(result)

stop all instances of node.js server

Windows Machine:

Need to kill a Node.js server, and you don't have any other Node processes running, you can tell your machine to kill all processes named node.exe. That would look like this:

taskkill /im node.exe

And if the processes still persist, you can force the processes to terminate by adding the /f flag:

taskkill /f /im node.exe

If you need more fine-grained control and need to only kill a server that is running on a specific port, you can use netstat to find the process ID, then send a kill signal to it. So in your case, where the port is 8080, you could run the following:

C:\>netstat -ano | find "LISTENING" | find "8080"

The fifth column of the output is the process ID:

  TCP    0.0.0.0:8080           0.0.0.0:0              LISTENING       14828
  TCP    [::]:8080              [::]:0                 LISTENING       14828

You could then kill the process with taskkill /pid 14828. If the process refuses to exit, then just add the /f (force) parameter to the command.


Linux machine:

The process is almost identical. You could either kill all Node processes running on the machine (use -$SIGNAL if SIGKILL is insufficient):

killall node

Or also using netstat, you can find the PID of a process listening on a port:

$ netstat -nlp | grep :8080
tcp        0      0 0.0.0.0:8080         0.0.0.0:*                   LISTEN      1073/node

The process ID in this case is the number before the process name in the sixth column, which you could then pass to the kill command:

$ kill 1073

If the process refuses to exit, then just use the -9 flag, which is a SIGTERM and cannot be ignored:

$ kill -9 1073

Error in plot.window(...) : need finite 'xlim' values

I had the same problem. I solve it when I convert string to factor. In your case, check the class of variable and check if they are numeric and 'train and test' should be factor.

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

I just finished setting up my XAMPP on the MAC and had the same trouble. I just fixed it. It is not quite clear what OS you're using but you need to run the XAMPP security. You indicate you've done that, but here it is anyway for the MAC

sudo /Applications/XAMPP/xamppfiles/xampp security 

Set your password on the questions you get.

In you're phpmyadmin import the "create_tables.sql" .. Which can be found in the ./phpmyadmin/sql folder.

Next open the config.inc.php file inside the ./phpmyadmin folder.

$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = 'you_password';

Make sure to log out and log in to reflect the changes within phpmyadmin

jquery how to use multiple ajax calls one after the end of the other

You could also use jquery when and then functions. for example

 $.when( $.ajax( "test.aspx" ) ).then(function( data, textStatus, jqXHR ) {
  //another ajax call
});

https://api.jquery.com/jQuery.when/

Remove row lines in twitter bootstrap

This is what worked for me..

.table-no-border>thead>tr>th, 
.table-no-border>tbody>tr>th, 
.table-no-border>tfoot>tr>th, 
.table-no-border>thead>tr>td, 
.table-no-border>tbody>tr>td, 
.table-no-border>tfoot>tr>td,
.table-no-border>tbody,
.table-no-border>thead,
.table-no-border>tfoot{
  border-top: none !important; 
  border-bottom: none !important; 
}

Had to whip out the !important to make it stick.

Does Python have an argc argument?

In python a list knows its length, so you can just do len(sys.argv) to get the number of elements in argv.

Filter dict to contain only certain keys?

Given your original dictionary orig and the set of entries that you're interested in keys:

filtered = dict(zip(keys, [orig[k] for k in keys]))

which isn't as nice as delnan's answer, but should work in every Python version of interest. It is, however, fragile to each element of keys existing in your original dictionary.

Creating a div element inside a div element in javascript

Yes, you either need to do this onload or in a <script> tag after the closing </body> tag, when the lc element is already found in the document's DOM tree.

sqlplus how to find details of the currently connected database session

Try:

select * from v$session where sid = SYS_CONTEXT('USERENV','SID');

You might also be interested in this AskTom post

After seing your comment, you can do:

SELECT * FROM global_name;

How to check if a string in Python is in ASCII?

How about doing this?

import string

def isAscii(s):
    for c in s:
        if c not in string.ascii_letters:
            return False
    return True

How to skip to next iteration in jQuery.each() util?

Javascript sort of has the idea of 'truthiness' and 'falsiness'. If a variable has a value then, generally 9as you will see) it has 'truthiness' - null, or no value tends to 'falsiness'. The snippets below might help:

var temp1; 
if ( temp1 )...  // false

var temp2 = true;
if ( temp2 )...  // true

var temp3 = "";
if ( temp3 ).... // false

var temp4 = "hello world";
if ( temp4 )...  // true

Hopefully that helps?

Also, its worth checking out these videos from Douglas Crockford

update: thanks @cphpython for spotting the broken links - I've updated to point at working versions now

The Javascript language

Javascript - The Good Parts

What is The difference between ListBox and ListView

A ListView let you define a set of views for it and gives you a native way (WPF binding support) to control the display of ListView by using defined views.

Example:

XAML

<ListView ItemsSource="{Binding list}" Name="listv" MouseEnter="listv_MouseEnter" MouseLeave="listv_MouseLeave">
        <ListView.Resources>
            <GridView x:Key="one">
                <GridViewColumn Header="ID" >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding id}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="Name" >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding name}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
            <GridView x:Key="two">                    
                <GridViewColumn Header="Name" >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding name}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.Resources>
        <ListView.Style>
            <Style TargetType="ListView">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ViewType}" Value="1">
                        <Setter Property="View" Value="{StaticResource one}" />
                    </DataTrigger>
                </Style.Triggers>
                <Setter Property="View" Value="{StaticResource two}" />
            </Style>
        </ListView.Style>  

Code Behind:

private int viewType;

public int ViewType
{
    get { return viewType; }
    set 
    { 
        viewType = value;
        UpdateProperty("ViewType");
    }
}        

private void listv_MouseEnter(object sender, MouseEventArgs e)
{
    ViewType = 1;
}

private void listv_MouseLeave(object sender, MouseEventArgs e)
{
    ViewType = 2;
}

OUTPUT:

Normal View: View 2 in above XAML

Normal

MouseOver View: View 1 in above XAML

Mouse Over

If you try to achieve above in a ListBox, probably you'll end up writing a lot more code forControlTempalate/ItemTemplate of ListBox.

How to get all columns' names for all the tables in MySQL?

Similar to the answer posted by @suganya this doesn't directly answer the question but is a quicker alternative for a single table:

DESCRIBE column_name;

Batch file script to zip files

This is the correct syntax for archiving individual; folders in a batch as individual zipped files...

for /d %%X in (*) do "c:\Program Files\7-Zip\7z.exe" a -mx "%%X.zip" "%%X\*"

Matching a Forward Slash with a regex

You need to escape the / with a \.

/\//ig // matches /

Excel function to make SQL-like queries on worksheet data?

You can use Get External Data (dispite its name), located in the 'Data' tab of Excel 2010, to set up a connection in a workbook to query data from itself. Use From Other Sources From Microsoft Query to connect to Excel

Once set up you can use VBA to manipulate the connection to, among other thing, view and modify the SQL command that drives the query. This query does reference the in memory workbook, so doen't require a save to refresh the latest data.

Here's a quick Sub to demonstrate accessing the connection objects

Sub DemoConnection()
    Dim c As Connections
    Dim wb As Workbook
    Dim i As Long
    Dim strSQL As String

    Set wb = ActiveWorkbook
    Set c = wb.Connections
    For i = 1 To c.Count
        ' Reresh the data
        c(i).Refresh 
        ' view the SQL query
        strSQL = c(i).ODBCConnection.CommandText
        MsgBox strSQL
    Next
End Sub

Output data from all columns in a dataframe in pandas

There is too much data to be displayed on the screen, therefore a summary is displayed instead.

If you want to output the data anyway (it won't probably fit on a screen and does not look very well):

print paramdata.values

converts the dataframe to its numpy-array matrix representation.

paramdata.columns

stores the respective column names and

paramdata.index

stores the respective index (row names).

How can I remove or replace SVG content?

Setting the id attribute when appending the svg element can also let d3 select so remove() later on this element by id :

var svg = d3.select("theParentElement").append("svg")
.attr("id","the_SVG_ID")
.attr("width",...

...

d3.select("#the_SVG_ID").remove();

Cloning git repo causes error - Host key verification failed. fatal: The remote end hung up unexpectedly

The issue could be that Github isn't present in your ~/.ssh/known_hosts file.

Append GitHub to the list of authorized hosts:

ssh-keyscan -H github.com >> ~/.ssh/known_hosts

Side-by-side plots with ggplot2

One downside of the solutions based on grid.arrange is that they make it difficult to label the plots with letters (A, B, etc.), as most journals require.

I wrote the cowplot package to solve this (and a few other) issues, specifically the function plot_grid():

library(cowplot)

iris1 <- ggplot(iris, aes(x = Species, y = Sepal.Length)) +
  geom_boxplot() + theme_bw()

iris2 <- ggplot(iris, aes(x = Sepal.Length, fill = Species)) +
  geom_density(alpha = 0.7) + theme_bw() +
  theme(legend.position = c(0.8, 0.8))

plot_grid(iris1, iris2, labels = "AUTO")

enter image description here

The object that plot_grid() returns is another ggplot2 object, and you can save it with ggsave() as usual:

p <- plot_grid(iris1, iris2, labels = "AUTO")
ggsave("plot.pdf", p)

Alternatively, you can use the cowplot function save_plot(), which is a thin wrapper around ggsave() that makes it easy to get the correct dimensions for combined plots, e.g.:

p <- plot_grid(iris1, iris2, labels = "AUTO")
save_plot("plot.pdf", p, ncol = 2)

(The ncol = 2 argument tells save_plot() that there are two plots side-by-side, and save_plot() makes the saved image twice as wide.)

For a more in-depth description of how to arrange plots in a grid see this vignette. There is also a vignette explaining how to make plots with a shared legend.

One frequent point of confusion is that the cowplot package changes the default ggplot2 theme. The package behaves that way because it was originally written for internal lab uses, and we never use the default theme. If this causes problems, you can use one of the following three approaches to work around them:

1. Set the theme manually for every plot. I think it's good practice to always specify a particular theme for each plot, just like I did with + theme_bw() in the example above. If you specify a particular theme, the default theme doesn't matter.

2. Revert the default theme back to the ggplot2 default. You can do this with one line of code:

theme_set(theme_gray())

3. Call cowplot functions without attaching the package. You can also not call library(cowplot) or require(cowplot) and instead call cowplot functions by prepending cowplot::. E.g., the above example using the ggplot2 default theme would become:

## Commented out, we don't call this
# library(cowplot)

iris1 <- ggplot(iris, aes(x = Species, y = Sepal.Length)) +
  geom_boxplot()

iris2 <- ggplot(iris, aes(x = Sepal.Length, fill = Species)) +
  geom_density(alpha = 0.7) +
  theme(legend.position = c(0.8, 0.8))

cowplot::plot_grid(iris1, iris2, labels = "AUTO")

enter image description here

Updates:

  • As of cowplot 1.0, the default ggplot2 theme is not changed anymore.
  • As of ggplot2 3.0.0, plots can be labeled directly, see e.g. here.

How does Trello access the user's clipboard?

Disclosure: I wrote the code that Trello uses; the code below is the actual source code Trello uses to accomplish the clipboard trick.


We don't actually "access the user's clipboard", instead we help the user out a bit by selecting something useful when they press Ctrl+C.

Sounds like you've figured it out; we take advantage of the fact that when you want to hit Ctrl+C, you have to hit the Ctrl key first. When the Ctrl key is pressed, we pop in a textarea that contains the text we want to end up on the clipboard, and select all the text in it, so the selection is all set when the C key is hit. (Then we hide the textarea when the Ctrl key comes up.)

Specifically, Trello does this:

TrelloClipboard = new class
  constructor: ->
    @value = ""

    $(document).keydown (e) =>
      # Only do this if there's something to be put on the clipboard, and it
      # looks like they're starting a copy shortcut
      if !@value || !(e.ctrlKey || e.metaKey)
        return

      if $(e.target).is("input:visible,textarea:visible")
        return

      # Abort if it looks like they've selected some text (maybe they're trying
      # to copy out a bit of the description or something)
      if window.getSelection?()?.toString()
        return

      if document.selection?.createRange().text
        return

      _.defer =>
        $clipboardContainer = $("#clipboard-container")
        $clipboardContainer.empty().show()
        $("<textarea id='clipboard'></textarea>")
        .val(@value)
        .appendTo($clipboardContainer)
        .focus()
        .select()

    $(document).keyup (e) ->
      if $(e.target).is("#clipboard")
        $("#clipboard-container").empty().hide()

  set: (@value) ->

In the DOM we've got:

<div id="clipboard-container"><textarea id="clipboard"></textarea></div>

CSS for the clipboard stuff:

#clipboard-container {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 0px;
  height: 0px;
  z-index: 100;
  display: none;
  opacity: 0;
}
#clipboard {
  width: 1px;
  height: 1px;
  padding: 0px;
}

... and the CSS makes it so you can't actually see the textarea when it pops in ... but it's "visible" enough to copy from.

When you hover over a card, it calls

TrelloClipboard.set(cardUrl)

... so then the clipboard helper knows what to select when the Ctrl key is pressed.

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

add this at the top of file,

header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");

Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell

Some more numbers and explanations for the C version. Apparently noone did it during all those years. Remember to upvote this answer so it can get on top for everyone to see and learn.

Step One: Benchmark of the author's programs

Laptop Specifications:

  • CPU i3 M380 (931 MHz - maximum battery saving mode)
  • 4GB memory
  • Win7 64 bits
  • Microsoft Visual Studio 2012 Ultimate
  • Cygwin with gcc 4.9.3
  • Python 2.7.10

Commands:

compiling on VS x64 command prompt > `for /f %f in ('dir /b *.c') do cl /O2 /Ot /Ox %f -o %f_x64_vs2012.exe`
compiling on cygwin with gcc x64   > `for f in ./*.c; do gcc -m64 -O3 $f -o ${f}_x64_gcc.exe ; done`
time (unix tools) using cygwin > `for f in ./*.exe; do  echo "----------"; echo $f ; time $f ; done`

.

----------
$ time python ./original.py

real    2m17.748s
user    2m15.783s
sys     0m0.093s
----------
$ time ./original_x86_vs2012.exe

real    0m8.377s
user    0m0.015s
sys     0m0.000s
----------
$ time ./original_x64_vs2012.exe

real    0m8.408s
user    0m0.000s
sys     0m0.015s
----------
$ time ./original_x64_gcc.exe

real    0m20.951s
user    0m20.732s
sys     0m0.030s

Filenames are: integertype_architecture_compiler.exe

  • integertype is the same as the original program for now (more on that later)
  • architecture is x86 or x64 depending on the compiler settings
  • compiler is gcc or vs2012

Step Two: Investigate, Improve and Benchmark Again

VS is 250% faster than gcc. The two compilers should give a similar speed. Obviously, something is wrong with the code or the compiler options. Let's investigate!

The first point of interest is the integer types. Conversions can be expensive and consistency is important for better code generation & optimizations. All integers should be the same type.

It's a mixed mess of int and long right now. We're going to improve that. What type to use? The fastest. Gotta benchmark them'all!

----------
$ time ./int_x86_vs2012.exe

real    0m8.440s
user    0m0.016s
sys     0m0.015s
----------
$ time ./int_x64_vs2012.exe

real    0m8.408s
user    0m0.016s
sys     0m0.015s
----------
$ time ./int32_x86_vs2012.exe

real    0m8.408s
user    0m0.000s
sys     0m0.015s
----------
$ time ./int32_x64_vs2012.exe

real    0m8.362s
user    0m0.000s
sys     0m0.015s
----------
$ time ./int64_x86_vs2012.exe

real    0m18.112s
user    0m0.000s
sys     0m0.015s
----------
$ time ./int64_x64_vs2012.exe

real    0m18.611s
user    0m0.000s
sys     0m0.015s
----------
$ time ./long_x86_vs2012.exe

real    0m8.393s
user    0m0.015s
sys     0m0.000s
----------
$ time ./long_x64_vs2012.exe

real    0m8.440s
user    0m0.000s
sys     0m0.015s
----------
$ time ./uint32_x86_vs2012.exe

real    0m8.362s
user    0m0.000s
sys     0m0.015s
----------
$ time ./uint32_x64_vs2012.exe

real    0m8.393s
user    0m0.015s
sys     0m0.015s
----------
$ time ./uint64_x86_vs2012.exe

real    0m15.428s
user    0m0.000s
sys     0m0.015s
----------
$ time ./uint64_x64_vs2012.exe

real    0m15.725s
user    0m0.015s
sys     0m0.015s
----------
$ time ./int_x64_gcc.exe

real    0m8.531s
user    0m8.329s
sys     0m0.015s
----------
$ time ./int32_x64_gcc.exe

real    0m8.471s
user    0m8.345s
sys     0m0.000s
----------
$ time ./int64_x64_gcc.exe

real    0m20.264s
user    0m20.186s
sys     0m0.015s
----------
$ time ./long_x64_gcc.exe

real    0m20.935s
user    0m20.809s
sys     0m0.015s
----------
$ time ./uint32_x64_gcc.exe

real    0m8.393s
user    0m8.346s
sys     0m0.015s
----------
$ time ./uint64_x64_gcc.exe

real    0m16.973s
user    0m16.879s
sys     0m0.030s

Integer types are int long int32_t uint32_t int64_t and uint64_t from #include <stdint.h>

There are LOTS of integer types in C, plus some signed/unsigned to play with, plus the choice to compile as x86 or x64 (not to be confused with the actual integer size). That is a lot of versions to compile and run ^^

Step Three: Understanding the Numbers

Definitive conclusions:

  • 32 bits integers are ~200% faster than 64 bits equivalents
  • unsigned 64 bits integers are 25 % faster than signed 64 bits (Unfortunately, I have no explanation for that)

Trick question: "What are the sizes of int and long in C?"
The right answer is: The size of int and long in C are not well-defined!

From the C spec:

int is at least 32 bits
long is at least an int

From the gcc man page (-m32 and -m64 flags):

The 32-bit environment sets int, long and pointer to 32 bits and generates code that runs on any i386 system.
The 64-bit environment sets int to 32 bits and long and pointer to 64 bits and generates code for AMD’s x86-64 architecture.

From MSDN documentation (Data Type Ranges) https://msdn.microsoft.com/en-us/library/s3f49ktz%28v=vs.110%29.aspx :

int, 4 bytes, also knows as signed
long, 4 bytes, also knows as long int and signed long int

To Conclude This: Lessons Learned

  • 32 bits integers are faster than 64 bits integers.

  • Standard integers types are not well defined in C nor C++, they vary depending on compilers and architectures. When you need consistency and predictability, use the uint32_t integer family from #include <stdint.h>.

  • Speed issues solved. All other languages are back hundreds percent behind, C & C++ win again ! They always do. The next improvement will be multithreading using OpenMP :D

Android: Background Image Size (in Pixel) which Support All Devices

The following are the best dimensions for the app to run in all devices. For understanding multiple supporting screens you have to read http://developer.android.com/guide/practices/screens_support.html

xxxhdpi: 1280x1920 px
xxhdpi: 960x1600 px
xhdpi: 640x960 px
hdpi: 480x800 px
mdpi: 320x480 px
ldpi: 240x320 px

push() a two-dimensional array

You have to loop through all rows, and add the missing rows and columns. For the already existing rows, you loop from c to cols, for the new rows, first push an empty array to outer array, then loop from 0 to cols:

var r = 3; //start from rows 3
var c = 5; //start from col 5

var rows = 8;
var cols = 7;

for (var i = 0; i < rows; i++) {
  var start;
  if (i < r) {
    start =  c;
  } else {
    start = 0;
    myArray.push([]);
  }
  for (var j = start; j < cols; j++) {
        myArray[i].push(0);
    }
}

Assign a class name to <img> tag instead of write it in css file?

Its depend. If you have more than two images in .column but you only need some images to have css applied then its better to add class to image directly instead of doing .column img{/*styling for image here*/}

In performance aspect i thing apply class to image is better because by doing so css will not look for possible child image.

How do I create a Python function with optional arguments?

Just use the *args parameter, which allows you to pass as many arguments as you want after your a,b,c. You would have to add some logic to map args->c,d,e,f but its a "way" of overloading.

def myfunc(a,b, *args, **kwargs):
   for ar in args:
      print ar
myfunc(a,b,c,d,e,f)

And it will print values of c,d,e,f


Similarly you could use the kwargs argument and then you could name your parameters.

def myfunc(a,b, *args, **kwargs):
      c = kwargs.get('c', None)
      d = kwargs.get('d', None)
      #etc
myfunc(a,b, c='nick', d='dog', ...)

And then kwargs would have a dictionary of all the parameters that are key valued after a,b

How do I delete everything below row X in VBA/Excel?

Another option is Sheet1.Rows(x & ":" & Sheet1.Rows.Count).ClearContents (or .Clear). The reason you might want to use this method instead of .Delete is because any cells with dependencies in the deleted range (e.g. formulas that refer to those cells, even if empty) will end up showing #REF. This method will preserve formula references to the cleared cells.

Visual studio - getting error "Metadata file 'XYZ' could not be found" after edit continue

I had same issue too.

In my case, I recently add an internal class to somewhere in project. One of the dependencies in solution has same class name and both of them are added correctly to references.

I changed my last activity and rebuild, it works.

Be sure that your compiler messages are valid. In my case I catch reference error from there, not listed as an error in Error List.

Disable text input history

<input type="text" autocomplete="off"/>

Should work. Alternatively, use:

<form autocomplete="off" … >

for the entire form (see this related question).

Regular expression search replace in Sublime Text 2

Looking at Sublime Text Unofficial Documentation's article on Search and Replace, it looks like +(.+) is the capture group you might want... but I personally used (.*) and it worked well. To REPLACE in the way you are saying, you might like this conversation in the forums, specifically this post which says to simply use $1 to use the first captured group.

And since pictures are better than words...

Before: before find/replace

After: after find/replace

Capture event onclose browser

Men, use this:

if(myWindow.closed){
    callback();
    return;
}

How to get the size of the current screen in WPF?

Center Window on the screen in XAML WindowStartupLocation="CenterOwner" then call in WindowLoaded()

double ScreenHeight = 2 * (Top + 0.5 * Height);

How do you specify a debugger program in Code::Blocks 12.11?

Download codeblocks-13.12mingw-setup.exe instead of codeblocks-13.12setup.exe from the official site. Here 13.12 is the latest version so far.

How to compare two dates in php

I know this is late, but for future reference, put the date format into a recognised format by using str_replace then your function will work. (replace the underscore with a dash)

//change the format to dashes instead of underscores, then get the timestamp
$date1 = strtotime(str_replace("_", "-",$date1));
$date2 = strtotime(str_replace("_", "-",$date2));

//compare the dates
if($date1 < $date2){
   //convert the date back to underscore format if needed when printing it out.
   echo '1 is small='.$date1.','.date('d_m_y',$date1);
}else{
   echo '2 is small='.$date2.','.date('d_m_y',$date2);
}

How do you change the colour of each category within a highcharts column chart?

Also you can set option:

  {plotOptions: {column: {colorByPoint: true}}}

for more information read docs

Installation error: INSTALL_FAILED_OLDER_SDK

Ionic Android emulator error INSTALL_FAILED_OLDER_SDK

So, basically it means that the installation has failed due to having an older SDK version than the targetSdkVersion specified in your app (it's a Gradle issue). Just edit the AndroidManifest.xml file and add the following code:

_x000D_
_x000D_
<uses-sdk android:minSdkVersion="19" android:targetSdkVersion="14"/>
_x000D_
_x000D_
_x000D_

After days looking for the solution, that's it.

Works fine for me!

How to break nested loops in JavaScript?

You should be able to break to a label, like so:

function foo ()
{
    dance:
    for(var k = 0; k < 4; k++){
        for(var m = 0; m < 4; m++){
            if(m == 2){
                break dance;
            }
        }
    }
}

Determine which element the mouse pointer is on top of in JavaScript

Let me start out by saying that I don't recommend using the method I'm about to suggest. It's much better to use event driven development and bind events only to the elements you're interested in knowing whether or not the mouse is over with mouseover, mouseout, mouseenter, mouseleave, etc.

If you absolutely must have the ability to know which element the mouse is over, you'd need to write a function that binds the mouseover event to everything in the DOM, and then store whatever the current element is in some variable.

You could so something like this:

window.which_element_is_the_mouse_on = (function() {

    var currentElement;

    $("body *").on('mouseover', function(e) {
        if(e.target === e.currentTarget) {
            currentElement = this;
        }
    });

    return function() {
        console.log(currentElement);
    }
}());

Basically, I've created an immediate function which sets the event on all elements and stores the current element within the closure to minimize your footprint.

Here's a working demo that calls window.which_element_is_the_mouse_on every second and logs what element the mouse is currently over to the console.

http://jsfiddle.net/LWFpJ/1/

Exclude property from type

Typescript 3.5

As of Typescript 3.5, the Omit helper will be included: TypeScript 3.5 RC - The Omit Helper Type

You can use it directly, and you should remove your own definition of the Omit helper when updating.

android - save image into gallery

Actually, you can save you picture at any place. If you want to save in a public space, so any other application can access, use this code:

storageDir = new File(
    Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES
    ), 
    getAlbumName()
);

The picture doesn't go to the album. To do this, you need to call a scan:

private void galleryAddPic() {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(mCurrentPhotoPath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    this.sendBroadcast(mediaScanIntent);
}

You can found more info at https://developer.android.com/training/camera/photobasics.html#TaskGallery

How to force page refreshes or reloads in jQuery?

You can refresh the events after adding new ones by applying the following code: -Release the Events -set Event Source -Re-render Events

  $('#calendar').fullCalendar('removeEvents');
                  $('#calendar').fullCalendar('addEventSource', YoureventSource);         
                  $('#calendar').fullCalendar('rerenderEvents' );

That will solve the problem

Pandas: Creating DataFrame from Series

No need to initialize an empty DataFrame (you weren't even doing that, you'd need pd.DataFrame() with the parens).

Instead, to create a DataFrame where each series is a column,

  1. make a list of Series, series, and
  2. concatenate them horizontally with df = pd.concat(series, axis=1)

Something like:

series = [pd.Series(mat[name][:, 1]) for name in Variables]
df = pd.concat(series, axis=1)

Remove a folder from git tracking

if file is committed and pushed to github then you should run

git rm --fileName

git ls-files to make sure that the file is removed or untracked

git commit -m "UntrackChanges"

git push

Convert the values in a column into row names in an existing data frame

You can execute this in 2 simple statements:

row.names(samp) <- samp$names
samp[1] <- NULL

Is it possible to use std::string in a constexpr?

As of C++20, yes.

As of C++17, you can use string_view:

constexpr std::string_view sv = "hello, world";

A string_view is a string-like object that acts as an immutable, non-owning reference to any sequence of char objects.

Git: list only "untracked" files (also, custom commands)

When looking for files to potentially add. The output from git show does that but it also includes a lot of other stuff. The following command is useful to get the same list of files but without all of the other stuff.

 git status --porcelain | grep "^?? " | sed -e 's/^[?]* //'

This is useful when combined in a pipeline to find files matching a specific pattern and then piping that to git add.

git status --porcelain | grep "^?? "  | sed -e 's/^[?]* //' | \
egrep "\.project$|\.settings$\.classfile$" | xargs -n1 git add

Regular expression to match any character being repeated more than 10 times

You can also use PowerShell to quickly replace words or character reptitions. PowerShell is for Windows. Current version is 3.0.

$oldfile = "$env:windir\WindowsUpdate.log"

$newfile = "$env:temp\newfile.txt"
$text = (Get-Content -Path $oldfile -ReadCount 0) -join "`n"

$text -replace '/(.)\1{9,}/', ' ' | Set-Content -Path $newfile

How to set fake GPS location on IOS real device

I had a similar issue, but with no source code to run on Xcode.

So if you want to test an application on a real device with a fake location you should use a VPN application.

There are plenty in the App Store to choose from - free ones without the option to choose a specific country/city and free ones which assign you a random location or asks you to choose from a limited set of default options.

Git: How do I list only local branches?

There's a great answer to a post about how to delete local only branches. In it, the fellow builds a command to list out the local branches:

git branch -vv | cut -c 3- | awk '$3 !~/\[/ { print $1 }'

The answer has a great explanation about how this command was derived, so I would suggest you go and read that post.

Export multiple classes in ES6 modules

@webdeb's answer didn't work for me, I hit an unexpected token error when compiling ES6 with Babel, doing named default exports.

This worked for me, however:

// Foo.js
export default Foo
...

// bundle.js
export { default as Foo } from './Foo'
export { default as Bar } from './Bar'
...

// and import somewhere..
import { Foo, Bar } from './bundle'

How do I delete an exported environment variable?

As mentioned in the above answers, unset GNUPLOT_DRIVER_DIR should work if you have used export to set the variable. If you have set it permanently in ~/.bashrc or ~/.zshrc then simply removing it from there will work.

Difference between <input type='button' /> and <input type='submit' />

IE 8 actually uses the first button it encounters submit or button. Instead of easily indicating which is desired by making it a input type=submit the order on the page is actually significant.

how can I check if a file exists?

an existing folder will FAIL with FileExists

Function FileExists(strFileName)
' Check if a file exists - returns True or False

use instead or in addition:

Function FolderExists(strFolderPath)
' Check if a path exists

Find the index of a char in string?

Contanis occur if using the method of the present letter, and store the corresponding number using the IndexOf method, see example below.

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim myString As String = "abcdef"
    Dim numberString As String = String.Empty

    If myString.Contains("d") Then
        numberString = myString.IndexOf("d")
    End If
End Sub

Another sample with TextBox

  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim myString As String = "abcdef"
    Dim numberString As String = String.Empty

    If myString.Contains(me.TextBox1.Text) Then
        numberString = myString.IndexOf(Me.TextBox1.Text)
    End If
End Sub

Regards

How to remove an element slowly with jQuery?

All the answers are good, but I found they all lacked that professional "polish".

I came up with this, fading out, sliding up, then removing:

$target.fadeTo(1000, 0.01, function(){ 
    $(this).slideUp(150, function() {
        $(this).remove(); 
    }); 
});

What is in your .vimrc?

Probably the most significant things below are the font choices and the colour schemes. Yes, I have spent far too long enjoyably fiddling with those things. :)

"set tildeop
set nosmartindent
" set guifont=courier
" awesome programming font
" set guifont=peep:h09:cANSI
" another nice looking font for programming and general use
set guifont=Bitstream_Vera_Sans_MONO:h09:cANSI
set lines=68
set tabstop=2
set shiftwidth=2
set expandtab
set ignorecase
set nobackup
" set writebackup

" Some of my favourite colour schemes, lovingly crafted over the years :)
" very dark scarlet background, almost white text
" hi Normal   guifg=#FFFFF0 guibg=#3F0000 ctermfg=white ctermbg=Black
" C64 colours
"hi Normal   guifg=#8CA1EC guibg=#372DB4 ctermfg=white ctermbg=Black 
" nice forest green background with bisque fg
hi Normal   guifg=#9CfCb1 guibg=#279A1D ctermfg=white ctermbg=Black 
" dark green background with almost white text 
"hi Normal   guifg=#FFFFF0 guibg=#003F00 ctermfg=white ctermbg=Black

" french blue background, almost white text
"hi Normal   guifg=#FFFFF0 guibg=#00003F ctermfg=white ctermbg=Black

" slate blue bg, grey text
"hi Normal   guifg=#929Cb1 guibg=#20403F ctermfg=white ctermbg=Black 

" yellow/orange bg, black text
hi Normal   guifg=#000000 guibg=#f8db3a ctermfg=white ctermbg=Black 

How do I read / convert an InputStream into a String in Java?

A nice way to do this is using Apache commons IOUtils to copy the InputStream into a StringWriter... something like

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();

or even

// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding); 

Alternatively, you could use ByteArrayOutputStream if you don't want to mix your Streams and Writers

Return zero if no record is found

I'm not familiar with postgresql, but in SQL Server or Oracle, using a subquery would work like below (in Oracle, the SELECT 0 would be SELECT 0 FROM DUAL)

SELECT SUM(sub.value)
FROM
( 
  SELECT SUM(columnA) as value FROM my_table
  WHERE columnB = 1
  UNION
  SELECT 0 as value
) sub

Maybe this would work for postgresql too?

Convert or extract TTC font to TTF - how to?

You can use onlinefontconverter.com site. It works fine and have plenty of output formats (afm bin cff dfont eot pfa pfb pfm ps pt3 suit svg t42 tfm ttc ttf woff). One of the advantages I saw, is that it export all the fonts contained inside the ttc at once (which is very convenient).

Genymotion Android emulator - adb access?

Connect didn't work for me, The problem was that Genymotion uses its own dk-tools and you need to change it to custom SDK tools.

More info: https://stackoverflow.com/a/26630862/4154438

Loop through a Map with JSTL

Like this:

<c:forEach var="entry" items="${myMap}">
  Key: <c:out value="${entry.key}"/>
  Value: <c:out value="${entry.value}"/>
</c:forEach>

SELECT * FROM in MySQLi

"SELECT * FROM tablename WHERE field1 = 'value' && field2 = 'value2'";

becomes

"SELECT * FROM tablename WHERE field1 = ? && field2 = ?";

which is passed to the $mysqli::prepare:

$stmt = $mysqli->prepare(
  "SELECT * FROM tablename WHERE field1 = ? && field2 = ?");
$stmt->bind_param( "ss", $value, $value2); 
// "ss' is a format string, each "s" means string
$stmt->execute();

$stmt->bind_result($col1, $col2);
// then fetch and close the statement

OP comments:

so if i have 5 parameters, i could potentially have "sssis" or something (depending on the types of inputs?)

Right, one type specifier per ? parameter in the prepared statement, all of them positional (first specifier applies to first ? which is replaced by first actual parameter (which is the second parameter to bind_param)).

mysqli will take care of escaping and quoting (I think).

Dart/Flutter : Converting timestamp

If you are here to just convert Timestamp into DateTime,

Timestamp timestamp = widget.firebaseDocument[timeStampfield];
DateTime date = Timestamp.fromMillisecondsSinceEpoch(
                timestamp.millisecondsSinceEpoch).toDate();

Disable mouse scroll wheel zoom on embedded Google Maps

I just register one account on developers.google.com and get a token for call a Maps API, and just disable that like this (scrollwheel: false):

    var map;
    function initMap() {
        map = new google.maps.Map(document.getElementById('container_google_maps'), {
            center: {lat: -34.397, lng: 150.644},
            zoom: 8,
            scrollwheel: false
        });
    }

Recreate the default website in IIS

I deleted the C:\inetpub folder and reinstalled IIS which recreated the default website and settings.

Is there a simple JavaScript slider?

There's a nice javascript slider, it's very easy to implement. You can download the zip package here: http://ruwix.com/javascript-volume-slider-control/


p.s. here the simplified version of the above script:

enter image description here

DEMO link

How to get std::vector pointer to the raw data?

something.data() will return a pointer to the data space of the vector.

How to install a specific version of a package with pip?

Use ==:

pip install django_modeltranslation==0.4.0-beta2

Why isn't ProjectName-Prefix.pch created automatically in Xcode 6?

You need to create own PCH file
Add New file -> Other-> PCH file

Then add the path of this PCH file to your build setting->prefix header->path

($(SRCROOT)/filename.pch)

enter image description here

How to read PDF files using Java?

PDFBox contains tools for text extraction.

iText has more low-level support for text manipulation, but you'd have to write a considerable amount of code to get text extraction.

iText in Action contains a good overview of the limitations of text extraction from PDF, regardless of the library used (Section 18.2: Extracting and editing text), and a convincing explanation why the library does not have text extraction support. In short, it's relatively easy to write a code that will handle simple cases, but it's basically impossible to extract text from PDF in general.

Where can I find the error logs of nginx, using FastCGI and Django?

Errors are stored in the nginx log file. You can specify it in the root of the nginx configuration file:

error_log  /var/log/nginx/nginx_error.log  warn;

On Mac OS X with Homebrew, the log file was found by default at the following location:

/usr/local/var/log/nginx

Finding the average of a list

There is a statistics library if you are using python >= 3.4

https://docs.python.org/3/library/statistics.html

You may use it's mean method like this. Let's say you have a list of numbers of which you want to find mean:-

list = [11, 13, 12, 15, 17]
import statistics as s
s.mean(list)

It has other methods too like stdev, variance, mode, harmonic mean, median etc which are too useful.

How to compare two vectors for equality element by element in C++?

If they really absolutely have to remain unsorted (which they really don't.. and if you're dealing with hundreds of thousands of elements then I have to ask why you would be comparing vectors like this), you can hack together a compare method which works with unsorted arrays.

The only way I though of to do that was to create a temporary vector3 and pretend to do a set_intersection by adding all elements of vector1 to it, then doing a search for each individual element of vector2 in vector3 and removing it if found. I know that sounds terrible, but that's why I'm not writing any C++ standard libraries anytime soon.

Really, though, just sort them first.

Image vs Bitmap class

This is a clarification because I have seen things done in code which are honestly confusing - I think the following example might assist others.

As others have said before - Bitmap inherits from the Abstract Image class

Abstract effectively means you cannot create a New() instance of it.

    Image imgBad1 = new Image();        // Bad - won't compile
    Image imgBad2 = new Image(200,200); // Bad - won't compile

But you can do the following:

    Image imgGood;  // Not instantiated object!
    // Now you can do this
    imgGood = new Bitmap(200, 200);

You can now use imgGood as you would the same bitmap object if you had done the following:

    Bitmap bmpGood = new Bitmap(200,200);

The nice thing here is you can draw the imgGood object using a Graphics object

    Graphics gr = default(Graphics);
    gr = Graphics.FromImage(new Bitmap(1000, 1000));
    Rectangle rect = new Rectangle(50, 50, imgGood.Width, imgGood.Height); // where to draw
    gr.DrawImage(imgGood, rect);

Here imgGood can be any Image object - Bitmap, Metafile, or anything else that inherits from Image!

Stretch background image css?

CSS3: http://webdesign.about.com/od/styleproperties/p/blspbgsize.htm

.style1 {
  ...
  background-size: 100%;
}

You can specify just width or height with:

background-size: 100% 50%;

Which will stretch it 100% of the width and 50% of the height.


Browser support: http://caniuse.com/#feat=background-img-opts

How can I get a Dialog style activity window to fill the screen?

You may add this values to your style android:windowMinWidthMajor and android:windowMinWidthMinor

<style name="Theme_Dialog" parent="android:Theme.Holo.Dialog">
    ...
    <item name="android:windowMinWidthMajor">97%</item>
    <item name="android:windowMinWidthMinor">97%</item>
</style>

MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Is it possible the root password is not what you think it is? Have you checked the file /root/.mysql_secret for the password? That is the default location for the automated root password that is generated from starting from version 5.7.

cat /root/.mysql_secret

How do you remove an invalid remote branch reference from Git?

You might be needing a cleanup:

git gc --prune=now

or you might be needing a prune:

git remote prune public

prune

Deletes all stale tracking branches under <name>. These stale branches have already been removed from the remote repository referenced by <name>, but are still locally available in "remotes/<name>".

With --dry-run option, report what branches will be pruned, but do no actually prune them.

However, it appears these should have been cleaned up earlier with

git remote rm public 

rm

Remove the remote named <name>. All remote tracking branches and configuration settings for the remote are removed.

So it might be you hand-edited your config file and this did not occur, or you have privilege problems.

Maybe run that again and see what happens.


Advice Context

If you take a look in the revision logs, you'll note I suggested more "correct" techniques, which for whatever reason didn't want to work on their repository.

I suspected the OP had done something that left their tree in an inconsistent state that caused it to behave a bit strangely, and git gc was required to fix up the left behind cruft.

Usually git branch -rd origin/badbranch is sufficient for nuking a local tracking branch , or git push origin :badbranch for nuking a remote branch, and usually you will never need to call git gc

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

None of these options worked for me, in the end it was;

Test > Test Settings > *.testrunconfig

I had to add a new line

<DeploymentItem filename="packages\Newtonsoft.Json.4.5.8\lib\net40\Newtonsoft.Json.dll" />

Make sure the path and version is correct for your setup.

Json.net serialize/deserialize derived types?

You have to enable Type Name Handling and pass that to the (de)serializer as a settings parameter.

Base object1 = new Base() { Name = "Object1" };
Derived object2 = new Derived() { Something = "Some other thing" };
List<Base> inheritanceList = new List<Base>() { object1, object2 };

JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
string Serialized = JsonConvert.SerializeObject(inheritanceList, settings);
List<Base> deserializedList = JsonConvert.DeserializeObject<List<Base>>(Serialized, settings);

This will result in correct deserialization of derived classes. A drawback to it is that it will name all the objects you are using, as such it will name the list you are putting the objects in.

Array[n] vs Array[10] - Initializing array with variable vs real number

In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard), you can do:

int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:

int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!

Or, better yet, use a standard container:

int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>

If you still want a proper array, you can use a constant, not a variable, when creating it:

const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)

Similarly, if you want to get the size from a function in C++11, you can use a constexpr:

constexpr int n()
{
    return 10;
}

double a[n()]; // n() is a compile time constant expression

Difference between $(window).load() and $(document).ready() functions

From jquery prospective - it's just adding load/onload event to window and document. Check this out:

window.onload vs document.onload

How do I make an http request using cookies on Android?

Since Apache library is deprecated, for those who want to use HttpURLConncetion , I wrote this class to send Get and Post Request with the help of this answer:

public class WebService {

static final String COOKIES_HEADER = "Set-Cookie";
static final String COOKIE = "Cookie";

static CookieManager msCookieManager = new CookieManager();

private static int responseCode;

public static String sendPost(String requestURL, String urlParameters) {

    URL url;
    String response = "";
    try {
        url = new URL(requestURL);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");

        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");

        if (msCookieManager.getCookieStore().getCookies().size() > 0) {
            //While joining the Cookies, use ',' or ';' as needed. Most of the server are using ';'
            conn.setRequestProperty(COOKIE ,
                    TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
        }

        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));

        if (urlParameters != null) {
            writer.write(urlParameters);
        }
        writer.flush();
        writer.close();
        os.close();

        Map<String, List<String>> headerFields = conn.getHeaderFields();
        List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);

        if (cookiesHeader != null) {
            for (String cookie : cookiesHeader) {
                msCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
            }
        }

        setResponseCode(conn.getResponseCode());

        if (getResponseCode() == HttpsURLConnection.HTTP_OK) {

            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line = br.readLine()) != null) {
                response += line;
            }
        } else {
            response = "";
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return response;
}


// HTTP GET request
public static String sendGet(String url) throws Exception {

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    //add request header 
    con.setRequestProperty("User-Agent", "Mozilla");
    /*
    * https://stackoverflow.com/questions/16150089/how-to-handle-cookies-in-httpurlconnection-using-cookiemanager
    * Get Cookies form cookieManager and load them to connection:
     */
    if (msCookieManager.getCookieStore().getCookies().size() > 0) {
        //While joining the Cookies, use ',' or ';' as needed. Most of the server are using ';'
        con.setRequestProperty(COOKIE ,
                TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
    }

    /*
    * https://stackoverflow.com/questions/16150089/how-to-handle-cookies-in-httpurlconnection-using-cookiemanager
    * Get Cookies form response header and load them to cookieManager:
     */
    Map<String, List<String>> headerFields = con.getHeaderFields();
    List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
    if (cookiesHeader != null) {
        for (String cookie : cookiesHeader) {
            msCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
        }
    }


    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    return response.toString();
}

public static void setResponseCode(int responseCode) {
    WebService.responseCode = responseCode;
    Log.i("Milad", "responseCode" + responseCode);
}


public static int getResponseCode() {
    return responseCode;
}
}

How to make a website secured with https

I think you are getting confused with your site Authentication and SSL.

If you need to get your site into SSL, then you would need to install a SSL certificate into your web server. You can buy a certificate for yourself from one of the places like Symantec etc. The certificate would contain your public/private key pair, along with other things.

You wont need to do anything in your source code, and you can still continue to use your Form Authntication (or any other) in your site. Its just that, any data communication that takes place between the web server and the client will encrypted and signed using your certificate. People would use secure-HTTP (https://) to access your site.

View this for more info --> http://en.wikipedia.org/wiki/Transport_Layer_Security

How to check whether a Button is clicked by using JavaScript

Try adding an event listener for clicks:

document.getElementById('button').addEventListener("click", function() {
   alert("You clicked me");
}?);?

Using addEventListener is probably a better idea then setting onclick - onclick can easily be overwritten by another piece of code.

You can use a variable to store whether or not the button has been clicked before:

var clicked = false
document.getElementById('button').addEventListener("click", function() {
   clicked = true
}?);?

addEventListener on MDN

Send POST data via raw json with postman

Just check JSON option from the drop down next to binary; when you click raw. This should do

skill synon pass json to postman

php stdClass to array

Here is the best Object to Array function I have - works recursively:

function object_to_array($obj, &$arr){

    if(!is_object($obj) && !is_array($obj)){
        $arr = $obj;
        return $arr;
    }

    foreach ($obj as $key => $value)
    {
        if (!empty($value))
        {
            $arr[$key] = array();
            object_to_array_v2($value, $arr[$key]);
        }
        else
        {
            $arr[$key] = $value;
        }
    }
    return $arr;
}

$clean_array = object_to_array($object_data_here);

How to use JavaScript source maps (.map files)?

The .map files are for js and css (and now ts too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.

Same for CSS files. Once you take a SASS or LESS file and compile it to CSS, it looks nothing like its original form. If you enable sourcemaps, then you can see the original state of the file, instead of the modified state.

So, to answer you questions in order:

  • What is it for? To de-reference uglified code
  • How can a developer use it? You use it for debugging a production app. In development mode you can use the full version of Angular. In production, you would use the minified version.
  • Should I care about creating a js.map file? If you care about being able to debug production code easier, then yes, you should do it.
  • How does it get created? It is created at build time. There are build tools that can build your .map file for you as it does other files. https://github.com/gruntjs/grunt-contrib-uglify/issues/71

I hope this makes sense.

Inserting records into a MySQL table using Java

this can also be done like this if you don't want to use prepared statements.

String sql = "INSERT INTO course(course_code,course_desc,course_chair)"+"VALUES('"+course_code+"','"+course_desc+"','"+course_chair+"');"

Why it didnt insert value is because you were not providing values, but you were providing names of variables that you have used.

Pandas dataframe fillna() only some columns in place

using the top answer produces a warning about making changes to a copy of a df slice. Assuming that you have other columns, a better way to do this is to pass a dictionary:
df.fillna({'A': 'NA', 'B': 'NA'}, inplace=True)

What is C# analog of C++ std::pair?

I was asking the same question just now after a quick google I found that There is a pair class in .NET except its in the System.Web.UI ^ ~ ^ (http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx) goodness knows why they put it there instead of the collections framework

Get most recent row for given ID

Simple Way To Achieve

I know it's an old question You can also do something like

SELECT * FROM Table WHERE id=1 ORDER BY signin DESC

In above, query the first record will be the most recent record.

For only one record you can use something like

SELECT top(1) * FROM Table WHERE id=1 ORDER BY signin DESC

Above query will only return one latest record.

Cheers!

creating json object with variables

You're referencing a DOM element when doing something like $('#lastName'). That's an element with id attribute "lastName". Why do that? You want to reference the value stored in a local variable, completely unrelated. Try this (assuming the assignment to formObject is in the same scope as the variable declarations) -

var formObject = {
    formObject: [
        {
            firstName:firstName,  // no need to quote variable names
            lastName:lastName
        },
        {
            phoneNumber:phoneNumber,
            address:address
        }
    ]
};

This seems very odd though: you're creating an object "formObject" that contains a member called "formObject" that contains an array of objects.

How to load data from a text file in a PostgreSQL database?

Let consider that your data are in the file values.txt and that you want to import them in the database table myTable then the following query does the job

COPY myTable FROM 'value.txt' (DELIMITER('|'));

https://www.postgresql.org/docs/current/static/sql-copy.html

Sniffing/logging your own Android Bluetooth traffic

On Xiaomi Redmi Note 9s This configuration file can also be found /storage/emulated/0/MIUI/debug_log/common named as hci_snoop20210210214303.cfa hci_snoop20210211095126.cfa

With enabled 'Settings->Developer Options, then checking the box next to "Bluetooth HCI Snoop Log." '

I was used Total Commander for taking file from Internal storage

Only using @JsonIgnore during serialization, but not deserialization

You can use @JsonIgnoreProperties at class level and put variables you want to igonre in json in "value" parameter.Worked for me fine.

@JsonIgnoreProperties(value = { "myVariable1","myVariable2" })
public class MyClass {
      private int myVariable1;,
      private int myVariable2;
}

How and where to use ::ng-deep?

Just an update:

You should use ::ng-deep instead of /deep/ which seems to be deprecated.

Per documentation:

The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.

You can find it here

Excel VBA Run Time Error '424' object required

Simply remove the .value from your code.

Set envFrmwrkPath = ActiveSheet.Range("D6").Value

instead of this, use:

Set envFrmwrkPath = ActiveSheet.Range("D6")

Best way to convert IList or IEnumerable to Array

I feel like reinventing the wheel...

public static T[] ConvertToArray<T>(this IEnumerable<T> enumerable)
{
    if (enumerable == null)
        throw new ArgumentNullException("enumerable");

    return enumerable as T[] ?? enumerable.ToArray();
}

How to redirect the output of print to a TXT file

Building on previous answers, I think it's a perfect use case for doing it (simple) context manager style:

import sys

class StdoutRedirection:
    """Standard output redirection context manager"""

    def __init__(self, path):
        self._path = path

    def __enter__(self):
        sys.stdout = open(self._path, mode="w")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stdout.close()
        sys.stdout = sys.__stdout__

and then:

with StdoutRedirection("path/to/file"):
    print("Hello world")

Also it would be really easy to add some functionality to StdoutRedirection class (e.g. a method that lets you change the path)

TypeError: unsupported operand type(s) for -: 'str' and 'int'

For future reference Python is strongly typed. Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from str to int) so you must do this yourself. You'll like that in the long-run, trust me!

How to write LDAP query to test if user is member of a group?

If you are using OpenLDAP (i.e. slapd) which is common on Linux servers, then you must enable the memberof overlay to be able to match against a filter using the (memberOf=XXX) attribute.

Also, once you enable the overlay, it does not update the memberOf attributes for existing groups (you will need to delete out the existing groups and add them back in again). If you enabled the overlay to start with, when the database was empty then you should be OK.

IE prompts to open or save json result from server

I faced this while using jQuery FileUpload plugin.

Then I took a look in their documentation, most exactly in the Content-Type Negotiation section and followed their suggestion for Ruby/Rails.

render(json: <some-data>, content_type: request.format)

Which fixed the issue for me.

Quick Explanation: for old IE/Opera versions, this plugin will use an iframe with text/plain or text/html content-type, so if you force the response to json, browser will try download it. Using the same content-type as in the request will make it work for any browser.

Git error when trying to push -- pre-receive hook declined

In case it helps someone :

I had a blank repo with no master branch to unprotect (in Gitlab) so before running git push -u origin --all

  • I had to run git push -u origin master first,
  • unprotect the master branch temporarily
  • push the rest (--all & --tags)

Git push rejected "non-fast-forward"

Well I used the advice here and it screwed me as it merged my local code directly to master. .... so take it all with a grain of salt. My coworker said the following helped resolve the issue, needed to repoint my branch.

 git branch --set-upstream-to=origin/feature/my-current-branch feature/my-current-branch

How to echo out table rows from the db (php)

Expanding on the accepted answer:

function mysql_query_or_die($query) {
    $result = mysql_query($query);
    if ($result)
        return $result;
    else {
        $err = mysql_error();
        die("<br>{$query}<br>*** {$err} ***<br>");
    }
}

...
$query = "SELECT * FROM my_table";
$result = mysql_query_or_die($query);
echo("<table>");
$first_row = true;
while ($row = mysql_fetch_assoc($result)) {
    if ($first_row) {
        $first_row = false;
        // Output header row from keys.
        echo '<tr>';
        foreach($row as $key => $field) {
            echo '<th>' . htmlspecialchars($key) . '</th>';
        }
        echo '</tr>';
    }
    echo '<tr>';
    foreach($row as $key => $field) {
        echo '<td>' . htmlspecialchars($field) . '</td>';
    }
    echo '</tr>';
}
echo("</table>");

Benefits:

  • Using mysql_fetch_assoc (instead of mysql_fetch_array with no 2nd parameter to specify type), we avoid getting each field twice, once for a numeric index (0, 1, 2, ..), and a second time for the associative key.

  • Shows field names as a header row of table.

  • Shows how to get both column name ($key) and value ($field) for each field, as iterate over the fields of a row.

  • Wrapped in <table> so displays properly.

  • (OPTIONAL) dies with display of query string and mysql_error, if query fails.

Example Output:

Id      Name
777     Aardvark
50      Lion
9999    Zebra

Is there a simple way to remove unused dependencies from a maven pom.xml?

Have you looked at the Maven Dependency Plugin ? That won't remove stuff for you but has tools to allow you to do the analysis yourself. I'm thinking particularly of

mvn dependency:tree

What's the best way to use R scripts on the command line (terminal)?

#!/path/to/R won't work because R is itself a script, so execve is unhappy.

I use R --slave -f script

Convert A String (like testing123) To Binary In Java

While playing around with the answers I found here to become familiar with it I twisted Nuoji's solution a bit so that I could understand it faster when looking at it in the future.

public static String stringToBinary(String str, boolean pad ) {
    byte[] bytes = str.getBytes();
    StringBuilder binary = new StringBuilder();
    for (byte b : bytes)
    {
       binary.append(Integer.toBinaryString((int) b));
       if(pad) { binary.append(' '); }
    }
    return binary.toString();        
}

PHP prepend leading zero before single digit number, on-the-fly

You can use str_pad for adding 0's

str_pad($month, 2, '0', STR_PAD_LEFT); 

string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )

Using Mysql in the command line in osx - command not found?

That means /usr/local/mysql/bin/mysql is not in the PATH variable..

Either execute /usr/local/mysql/bin/mysql to get your mysql shell,

or type this in your terminal:

PATH=$PATH:/usr/local/mysql/bin

to add that to your PATH variable so you can just run mysql without specifying the path

How to import set of icons into Android Studio project

just like Gregory Seront said here:

Actually if you downloaded the icons pack from the android web site, you will see that you have one folder per resolution named drawable-mdpi etc. Copy all folders into the res (not the drawable) folder in Android Studio. This will automatically make all the different resolution of the icon available.

but if your not getting the images from a generator site (maybe your UX team provides them), just make sure your folders are named drawable-hdpi, drawable-mdpi, etc. then in mac select all folders by holding shift and then copy them (DO NOT DRAG). Paste the folders into the res folder. android will take care of the rest and copy all drawables into the correct folder.

How to Read and Write from the Serial Port

I spent a lot of time to use SerialPort class and has concluded to use SerialPort.BaseStream class instead. You can see source code: SerialPort-source and SerialPort.BaseStream-source for deep understanding. I created and use code that shown below.

  • The core function public int Recv(byte[] buffer, int maxLen) has name and works like "well known" socket's recv().

  • It means that

    • in one hand it has timeout for no any data and throws TimeoutException.
    • In other hand, when any data has received,
      • it receives data either until maxLen bytes
      • or short timeout (theoretical 6 ms) in UART data flow

.

public class Uart : SerialPort

    {
        private int _receiveTimeout;

        public int ReceiveTimeout { get => _receiveTimeout; set => _receiveTimeout = value; }

        static private string ComPortName = "";

        /// <summary>
        /// It builds PortName using ComPortNum parameter and opens SerialPort.
        /// </summary>
        /// <param name="ComPortNum"></param>
        public Uart(int ComPortNum) : base()
        {
            base.BaudRate = 115200; // default value           
            _receiveTimeout = 2000;
            ComPortName = "COM" + ComPortNum;

            try
            {
                base.PortName = ComPortName;
                base.Open();
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine("Error: Port {0} is in use", ComPortName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Uart exception: " + ex);
            }
        } //Uart()

        /// <summary>
        /// Private property returning positive only Environment.TickCount
        /// </summary>
        private int _tickCount { get => Environment.TickCount & Int32.MaxValue; }


        /// <summary>
        /// It uses SerialPort.BaseStream rather SerialPort functionality .
        /// It Receives up to maxLen number bytes of data, 
        /// Or throws TimeoutException if no any data arrived during ReceiveTimeout. 
        /// It works likes socket-recv routine (explanation in body).
        /// Returns:
        ///    totalReceived - bytes, 
        ///    TimeoutException,
        ///    -1 in non-ComPortNum Exception  
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="maxLen"></param>
        /// <returns></returns>
        public int Recv(byte[] buffer, int maxLen)
        {
            /// The routine works in "pseudo-blocking" mode. It cycles up to first 
            /// data received using BaseStream.ReadTimeout = TimeOutSpan (2 ms).
            /// If no any message received during ReceiveTimeout property, 
            /// the routine throws TimeoutException 
            /// In other hand, if any data has received, first no-data cycle
            /// causes to exit from routine.

            int TimeOutSpan = 2;
            // counts delay in TimeOutSpan-s after end of data to break receive
            int EndOfDataCnt;
            // pseudo-blocking timeout counter
            int TimeOutCnt = _tickCount + _receiveTimeout; 
            //number of currently received data bytes
            int justReceived = 0;
            //number of total received data bytes
            int totalReceived = 0;

            BaseStream.ReadTimeout = TimeOutSpan;
            //causes (2+1)*TimeOutSpan delay after end of data in UART stream
            EndOfDataCnt = 2;
            while (_tickCount < TimeOutCnt && EndOfDataCnt > 0)
            {
                try
                {
                    justReceived = 0; 
                    justReceived = base.BaseStream.Read(buffer, totalReceived, maxLen - totalReceived);
                    totalReceived += justReceived;

                    if (totalReceived >= maxLen)
                        break;
                }
                catch (TimeoutException)
                {
                    if (totalReceived > 0) 
                        EndOfDataCnt--;
                }
                catch (Exception ex)
                {                   
                    totalReceived = -1;
                    base.Close();
                    Console.WriteLine("Recv exception: " + ex);
                    break;
                }

            } //while
            if (totalReceived == 0)
            {              
                throw new TimeoutException();
            }
            else
            {               
                return totalReceived;
            }
        } // Recv()            
    } // Uart

Difference between / and /* in servlet mapping url pattern

I think Candy's answer is mostly correct. There is one small part I think otherwise.

To map host:port/context/hello.jsp

  1. No exact URL servlets installed, next.
  2. Found wildcard paths servlets, return.

I believe that why "/*" does not match host:port/context/hello because it treats "/hello" as a path instead of a file (since it does not have an extension).

"unrecognized selector sent to instance" error in Objective-C

In my case the function was not expecting an argument but the button was configured to send one causing the error. To fix this I had to rewire the event handler.

Here is my function:

enter image description here

Notice it contains no arguments.

Here is an image of my button configuration (right click on the button to view it):

enter image description here

Notice there are 3 event handlers.

To fix this I had to remove each of the event items since one of them was sending a reference to itself to the enterPressed function. To remove these items I clicked on the little x icon next to the name of each item until there were no items shown.

enter image description here

Next I had to reconnect the button to the event. To do this hold down the Control key and then drag a line from the button to the action. It should say "Connect Action". Note: I had to restart XCode for this to work for some reason; otherwise it only let me insert actions (aka create a new action) above or below the function.

enter image description here

You should now have a single event handler wired to the button event that passes no arguments:

enter image description here

This answer compliments the answer by @Leonard Challis which you should read as well.

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

References are "hidden pointers" (non-null) to things which can change (lvalues). You cannot define them to a constant. It should be a "variable" thing.

EDIT::

I am thinking of

int &x = y;

as almost equivalent of

int* __px = &y;
#define x (*__px)

where __px is a fresh name, and the #define x works only inside the block containing the declaration of x reference.

How do you install an APK file in the Android emulator?

1) paste the myapp.apk in platform-tools folder , in my case C:\Users\mazbizxam\AppData\Local\Android\android-sdk\platform-tools, this is the link in my case it may change to you people

2)open the directory in CMD CD C:\Users\mazbizxam\AppData\Local\Android\android-sdk\platform-tools

3)Now you are in platform-tools folder , just type adb install myapp.apk

please ensure that your emulator is turn on , if every thing is ok apk will install

How to stop a goroutine

Typically, you pass the goroutine a (possibly separate) signal channel. That signal channel is used to push a value into when you want the goroutine to stop. The goroutine polls that channel regularly. As soon as it detects a signal, it quits.

quit := make(chan bool)
go func() {
    for {
        select {
        case <- quit:
            return
        default:
            // Do other stuff
        }
    }
}()

// Do stuff

// Quit goroutine
quit <- true

What arguments are passed into AsyncTask<arg1, arg2, arg3>?

  • in Short, There are 3 parameters in AsyncTask

    1. parameters for Input use in DoInBackground(String... params)

    2. parameters for show status of progress use in OnProgressUpdate(String... status)

    3. parameters for result use in OnPostExcute(String... result)

    Note : - [Type of parameters can vary depending on your requirement]

What are the differences between C, C# and C++ in terms of real-world applications?

C - an older programming language that is described as Hands-on. As the programmer you must tell the program to do everything. Also this language will let you do almost anything. It does not support object orriented code. Thus no classes.

C++ - an extention language per se of C. In C code ++ means increment 1. Thus C++ is better than C. It allows for highly controlled object orriented code. Once again a very hands on language that goes into MUCH detail.

C# - Full object orriented code resembling the style of C/C++ code. This is really closer to JAVA. C# is the latest version of the C style languages and is very good for developing web applications.

CORS: credentials mode is 'include'

If it helps, I was using centrifuge with my reactjs app, and, after checking some comments below, I looked at the centrifuge.js library file, which in my version, had the following code snippet:

if ('withCredentials' in xhr) {
 xhr.withCredentials = true;
}

After I removed these three lines, the app worked fine, as expected.

Hope it helps!

How to ping multiple servers and return IP address and Hostnames using batch script?

@echo off

set workdir={your working dir. for example - C:\work } set iplist=%workdir%\IP-list.txt

setlocal enabledelayedexpansion
set OUTPUT_FILE=%workdir%\result.csv

>nul copy nul %OUTPUT_FILE%
echo HOSTNAME,LONGNAME,IPADDRESS,STATE >%OUTPUT_FILE%
for /f %%i in (%iplist%) do (
    set SERVER_ADDRESS_I=UNRESOLVED
    set SERVER_ADDRESS_L=UNRESOLVED
    for /f "tokens=1,2,3" %%x in ('ping -a -n 1 %%i ^&^& echo SERVER_IS_UP') do (
    if %%x==Pinging set SERVER_ADDRESS_L=%%y
    if %%x==Pinging set SERVER_ADDRESS_I=%%z
        if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
    )
    echo %%i [!SERVER_ADDRESS_L::=!] !SERVER_ADDRESS_I::=! is !SERVER_STATE!
    echo %%i,!SERVER_ADDRESS_L::=!,!SERVER_ADDRESS_I::=!,!SERVER_STATE! >>%OUTPUT_FILE%
)

How to change color of Toolbar back button in Android?

Just use the MaterialToolbar and override the default colors:

    <com.google.android.material.appbar.MaterialToolbar
        style="@style/Widget.MaterialComponents.Toolbar.Primary"
        android:theme="@style/MyThemeOverlay_Toolbar"
        ..>

with:

  <style name="MyThemeOverlay_Toolbar" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- color used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/...</item>
  </style>

enter image description here

If you are using the androidx.appcompat.widget.Toolbar or the MaterialToolbar with the default style (Widget.MaterialComponents.Toolbar) you can use:

<androidx.appcompat.widget.Toolbar
    android:theme="@style/MyThemeOverlay_Toolbar2"

with:

  <style name="MyThemeOverlay_Toolbar2" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- This attributes is used by title -->
    <item name="android:textColorPrimary">@color/white</item>

    <!-- This attributes is used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/secondaryColor</item>
  </style>

How can I create persistent cookies in ASP.NET?

As I understand you use ASP.NET authentication and to set cookies persistent you need to set FormsAuthenticationTicket.IsPersistent = true It is the main idea.

bool isPersisted = true;
var authTicket = new FormsAuthenticationTicket(
1,
user_name, 
DateTime.Now,
DateTime.Now.AddYears(1),//Expiration (you can set it to 1 year)
isPersisted,//THIS IS THE MAIN FLAG
addition_data);
    HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket );
    if (isPersisted)
        authCookie.Expires = authTicket.Expiration;

HttpContext.Current.Response.Cookies.Add(authCookie);

How to import popper.js?

add popper**.js** as dependency instead of popper (only): see the difference in bold.

yarn add popper.js , instead of yarn add popper

it makes the difference.

and include the script according your needs:

as html or the library access as a dependency in SPA applications like react or angular

Font is not available to the JVM with Jasper Reports

I faced the issue with my web application based on Spring 3 and deployed on Weblogic 10.3 on Oracle Linux 6. The solution mentioned at the link did not work for me.

I had to take the following steps - 1. Copy the Arial*.ttf font files to JROCKIT_JAVA_HOME/jre/lib/fonts directory 2. Make entries of the fonts in fontconfig.properties.src 3. Restart the cluster from Weblogic console

filename.Arial=Arial.ttf
filename.Arial_Bold=Arial_Bold.ttf
filename.Arial_Italic=Arial_Italic.ttf
filename.Arial_Bold_Italic=Arial_Bold_Italic.ttf

TypeError: 'str' object cannot be interpreted as an integer

Or you can also use eval(input('prompt')).

Use of "instanceof" in Java

instanceof is used to check if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

Read more from the Oracle language definition here.

How do you scroll up/down on the console of a Linux VM

Press the Shift key when scrolling the mouse up/down works for me when loggin in Ubuntu using Terminal ssh in Yosemite.

What is WEB-INF used for in a Java EE web application?

The Servlet 2.4 specification says this about WEB-INF (page 70):

A special directory exists within the application hierarchy named WEB-INF. This directory contains all things related to the application that aren’t in the document root of the application. The WEB-INF node is not part of the public document tree of the application. No file contained in the WEB-INF directory may be served directly to a client by the container. However, the contents of the WEB-INF directory are visible to servlet code using the getResource and getResourceAsStream method calls on the ServletContext, and may be exposed using the RequestDispatcher calls.

This means that WEB-INF resources are accessible to the resource loader of your Web-Application and not directly visible for the public.

This is why a lot of projects put their resources like JSP files, JARs/libraries and their own class files or property files or any other sensitive information in the WEB-INF folder. Otherwise they would be accessible by using a simple static URL (usefull to load CSS or Javascript for instance).

Your JSP files can be anywhere though from a technical perspective. For instance in Spring you can configure them to be in WEB-INF explicitly:

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    p:prefix="/WEB-INF/jsp/" 
    p:suffix=".jsp" >
</bean>

The WEB-INF/classes and WEB-INF/lib folders mentioned in Wikipedia's WAR files article are examples of folders required by the Servlet specification at runtime.

It is important to make the difference between the structure of a project and the structure of the resulting WAR file.

The structure of the project will in some cases partially reflect the structure of the WAR file (for static resources such as JSP files or HTML and JavaScript files, but this is not always the case.

The transition from the project structure into the resulting WAR file is done by a build process.

While you are usually free to design your own build process, nowadays most people will use a standardized approach such as Apache Maven. Among other things Maven defines defaults for which resources in the project structure map to what resources in the resulting artifact (the resulting artifact is the WAR file in this case). In some cases the mapping consists of a plain copy process in other cases the mapping process includes a transformation, such as filtering or compiling and others.

One example: The WEB-INF/classes folder will later contain all compiled java classes and resources (src/main/java and src/main/resources) that need to be loaded by the Classloader to start the application.

Another example: The WEB-INF/lib folder will later contain all jar files needed by the application. In a maven project the dependencies are managed for you and maven automatically copies the needed jar files to the WEB-INF/lib folder for you. That explains why you don't have a lib folder in a maven project.

ssh: check if a tunnel is alive

stunnel is a good tool to make semi-permanent connections between hosts.

http://www.stunnel.org/

System.loadLibrary(...) couldn't find native library in my case

In my case i must exclude compiling sources by gradle and set libs path

android {

    ...
    sourceSets {
        ...
        main.jni.srcDirs = []
        main.jniLibs.srcDirs = ['libs']
    }
....

Return from lambda forEach() in java

This what helped me:

List<RepositoryFile> fileList = response.getRepositoryFileList();
RepositoryFile file1 = fileList.stream().filter(f -> f.getName().contains("my-file.txt")).findFirst().orElse(null);

Taken from Java 8 Finding Specific Element in List with Lambda

Trim Whitespaces (New Line and Tab space) in a String in Oracle

This how I would implement it:

     REGEXP_REPLACE(text,'(^[[:space:]]*|[[:space:]]*$)')

Case insensitive access for generic dictionary

There is much simpler way:

using System;
using System.Collections.Generic;
....
var caseInsensitiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

Gridview with two columns and auto resized images

another simple approach with modern built-in stuff like PercentRelativeLayout is now available for new users who hit this problem. thanks to android team for release this item.

<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
app:layout_widthPercent="50%">

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop" />

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="#55000000"
        android:paddingBottom="15dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:textColor="@android:color/white" />

</FrameLayout>

and for better performance you can use some stuff like picasso image loader which help you to fill whole width of every image parents. for example in your adapter you should use this:

int width= context.getResources().getDisplayMetrics().widthPixels;
    com.squareup.picasso.Picasso
            .with(context)
            .load("some url")
            .centerCrop().resize(width/2,width/2)
            .error(R.drawable.placeholder)
            .placeholder(R.drawable.placeholder)
            .into(item.drawableId);

now you dont need CustomImageView Class anymore.

P.S i recommend to use ImageView in place of Type Int in class Item.

hope this help..

Center-align a HTML table

<table align="center"></table>

This works for me.

Node.js connect only works on localhost

Working for me with this line (simply add --listen when running) :

node server.js -p 3000 -a : --listen 192.168.1.100

Hope it helps...

Re-order columns of table in Oracle

Since the release of Oracle 12c it is now easier to rearrange columns logically.

Oracle 12c added support for making columns invisible and that feature can be used to rearrange columns logically.

Quote from the documentation on invisible columns:

When you make an invisible column visible, the column is included in the table's column order as the last column.

Example

Create a table:

CREATE TABLE t (
    a INT,
    b INT,
    d INT,
    e INT
);

Add a column:

ALTER TABLE t ADD (c INT);

Move the column to the middle:

ALTER TABLE t MODIFY (d INVISIBLE, e INVISIBLE);
ALTER TABLE t MODIFY (d VISIBLE, e VISIBLE);

DESCRIBE t;

Name
----
A
B
C
D
E

Credits

I learned about this from an article by Tom Kyte on new features in Oracle 12c.

In AVD emulator how to see sdcard folder? and Install apk to AVD?

I have used the following procedure.

Android Studio 3.4.1

View>Tool Windows>Device File Explorer

enter image description here

The developers of this app have not set up this app properly for Facebook Login?

Hemang's answer was right, BUT, there's one extra step you'll need, which is to add a Facebook App ID. (I discovered I was missing this part): enter image description here

Once you've done that in addition to Hemang's answer, you'll be good to go!

Setting table row height

line-height only works when it is larger then the current height of the content of <td> . So, if you have a 50x50 icon in the table, the tr line-height will not make a row smaller than 50px (+ padding).

Since you've already set the padding to 0 it must be something else,
for example a large font-size inside td that is larger than your 14px.

Is there a way to make text unselectable on an HTML page?

Absolutely position divs over the text area with a z-index higher and give these divs a transparent GIF background graphic.

Note after a bit more thought - You'd need to have these 'covers' be linked so clicking on them would take you to where the tab was supposed to, which means you could/should do this with the anchor element set to display:box, width and height set as well as the transparent background image.

The equivalent of wrap_content and match_parent in flutter?

Use FractionallySizedBox widget.

FractionallySizedBox(
  widthFactor: 1.0, // width w.r.t to parent
  heightFactor: 1.0,  // height w.r.t to parent
  child: *Your Child Here*
}

This widget is also very useful when you want to size your child at a fractional of its parent's size.

Example:

If you want the child to occupy 50% width of its parent, provide widthFactor as 0.5

SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

Varchar Date Convert to Date and Change the Format

Nov 12 2016 12:00 , 21/12/2016, 21-12-2016 this Query Works for above to change to this Format dd/MM/yyyy SELECT [Member_ID],[Name] , Convert(varchar(50),Convert(date,[DOB],103),103) as DOB ,[NICNO],[Relation] FROM [dbo].[tbl_FamilMember]

removeEventListener on anonymous functions in JavaScript

I know this is a fairly old thread, but thought I might put in my two cents for those who find it useful.

The script (apologies about the uncreative method names):

window.Listener = {
    _Active: [],
    remove: function(attached, on, callback, capture){
        for(var i = 0; i < this._Active.length; i++){
            var current = this._Active[i];
            if(current[0] === attached && current[1] === on && current[2] === callback){
                attached.removeEventListener(on, callback, (capture || false));
                return this._Active.splice(i, 1);
            }
        }
    }, removeAtIndex(i){
        if(this._Active[i]){
            var remove = this._Active[i];
            var attached = remove[0], on = remove[1], callback = remove[2];
            attached.removeEventListener(on, callback, false);
            return this._Active.splice(i, 1);
        }
    }, purge: function(){
        for(var i = 0; i < this._Active.length; i++){
            var current = this._Active[i];
            current[0].removeEventListener(current[1], current[2]);
            this._Active.splice(i, 1);
        }
    }, declare: function(attached, on, callback, capture){
        attached.addEventListener(on, callback, (capture || false));
        if(this._Active.push([attached, on, callback])){
            return this._Active.length - 1;
        }
    }
};

And you can use it like so:

// declare a new onclick listener attached to the document
var clickListener = Listener.declare(document, "click" function(e){
    // on click, remove the listener and log the clicked element
    console.log(e.target);
    Listener.removeAtIndex(clickListener);
});

// completely remove all active listeners 
// (at least, ones declared via the Listener object)
Listener.purge();

// works exactly like removeEventListener
Listener.remove(element, on, callback);

jQuery document.createElement equivalent?

What about this, for example when you want to add a <option> element inside a <select>

$('<option/>')
  .val(optionVal)
  .text('some option')
  .appendTo('#mySelect')

You can obviously apply to any element

$('<div/>')
  .css('border-color', red)
  .text('some text')
  .appendTo('#parentDiv')

Equivalent of explode() to work with strings in MySQL

I try with SUBSTRING_INDEX(string,delimiter,count)

mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', 2);
-> 'www.mysql'

mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', -2);
-> 'mysql.com'

see more on mysql.com http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_substring-index

Fixed digits after decimal with f-strings

Include the type specifier in your format expression:

>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'

Format a Go string without printing?

Sprintf is what you are looking for.

Example

fmt.Sprintf("foo: %s", bar)

You can also see it in use in the Errors example as part of "A Tour of Go."

return fmt.Sprintf("at %v, %s", e.When, e.What)

How to Remove Line Break in String

Clean function can be called from VBA this way:

Range("A1").Value = Application.WorksheetFunction.Clean(Range("A1"))

However as written here, the CLEAN function was designed to remove the first 32 non-printing characters in the 7 bit ASCII code (values 0 through 31) from text. In the Unicode character set, there are additional nonprinting characters (values 127, 129, 141, 143, 144, and 157). By itself, the CLEAN function does not remove these additional nonprinting characters.

Rick Rothstein have written code to handle even this situation here this way:

Function CleanTrim(ByVal S As String, Optional ConvertNonBreakingSpace As Boolean = True) As String
  Dim X As Long, CodesToClean As Variant
  CodesToClean = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, _
                       21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 127, 129, 141, 143, 144, 157)
  If ConvertNonBreakingSpace Then S = Replace(S, Chr(160), " ")
  For X = LBound(CodesToClean) To UBound(CodesToClean)
    If InStr(S, Chr(CodesToClean(X))) Then S = Replace(S, Chr(CodesToClean(X)), "")
  Next
  CleanTrim = WorksheetFunction.Trim(S)
End Function

How to handle change of checkbox using jQuery?

$("input[type=checkbox]").on("change", function() { 

    if (this.checked) {

      //do your stuff

     }
});

How to see the actual Oracle SQL statement that is being executed

-- i use something like this, with concepts and some code stolen from asktom.
-- suggestions for improvements are welcome

WITH
sess AS
(
SELECT *
FROM V$SESSION
WHERE USERNAME = USER
ORDER BY SID
)
SELECT si.SID,
si.LOCKWAIT,
si.OSUSER,
si.PROGRAM,
si.LOGON_TIME,
si.STATUS,
(
SELECT ROUND(USED_UBLK*8/1024,1)
FROM V$TRANSACTION,
sess
WHERE sess.TADDR = V$TRANSACTION.ADDR
AND sess.SID = si.SID

) rollback_remaining,

(
SELECT (MAX(DECODE(PIECE, 0,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 1,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 2,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 3,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 4,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 5,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 6,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 7,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 8,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 9,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 10,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 11,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 12,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 13,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 14,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 15,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 16,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 17,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 18,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 19,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 20,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 21,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 22,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 23,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 24,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 25,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 26,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 27,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 28,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 29,SQL_TEXT,NULL)))
FROM V$SQLTEXT_WITH_NEWLINES
WHERE ADDRESS = SI.SQL_ADDRESS AND
PIECE < 30
) SQL_TEXT
FROM sess si;