Programs & Examples On #Mschart

This tag refers to the System.Windows.Forms.DataVisualization.Charting and System.Web.ui.datavisualization.charting Namespaces, used to create controls for charting using the .NET framework.

Line Break in XML formatting?

Here is what I use when I don't have access to the source string, e.g. for downloaded HTML:

// replace newlines with <br>
public static String replaceNewlinesWithBreaks(String source) {
    return source != null ? source.replaceAll("(?:\n|\r\n)","<br>") : "";
}

For XML you should probably edit that to replace with <br/> instead.

Example of its use in a function (additional calls removed for clarity):

// remove HTML tags but preserve supported HTML text styling (if there is any)
public static CharSequence getStyledTextFromHtml(String source) {
    return android.text.Html.fromHtml(replaceNewlinesWithBreaks(source));
}

...and a further example:

textView.setText(getStyledTextFromHtml(someString));

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

Nothing worked for me for these errors EXCEPT

... was not expected, 
... there is an error in XML document (1,2)
... System.FormatException Input String was not in correct format ...

Except this way

1- You need to inspect the xml response as string (the response that you are trying to de-serialize to an object)

2- Use online tools for string unescape and xml prettify/formatter

3- MAKE SURE that the C# Class (main class) you are trying to map/deserialize the xml string to HAS AN XmlRootAttribute that matches the root element of the response.

Exmaple:

My XML Response was staring like :

<ShipmentCreationResponse xmlns="http://ws.aramex.net/ShippingAPI/v1/">
       <Transaction i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"/>
           ....

And the C# class definition + attributes was like :

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.MessageContractAttribute(WrapperName="ShipmentCreationResponse", WrapperNamespace="http://ws.aramex.net/ShippingAPI/v1/", IsWrapped=true)]
public partial class ShipmentCreationResponse {
  .........
}

Note that the class definition does not have "XmlRootAttribute"

[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://ws.aramex.net/ShippingAPI/v1/", IsNullable = false)]

And when i try to de serialize using a generic method :

public static T Deserialize<T>(string input) where T : class
{
    System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));

    using (System.IO.StringReader sr = new System.IO.StringReader(input))
    {
        return (T)ser.Deserialize(sr);
    }
}





var _Response = GeneralHelper.XMLSerializer.Deserialize<ASRv2.ShipmentCreationResponse>(xml);

I was getting the errors above

... was not expected, ... there is an error in XML document (1,2) ...

Now by just adding the "XmlRootAttribute" that fixed the issue for ever and for every other requests/responses i had a similar issue with:

[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://ws.aramex.net/ShippingAPI/v1/", IsNullable = false)]

..

[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ws.aramex.net/ShippingAPI/v1/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://ws.aramex.net/ShippingAPI/v1/", IsNullable = false)]
public partial class ShipmentCreationResponse
{
    ........
}

HTTP GET in VB.NET

In VB.NET:

Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString("http://api.hostip.info/?ip=68.180.206.184")

In C#:

System.Net.WebClient webClient = new System.Net.WebClient();
string result = webClient.DownloadString("http://api.hostip.info/?ip=68.180.206.184");

Nginx 403 error: directory index of [folder] is forbidden

I resolved my problem, if i configure like follow:

location = /login {
    index  login2.html;
}

It'll show the 403 error.

[error] 4212#2916: *2 directory index of "D:\path/to/login/" is forbidden

I've tried autoindex on, but not working. If i change my configure like this, it works.

location = /login/ {
    index  login2.html;
}

I think the exact matching, if it's a path should be a directory.

Plot logarithmic axes with matplotlib in python

if you want to change the base of logarithm, just add:

plt.yscale('log',base=2) 

Before Matplotlib 3.3, you would have to use basex/basey as the bases of log

How to extract text from the PDF document?

Download the class.pdf2text.php @ https://pastebin.com/dvwySU1a or http://www.phpclasses.org/browse/file/31030.html (Registration required)

Code:

include('class.pdf2text.php');
$a = new PDF2Text();
$a->setFilename('filename.pdf'); 
$a->decodePDF();
echo $a->output(); 

  • class.pdf2text.php Project Home

  • pdf2textclass doesn't work with all the PDF's I've tested, If it doesn't work for you, try PDF Parser


Update .NET web service to use TLS 1.2

if you're using .Net earlier than 4.5 you wont have Tls12 in the enum so state is explicitly mentioned here

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

py2exe - generate single executable file

As the other poster mention, py2exe, will generate an executable + some libraries to load. You can also have some data to add to your program.

Next step is to use an installer, to package all this into one easy-to-use installable/unistallable program.

I have used InnoSetup with delight for several years and for commercial programs, so I heartily recommend it.

What is a "web service" in plain English?

A web service differs from a web site in that a web service provides information consumable by software rather than humans. As a result, we are usually talking about exposed JSON, XML, or SOAP services.

Web services are a key component in "mashups". Mashups are when information from many websites is automatically aggregated into a new and useful service. For example, there are sites that aggregate Google Maps with information about police reports to give you a graphical representation of crime in your area. Another type of mashup would be to take real stock data provided by another site and combine it with a fake trading application to create a stock-market "game".

Web services are also used to provide news (see RSS), latest items added to a site, information on new products, podcasts, and other great features that make the modern web turn.

Hope this helps!

Iterating over ResultSet and adding its value in an ArrayList

If I've understood your problem correctly, there are two possible problems here:

  • resultset is null - I assume that this can't be the case as if it was you'd get an exception in your while loop and nothing would be output.
  • The second problem is that resultset.getString(i++) will get columns 1,2,3 and so on from each subsequent row.

I think that the second point is probably your problem here.

Lets say you only had 1 row returned, as follows:

Col 1, Col 2, Col 3 
A    ,     B,     C

Your code as it stands would only get A - it wouldn't get the rest of the columns.

I suggest you change your code as follows:

ResultSet resultset = ...;
ArrayList<String> arrayList = new ArrayList<String>(); 
while (resultset.next()) {                      
    int i = 1;
    while(i <= numberOfColumns) {
        arrayList.add(resultset.getString(i++));
    }
    System.out.println(resultset.getString("Col 1"));
    System.out.println(resultset.getString("Col 2"));
    System.out.println(resultset.getString("Col 3"));                    
    System.out.println(resultset.getString("Col n"));
}

Edit:

To get the number of columns:

ResultSetMetaData metadata = resultset.getMetaData();
int numberOfColumns = metadata.getColumnCount();

Conversion failed when converting the varchar value 'simple, ' to data type int

Given that you're only converting to ints to then perform a comparison, I'd just switch the table definition around to using varchar also:

Create table #myTempTable
(
num varchar(12)
)
insert into #myTempTable (num) values (1),(2),(3),(4),(5)

and remove all of the attempted CONVERTs from the rest of the query.

 SELECT a.name, a.value AS value, COUNT(*) AS pocet   
 FROM 
 (SELECT item.name, value.value 
  FROM mdl_feedback AS feedback 
  INNER JOIN mdl_feedback_item AS item 
       ON feedback.id = item.feedback
  INNER JOIN mdl_feedback_value AS value 
       ON item.id = value.item 
   WHERE item.typ = 'multichoicerated' AND item.feedback IN (43)
 ) AS a 
 INNER JOIN #myTempTable 
     on a.value = #myTempTable.num
 GROUP BY a.name, a.value ORDER BY a.name

gcc/g++: "No such file or directory"

this works for me, sudo apt-get install libx11-dev

How can I use pickle to save a dict?

I've found pickling confusing (possibly because I'm thick). I found that this works, though:

myDictionaryString=str(myDictionary)

Which you can then write to a text file. I gave up trying to use pickle as I was getting errors telling me to write integers to a .dat file. I apologise for not using pickle.

error: the details of the application error from being viewed remotely

Dear olga is clear what the message says. Turn off the custom errors to see the details about this error for fix it, and then you close them back. So add mode="off" as:

<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>

Relative answer: Deploying website: 500 - Internal server error

By the way: The error message declare that the web.config is not the one you type it here. Maybe you have forget to upload your web.config ? And remember to close the debug flag on the web.config that you use for online pages.

Useful example of a shutdown hook in Java?

Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html

What are the complexity guarantees of the standard containers?

Another quick lookup table is available at this github page

Note : This does not consider all the containers such as, unordered_map etc. but is still great to look at. It is just a cleaner version of this

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

What are .NumberFormat Options In Excel VBA?

Thanks to this question (and answers), I discovered an easy way to get at the exact NumberFormat string for virtually any format that Excel has to offer.


How to Obtain the NumberFormat String for Any Excel Number Format


Step 1: In the user interface, set a cell to the NumberFormat you want to use.

I manually formatted a cell to Chinese (PRC) currency

In my example, I selected the Chinese (PRC) Currency from the options contained in the "Account Numbers Format" combo box.

Step 2: Expand the Number Format dropdown and select "More Number Formats...".

Open the Number Format dropdown

Step 3: In the Number tab, in Category, click "Custom".

Click Custom

The "Sample" section shows the Chinese (PRC) currency formatting that I applied.

The "Type" input box contains the NumberFormat string that you can use programmatically.

So, in this example, the NumberFormat of my Chinese (PRC) Currency cell is as follows:

_ [$¥-804]* #,##0.00_ ;_ [$¥-804]* -#,##0.00_ ;_ [$¥-804]* "-"??_ ;_ @_ 

If you do these steps for each NumberFormat that you desire, then the world is yours.

I hope this helps.

Can I convert long to int?

A possible way is to use the modulo operator to only let the values stay in the int32 range, and then cast it to int.

var intValue= (int)(longValue % Int32.MaxValue);

Laravel where on relationship object

I created a custom query scope in BaseModel (my all models extends this class):

/**
 * Add a relationship exists condition (BelongsTo).
 *
 * @param  Builder        $query
 * @param  string|Model   $relation   Relation string name or you can try pass directly model and method will try guess relationship
 * @param  mixed          $modelOrKey
 * @return Builder|static
 */
public function scopeWhereHasRelated(Builder $query, $relation, $modelOrKey = null)
{
    if ($relation instanceof Model && $modelOrKey === null) {
        $modelOrKey = $relation;
        $relation   = Str::camel(class_basename($relation));
    }

    return $query->whereHas($relation, static function (Builder $query) use ($modelOrKey) {
        return $query->whereKey($modelOrKey instanceof Model ? $modelOrKey->getKey() : $modelOrKey);
    });
}

You can use it in many contexts for example:

Event::whereHasRelated('participants', 1)->isNotEmpty(); // where has participant with id = 1 

Furthermore, you can try to omit relationship name and pass just model:

$participant = Participant::find(1);
Event::whereHasRelated($participant)->first(); // guess relationship based on class name and get id from model instance

How to use if statements in underscore.js templates?

This should do the trick:

<% if (typeof(date) !== "undefined") { %>
    <span class="date"><%= date %></span>
<% } %>

Remember that in underscore.js templates if and for are just standard javascript syntax wrapped in <% %> tags.

php refresh current page?

header('Location: '.$_SERVER['REQUEST_URI']);

How do JavaScript closures work?

I do not understand why the answers are so complex here.

Here is a closure:

var a = 42;

function b() { return a; }

Yes. You probably use that many times a day.


There is no reason to believe closures are a complex design hack to address specific problems. No, closures are just about using a variable that comes from a higher scope from the perspective of where the function was declared (not run).

Now what it allows you to do can be more spectacular, see other answers.

Predefined type 'System.ValueTuple´2´ is not defined or imported

I would not advise adding ValueTuple as a package reference to the .net Framework projects. As you know this assembly is available from 4.7 .NET Framework.

There can be certain situations when your project will try to include at all costs ValueTuple from .NET Framework folder instead of package folder and it can cause some assembly not found errors.

We had this problem today in company. We had solution with 2 projects (I oversimplify that) :

  • Lib
  • Web

Lib was including ValueTuple and Web was using Lib. It turned out that by some unknown reason Web when trying to resolve path to ValueTuple was having HintPath into .NET Framework directory and was taking incorrect version. Our application was crashing because of that. ValueTuple was not defined in .csproj of Web nor HintPath for that assembly. The problem was very weird. Normally it would copy the assembly from package folder. This time was not normal.

For me it is always risk to add System.* package references. They are often like time-bomb. They are fine at start and they can explode in your face in the worst moment. My rule of thumb: Do not use System.* Nuget package for .NET Framework if there is no real need for them.

We resolved our problem by adding manually ValueTuple into .csproj file inside Web project.

Should MySQL have its timezone set to UTC?

PHP and MySQL have their own default timezone configurations. You should synchronize time between your data base and web application, otherwise you could run some issues.

Read this tutorial: How To Synchronize Your PHP and MySQL Timezones

PHPExcel set border and format for all sheets in spreadsheet

To answer your extra question:

You can set which rows should be repeated on every page using:

$objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 5);

Now, row 1, 2, 3, 4 and 5 will be repeated.

How to read files from resources folder in Scala?

Onliner solution for Scala >= 2.12

val source_html = Source.fromResource("file.html").mkString

Pass multiple arguments into std::thread

You literally just pass them in std::thread(func1,a,b,c,d); that should have compiled if the objects existed, but it is wrong for another reason. Since there is no object created you cannot join or detach the thread and the program will not work correctly. Since it is a temporary the destructor is immediately called, since the thread is not joined or detached yet std::terminate is called. You could std::join or std::detach it before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach .

This is how it should be done.

std::thread t(func1,a,b,c,d);
t.join();  

You could also detach the thread, read-up on threads if you don't know the difference between joining and detaching.

How to grant permission to users for a directory using command line in Windows?

Bulk folder creation and grant permission works me by using the below powershell script.

Import-Csv "D:\Scripts\foldernames.csv" | foreach-object {
    $username = $_.foldername 

    # foldername is the header of csv file

    $domain = “example.com”

    $folder= "D:\Users"

    $domainusername = $domain+“\”+$username

    New-Item $folder\$username –Type Directory

    Get-Acl $folder\$username  

    $acl = Get-Acl $folder\$username

    $acl.SetAccessRuleProtection($True, $False)

    $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
    $acl.AddAccessRule($rule)

    $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("SYSTEM","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
    $acl.AddAccessRule($rule)

    $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$domain\Domain Admins","Read", "ContainerInherit, ObjectInherit", "None", "Allow")
    $acl.AddAccessRule($rule)

    $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($domainusername,"Modify", "ContainerInherit, ObjectInherit", "None", "Allow")
    $acl.AddAccessRule($rule)

    Set-Acl $folder\$username $acl
}

Note: You have to create same domain username in csv file otherwise you will get permission issues

How do I find the width & height of a terminal window?

  • tput cols tells you the number of columns.
  • tput lines tells you the number of rows.

File path issues in R using Windows ("Hex digits in character string" error)

A simple way is to use python. in python terminal type

r"C:\Users\surfcat\Desktop\2006_dissimilarity.csv" and you'll get back 'C:\Users\surfcat\Desktop\2006_dissimilarity.csv'

Closing pyplot windows

Please use

plt.show(block=False)
plt.close('all')

Format Date/Time in XAML in Silverlight

For me this worked:

<TextBlock Text="{Binding Date , StringFormat=g}" Width="130"/>

If want to show seconds also using G instead of g :

<TextBlock Text="{Binding Date , StringFormat=G}" Width="130"/>

Also if want for changing date type to another like Persian , using Language :

<TextBlock Text="{Binding Date , StringFormat=G}" Width="130" Language="fa-IR"/>

Cannot open local file - Chrome: Not allowed to load local resource

You won't be able to load an image outside of the project directory or from a user level directory, hence the "cannot access local resource warning".

But if you were to place the file in a root folder of your project like in {rootFolder}\Content\my-image.jpg and referenced it like so:

<img src="/Content/my-image.jpg" />

Exception in thread "main" java.lang.Error: Unresolved compilation problems

Your problem is in this line: Message messageObject = new Message ();
This error says that the Message class is not known at compile time.

So you need to import the Message class.

Something like this:

import package1.package2.Message;

Check this out.

http://docs.oracle.com/javase/tutorial/java/package/usepkgs.html

LINQ Contains Case Insensitive

StringComparison.InvariantCultureIgnoreCase just do the job for me:

.Where(fi => fi.DESCRIPTION.Contains(description, StringComparison.InvariantCultureIgnoreCase));

Groovy String to Date

Date#parse is deprecated . The alternative is :

java.text.DateFormat#parse 

thereFore :

 new SimpleDateFormat("E MMM dd H:m:s z yyyy", Locale.ARABIC).parse(testDate)

Note that SimpleDateFormat is an implementation of DateFormat

Multiple try codes in one block

You could try a for loop


for func,args,kwargs in zip([a,b,c,d], 
                            [args_a,args_b,args_c,args_d],
                            [kw_a,kw_b,kw_c,kw_d]):
    try:
       func(*args, **kwargs)
       break
    except:
       pass

This way you can loop as many functions as you want without making the code look ugly

How to unit test abstract classes: extend with stubs?

Following @patrick-desjardins answer, I implemented abstract and it's implementation class along with @Test as follows:

Abstract class - ABC.java

import java.util.ArrayList;
import java.util.List;

public abstract class ABC {

    abstract String sayHello();

    public List<String> getList() {
        final List<String> defaultList = new ArrayList<>();
        defaultList.add("abstract class");
        return defaultList;
    }
}

As Abstract classes cannot be instantiated, but they can be subclassed, concrete class DEF.java, is as follows:

public class DEF extends ABC {

    @Override
    public String sayHello() {
        return "Hello!";
    }
}

@Test class to test both abstract as well as non-abstract method:

import org.junit.Before;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.contains;
import java.util.Collection;
import java.util.List;
import static org.hamcrest.Matchers.equalTo;

import org.junit.Test;

public class DEFTest {

    private DEF def;

    @Before
    public void setup() {
        def = new DEF();
    }

    @Test
    public void add(){
        String result = def.sayHello();
        assertThat(result, is(equalTo("Hello!")));
    }

    @Test
    public void getList(){
        List<String> result = def.getList();
        assertThat((Collection<String>) result, is(not(empty())));
        assertThat(result, contains("abstract class"));
    }
}

PHP syntax question: What does the question mark and colon mean?

It's the ternary form of the if-else operator. The above statement basically reads like this:

if ($add_review) then {
    return FALSE; //$add_review evaluated as True
} else {
    return $arg //$add_review evaluated as False
}

See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/

Check if PHP session has already started

Recommended way for versions of PHP >= 5.4.0 , PHP 7

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

Reference: http://www.php.net/manual/en/function.session-status.php

For versions of PHP < 5.4.0

if(session_id() == '') {
    session_start();
}

Downloading images with node.js

You can use Axios (a promise-based HTTP client for Node.js) to download images in the order of your choosing in an asynchronous environment:

npm i axios

Then, you can use the following basic example to begin downloading images:

const fs = require('fs');
const axios = require('axios');

/* ============================================================
  Function: Download Image
============================================================ */

const download_image = (url, image_path) =>
  axios({
    url,
    responseType: 'stream',
  }).then(
    response =>
      new Promise((resolve, reject) => {
        response.data
          .pipe(fs.createWriteStream(image_path))
          .on('finish', () => resolve())
          .on('error', e => reject(e));
      }),
  );

/* ============================================================
  Download Images in Order
============================================================ */

(async () => {
  let example_image_1 = await download_image('https://example.com/test-1.png', 'example-1.png');

  console.log(example_image_1.status); // true
  console.log(example_image_1.error); // ''

  let example_image_2 = await download_image('https://example.com/does-not-exist.png', 'example-2.png');

  console.log(example_image_2.status); // false
  console.log(example_image_2.error); // 'Error: Request failed with status code 404'

  let example_image_3 = await download_image('https://example.com/test-3.png', 'example-3.png');

  console.log(example_image_3.status); // true
  console.log(example_image_3.error); // ''
})();

Multiple separate IF conditions in SQL Server

IF you are checking one variable against multiple condition then you would use something like this Here the block of code where the condition is true will be executed and other blocks will be ignored.

IF(@Var1 Condition1)
     BEGIN
      /*Your Code Goes here*/
     END

ELSE IF(@Var1 Condition2)
      BEGIN
        /*Your Code Goes here*/ 
      END 

    ELSE      --<--- Default Task if none of the above is true
     BEGIN
       /*Your Code Goes here*/
     END

If you are checking conditions against multiple variables then you would have to go for multiple IF Statements, Each block of code will be executed independently from other blocks.

IF(@Var1 Condition1)
 BEGIN
   /*Your Code Goes here*/
 END


IF(@Var2 Condition1)
 BEGIN
   /*Your Code Goes here*/
 END


IF(@Var3 Condition1)
 BEGIN
   /*Your Code Goes here*/
 END

After every IF statement if there are more than one statement being executed you MUST put them in BEGIN..END Block. Anyway it is always best practice to use BEGIN..END blocks

Update

Found something in your code some BEGIN END you are missing

ELSE IF(@ID IS NOT NULL AND @ID in (SELECT ID FROM Places))   -- Outer Most Block ELSE IF
BEGIN   
     SELECT @MyName = Name ...  
    ...Some stuff....                       
    IF(SOMETHNG_1)         -- IF
                 --BEGIN
        BEGIN TRY               
            UPDATE ....                                                                 
        END TRY

        BEGIN CATCH
            SELECT ERROR_MESSAGE() AS 'Message' 
            RETURN -1
        END CATCH
                -- END
    ELSE IF(SOMETHNG_2)    -- ELSE IF
                 -- BEGIN
        BEGIN TRY
            UPDATE ...                                                      
        END TRY
        BEGIN CATCH
            SELECT ERROR_MESSAGE() AS 'Message' 
            RETURN -1
        END CATCH   
               -- END
    ELSE                  -- ELSE
        BEGIN
            BEGIN TRY
                UPDATE ...                                                              
            END TRY
            BEGIN CATCH
                SELECT ERROR_MESSAGE() AS 'Message' 
                RETURN -1
            END CATCH   
         END             
      --The above works I then insert this below and these if statement become nested----
          IF(@A!= @SA)
            BEGIN
             exec Store procedure 
                    @FIELD = 15,
                    ... more params...
            END                 
        IF(@S!= @SS)
          BEGIN
             exec Store procedure 
                    @FIELD = 10,
                    ... more params...

Server configuration by allow_url_fopen=0 in

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

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

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

How to add a new schema to sql server 2008?

In SQL Server 2016 SSMS expand 'DATABASNAME' > expand 'SECURITY' > expand 'SCHEMA' ; right click 'SCHEMAS' from the popup left click 'NEW SCHEMAS...' add the name on the window that opens and add an owner i.e dbo click 'OK' button

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

I also get this issue when i change package name of my application.

In your android studio project find "google-services.json" file. Open it. and check whether package name of your application is same as written in this file.

The package name of your application and package name written in "google-services.json" file must be same.

how to set start page in webconfig file in asp.net c#

You can achieve it by code also, In you Global.asax file in Session_Start event write response.redirect to your start page like following.

void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started

            Response.Redirect("~/Index.aspx");

        }

You can get redirect page name from database or any other storage to change the application start page while application is running no need to edit web.config or change any IIS settings

Putting a simple if-then-else statement on one line

<execute-test-successful-condition> if <test> else <execute-test-fail-condition>

with your code-snippet it would become,

count = 0 if count == N else N + 1

'Must Override a Superclass Method' Errors after importing a project into Eclipse

Eclipse is defaulting to Java 1.5 and you have classes implementing interface methods (which in Java 1.6 can be annotated with @Override, but in Java 1.5 can only be applied to methods overriding a superclass method).

Go to your project/IDE preferences and set the Java compiler level to 1.6 and also make sure you select JRE 1.6 to execute your program from Eclipse.

How do I use regex in a SQLite query?

for rails

            db = ActiveRecord::Base.connection.raw_connection
            db.create_function('regexp', 2) do |func, pattern, expression|
              func.result = expression.to_s.match(Regexp.new(pattern.to_s, Regexp::IGNORECASE)) ? 1 : 0
            end

How does #include <bits/stdc++.h> work in C++?

That header file is not part of the C++ standard, is therefore non-portable, and should be avoided.

Moreover, even if there were some catch-all header in the standard, you would want to avoid it in lieu of specific headers, since the compiler has to actually read in and parse every included header (including recursively included headers) every single time that translation unit is compiled.

Java 8 Lambda Stream forEach with multiple statements

List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");

//lambda
//Output : A,B,C,D,E
items.forEach(item->System.out.println(item));

//Output : C
items.forEach(item->{
    System.out.println(item);
    System.out.println(item.toLowerCase());
  }
});

How do I profile memory usage in Python?

maybe it help:
<see additional>

pip install gprof2dot
sudo apt-get install graphviz

gprof2dot -f pstats profile_for_func1_001 | dot -Tpng -o profile.png

def profileit(name):
    """
    @profileit("profile_for_func1_001")
    """
    def inner(func):
        def wrapper(*args, **kwargs):
            prof = cProfile.Profile()
            retval = prof.runcall(func, *args, **kwargs)
            # Note use of name from outer scope
            prof.dump_stats(name)
            return retval
        return wrapper
    return inner

@profileit("profile_for_func1_001")
def func1(...)

Cycles in an Undirected Graph

An undirected graph is acyclic (i.e., a forest) if a DFS yields no back edges. Since back edges are those edges (u, v) connecting a vertex u to an ancestor v in a depth-first tree, so no back edges means there are only tree edges, so there is no cycle. So we can simply run DFS. If find a back edge, there is a cycle. The complexity is O(V) instead of O(E + V). Since if there is a back edge, it must be found before seeing |V| distinct edges. This is because in a acyclic (undirected) forest, |E| = |V| + 1.

How do I get the collection of Model State Errors in ASP.NET MVC?

Putting together several answers from above, this is what I ended up using:

var validationErrors = ModelState.Values.Where(E => E.Errors.Count > 0)
    .SelectMany(E => E.Errors)
    .Select(E => E.ErrorMessage)
    .ToList();

validationErrors ends up being a List<string> that contains each error message. From there, it's easy to do what you want with that list.

enter image description here

How to change lowercase chars to uppercase using the 'keyup' event?

Make sure that the field has this attribute in its html.

_x000D_
_x000D_
ClientIDMode="Static"
_x000D_
_x000D_
_x000D_

and then use this in your script:

_x000D_
_x000D_
$("#NameOfYourTextBox").change(function () {_x000D_
                 $(this).val($(this).val().toUpperCase());_x000D_
             });
_x000D_
_x000D_
_x000D_

check the null terminating character in char*

You have used '/0' instead of '\0'. This is incorrect: the '\0' is a null character, while '/0' is a multicharacter literal.

Moreover, in C it is OK to skip a zero in your condition:

while (*(forward++)) {
    ...
}

is a valid way to check character, integer, pointer, etc. for being zero.

How to create PDF files in Python

If you are familiar with LaTex you might want to consider pylatex

One of the advantages of pylatex is that it is easy to control the image quality. The images in your pdf will be of the same quality as the original images. When using reportlab, I experienced that the images were automatically compressed, and the image quality reduced.

The disadvantage of pylatex is that, since it is based on LaTex, it can be hard to place images exactly where you want on the page. However, I have found that using the position argument in the Figure class, and sometimes Subfigure, gives good enough results.

Example code for creating a pdf with a single image:

from pylatex import Document, Figure

doc = Document(documentclass="article")
with doc.create(Figure(position='p')) as fig:
fig.add_image('Lenna.png')

doc.generate_pdf('test', compiler='latexmk', compiler_args=["-pdf", "-pdflatex=pdflatex"], clean_tex=True)

In addition to installing pylatex (pip install pylatex), you need to install LaTex. For Ubuntu and other Debian systems you can run sudo apt-get install texlive-full. If you are using Windows I would recommend MixTex

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

This is fixed by:

a) adding schemas: [ CUSTOM_ELEMENTS_SCHEMA ] to every component or

b) adding

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

and

schemas: [
  CUSTOM_ELEMENTS_SCHEMA
],

to your module.

Python argparse: default value or specified value

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--example', nargs='?', const=1, type=int)
args = parser.parse_args()
print(args)

% test.py 
Namespace(example=None)
% test.py --example
Namespace(example=1)
% test.py --example 2
Namespace(example=2)

  • nargs='?' means 0-or-1 arguments
  • const=1 sets the default when there are 0 arguments
  • type=int converts the argument to int

If you want test.py to set example to 1 even if no --example is specified, then include default=1. That is, with

parser.add_argument('--example', nargs='?', const=1, type=int, default=1)

then

% test.py 
Namespace(example=1)

Set QLineEdit to accept only numbers

QLineEdit::setValidator(), for example:

myLineEdit->setValidator( new QIntValidator(0, 100, this) );

or

myLineEdit->setValidator( new QDoubleValidator(0, 100, 2, this) );

See: QIntValidator, QDoubleValidator, QLineEdit::setValidator

Npm Error - No matching version found for

Try removing "package-lock.json" and running "npm install && npm update", it'll install the latest version and clear all errors.

how to get the value of css style using jquery

You code is correct. replace items with .items as below

<script>
  var n = $(".items").css("left");
  if(n == -900){
    $(".items span").fadeOut("slow");
  }
</script>

How to get date, month, year in jQuery UI datepicker?

You can use method getDate():

$('#calendar').datepicker({
    dateFormat: 'yy-m-d',
    inline: true,
    onSelect: function(dateText, inst) { 
        var date = $(this).datepicker('getDate'),
            day  = date.getDate(),  
            month = date.getMonth() + 1,              
            year =  date.getFullYear();
        alert(day + '-' + month + '-' + year);
    }
});

FIDDLE

std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

They are not really same mutexes, lock_guard<muType> has nearly the same as std::mutex, with a difference that it's lifetime ends at the end of the scope (D-tor called) so a clear definition about these two mutexes :

lock_guard<muType> has a mechanism for owning a mutex for the duration of a scoped block.

And

unique_lock<muType> is a wrapper allowing deferred locking, time-constrained attempts at locking, recursive locking, transfer of lock ownership, and use with condition variables.

Here is an example implemetation :

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <chrono>

using namespace std::chrono;

class Product{

   public:

       Product(int data):mdata(data){
       }

       virtual~Product(){
       }

       bool isReady(){
       return flag;
       }

       void showData(){

        std::cout<<mdata<<std::endl;
       }

       void read(){

         std::this_thread::sleep_for(milliseconds(2000));

         std::lock_guard<std::mutex> guard(mmutex);

         flag = true;

         std::cout<<"Data is ready"<<std::endl;

         cvar.notify_one();

       }

       void task(){

       std::unique_lock<std::mutex> lock(mmutex);

       cvar.wait(lock, [&, this]() mutable throw() -> bool{ return this->isReady(); });

       mdata+=1;

       }

   protected:

    std::condition_variable cvar;
    std::mutex mmutex;
    int mdata;
    bool flag = false;

};

int main(){

     int a = 0;
     Product product(a);

     std::thread reading(product.read, &product);
     std::thread setting(product.task, &product);

     reading.join();
     setting.join();


     product.showData();
    return 0;
}

In this example, i used the unique_lock<muType> with condition variable

How do I create an empty array/matrix in NumPy?

To create an empty multidimensional array in NumPy (e.g. a 2D array m*n to store your matrix), in case you don't know m how many rows you will append and don't care about the computational cost Stephen Simmons mentioned (namely re-buildinging the array at each append), you can squeeze to 0 the dimension to which you want to append to: X = np.empty(shape=[0, n]).

This way you can use for example (here m = 5 which we assume we didn't know when creating the empty matrix, and n = 2):

import numpy as np

n = 2
X = np.empty(shape=[0, n])

for i in range(5):
    for j  in range(2):
        X = np.append(X, [[i, j]], axis=0)

print X

which will give you:

[[ 0.  0.]
 [ 0.  1.]
 [ 1.  0.]
 [ 1.  1.]
 [ 2.  0.]
 [ 2.  1.]
 [ 3.  0.]
 [ 3.  1.]
 [ 4.  0.]
 [ 4.  1.]]

How to remove the arrows from input[type="number"] in Opera

Those arrows are part of the Shadow DOM, which are basically DOM elements on your page which are hidden from you. If you're new to the idea, a good introductory read can be found here.

For the most part, the Shadow DOM saves us time and is good. But there are instances, like this question, where you want to modify it.

You can modify these in Webkit now with the right selectors, but this is still in the early stages of development. The Shadow DOM itself has no unified selectors yet, so the webkit selectors are proprietary (and it isn't just a matter of appending -webkit, like in other cases).

Because of this, it seems likely that Opera just hasn't gotten around to adding this yet. Finding resources about Opera Shadow DOM modifications is tough, though. A few unreliable internet sources I've found all say or suggest that Opera doesn't currently support Shadow DOM manipulation.

I spent a bit of time looking through the Opera website to see if there'd be any mention of it, along with trying to find them in Dragonfly...neither search had any luck. Because of the silence on this issue, and the developing nature of the Shadow DOM + Shadow DOM manipulation, it seems to be a safe conclusion that you just can't do it in Opera, at least for now.

How to remove an iOS app from the App Store

I just changed availability date to a future date. After doing that, I received following message -

You have selected an Available Date in the future. This will remove your currently live version from the App Store until the new date. Changing Available Date affects all versions of the application, both Ready For Sale and In Review.

Which means that the app is removed and no longer available.

How to add background-image using ngStyle (angular2)?

Also you can try this:

[style.background-image]="'url(' + photo + ')'"

pandas groupby sort within groups

You could also just do it in one go, by doing the sort first and using head to take the first 3 of each group.

In[34]: df.sort_values(['job','count'],ascending=False).groupby('job').head(3)

Out[35]: 
   count     job source
4      7   sales      E
2      6   sales      C
1      4   sales      B
5      5  market      A
8      4  market      D
6      3  market      B

Defining array with multiple types in TypeScript

Im using this version:

exampleArr: Array<{ id: number, msg: string}> = [
   { id: 1, msg: 'message'},
   { id: 2, msg: 'message2'}
 ]

It is a little bit similar to the other suggestions but still easy and quite good to remember.

How to get the xml node value in string

XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
    Console.WriteLine(n[0].InnerText); //Will output '08:29:57'
}

or you could wrap in foreach loop to print each value

XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
    foreach(XmlNode curr in n) {
        Console.WriteLine(curr.InnerText);
    }
}

Display Two <div>s Side-by-Side

Try to Use Flex as that is the new standard of html5.

http://jsfiddle.net/maxspan/1b431hxm/

<div id="row1">
    <div id="column1">I am column one</div>
    <div id="column2">I am column two</div>
</div>

#row1{
    display:flex;
    flex-direction:row;
justify-content: space-around;
}

#column1{
    display:flex;
    flex-direction:column;

}


#column2{
    display:flex;
    flex-direction:column;
}

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

Add click event on div tag using javascript

the document class selector:

document.getElementsByClassName('drill_cursor')[0].addEventListener('click',function(){},false)

also the document query selector https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector

document.querySelector(".drill_cursor").addEventListener('click',function(){},false)

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

If you're going to use a Control from another thread before showing or doing other things with the Control, consider forcing the creation of its handle within the constructor. This is done using the CreateHandle function.

In a multi-threaded project, where the "controller" logic isn't in a WinForm, this function is instrumental in Control constructors for avoiding this error.

CORS with POSTMAN

If you use a website and you fill out a form to submit information (your social security number for example) you want to be sure that the information is being sent to the site you think it's being sent to. So browsers were built to say, by default, 'Do not send information to a domain other than the domain being visited).

Eventually that became too limiting but the default idea still remains in browsers. Don't let the web page send information to a different domain. But this is all browser checking. Chrome and firefox, etc have built in code that says 'before send this request, we're going to check that the destination matches the page being visited'.

Postman (or CURL on the cmd line) doesn't have those built in checks. You're manually interacting with a site so you have full control over what you're sending.

The import com.google.android.gms cannot be resolved

Another way is to let Eclipse do the import work for you. Hover your mouse over the com.google.android.gms import that can not be resolved and towards the bottom of the popup menu, select the Fix project setup... option as below. Then it'll prompt to import the google play services library. Select that and you should be good to go.

enter image description here

Mipmap drawables for icons

How are these mipmap images different from the other familiar drawable images?

Here is my two cents in trying to explain the difference. There are two cases you deal with when working with images in Android:

  1. You want to load an image for your device density and you are going to use it "as is", without changing its actual size. In this case you should work with drawables and Android will give you the best fitting image.

  2. You want to load an image for your device density, but this image is going to be scaled up or down. For instance this is needed when you want to show a bigger launcher icon, or you have an animation, which increases image's size. In such cases, to ensure best image quality, you should put your image into mipmap folder. What Android will do is, it will try to pick up the image from a higher density bucket instead of scaling it up. This will increase sharpness (quality) of the image.

Thus, the rule of thumb to decide where to put your image into would be:

  • Launcher icons always go into mipmap folder.
  • Images, which are often scaled up (or extremely scaled down) and whose quality is critical for the app, go into mipmap folder as well.
  • All other images are usual drawables.

How to handle notification when app in background in Firebase

Working as of July 2019

Android compileSdkVersion 28, buildToolsVersion 28.0.3 and firebase-messaging:19.0.1

After many many hours of researching through all of the other StackOverflow questions and answers, and trying innumerable outdated solutions, this solution managed to show notifications in these 3 scenarios:

- App is in foreground:
the notification is received by the onMessageReceived method at my MyFirebaseMessagingService class

- App has been killed (it is not running in background): the notification is sent to the notification tray automatically by FCM. When the user touches the notification the app is launched by calling the activity that has android.intent.category.LAUNCHER in the manifest. You can get the data part of the notification by using getIntent().getExtras() at the onCreate() method.

- App is in background: the notification is sent to the notification tray automatically by FCM. When the user touches the notification the app is brought to the foreground by launching the activity that has android.intent.category.LAUNCHER in the manifest. As my app has launchMode="singleTop" in that activity, the onCreate() method is not called because one activity of the same class is already created, instead the onNewIntent() method of that class is called and you get the data part of the notification there by using intent.getExtras().

Steps: 1- If you define your app's main activity like this:

<activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:screenOrientation="portrait"
    android:launchMode="singleTop">
    <intent-filter>
        <action android:name=".MainActivity" />
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

2- add these lines at the onCreate() method of your MainActivity.class

Intent i = getIntent();
Bundle extras = i.getExtras();
if (extras != null) {
    for (String key : extras.keySet()) {
        Object value = extras.get(key);
        Log.d(Application.APPTAG, "Extras received at onCreate:  Key: " + key + " Value: " + value);
    }
    String title = extras.getString("title");
    String message = extras.getString("body");
    if (message!=null && message.length()>0) {
        getIntent().removeExtra("body");
        showNotificationInADialog(title, message);
    }
}

and these methods to the same MainActivity.class:

@Override
public void onNewIntent(Intent intent){
    //called when a new intent for this class is created.
    // The main case is when the app was in background, a notification arrives to the tray, and the user touches the notification

    super.onNewIntent(intent);

    Log.d(Application.APPTAG, "onNewIntent - starting");
    Bundle extras = intent.getExtras();
    if (extras != null) {
        for (String key : extras.keySet()) {
            Object value = extras.get(key);
            Log.d(Application.APPTAG, "Extras received at onNewIntent:  Key: " + key + " Value: " + value);
        }
        String title = extras.getString("title");
        String message = extras.getString("body");
        if (message!=null && message.length()>0) {
            getIntent().removeExtra("body");
            showNotificationInADialog(title, message);
        }
    }
}


private void showNotificationInADialog(String title, String message) {

    // show a dialog with the provided title and message
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(title);
    builder.setMessage(message);
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.cancel();
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}

3- create the class MyFirebase like this:

package com.yourcompany.app;

import android.content.Intent;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends FirebaseMessagingService {


    public MyFirebaseMessagingService() {
        super();
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d(Application.APPTAG, "myFirebaseMessagingService - onMessageReceived - message: " + remoteMessage);

        Intent dialogIntent = new Intent(this, NotificationActivity.class);
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        dialogIntent.putExtra("msg", remoteMessage);
        startActivity(dialogIntent);

    }

}

4- create a new class NotificationActivity.class like this:

package com.yourcompany.app;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.ContextThemeWrapper;

import com.google.firebase.messaging.RemoteMessage;

public class NotificationActivity extends AppCompatActivity {

private Activity context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = this;
    Bundle extras = getIntent().getExtras();

    Log.d(Application.APPTAG, "NotificationActivity - onCreate - extras: " + extras);

    if (extras == null) {
        context.finish();
        return;
    }

    RemoteMessage msg = (RemoteMessage) extras.get("msg");

    if (msg == null) {
        context.finish();
        return;
    }

    RemoteMessage.Notification notification = msg.getNotification();

    if (notification == null) {
        context.finish();
        return;
    }

    String dialogMessage;
    try {
        dialogMessage = notification.getBody();
    } catch (Exception e){
        context.finish();
        return;
    }
    String dialogTitle = notification.getTitle();
    if (dialogTitle == null || dialogTitle.length() == 0) {
        dialogTitle = "";
    }

    AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(context, R.style.myDialog));
    builder.setTitle(dialogTitle);
    builder.setMessage(dialogMessage);
    builder.setPositiveButton(getResources().getString(R.string.accept), new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.cancel();
        }
    });
    AlertDialog alert = builder.create();
    alert.show();

}

}

5- Add these lines to your app Manifest, inside your tags

    <service
        android:name=".MyFirebaseMessagingService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/default_notification_channel_id"/>

    <activity android:name=".NotificationActivity"
        android:theme="@style/myDialog"> </activity>

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/notification_icon"/>

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/color_accent" />

6- add these lines in your Application.java onCreate() method, or in MainActivity.class onCreate() method:

      // notifications channel creation
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      // Create channel to show notifications.
      String channelId = getResources().getString("default_channel_id");
      String channelName = getResources().getString("General announcements");
      NotificationManager notificationManager = getSystemService(NotificationManager.class);
      notificationManager.createNotificationChannel(new NotificationChannel(channelId,
              channelName, NotificationManager.IMPORTANCE_LOW));
  }

Done.

Now for this to work well in the 3 mentioned scenarios, you have to send the notification from the Firebase web console in the following way:

In the Notification section: Notification Title = Title to display in the notification dialog (optional) Notification text = Message to show to the user (required) Then in the Target section: App = your Android app and in Additional Options section: Android Notification Channel = default_channel_id Custom Data key: title value: (same text here than in the Title field of the Notification section) key: body value: (same text here than in the Message field of the Notification section) key:click_action value: .MainActivity Sound=Disabled
Expires=4 weeks

You can debug it in the Emulator with API 28 with Google Play.

Happy coding!

Spark: subtract two DataFrames

I tried subtract, but the result was not consistent. If I run df1.subtract(df2), not all lines of df1 are shown on the result dataframe, probably due distinct cited on the docs.

This solved my problem: df1.exceptAll(df2)

notifyDataSetChange not working from custom adapter

I had the same problem using ListAdapter

I let Android Studio implement methods for me and this is what I got:

public class CustomAdapter implements ListAdapter {
    ...
    @Override
    public void registerDataSetObserver(DataSetObserver observer) {

    }

    @Override
    public void unregisterDataSetObserver(DataSetObserver observer) {

    }
    ...
}

The problem is that these methods do not call super implementations so notifyDataSetChange is never called.

Either remove these overrides manually or add super calls and it should work again.

@Override
public void registerDataSetObserver(DataSetObserver observer) {
    super.registerDataSetObserver(observer);
}

@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
    super.unregisterDataSetObserver(observer);
}

Android Endless List

The key of this problem is to detect the load-more event, start an async request for data and then update the list. Also an adapter with loading indicator and other decorators is needed. In fact, the problem is very complicated in some corner cases. Just a OnScrollListener implementation is not enough, because sometimes the items do not fill the screen.

I have written a personal package which support endless list for RecyclerView, and also provide a async loader implementation AutoPagerFragment which makes it very easy to get data from a multi-page source. It can load any page you want into a RecyclerView on a custom event, not only the next page.

Here is the address: https://github.com/SphiaTower/AutoPagerRecyclerManager

Update UI from Thread in Android

The most simplest solution I have seen to supply a short execution to the UI thread is via the post() method of a view. This is needed since UI methods are not re-entrant. The method for this is:

package android.view;

public class View;

public boolean post(Runnable action);

The post() method corresponds to the SwingUtilities.invokeLater(). Unfortunately I didn't find something simple that corresponds to the SwingUtilities.invokeAndWait(), but one can build the later based on the former with a monitor and a flag.

So what you save by this is creating a handler. You simply need to find your view and then post on it. You can find your view via findViewById() if you tend to work with id-ed resources. The resulting code is very simple:

/* inside your non-UI thread */

view.post(new Runnable() {
        public void run() {
            /* the desired UI update */
        }
    });
}

Note: Compared to SwingUtilities.invokeLater() the method View.post() does return a boolean, indicating whether the view has an associated event queue. Since I used the invokeLater() resp. post() anyway only for fire and forget, I did not check the result value. Basically you should call post() only after onAttachedToWindow() has been called on the view.

Best Regards

How to solve munmap_chunk(): invalid pointer error in C++

This happens when the pointer passed to free() is not valid or has been modified somehow. I don't really know the details here. The bottom line is that the pointer passed to free() must be the same as returned by malloc(), realloc() and their friends. It's not always easy to spot what the problem is for a novice in their own code or even deeper in a library. In my case, it was a simple case of an undefined (uninitialized) pointer related to branching.

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. GNU 2012-05-10 MALLOC(3)

char *words; // setting this to NULL would have prevented the issue

if (condition) {
    words = malloc( 512 );

    /* calling free sometime later works here */

    free(words)
} else {

    /* do not allocate words in this branch */
}

/* free(words);  -- error here --
*** glibc detected *** ./bin: munmap_chunk(): invalid pointer: 0xb________ ***/

There are many similar questions here about the related free() and rellocate() functions. Some notable answers providing more details:

*** glibc detected *** free(): invalid next size (normal): 0x0a03c978 ***
*** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 ***
glibc detected, realloc(): invalid pointer


IMHO running everything in a debugger (Valgrind) is not the best option because errors like this are often caused by inept or novice programmers. It's more productive to figure out the issue manually and learn how to avoid it in the future.

Laravel - Session store not set on request

If you are using CSRF enter 'before'=>'csrf'

In your case Route::get('auth/login', ['before'=>'csrf','uses' => 'Auth\AuthController@getLogin', 'as' => 'login']);

For more details view Laravel 5 Documentation Security Protecting Routes

MongoDB Aggregation: How to get total records count?

This could be work for multiple match conditions

            const query = [
                {
                    $facet: {
                    cancelled: [
                        { $match: { orderStatus: 'Cancelled' } },
                        { $count: 'cancelled' }
                    ],
                    pending: [
                        { $match: { orderStatus: 'Pending' } },
                        { $count: 'pending' }
                    ],
                    total: [
                        { $match: { isActive: true } },
                        { $count: 'total' }
                    ]
                    }
                },
                {
                    $project: {
                    cancelled: { $arrayElemAt: ['$cancelled.cancelled', 0] },
                    pending: { $arrayElemAt: ['$pending.pending', 0] },
                    total: { $arrayElemAt: ['$total.total', 0] }
                    }
                }
                ]
                Order.aggregate(query, (error, findRes) => {})

Pandas left outer join multiple dataframes on multiple columns

Merge them in two steps, df1 and df2 first, and then the result of that to df3.

In [33]: s1 = pd.merge(df1, df2, how='left', on=['Year', 'Week', 'Colour'])

I dropped year from df3 since you don't need it for the last join.

In [39]: df = pd.merge(s1, df3[['Week', 'Colour', 'Val3']],
                       how='left', on=['Week', 'Colour'])

In [40]: df
Out[40]: 
   Year Week Colour  Val1  Val2 Val3
0  2014    A    Red    50   NaN  NaN
1  2014    B    Red    60   NaN   60
2  2014    B  Black    70   100   10
3  2014    C    Red    10    20  NaN
4  2014    D  Green    20   NaN   20

[5 rows x 6 columns]

Display tooltip on Label's hover?

Tooltips in bootstrap are good, but there is also a very good tooltip function in jQuery UI, which you can read about here.

Example:

<label for="male" id="foo" title="Hello This Will Have Some Value">Hello...</label>

Then, assuming you have already referenced jQuery and jQueryUI libraries in your head, add a script element like this:

<script type="text/javascript">
$(document).ready(function(){
    $(this).tooltip();
});
</script>

This will display the contents of the title attribute as a tooltip when you rollover any element with a title attribute.

Javascript receipt printing using POS Printer

You could try using https://www.printnode.com which is essentially exactly the service that you are looking for. You download and install a desktop client onto the users computer - https://www.printnode.com/download. You can then discover and print to any printers on that user's computer using their JSON API https://www.printnode.com/docs/api/curl/. They have lots of libs here: https://github.com/PrintNode/

How to get index of an item in java.util.Set

A small static custom method in a Util class would help:

 public static int getIndex(Set<? extends Object> set, Object value) {
   int result = 0;
   for (Object entry:set) {
     if (entry.equals(value)) return result;
     result++;
   }
   return -1;
 }

If you need/want one class that is a Set and offers a getIndex() method, I strongly suggest to implement a new Set and use the decorator pattern:

 public class IndexAwareSet<T> implements Set {
   private Set<T> set;
   public IndexAwareSet(Set<T> set) {
     this.set = set;
   }

   // ... implement all methods from Set and delegate to the internal Set

   public int getIndex(T entry) {
     int result = 0;
     for (T entry:set) {
       if (entry.equals(value)) return result;
       result++;
     }
     return -1;
   }
 }

How can I tell when a MySQL table was last updated?

Cache the query in a global variable when it is not available.

Create a webpage to force the cache to be reloaded when you update it.

Add a call to the reloading page into your deployment scripts.

Randomize a List<T>

    public static List<T> Randomize<T>(List<T> list)
    {
        List<T> randomizedList = new List<T>();
        Random rnd = new Random();
        while (list.Count > 0)
        {
            int index = rnd.Next(0, list.Count); //pick a random item from the master list
            randomizedList.Add(list[index]); //place it at the end of the randomized list
            list.RemoveAt(index);
        }
        return randomizedList;
    }

Set Locale programmatically

There is a super simple way.

in BaseActivity, Activity or Fragment override attachBaseContext

 override fun attachBaseContext(context: Context) {
    super.attachBaseContext(context.changeLocale("tr"))
}

extension

fun Context.changeLocale(language:String): Context {
    val locale = Locale(language)
    Locale.setDefault(locale)
    val config = this.resources.configuration
    config.setLocale(locale)
    return createConfigurationContext(config)
}

ASP.NET set hiddenfield a value in Javascript

Prior to ASP.Net 4.0

ClientID

Get the client id generated in the page that uses Master page. As Master page is UserControl type, It will have its own Id and it treats the page as Child control and generates a different id with prefix like ctrl_.

This can be resolved by using <%= ControlName.ClientID %> in a page and can be assigned to any string or a javascript variables that can be referred later.

var myHidden=document.getElementById('<%= hdntxtbxTaksit.ClientID %>');
  • Asp.net server control id will be vary if you use Master page.

ASP.Net 4.0 +

ClientIDMode Property

Use this property to control how you want to generate the ID for you. For your case setting ClientIDMode="static" in page level will resolve the problem. The same thing can be applied at control level as well.

git with IntelliJ IDEA: Could not read from remote repository

You need to Generate a new SSH key and add it to your ssh-agent. For That you should follow this link.

After you create the public key and add it to your github account, you should use Built-in (not Native) option under Setting-> Version Control -> Git -> SSH executable in your Intellij Idea.

How can I group by date time column without taking time into consideration

I believe you need to group by , in that day of the month of the year . so why not using TRUNK_DATE functions . The way it works is described below :

Group By DATE_TRUNC('day' , 'occurred_at_time')

How to get row number from selected rows in Oracle

The below query helps to get the row number in oracle,

SELECT ROWNUM AS SNO,ID,NAME,EMAIL,BRANCH FROM student WHERE NAME LIKE '%ram%';

std::string to char*

Alternatively , you can use vectors to get a writable char* as demonstrated below;

//this handles memory manipulations and is more convenient
string str;
vector <char> writable (str.begin (), str.end) ;
writable .push_back ('\0'); 
char* cstring = &writable[0] //or &*writable.begin () 

//Goodluck  

Regex for quoted string with escaping quotes

here is one that work with both " and ' and you easily add others at the start.

("|')(?:\\\1|[^\1])*?\1

it uses the backreference (\1) match exactley what is in the first group (" or ').

http://www.regular-expressions.info/backref.html

Python 2.7.10 error "from urllib.request import urlopen" no module named request

Try using urllib2:

https://docs.python.org/2/library/urllib2.html

This line should work to replace urlopen:

from urllib2 import urlopen

Tested in Python 2.7 on Macbook Pro

Try posting a link to the git in question.

Why powershell does not run Angular commands?

open windows powershell, run as administrater and SetExecution policy as Unrestricted then it will work.

Implement a loading indicator for a jQuery AJAX call

A loading indicator is simply an animated image (.gif) that is displayed until the completed event is called on the AJAX request. http://ajaxload.info/ offers many options for generating loading images that you can overlay on your modals. To my knowledge, Bootstrap does not provide the functionality built-in.

Show dialog from fragment?

 public void showAlert(){


     AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
     LayoutInflater inflater = getActivity().getLayoutInflater();
     View alertDialogView = inflater.inflate(R.layout.test_dialog, null);
     alertDialog.setView(alertDialogView);

     TextView textDialog = (TextView) alertDialogView.findViewById(R.id.text_testDialogMsg);
     textDialog.setText(questionMissing);

     alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
             dialog.cancel();
         }
     });
     alertDialog.show();

}

where .test_dialog is of xml custom

Set selected radio from radio group with a value

With the help of the attribute selector you can select the input element with the corresponding value. Then you have to set the attribute explicitly, using .attr:

var value = 5;
$("input[name=mygroup][value=" + value + "]").attr('checked', 'checked');

Since jQuery 1.6, you can also use the .prop method with a boolean value (this should be the preferred method):

$("input[name=mygroup][value=" + value + "]").prop('checked', true);

Remember you first need to remove checked attribute from any of radio buttons under one radio buttons group only then you will be able to add checked property / attribute to one of the radio button in that radio buttons group.

Code To Remove Checked Attribute from all radio buttons of one radio button group -

$('[name="radioSelectionName"]').removeAttr('checked');

Required attribute on multiple checkboxes with the same name?

To provide another approach similar to the answer by @IvanCollantes. It works by additionally filtering the required checkboxes by name. I also simplified the code a bit and checks for a default checked checkbox.

_x000D_
_x000D_
jQuery(function($) {_x000D_
  var requiredCheckboxes = $(':checkbox[required]');_x000D_
  requiredCheckboxes.on('change', function(e) {_x000D_
    var checkboxGroup = requiredCheckboxes.filter('[name="' + $(this).attr('name') + '"]');_x000D_
    var isChecked = checkboxGroup.is(':checked');_x000D_
    checkboxGroup.prop('required', !isChecked);_x000D_
  });_x000D_
  requiredCheckboxes.trigger('change');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<form target="_blank">_x000D_
  <p>_x000D_
    At least one checkbox from each group is required..._x000D_
  </p>_x000D_
  <fieldset>_x000D_
    <legend>Checkboxes Group test</legend>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test[]" value="1" checked="checked" required="required">test-1_x000D_
    </label>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test[]" value="2" required="required">test-2_x000D_
    </label>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test[]" value="3" required="required">test-3_x000D_
    </label>_x000D_
  </fieldset>_x000D_
  <br>_x000D_
  <fieldset>_x000D_
    <legend>Checkboxes Group test2</legend>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test2[]" value="1" required="required">test2-1_x000D_
    </label>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test2[]" value="2" required="required">test2-2_x000D_
    </label>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test2[]" value="3" required="required">test2-3_x000D_
    </label>_x000D_
  </fieldset>_x000D_
  <hr>_x000D_
  <button type="submit" value="submit">Submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How do you convert a time.struct_time object into a datetime object?

Use time.mktime() to convert the time tuple (in localtime) into seconds since the Epoch, then use datetime.fromtimestamp() to get the datetime object.

from datetime import datetime
from time import mktime

dt = datetime.fromtimestamp(mktime(struct))

Log to the base 2 in python

>>> def log2( x ):
...     return math.log( x ) / math.log( 2 )
... 
>>> log2( 2 )
1.0
>>> log2( 4 )
2.0
>>> log2( 8 )
3.0
>>> log2( 2.4 )
1.2630344058337937
>>> 

Loop through all the files with a specific extension

I agree withe the other answers regarding the correct way to loop through the files. However the OP asked:

The code above doesn't work, do you know why?

Yes!

An excellent article What is the difference between test, [ and [[ ?] explains in detail that among other differences, you cannot use expression matching or pattern matching within the test command (which is shorthand for [ )


Feature            new test [[    old test [           Example

Pattern matching    = (or ==)    (not available)    [[ $name = a* ]] || echo "name does not start with an 'a': $name"

Regular Expression     =~        (not available)    [[ $(date) =~ ^Fri\ ...\ 13 ]] && echo "It's Friday the 13th!"
matching

So this is the reason your script fails. If the OP is interested in an answer with the [[ syntax (which has the disadvantage of not being supported on as many platforms as the [ command), I would be happy to edit my answer to include it.

EDIT: Any protips for how to format the data in the answer as a table would be helpful!

How to know that a string starts/ends with a specific string in jQuery?

For startswith, you can use indexOf:

if(str.indexOf('Hello') == 0) {

...

ref

and you can do the maths based on string length to determine 'endswith'.

if(str.lastIndexOf('Hello') == str.length - 'Hello'.length) {

Android check internet connection

All official methods only tells whether a device is open for network or not,
If your device is connected to Wifi but Wifi is not connected to internet then these method will fail (Which happen many time), No inbuilt network detection method will tell about this scenario, so created Async Callback class which will return in onConnectionSuccess and onConnectionFail

new CheckNetworkConnection(this, new CheckNetworkConnection.OnConnectionCallback() {

    @Override
    public void onConnectionSuccess() {
        Toast.makeText(context, "onSuccess()", toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFail(String msg) {
        Toast.makeText(context, "onFail()", toast.LENGTH_SHORT).show();
    }
}).execute();

Network Call from async Task

public class CheckNetworkConnection extends AsyncTask < Void, Void, Boolean > {
    private OnConnectionCallback onConnectionCallback;
    private Context context;

    public CheckNetworkConnection(Context con, OnConnectionCallback onConnectionCallback) {
        super();
        this.onConnectionCallback = onConnectionCallback;
        this.context = con;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(Void...params) {
        if (context == null)
            return false;

        boolean isConnected = new NetWorkInfoUtility().isNetWorkAvailableNow(context);
        return isConnected;
    }

    @Override
    protected void onPostExecute(Boolean b) {
        super.onPostExecute(b);

        if (b) {
            onConnectionCallback.onConnectionSuccess();
        } else {
            String msg = "No Internet Connection";
            if (context == null)
                msg = "Context is null";
            onConnectionCallback.onConnectionFail(msg);
        }

    }

    public interface OnConnectionCallback {
        void onConnectionSuccess();

        void onConnectionFail(String errorMsg);
    }
}

Actual Class which will ping to server

class NetWorkInfoUtility {

    public boolean isWifiEnable() {
        return isWifiEnable;
    }

    public void setIsWifiEnable(boolean isWifiEnable) {
        this.isWifiEnable = isWifiEnable;
    }

    public boolean isMobileNetworkAvailable() {
        return isMobileNetworkAvailable;
    }

    public void setIsMobileNetworkAvailable(boolean isMobileNetworkAvailable) {
        this.isMobileNetworkAvailable = isMobileNetworkAvailable;
    }

    private boolean isWifiEnable = false;
    private boolean isMobileNetworkAvailable = false;

    public boolean isNetWorkAvailableNow(Context context) {
        boolean isNetworkAvailable = false;

        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        setIsWifiEnable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected());
        setIsMobileNetworkAvailable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected());

        if (isWifiEnable() || isMobileNetworkAvailable()) {
            /*Sometime wifi is connected but service provider never connected to internet
            so cross check one more time*/
            if (isOnline())
                isNetworkAvailable = true;
        }

        return isNetworkAvailable;
    }

    public boolean isOnline() {
        /*Just to check Time delay*/
        long t = Calendar.getInstance().getTimeInMillis();

        Runtime runtime = Runtime.getRuntime();
        try {
            /*Pinging to Google server*/
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
            int exitValue = ipProcess.waitFor();
            return (exitValue == 0);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            long t2 = Calendar.getInstance().getTimeInMillis();
            Log.i("NetWork check Time", (t2 - t) + "");
        }
        return false;
    }
}

How to count TRUE values in a logical vector

Another option which hasn't been mentioned is to use which:

length(which(z))

Just to actually provide some context on the "which is faster question", it's always easiest just to test yourself. I made the vector much larger for comparison:

z <- sample(c(TRUE,FALSE),1000000,rep=TRUE)
system.time(sum(z))
   user  system elapsed 
   0.03    0.00    0.03
system.time(length(z[z==TRUE]))
   user  system elapsed 
   0.75    0.07    0.83 
system.time(length(which(z)))
   user  system elapsed 
   1.34    0.28    1.64 
system.time(table(z)["TRUE"])
   user  system elapsed 
  10.62    0.52   11.19 

So clearly using sum is the best approach in this case. You may also want to check for NA values as Marek suggested.

Just to add a note regarding NA values and the which function:

> which(c(T, F, NA, NULL, T, F))
[1] 1 4
> which(!c(T, F, NA, NULL, T, F))
[1] 2 5

Note that which only checks for logical TRUE, so it essentially ignores non-logical values.

How to Specify "Vary: Accept-Encoding" header in .htaccess

I'm afraid Aularon didn't provide enough steps to complete the process. With a little trial and error, I was able to successfully enable Gzipping on my dedicated WHM server.

Below are the steps:

  • Run EasyApache within WHM, select Deflate within the Exhaustive Options list, and rebuild the server.

  • Once done, goto Services Configuration >> Apache Configuration >> Include Editor >> Post VirtualHost Include, select All Versions, and then paste the mod_headers.c and mod_headers.c code (listed above in Aularon's post) on top of on another within the input field.

  • Once saved, I was seeing a 75.36% data savings on average! You can run a before and after test by using this HTTP Compression tool to see your own results: http://www.whatsmyip.org/http_compression/

Hope this works for you all!

  • Matt

How to get "wc -l" to print just the number of lines without file name?

How about

wc -l file.txt | cut -d' ' -f1

i.e. pipe the output of wc into cut (where delimiters are spaces and pick just the first field)

Trim to remove white space

Why not try this?

html:

<p>
  a b c
</p>

js:

$("p").text().trim();

How do you make a div tag into a link

JS:

<div onclick="location.href='url'">content</div>

jQuery:

$("div").click(function(){
   window.location=$(this).find("a").attr("href"); return false;
});

Make sure to use cursor:pointer for these DIVs

Using $_POST to get select option value from HTML

You can access values in the $_POST array by their key. $_POST is an associative array, so to access taskOption you would use $_POST['taskOption'];.

Make sure to check if it exists in the $_POST array before proceeding though.

<form method="post" action="process.php">
  <select name="taskOption">
    <option value="first">First</option>
    <option value="second">Second</option>
    <option value="third">Third</option>
  </select>
  <input type="submit" value="Submit the form"/>
</form>

process.php

<?php
   $option = isset($_POST['taskOption']) ? $_POST['taskOption'] : false;
   if ($option) {
      echo htmlentities($_POST['taskOption'], ENT_QUOTES, "UTF-8");
   } else {
     echo "task option is required";
     exit; 
   }

Convert int (number) to string with leading zeros? (4 digits)

Use the formatting options available to you, use the Decimal format string. It is far more flexible and requires little to no maintenance compared to direct string manipulation.

To get the string representation using at least 4 digits:

int length = 4;
int number = 50;
string asString = number.ToString("D" + length); //"0050"

Command-line svn for Windows?

VisualSVN for Windows has a command-line-only executable (as well Visual Studio plugins). See https://www.visualsvn.com/downloads/

It is completely portable, so no installation is necessary.

How can I convert IPV6 address to IPV4 address?

Here is the code you are looking for in javascript. Well you know you can't convert all of the ipv6 addresses

<script>
function parseIp6(str)
{
  //init
  var ar=new Array;
  for(var i=0;i<8;i++)ar[i]=0;
  //check for trivial IPs
  if(str=="::")return ar;
  //parse
  var sar=str.split(':');
  var slen=sar.length;
  if(slen>8)slen=8;
  var j=0;
  for(var i=0;i<slen;i++){
    //this is a "::", switch to end-run mode
    if(i && sar[i]==""){j=9-slen+i;continue;}
    ar[j]=parseInt("0x0"+sar[i]);
    j++;
  }

  return ar;
}
function ipcnvfrom6(ip6)
{
  var ip6=parseIp6(ip6);
  var ip4=(ip6[6]>>8)+"."+(ip6[6]&0xff)+"."+(ip6[7]>>8)+"."+(ip6[7]&0xff);
  return ip4;
}
alert(ipcnvfrom6("::C0A8:4A07"));
</script>

Why doesn't Python have multiline comments?

Multi-line comments are easily breakable. What if you have the following in a simple calculator program?

operation = ''
print("Pick an operation:  +-*/")
# Get user input here

Try to comment that with a multi-line comment:

/*
operation = ''
print("Pick an operation:  +-*/")
# Get user input here
*/

Oops, your string contains the end comment delimiter.

How can you float: right in React Native?

You can float:right in react native using flex:

 <View style={{flex: 1, flexDirection: 'row'}}>
        <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
        <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
        <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
</View>

for more detail: https://facebook.github.io/react-native/docs/flexbox.html#flex-direction

How to set a default value with Html.TextBoxFor?

Try this also, that is remove new { } and replace it with string.

<%: Html.TextBoxFor(x => x.Age,"0") %>

How can strings be concatenated?

Use + for string concatenation as:

section = 'C_type'
new_section = 'Sec_' + section

Getting the docstring from a function

On ipython or jupyter notebook, you can use all the above mentioned ways, but i go with

my_func?

or

?my_func

for quick summary of both method signature and docstring.

I avoid using

my_func??

(as commented by @rohan) for docstring and use it only to check the source code

u'\ufeff' in Python string

I ran into this on Python 3 and found this question (and solution). When opening a file, Python 3 supports the encoding keyword to automatically handle the encoding.

Without it, the BOM is included in the read result:

>>> f = open('file', mode='r')
>>> f.read()
'\ufefftest'

Giving the correct encoding, the BOM is omitted in the result:

>>> f = open('file', mode='r', encoding='utf-8-sig')
>>> f.read()
'test'

Just my 2 cents.

Create a asmx web service in C# using visual studio 2013

on the web site box, you have selected .NETFramework 4.5 and it doesn show, so click there and choose the 3.5...i hope it helps.

Create HTML table using Javascript

In the html file there are three input boxes with userid,username,department respectively.

These inputboxes are used to get the input from the user.

The user can add any number of inputs to the page.

When clicking the button the script will enable the debugger mode.

In javascript, to enable the debugger mode, we have to add the following tag in the javascript.

/************************************************************************\

    Tools->Internet Options-->Advanced-->uncheck
    Disable script debugging(Internet Explorer)
    Disable script debugging(Other)

    <html xmlns="http://www.w3.org/1999/xhtml" >

    <head runat="server">

    <title>Dynamic Table</title>

    <script language="javascript" type="text/javascript">

    // <!CDATA[

    function CmdAdd_onclick() {

    var newTable,startTag,endTag;



    //Creating a new table

    startTag="<TABLE id='mainTable'><TBODY><TR><TD style=\"WIDTH: 120px\">User ID</TD>
    <TD style=\"WIDTH: 120px\">User Name</TD><TD style=\"WIDTH: 120px\">Department</TD></TR>"

    endTag="</TBODY></TABLE>"

    newTable=startTag;

    var trContents;

    //Get the row contents

    trContents=document.body.getElementsByTagName('TR');

    if(trContents.length>1)

    {

    for(i=1;i<trContents.length;i++)

    {

    if(trContents(i).innerHTML)

    {

    // Add previous rows

    newTable+="<TR>";

    newTable+=trContents(i).innerHTML;

    newTable+="</TR>";

    } 

    }

    }

    //Add the Latest row

    newTable+="<TR><TD style=\"WIDTH: 120px\" >" +
        document.getElementById('userid').value +"</TD>";

    newTable+="<TD style=\"WIDTH: 120px\" >" +
        document.getElementById('username').value +"</TD>";

    newTable+="<TD style=\"WIDTH: 120px\" >" +
        document.getElementById('department').value +"</TD><TR>";

    newTable+=endTag;

    //Update the Previous Table With New Table.

    document.getElementById('tableDiv').innerHTML=newTable;

    }

    // ]]>

    </script>

    </head>

    <body>

    <form id="form1" runat="server">

    <div>

    <br />

    <label>UserID</label> 

    <input id="userid" type="text" /><br />

    <label>UserName</label> 

    <input id="username" type="text" /><br />

    <label>Department</label> 

    <input id="department" type="text" />

    <center>

    <input id="CmdAdd" type="button" value="Add" onclick="return CmdAdd_onclick()" />
    </center>



    </div>

    <div id="tableDiv" style="text-align:center" >

    <table id="mainTable">

    <tr style="width:120px " >

    <td >User ID</td>

    <td>User Name</td>

    <td>Department</td>

    </tr>

    </table>

    </div>

    </form>

    </body>

    </html>

How to iterate over a string in C?

One common idiom is:

char* c = source;
while (*c) putchar(*c++);

A few notes:

  • In C, strings are null-terminated. You iterate while the read character is not the null character.
  • *c++ increments c and returns the dereferenced old value of c.
  • printf("%s") prints a null-terminated string, not a char. This is the cause of your access violation.

The pipe ' ' could not be found angular2 custom pipe

For Ionic you can face multiple issues as @Karl mentioned. The solution which works flawlessly for ionic lazy loaded pages is:

  1. Create pipes directory with following files: pipes.ts and pipes.module.ts

// pipes.ts content (it can have multiple pipes inside, just remember to

use @Pipe function before each class)
import { PipeTransform, Pipe } from "@angular/core";
@Pipe({ name: "toArray" })
export class toArrayPipe implements PipeTransform {
  transform(value, args: string[]): any {
    if (!value) return value;
    let keys = [];
    for (let key in value) {
      keys.push({ key: key, value: value[key] });
    }
    return keys;
  }
}

// pipes.module.ts content

import { NgModule } from "@angular/core";
import { IonicModule } from "ionic-angular";
import { toArrayPipe } from "./pipes";

@NgModule({
  declarations: [toArrayPipe],
  imports: [IonicModule],
  exports: [toArrayPipe]
})
export class PipesModule {}
  1. Include PipesModule into app.module and @NgModule imports section

    import { PipesModule } from "../pipes/pipes.module"; @NgModule({ imports: [ PipesModule ] });

  2. Include PipesModule in each of your .module.ts where you want to use custom pipes. Don't forget to add it into imports section. // Example. file: pages/my-custom-page/my-custom-page.module.ts

    import { PipesModule } from "../../pipes/pipes.module"; @NgModule({ imports: [ PipesModule ] })

  3. Thats it. Now you can use your custom pipe in your template. Ex.

<div *ngFor="let prop of myObject | toArray">{{ prop.key }}</div>

How do I check if an element is really visible with JavaScript?

Here is a part of the response that tells you if an element is in the viewport. You may need to check if there is nothing on top of it using elementFromPoint, but it's a bit longer.

function isInViewport(element) {
  var rect = element.getBoundingClientRect();
  var windowHeight = window.innerHeight || document.documentElement.clientHeight;
  var windowWidth = window.innerWidth || document.documentElement.clientWidth;

  return rect.bottom > 0 && rect.top < windowHeight && rect.right > 0 && rect.left < windowWidth;
}

How do I debug "Error: spawn ENOENT" on node.js?

I got the same error for windows 8.The issue is because of an environment variable of your system path is missing . Add "C:\Windows\System32\" value to your system PATH variable.

Copy multiple files with Ansible

You can use the with_fileglob loop for this:

- copy:
    src: "{{ item }}"
    dest: /etc/fooapp/
    owner: root
    mode: 600
  with_fileglob:
    - /playbooks/files/fooapp/*

Get Selected value from Multi-Value Select Boxes by jquery-select2?

Please, ckeck this simple example. You can get values in select2 multi.

var values = $('#id-select2-multi').val();
console.log(values);

How to loop and render elements in React.js without an array of objects to map?

I think this is the easiest way to loop in react js

<ul>
    {yourarray.map((item)=><li>{item}</li>)}
</ul>

How to check if anonymous object has a method?

typeof myObj.prop2 === 'function'; will let you know if the function is defined.

if(typeof myObj.prop2 === 'function') {
    alert("It's a function");
} else if (typeof myObj.prop2 === 'undefined') {
    alert("It's undefined");
} else {
    alert("It's neither undefined nor a function. It's a " + typeof myObj.prop2);
}

How to center horizontal table-cell

Just add this class in your css

.column p{
   text-align:center;
}

How to hide close button in WPF window?

goto window properties set

window style = none;

u wont get close buttons...

mysql_fetch_array() expects parameter 1 to be resource problem

In your database what is the type of "IDNO"? You may need to escape the sql here:

$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);

Is there a kind of Firebug or JavaScript console debug for Android?

I had the same problem, just use console.log(...) (like firebug), and the install a log viewer application, this will allow you to view all the logs for your browser.

How can I inspect the file system of a failed `docker build`?

The top answer works in the case that you want to examine the state immediately prior to the failed command.

However, the question asks how to examine the state of the failed container itself. In my situation, the failed command is a build that takes several hours, so rewinding prior to the failed command and running it again takes a long time and is not very helpful.

The solution here is to find the container that failed:

$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                          PORTS               NAMES
6934ada98de6        42e0228751b3        "/bin/sh -c './utils/"   24 minutes ago      Exited (1) About a minute ago                       sleepy_bell

Commit it to an image:

$ docker commit 6934ada98de6
sha256:7015687976a478e0e94b60fa496d319cdf4ec847bcd612aecf869a72336e6b83

And then run the image [if necessary, running bash]:

$ docker run -it 7015687976a4 [bash -il]

Now you are actually looking at the state of the build at the time that it failed, instead of at the time before running the command that caused the failure.

Force drop mysql bypassing foreign key constraint

If you are using phpmyadmin then this feature is already there.

  • Select the tables you want to drop
  • From the dropdown at the bottom of tables list, select drop
  • A new page will be opened having checkbox at the bottom saying "Foreign key check", uncheck it.
  • Confirm the deletion by accepting "yes".

Angular2 - TypeScript : Increment a number after timeout in AppComponent

You should put your processing into the class constructor or an OnInit hook method.

Select arrow style change

You can use this. Its Tested code

    select {
    background: url(http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png) no-repeat right !important;
    appearance: none !important;
    background-size: 25px 25px !important;
    background-position: 99% 50% !important;
}

Axios Delete request with body and headers?

I encountered the same problem... I solved it by creating a custom axios instance. and using that to make a authenticated delete request..

const token = localStorage.getItem('token');
const request = axios.create({
        headers: {
            Authorization: token
        }
    });

await request.delete('<your route>, { data: { <your data> }});

Visual Studio "Could not copy" .... during build

I realize this is just adding to the already huge amount of answers for this question, but thought it deserved mentioning that, although not perfect, a combination of the answers given by: @Stefano, @MichaelRibbons, and @IvanFerrerVilla has provided a decent bit of success, when neither of them on their own was very successful.

String.contains in Java

The obvious answer to this is "that's what the JLS says."

Thinking about why that is, consider that this behavior can be useful in certain cases. Let's say you want to check a string against a set of other strings, but the number of other strings can vary.

So you have something like this:

for(String s : myStrings) {
   check(aString.contains(s));
}

where some s's are empty strings.

If the empty string is interpreted as "no input," and if your purpose here is ensure that aString contains all the "inputs" in myStrings, then it is misleading for the empty string to return false. All strings contain it because it is nothing. To say they didn't contain it would imply that the empty string had some substance that was not captured in the string, which is false.

How does Tomcat locate the webapps directory?

Change appBase in server.xml

If you want to keep both previous webapps and a new one, you can use another Host instance with another port defined in tomcat.

HTML5 iFrame Seamless Attribute

It is possible to use the semless attribute right now, here i found a german article http://www.solife.cc/blog/html5-iframe-attribut-seamless-beispiele.html

and here are another presentation about this topic: http://benvinegar.github.com/seamless-talk/

You have to use the window.postMessage method to communicate between the parent and the iframe.

Textarea Auto height

It can be achieved using JS. Here is a 'one-line' solution using elastic.js:

$('#note').elastic();

Updated: Seems like elastic.js is not there anymore, but if you are looking for an external library, I can recommend autosize.js by Jack Moore. This is the working example:

_x000D_
_x000D_
autosize(document.getElementById("note"));
_x000D_
textarea#note {_x000D_
 width:100%;_x000D_
 box-sizing:border-box;_x000D_
 direction:rtl;_x000D_
 display:block;_x000D_
 max-width:100%;_x000D_
 line-height:1.5;_x000D_
 padding:15px 15px 30px;_x000D_
 border-radius:3px;_x000D_
 border:1px solid #F7E98D;_x000D_
 font:13px Tahoma, cursive;_x000D_
 transition:box-shadow 0.5s ease;_x000D_
 box-shadow:0 4px 6px rgba(0,0,0,0.1);_x000D_
 font-smoothing:subpixel-antialiased;_x000D_
 background:linear-gradient(#F9EFAF, #F7E98D);_x000D_
 background:-o-linear-gradient(#F9EFAF, #F7E98D);_x000D_
 background:-ms-linear-gradient(#F9EFAF, #F7E98D);_x000D_
 background:-moz-linear-gradient(#F9EFAF, #F7E98D);_x000D_
 background:-webkit-linear-gradient(#F9EFAF, #F7E98D);_x000D_
}
_x000D_
<script src="https://rawgit.com/jackmoore/autosize/master/dist/autosize.min.js"></script>_x000D_
<textarea id="note">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</textarea>
_x000D_
_x000D_
_x000D_

Check this similar topics too:

Autosizing textarea using Prototype

Textarea to resize based on content length

Creating a textarea with auto-resize

Creating a 3D sphere in Opengl using Visual C++

I don't understand how can datenwolf`s index generation can be correct. But still I find his solution rather clear. This is what I get after some thinking:

inline void push_indices(vector<GLushort>& indices, int sectors, int r, int s) {
    int curRow = r * sectors;
    int nextRow = (r+1) * sectors;

    indices.push_back(curRow + s);
    indices.push_back(nextRow + s);
    indices.push_back(nextRow + (s+1));

    indices.push_back(curRow + s);
    indices.push_back(nextRow + (s+1));
    indices.push_back(curRow + (s+1));
}

void createSphere(vector<vec3>& vertices, vector<GLushort>& indices, vector<vec2>& texcoords,
             float radius, unsigned int rings, unsigned int sectors)
{
    float const R = 1./(float)(rings-1);
    float const S = 1./(float)(sectors-1);

    for(int r = 0; r < rings; ++r) {
        for(int s = 0; s < sectors; ++s) {
            float const y = sin( -M_PI_2 + M_PI * r * R );
            float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
            float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );

            texcoords.push_back(vec2(s*S, r*R));
            vertices.push_back(vec3(x,y,z) * radius);
            push_indices(indices, sectors, r, s);
        }
    }
}

Read pdf files with php

You might want to also try this application http://pdfbox.apache.org/. A working example can be found at https://www.jinises.com

How do I use a compound drawable instead of a LinearLayout that contains an ImageView and a TextView

if for some reason you need to add via code, you can use this:

mTextView.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);

where left, top, right bottom are Drawables

Maven project.build.directory

You can find the most up to date answer for the value in your project just execute the

mvn3 help:effective-pom

command and find the <build> ... <directory> tag's value in the result aka in the effective-pom. It will show the value of the Super POM unless you have overwritten.

How to convert the time from AM/PM to 24 hour format in PHP?

$Hour1 = "09:00 am";
$Hour =  date("H:i", strtotime($Hour1));  

Using python PIL to turn a RGB image into a pure black and white image

A simple way to do it using python :

Python
import numpy as np
import imageio

image = imageio.imread(r'[image-path]', as_gray=True)

# getting the threshold value
thresholdValue = np.mean(image)

# getting the dimensions of the image
xDim, yDim = image.shape

# turn the image into a black and white image
for i in range(xDim):
    for j in range(yDim):
        if (image[i][j] > thresholdValue):
            image[i][j] = 255
        else:
            image[i][j] = 0

How do HashTables deal with collisions?

Update since Java 8: Java 8 uses a self-balanced tree for collision-handling, improving the worst case from O(n) to O(log n) for lookup. The use of a self-balanced tree was introduced in Java 8 as an improvement over chaining (used until java 7), which uses a linked-list, and has a worst case of O(n) for lookup (as it needs to traverse the list)

To answer the second part of your question, insertion is done by mapping a given element to a given index in the underlying array of the hashmap, however, when a collision occurs, all elements must still be preserved (stored in a secondary data-structure, and not just replaced in the underlying array). This is usually done by making each array-component (slot) be a secondary datastructure (aka bucket), and the element is added to the bucket residing on the given array-index (if the key does not already exist in the bucket, in which case it is replaced).

During lookup, the key is hashed to it's corresponding array-index, and search is performed for an element matching the (exact) key in the given bucket. Because the bucket does not need to handle collisions (compares keys directly), this solves the problem of collisions, but does so at the cost of having to perform insertion and lookup on the secondary datastructure. The key point is that in a hashmap, both the key and the value is stored, and so even if the hash collides, keys are compared directly for equality (in the bucket), and thus can be uniquely identified in the bucket.

Collission-handling brings the worst-case performance of insertion and lookup from O(1) in the case of no collission-handling to O(n) for chaining (a linked-list is used as secondary datastructure) and O(log n) for self-balanced tree.

References:

Java 8 has come with the following improvements/changes of HashMap objects in case of high collisions.

  • The alternative String hash function added in Java 7 has been removed.

  • Buckets containing a large number of colliding keys will store their entries in a balanced tree instead of a linked list after certain threshold is reached.

Above changes ensure performance of O(log(n)) in worst case scenarios (https://www.nagarro.com/en/blog/post/24/performance-improvement-for-hashmap-in-java-8)

How to fix a locale setting warning from Perl

Another Git-related answer:

The source of the problem might be the Git server. If all else fails, try doing dpkg-reconfigure locales (or whatever is appropriate for your distribution) on the server.

Difference between acceptance test and functional test?

  1. Audience. Functional testing is to assure members of the team producing the software that it does what they expect. Acceptance testing is to assure the consumer that it meets their needs.

  2. Scope. Functional testing only tests the functionality of one component at a time. Acceptance testing covers any aspect of the product that matters to the consumer enough to test before accepting the software (i.e., anything worth the time or money it will take to test it to determine its acceptability).

Software can pass functional testing, integration testing, and system testing; only to fail acceptance tests when the customer discovers that the features just don't meet their needs. This would usually imply that someone screwed up on the spec. Software could also fail some functional tests, but pass acceptance testing because the customer is willing to deal with some functional bugs as long as the software does the core things they need acceptably well (beta software will often be accepted by a subset of users before it is completely functional).

Lazy Method for Reading Big File in Python?

In Python 3.8+ you can use .read() in a while loop:

with open("somefile.txt") as f:
    while chunk := f.read(8192):
        do_something(chunk)

Of course, you can use any chunk size you want, you don't have to use 8192 (2**13) bytes. Unless your file's size happens to be a multiple of your chunk size, the last chunk will be smaller than your chunk size.

Convert list of ints to one number?

Using a generator expression:

def magic(numbers):
    digits = ''.join(str(n) for n in numbers)
    return int(digits)

Removing pip's cache?

On Windows 7, I had to delete %HOMEPATH%/pip.

Why aren't Xcode breakpoints functioning?

In my case i was overriding the existing app store build with my build.I removed the same and its working now.

type checking in javascript

A clean approach

You can consider using a very small, dependency-free library like Not. Solves all problems:

// at the basic level it supports primitives
let number = 10
let array = []
not('number', 10) // returns false
not('number', []) // throws error

// so you need to define your own:
let not = Object.create(Not)

not.defineType({
    primitive: 'number',
    type: 'integer',
    pass: function(candidate) {
        // pre-ECMA6
        return candidate.toFixed(0) === candidate.toString()
        // ECMA6
        return Number.isInteger(candidate)
    }
})
not.not('integer', 4.4) // gives error message
not.is('integer', 4.4) // returns false
not.is('integer', 8) // returns true

If you make it a habit, your code will be much stronger. Typescript solves part of the problem but doesn't work at runtime, which is also important.

function test (string, boolean) {
    // any of these below will throw errors to protect you
    not('string', string)
    not('boolean', boolean)

    // continue with your code.
}

C# catch a stack overflow exception

The right way is to fix the overflow, but....

You can give yourself a bigger stack:-

using System.Threading;
Thread T = new Thread(threadDelegate, stackSizeInBytes);
T.Start();

You can use System.Diagnostics.StackTrace FrameCount property to count the frames you've used and throw your own exception when a frame limit is reached.

Or, you can calculate the size of the stack remaining and throw your own exception when it falls below a threshold:-

class Program
{
    static int n;
    static int topOfStack;
    const int stackSize = 1000000; // Default?

    // The func is 76 bytes, but we need space to unwind the exception.
    const int spaceRequired = 18*1024; 

    unsafe static void Main(string[] args)
    {
        int var;
        topOfStack = (int)&var;

        n=0;
        recurse();
    }

    unsafe static void recurse()
    {
        int remaining;
        remaining = stackSize - (topOfStack - (int)&remaining);
        if (remaining < spaceRequired)
            throw new Exception("Cheese");
        n++;
        recurse();
    }
}

Just catch the Cheese. ;)

Is there any sizeof-like method in Java?

yes..in JAVA

System.out.println(Integer.SIZE/8);  //gives you 4.
System.out.println(Integer.SIZE);   //gives you 32.

//Similary for Byte,Long,Double....

Get int value from enum in C#

Use:

Question question = Question.Role;
int value = Convert.ToInt32(question);

Count a list of cells with the same background color

Yes VBA is the way to go.

But, if you don't need to have a cell with formula that auto-counts/updates the number of cells with a particular colour, an alternative is simply to use the 'Find and Replace' function and format the cell to have the appropriate colour fill.

Hitting 'Find All' will give you the total number of cells found at the bottom left of the dialogue box.

enter image description here

This becomes especially useful if your search range is massive. The VBA script will be very slow but the 'Find and Replace' function will still be very quick.

How to pass form input value to php function

No, the action should be the name of php file. With on click you may only call JavaScript. And please be aware the hiding your code from the user undermines trust. JS runs on the browser so some trust is needed.

How to return a string value from a Bash function

There is no better way I know of. Bash knows only status codes (integers) and strings written to the stdout.

Converting ArrayList to Array in java

What you did with the iteration is not wrong from what I can make of it based on the question. It gives you a valid array of String objects. Like mentioned in another answer it is however easier to use the toArray() method available for the ArrayList object => http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html#toArray%28%29

Just a side note. If you would iterate your dsf array properly and print each element on its own you would get valid output. Like this:

for(String str : dsf){
   System.out.println(str);
}

What you probably tried to do was print the complete Array object at once since that would give an object memory address like you got in your question. If you see that kind of output you need to provide a toString() method for the object you're printing.

function to return a string in java

Your code is fine. There's no problem with returning Strings in this manner.

In Java, a String is a reference to an immutable object. This, coupled with garbage collection, takes care of much of the potential complexity: you can simply pass a String around without worrying that it would disapper on you, or that someone somewhere would modify it.

If you don't mind me making a couple of stylistic suggestions, I'd modify the code like so:

public String time_to_string(long t) // time in milliseconds
{
    if (t < 0)
    {
        return "-";
    }
    else
    {
        int secs = (int)(t/1000);
        int mins = secs/60;
        secs = secs - (mins * 60);
        return String.format("%d:%02d", mins, secs);
    }
}

As you can see, I've pushed the variable declarations as far down as I could (this is the preferred style in C++ and Java). I've also eliminated ans and have replaced the mix of string concatenation and String.format() with a single call to String.format().

PuTTY scripting to log onto host

You can use the -i privatekeyfilelocation in case you are using a private key instead of password based.

Angular 2: How to access an HTTP response body?

This is work for me 100% :

let data:Observable<any> = this.http.post(url, postData);
  data.subscribe((data) => {

  let d = data.json();
  console.log(d);
  console.log("result = " + d.result);
  console.log("url = " + d.image_url);      
  loader.dismiss();
});

How to pause for specific amount of time? (Excel/VBA)

this works flawlessly for me. insert any code before or after the "do until" loop. In your case, put the 5 lines (time1= & time2= & "do until" loop) at the end inside your do loop

sub whatever()
Dim time1, time2

time1 = Now
time2 = Now + TimeValue("0:00:01")
    Do Until time1 >= time2
        DoEvents
        time1 = Now()
    Loop

End sub

fetch from origin with deleted remote branches?

You need to do the following

git fetch -p

This will update the local database of remote branches.

What does it mean when a PostgreSQL process is "idle in transaction"?

As mentioned here: Re: BUG #4243: Idle in transaction it is probably best to check your pg_locks table to see what is being locked and that might give you a better clue where the problem lies.

How can I change the font-size of a select option?

Tell the option element to be 13pt

select option{
    font-size: 13pt;
}

and then the first option element to be 7pt

select option:first-child {
    font-size: 7pt;
}

Running demo: http://jsfiddle.net/VggvD/1/

jQuery autocomplete tagging plug-in like StackOverflow's input tags?

Bootstrap: If you are using Bootstrap. This is a really good one: Select2

Also, TokenInput is an interesting one. First, it does not depend on jQuery-UI, second its config is very smooth.

The only issue I had it does not support free-tagging natively. So, I have to return the query-string back to client as a part of response JSON.


As @culithay mentioned in the comment, TokenInput supports a lot of features to customize. And highlight of some feature that the others don't have:

  • tokenLimit: The maximum number of results allowed to be selected by the user. Use null to allow unlimited selections
  • minChars: The minimum number of characters the user must enter before a search is performed.
  • queryParam: The name of the query param which you expect to contain the search term on the server-side

Thanks culithay for the input.

Incrementing in C++ - When to use x++ or ++x?

Understanding the language syntax is important when considering clarity of code. Consider copying a character string, for example with post-increment:

char a[256] = "Hello world!";
char b[256];
int i = 0;
do {
  b[i] = a[i];
} while (a[i++]);

We want the loop to execute through encountering the zero character (which tests false) at the end of the string. That requires testing the value pre-increment and also incrementing the index. But not necessarily in that order - a way to code this with the pre-increment would be:

int i = -1;
do {
  ++i;
  b[i] = a[i];
} while (a[i]);

It is a matter of taste which is clearer and if the machine has a handfull of registers both should have identical execution time, even if a[i] is a function that is expensive or has side-effects. A significant difference might be the exit value of the index.

indexOf method in an object array?

var idx = myArray.reduce( function( cur, val, index ){

    if( val.hello === "stevie" && cur === -1 ) {
        return index;
    }
    return cur;

}, -1 );

How to use multiple @RequestMapping annotations in spring?

It's better to use PathVariable annotation if you still want to get the uri which was called.

@PostMapping("/pub/{action:a|b|c}")
public JSONObject handlexxx(@PathVariable String action, @RequestBody String reqStr){
...
}

or parse it from request object.

Java Date - Insert into database

You should be using java.sql.Timestamp instead of java.util.Date. Also using a PreparedStatement will save you worrying about the formatting.

How to install cron

Install cron on Linux/Unix:

apt-get install cron

Use cron on Linux/Unix

crontab -e

See the canonical answer about cron for more details: https://serverfault.com/questions/449651/why-is-my-crontab-not-working-and-how-can-i-troubleshoot-it

Disabling contextual LOB creation as createClob() method threw error

For anyone who is facing this problem with Spring Boot 2

by default spring boot was using hibernate 5.3.x version, I have added following property in my pom.xml

<hibernate.version>5.4.2.Final</hibernate.version>

and error was gone. Reason for error is already explained in posts above

Using request.setAttribute in a JSP page

Correct me if wrong...I think request does persist between consecutive pages..

Think you traverse from page 1--> page 2-->page 3.

You have some value set in the request object using setAttribute from page 1, which you retrieve in page 2 using getAttribute,then if you try setting something again in same request object to retrieve it in page 3 then it fails giving you null value as "the request that created the JSP, and the request that gets generated when the JSP is submitted are completely different requests and any attributes placed on the first one will not be available on the second".

I mean something like this in page 2 fails:

Where as the same thing has worked in case of page 1 like:

So I think I would need to proceed with either of the two options suggested by Phill.

Datagridview: How to set a cell in editing mode?

private void DgvRoomInformation_CellEnter(object sender, DataGridViewCellEventArgs e)
{
  if (DgvRoomInformation.CurrentCell.ColumnIndex == 4)  //example-'Column index=4'
  {
    DgvRoomInformation.BeginEdit(true);   
  }
}

how to pass value from one php page to another using session

Solution using just POST - no $_SESSION

page1.php

<form action="page2.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>

page2.php

<?php
    // this page outputs the contents of the textarea if posted
    $textarea1 = ""; // set var to avoid errors
    if(isset($_POST['textarea1'])){
        $textarea1 = $_POST['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

Solution using $_SESSION and POST

page1.php

<?php

    session_start(); // needs to be before anything else on page to use $_SESSION
    $textarea1 = "";
    if(isset($_POST['textarea1'])){
        $_SESSION['textarea1'] = $_POST['textarea1'];
    }

?>


<form action="page1.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>
<br /><br />
<a href="page2.php">Go to page2</a>

page2.php

<?php
    session_start(); // needs to be before anything else on page to use $_SESSION
    // this page outputs the textarea1 from the session IF it exists
    $textarea1 = ""; // set var to avoid errors
    if(isset($_SESSION['textarea1'])){
        $textarea1 = $_SESSION['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

WARNING!!! - This contains no validation!!!

How to find patterns across multiple lines using grep?

You can do that very easily if you can use Perl.

perl -ne 'if (/abc/) { $abc = 1; next }; print "Found in $ARGV\n" if ($abc && /efg/); }' yourfilename.txt

You can do that with a single regular expression too, but that involves taking the entire contents of the file into a single string, which might end up taking up too much memory with large files. For completeness, here is that method:

perl -e '@lines = <>; $content = join("", @lines); print "Found in $ARGV\n" if ($content =~ /abc.*efg/s);' yourfilename.txt

Declaring static constants in ES6 classes?

It is also possible to use Object.freeze on you class(es6)/constructor function(es5) object to make it immutable:

class MyConstants {}
MyConstants.staticValue = 3;
MyConstants.staticMethod = function() {
  return 4;
}
Object.freeze(MyConstants);
// after the freeze, any attempts of altering the MyConstants class will have no result
// (either trying to alter, add or delete a property)
MyConstants.staticValue === 3; // true
MyConstants.staticValue = 55; // will have no effect
MyConstants.staticValue === 3; // true

MyConstants.otherStaticValue = "other" // will have no effect
MyConstants.otherStaticValue === undefined // true

delete MyConstants.staticMethod // false
typeof(MyConstants.staticMethod) === "function" // true

Trying to alter the class will give you a soft-fail (won't throw any errors, it will simply have no effect).

What is an AssertionError? In which case should I throw it from my own code?

AssertionError is an Unchecked Exception which rises explicitly by programmer or by API Developer to indicate that assert statement fails.

assert(x>10);

Output:

AssertionError

If x is not greater than 10 then you will get runtime exception saying AssertionError.

css h1 - only as wide as the text

I recently solved this problem by using table-caption, though I cannot say if it is recommended. The other answers didn't seem to workout in my case.

h1 {
  display: table-caption;
}

BACKUP LOG cannot be performed because there is no current database backup

I am not sure whether the database backup file, you trying to restore, is coming from the same environment as you trying to restore it onto.

Remember that destination path of .mdf and .ldf files lives with the backup file itself.

If this is not a case, that means the backup file is coming from a different environment from your current hosting one, make sure that .mdf and .ldf file path is the same (exists) as on your machine, relocate these otherwise. (Mostly a case of restoring db in Docker image)

The way how to do it: In Databases -> Restore database -> [Files] option -> (Check "Relocate all files to folder" - mostly default path is populated on your hosting environment already)

jQuery load first 3 elements, click "load more" to display next 5 elements

Simple and with little changes. And also hide load more when entire list is loaded.

jsFiddle here.

$(document).ready(function () {
    // Load the first 3 list items from another HTML file
    //$('#myList').load('externalList.html li:lt(3)');
    $('#myList li:lt(3)').show();
    $('#showLess').hide();
    var items =  25;
    var shown =  3;
    $('#loadMore').click(function () {
        $('#showLess').show();
        shown = $('#myList li:visible').size()+5;
        if(shown< items) {$('#myList li:lt('+shown+')').show();}
        else {$('#myList li:lt('+items+')').show();
             $('#loadMore').hide();
             }
    });
    $('#showLess').click(function () {
        $('#myList li').not(':lt(3)').hide();
    });
});

Python: Convert timedelta to int in a dataframe

The simplest way to do this is by

df["DateColumn"] = (df["DateColumn"]).dt.days