Programs & Examples On #Fckeditor

WYSIWYG HTML editor and predecessor to CKEditor

Getting the textarea value of a ckeditor textarea with javascript

i found following code working for ckeditor 5

ClassicEditor
    .create( document.querySelector( '#editor' ) )
    .then( editor => {
        editor.model.document.on( 'change:data', () => {
            editorData = editor.getData();
        } );
    } )
    .catch( error => {
        console.error( error );
    } );

How can you integrate a custom file browser/uploader with CKEditor?

I have posted one small tutorial about integrating the FileBrowser available in old FCKEditor into CKEditor.

http://www.mixedwaves.com/2010/02/integrating-fckeditor-filemanager-in-ckeditor/

It contains step by step instructions for doing so and its pretty simple. I hope anybody in search of this will find this tutorial helpful.

UL list style not applying

  • Have you tried following the rule with !important?
  • Which stylesheet does FireBug show having last control over the element?
  • Is this live somewhere to be viewed by others?

Update

I'm fairly confident that providing code-examples would help you receive a solution must faster. If you can upload an example of this issue somewhere, or provide the markup so we can test it on our localhosts, you'll have a better chance of getting some valuable input.

The problem with questions is that they lead others to believe the person asking the question has sufficient knowledge to ask the question. In programming that isn't always the case. There may have been something you missed, or accidentally jipped. Without others having eyes on your code, they have to assume you missed nothing, and overlooked nothing.

How to "pretty" format JSON output in Ruby on Rails

#At Controller
def branch
    @data = Model.all
    render json: JSON.pretty_generate(@data.as_json)
end

How do you get the current time of day?

Datetime.TimeOfDay returns a TimeSpan and might be what you are looking for.

How to Use Sockets in JavaScript\HTML?

I think it is important to mention, now that this question is over 1 year old, that Socket.IO has since come out and seems to be the primary way to work with sockets in the browser now; it is also compatible with Node.js as far as I know.

Escape regex special characters in a Python string

I'm surprised no one has mentioned using regular expressions via re.sub():

import re
print re.sub(r'([\"])',    r'\\\1', 'it\'s "this"')  # it's \"this\"
print re.sub(r"([\'])",    r'\\\1', 'it\'s "this"')  # it\'s "this"
print re.sub(r'([\" \'])', r'\\\1', 'it\'s "this"')  # it\'s\ \"this\"

Important things to note:

  • In the search pattern, include \ as well as the character(s) you're looking for. You're going to be using \ to escape your characters, so you need to escape that as well.
  • Put parentheses around the search pattern, e.g. ([\"]), so that the substitution pattern can use the found character when it adds \ in front of it. (That's what \1 does: uses the value of the first parenthesized group.)
  • The r in front of r'([\"])' means it's a raw string. Raw strings use different rules for escaping backslashes. To write ([\"]) as a plain string, you'd need to double all the backslashes and write '([\\"])'. Raw strings are friendlier when you're writing regular expressions.
  • In the substitution pattern, you need to escape \ to distinguish it from a backslash that precedes a substitution group, e.g. \1, hence r'\\\1'. To write that as a plain string, you'd need '\\\\\\1' — and nobody wants that.

Free space in a CMD shell

You can avoid the commas by using /-C on the DIR command.

FOR /F "usebackq tokens=3" %%s IN (`DIR C:\ /-C /-O /W`) DO (
    SET FREE_SPACE=%%s
)
ECHO FREE_SPACE is %FREE_SPACE%

If you want to compare the available space to the space needed, you could do something like the following. I specified the number with thousands separator, then removed them. It is difficult to grasp the number without commas. The SET /A is nice, but it stops working with large numbers.

SET EXITCODE=0
SET NEEDED=100,000,000
SET NEEDED=%NEEDED:,=%

IF %FREE_SPACE% LSS %NEEDED% (
    ECHO Not enough.
    SET EXITCODE=1
)
EXIT /B %EXITCODE%

IE8 issue with Twitter Bootstrap 3

As previously stated there are two different problems: 1) IE8 doesn't support media queries 2) respond.js used in conjunction with cross-domain css files must be included as described before.

If you want to use BootstrapCDN here's a working example:

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<!--[if lt IE 9]>
    <link href="//netdna.bootstrapcdn.com/respond-proxy.html" id="respond-proxy" rel="respond-proxy" />
    <link href="img/ie/respond.proxy.gif" id="respond-redirect" rel="respond-redirect" />
    <script src="js/ie/html5shiv.js"></script>
    <script src="js/ie/respond.min.js"></script>
    <script src="js/ie/respond.proxy.js"></script>
<![endif]-->

Also make sure to copy respond.proxy.gif, respond.min.js and response.proxy.js in local directories

Try-catch speeding up my code?

This looks like a case of inlining gone bad. On an x86 core, the jitter has the ebx, edx, esi and edi register available for general purpose storage of local variables. The ecx register becomes available in a static method, it doesn't have to store this. The eax register often is needed for calculations. But these are 32-bit registers, for variables of type long it must use a pair of registers. Which are edx:eax for calculations and edi:ebx for storage.

Which is what stands out in the disassembly for the slow version, neither edi nor ebx are used.

When the jitter can't find enough registers to store local variables then it must generate code to load and store them from the stack frame. That slows down code, it prevents a processor optimization named "register renaming", an internal processor core optimization trick that uses multiple copies of a register and allows super-scalar execution. Which permits several instructions to run concurrently, even when they use the same register. Not having enough registers is a common problem on x86 cores, addressed in x64 which has 8 extra registers (r9 through r15).

The jitter will do its best to apply another code generation optimization, it will try to inline your Fibo() method. In other words, not make a call to the method but generate the code for the method inline in the Main() method. Pretty important optimization that, for one, makes properties of a C# class for free, giving them the perf of a field. It avoids the overhead of making the method call and setting up its stack frame, saves a couple of nanoseconds.

There are several rules that determine exactly when a method can be inlined. They are not exactly documented but have been mentioned in blog posts. One rule is that it won't happen when the method body is too large. That defeats the gain from inlining, it generates too much code that doesn't fit as well in the L1 instruction cache. Another hard rule that applies here is that a method won't be inlined when it contains a try/catch statement. The background behind that one is an implementation detail of exceptions, they piggy-back onto Windows' built-in support for SEH (Structure Exception Handling) which is stack-frame based.

One behavior of the register allocation algorithm in the jitter can be inferred from playing with this code. It appears to be aware of when the jitter is trying to inline a method. One rule it appears to use that only the edx:eax register pair can be used for inlined code that has local variables of type long. But not edi:ebx. No doubt because that would be too detrimental to the code generation for the calling method, both edi and ebx are important storage registers.

So you get the fast version because the jitter knows up front that the method body contains try/catch statements. It knows it can never be inlined so readily uses edi:ebx for storage for the long variable. You got the slow version because the jitter didn't know up front that inlining wouldn't work. It only found out after generating the code for the method body.

The flaw then is that it didn't go back and re-generate the code for the method. Which is understandable, given the time constraints it has to operate in.

This slow-down doesn't occur on x64 because for one it has 8 more registers. For another because it can store a long in just one register (like rax). And the slow-down doesn't occur when you use int instead of long because the jitter has a lot more flexibility in picking registers.

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

You start a thread which runs the static method SumData. However, SumData calls SetTextboxText which isn't static. Thus you need an instance of your form to call SetTextboxText.

jQuery: Scroll down page a set increment (in pixels) on click?

var y = $(window).scrollTop();  //your current y position on the page
$(window).scrollTop(y+150);

JComboBox Selection Change Listener?

Code example of ItemListener implementation

class ItemChangeListener implements ItemListener{
    @Override
    public void itemStateChanged(ItemEvent event) {
       if (event.getStateChange() == ItemEvent.SELECTED) {
          Object item = event.getItem();
          // do something with object
       }
    }       
}

Now we will get only selected item.

Then just add listener to your JComboBox

addItemListener(new ItemChangeListener());

What is thread Safe in java?

Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized, or whatever.

Show/hide div if checkbox selected

<input type="checkbox" name="check1" value="checkbox" onchange="showMe('div1')" /> checkbox

<div id="div1" style="display:none;">NOTICE</div>

  <script type="text/javascript">
<!--
   function showMe (box) {
    var chboxs = document.getElementById("div1").style.display;
    var vis = "none";
        if(chboxs=="none"){
         vis = "block"; }
        if(chboxs=="block"){
         vis = "none"; }
    document.getElementById(box).style.display = vis;
}
  //-->
</script>

How to limit the maximum value of a numeric field in a Django model?

Here is the best solution if you want some extra flexibility and don't want to change your model field. Just add this custom validator:

#Imports
from django.core.exceptions import ValidationError      

class validate_range_or_null(object):
    compare = lambda self, a, b, c: a > c or a < b
    clean = lambda self, x: x
    message = ('Ensure this value is between %(limit_min)s and %(limit_max)s (it is %(show_value)s).')
    code = 'limit_value'

    def __init__(self, limit_min, limit_max):
        self.limit_min = limit_min
        self.limit_max = limit_max

    def __call__(self, value):
        cleaned = self.clean(value)
        params = {'limit_min': self.limit_min, 'limit_max': self.limit_max, 'show_value': cleaned}
        if value:  # make it optional, remove it to make required, or make required on the model
            if self.compare(cleaned, self.limit_min, self.limit_max):
                raise ValidationError(self.message, code=self.code, params=params)

And it can be used as such:

class YourModel(models.Model):

    ....
    no_dependents = models.PositiveSmallIntegerField("How many dependants?", blank=True, null=True, default=0, validators=[validate_range_or_null(1,100)])

The two parameters are max and min, and it allows nulls. You can customize the validator if you like by getting rid of the marked if statement or change your field to be blank=False, null=False in the model. That will of course require a migration.

Note: I had to add the validator because Django does not validate the range on PositiveSmallIntegerField, instead it creates a smallint (in postgres) for this field and you get a DB error if the numeric specified is out of range.

Hope this helps :) More on Validators in Django.

PS. I based my answer on BaseValidator in django.core.validators, but everything is different except for the code.

How can I remove a trailing newline?

Careful with "foo".rstrip(os.linesep): That will only chomp the newline characters for the platform where your Python is being executed. Imagine you're chimping the lines of a Windows file under Linux, for instance:

$ python
Python 2.7.1 (r271:86832, Mar 18 2011, 09:09:48) 
[GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os, sys
>>> sys.platform
'linux2'
>>> "foo\r\n".rstrip(os.linesep)
'foo\r'
>>>

Use "foo".rstrip("\r\n") instead, as Mike says above.

How do you dynamically allocate a matrix?

You can also use std::vectors for achieving this:

using std::vector< std::vector<int> >

Example:

std::vector< std::vector<int> > a;

  //m * n is the size of the matrix

    int m = 2, n = 4;
    //Grow rows by m
    a.resize(m);
    for(int i = 0 ; i < m ; ++i)
    {
        //Grow Columns by n
        a[i].resize(n);
    }
    //Now you have matrix m*n with default values

    //you can use the Matrix, now
    a[1][0]=1;
    a[1][1]=2;
    a[1][2]=3;
    a[1][3]=4;

//OR
for(i = 0 ; i < m ; ++i)
{
    for(int j = 0 ; j < n ; ++j)
    {      //modify matrix
        int x = a[i][j];
    }

}

font-family is inherit. How to find out the font-family in chrome developer pane?

I think op wants to know what the font that is used on a webpage is, and hoped that info might be findable in the 'inspect' pane.

Try adding the Whatfont Chrome extension.

Go / golang time.Now().UnixNano() convert to milliseconds?

Keep it simple.

func NowAsUnixMilli() int64 {
    return time.Now().UnixNano() / 1e6
}

ALTER TABLE add constraint

Omit the parenthesis:

ALTER TABLE User 
    ADD CONSTRAINT userProperties
    FOREIGN KEY(properties)
    REFERENCES Properties(ID)

React Native android build failed. SDK location not found

Delete the local.properties from the android folder in your react project and try it.

I've done this and succeeded.

When running UPDATE ... datetime = NOW(); will all rows updated have the same date/time?

http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now

"NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored routine or trigger, NOW() returns the time at which the routine or triggering statement began to execute.) This differs from the behavior for SYSDATE(), which returns the exact time at which it executes as of MySQL 5.0.13. "

Is there any sizeof-like method in Java?

EhCache provides a SizeOf class that will try to use the Instrumentation agent and will fall back to a different approach if the agent is not loaded or cannot be loaded (details here).

Also see the agent from Heinz Kabutz.

Android Studio emulator does not come with Play Store for API 23

Wanted to comment on the last answer, but without login it’s only possible to make an answer:

To get rid of the "read only error" just stop the device immediately after it’s ready. My script looks as follows:

#!/bin/bash 
~/bin/AndroidSdk/tools/emulator @Nexus_6P_API_23 -no-boot-anim &
adb wait-for-device
adb shell stop
adb remount
adb push GmsCore.apk /system/priv-app
adb push GoogleServicesFramework.apk /system/priv-app
adb push GoogleLoginService.apk /system/priv-app
adb push Phonesky.apk /system/priv-app
adb shell start

Add my custom http header to Spring RestTemplate request / extend RestTemplate

If the goal is to have a reusable RestTemplate which is in general useful for attaching the same header to a series of similar request a org.springframework.boot.web.client.RestTemplateCustomizer parameter can be used with a RestTemplateBuilder:

 String accessToken= "<the oauth 2 token>";
 RestTemplate restTemplate = new RestTemplateBuilder(rt-> rt.getInterceptors().add((request, body, execution) -> {
        request.getHeaders().add("Authorization", "Bearer "+accessToken);
        return execution.execute(request, body);
    })).build();

How do you return the column names of a table?

try this

select * from <tablename> where 1=2

...............................................

How do I add a Fragment to an Activity with a programmatically created content view

This may help you

Defining a Fragment

create xml file for fragment view fragment_abc.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button" />

</LinearLayout>

create fragment ABCFragment.java

import androidx.fragment.app.Fragment;

public class FooFragment extends Fragment {
// The onCreateView method is called when Fragment should create its View object hierarchy,
// either dynamically or via XML layout inflation. 

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle 
savedInstanceState) {
    // Defines the xml file for the fragment
    return inflater.inflate(R.layout.fragment_abc, parent, false);
}

// This event is triggered soon after onCreateView().
// Any view setup should occur here.  E.g., view lookups and attaching view listeners.
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    // Setup any handles to view objects here
    // EditText etFoo = (EditText) view.findViewById(R.id.etFoo);
}
}

Add frameLayout in your activity

<FrameLayout
   android:id="@+id/your_placeholder"
   android:layout_width="match_parent"
   android:layout_height="match_parent">

now in activity, add following method

protected void setFragment() {
    // Begin the transaction
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    // Replace the contents of the container with the new fragment
    ft.replace(R.id.fragment_container, new ABCFragment());
    // or ft.add(R.id.your_placeholder, new ABCFragment());
    // Complete the changes added above
    ft.commit();
}

reference : https://guides.codepath.com/android/creating-and-using-fragments#defining-a-fragment

convert float into varchar in SQL server without scientific notation

None of the above worked for me. In the end I simply used this:

INSERT INTO [Destination_Table_Name]([Field_Name])
SELECT  CONCAT('#',CAST([Field_Name] AS decimal(38,0))) [Field_Name] 
FROM [dbo].[Source_Table_Name] WHERE ISNUMERIC([CIRCUIT_NUMBER]) = 1
 
INSERT INTO [Destination_Table_Name]([Field_Name])
SELECT  [Field_Name]
FROM [dbo].[Source_Table_Name] WHERE ISNUMERIC([CIRCUIT_NUMBER]) <> 1

Append TimeStamp to a File Name

you can use:

Stopwatch.GetTimestamp();

Display List in a View MVC

You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams> and you are passing var model = tm.Name.ToList(); name list. You have to pass list of Teams.

You have to pass following model

var model = new List<Teams>();

model.Add(new Teams { Name =  new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name =  new List<string>(){"John","XYZ"} });
return View(model);

Query for array elements inside JSON type

jsonb in Postgres 9.4+

You can use the same query as below, just with jsonb_array_elements().

But rather use the jsonb "contains" operator @> in combination with a matching GIN index on the expression data->'objects':

CREATE INDEX reports_data_gin_idx ON reports
USING gin ((data->'objects') jsonb_path_ops);

SELECT * FROM reports WHERE data->'objects' @> '[{"src":"foo.png"}]';

Since the key objects holds a JSON array, we need to match the structure in the search term and wrap the array element into square brackets, too. Drop the array brackets when searching a plain record.

More explanation and options:

json in Postgres 9.3+

Unnest the JSON array with the function json_array_elements() in a lateral join in the FROM clause and test for its elements:

SELECT data::text, obj
FROM   reports r, json_array_elements(r.data#>'{objects}') obj
WHERE  obj->>'src' = 'foo.png';

db<>fiddle here
Old sqlfiddle

The CTE (WITH query) just substitutes for a table reports.
Or, equivalent for just a single level of nesting:

SELECT *
FROM   reports r, json_array_elements(r.data->'objects') obj
WHERE  obj->>'src' = 'foo.png';

->>, -> and #> operators are explained in the manual.

Both queries use an implicit JOIN LATERAL.

Closely related:

Group by & count function in sqlalchemy

You can also count on multiple groups and their intersection:

self.session.query(func.count(Table.column1),Table.column1, Table.column2).group_by(Table.column1, Table.column2).all()

The query above will return counts for all possible combinations of values from both columns.

MySQL Nested Select Query?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

How to Edit a row in the datatable

Try the SetField method:

By passing column object :

table.Rows[rowIndex].SetField(column, value);

By Passing column index :

table.Rows[rowIndex].SetField(0 /*column index*/, value);

By Passing column name as string :

table.Rows[rowIndex].SetField("product_name" /*columnName*/, value);

Excel 2013 VBA Clear All Filters macro

This thread is ancient, but I wasn't happy with any of the given answers, and ended up writing my own. I'm sharing it now:

We start with:

  Sub ResetWSFilters(ws as worksheet)
             If ws.FilterMode Then   
     ws.ShowAllData   
     Else   
     End If  
    'This gets rid of "normal" filters - but tables will remain filtered
    For Each listObj In ws.ListObjects 
               If listObj.ShowHeaders Then   
                    listObj.AutoFilter.ShowAllData
                    listObj.Sort.SortFields.Clear    
               End If     
       Next listObj
        'And this gets rid of table filters
        End Sub

We can feed a specific worksheet to this macro which will unfilter just that one worksheet. Useful if you need to make sure just one worksheet is clear. However, I usually want to do the entire workbook

Sub ResetAllWBFilters(wb as workbook)
  Dim ws As Worksheet  
  Dim wb As Workbook  
  Dim listObj As ListObject    

       For Each ws In wb.Worksheets  
          If ws.FilterMode Then 
          ws.ShowAllData  
          Else   
          End If   
 'This removes "normal" filters in the workbook - however, it doesn't remove table filters           
   For Each listObj In ws.ListObjects 
        If listObj.ShowHeaders Then   
             listObj.AutoFilter.ShowAllData 
             listObj.Sort.SortFields.Clear    
        End If     
   Next listObj

        Next   
'And this removes table filters. You need both aspects to make it work.  
    End Sub

You can use this, by, for example, opening a workbook you need to deal with and resetting their filters before doing anything with it:

Sub ExampleOpen()
Set TestingWorkBook = Workbooks.Open("C:\Intel\......") 'The .open is assuming you need to open the workbook in question - different procedure if it's already open
Call ResetAllWBFilters(TestingWorkBook)
End Sub

The one I use the most: Resetting all filters in the workbook that the module is stored in:

Sub ResetFilters()
      Dim ws As Worksheet  
      Dim wb As Workbook  
      Dim listObj As ListObject  
       Set wb = ThisWorkbook  
       'Set wb = ActiveWorkbook
       'This is if you place the macro in your personal wb to be able to reset the filters on any wb you're currently working on. Remove the set wb = thisworkbook if that's what you need
           For Each ws In wb.Worksheets  
              If ws.FilterMode Then 
              ws.ShowAllData  
              Else   
              End If   
     'This removes "normal" filters in the workbook - however, it doesn't remove table filters           
       For Each listObj In ws.ListObjects 
            If listObj.ShowHeaders Then   
                 listObj.AutoFilter.ShowAllData 
                 listObj.Sort.SortFields.Clear    
            End If     
       Next listObj

            Next   
'And this removes table filters. You need both aspects to make it work.  
    End Sub

Spring Boot: Is it possible to use external application.properties files in arbitrary directories with a fat jar?

I managed to load an application.properties file in external path while using -jar option.

The key was PropertiesLauncher.

To use PropertiesLauncher, pom.xml file must be changed like this:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>  <!-- added -->
                <layout>ZIP</layout> <!-- to use PropertiesLaunchar -->
            </configuration>
        </plugin>
    </plugins>
</build>

For this, I referenced the following StackOverflow question: spring boot properties launcher unable to use . BTW, In Spring Boot Maven Plugin document(http://docs.spring.io/spring-boot/docs/1.1.7.RELEASE/maven-plugin/repackage-mojo.html), there is no mention that specifying ZIP triggers that PropertiesLauncher is used. (Perhaps in another document?)

After the jar file had been built, I could see that the PropertiesLauncher is used by inspecting Main-Class property in META-INF/MENIFEST.MF in the jar.

Now, I can run the jar as follows(in Windows):

java -Dloader.path=file:///C:/My/External/Dir,MyApp-0.0.1-SNAPSHOT.jar -jar MyApp-0.0.1-SNAPSHOT.jar

Note that the application jar file is included in loader.path.

Now an application.properties file in C:\My\External\Dir\config is loaded.

As a bonus, any file (for example, static html file) in that directory can also be accessed by the jar since it's in the loader path.

As for the non-jar (expanded) version mentioned in UPDATE 2, maybe there was a classpath order problem.

Download and save PDF file with Python requests module

You should use response.content in this case:

with open('/tmp/metadata.pdf', 'wb') as f:
    f.write(response.content)

From the document:

You can also access the response body as bytes, for non-text requests:

>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...

So that means: response.text return the output as a string object, use it when you're downloading a text file. Such as HTML file, etc.

And response.content return the output as bytes object, use it when you're downloading a binary file. Such as PDF file, audio file, image, etc.


You can also use response.raw instead. However, use it when the file which you're about to download is large. Below is a basic example which you can also find in the document:

import requests

url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'
r = requests.get(url, stream=True)

with open('/tmp/metadata.pdf', 'wb') as fd:
    for chunk in r.iter_content(chunk_size):
        fd.write(chunk)

chunk_size is the chunk size which you want to use. If you set it as 2000, then requests will download that file the first 2000 bytes, write them into the file, and do this again, again and again, unless it finished.

So this can save your RAM. But I'd prefer use response.content instead in this case since your file is small. As you can see use response.raw is complex.


Relates:

Make DateTimePicker work as TimePicker only in WinForms

If you want to do it from properties, you can do this by setting the Format property of DateTimePicker to DateTimePickerFormat.Time and ShowUpDown property to true. Also, customFormat can be set in properties.

sendKeys() in Selenium web driver

Try this, it will surely work:

driver.findElement(By.xpath("//label[text()='User Name:']/following::div/input")).sendKeys("UserName" + Keys.TAB);

Export specific rows from a PostgreSQL table as INSERT SQL script

Create a table with the set you want to export and then use the command line utility pg_dump to export to a file:

create table export_table as 
select id, name, city
from nyummy.cimory
where city = 'tokyo'
$ pg_dump --table=export_table --data-only --column-inserts my_database > data.sql

--column-inserts will dump as insert commands with column names.

--data-only do not dump schema.

As commented below, creating a view in instead of a table will obviate the table creation whenever a new export is necessary.

What is the meaning of curly braces?

In Python, curly braces are used to define a dictionary.

a={'one':1, 'two':2, 'three':3}
a['one']=1
a['three']=3

In other languages, { } are used as part of the flow control. Python however used indentation as its flow control because of its focus on readable code.

for entry in entries:
     code....

There's a little easter egg in Python when it comes to braces. Try running this on the Python Shell and enjoy.

from __future__ import braces

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;
}

JavaScript code to stop form submission

E.g if you have submit button on form ,inorder to stop its propogation simply write event.preventDefault(); in the function which is called upon clicking submit button or enter button.

Iterating through a list in reverse order in java

Guava offers Lists#reverse(List) and ImmutableList#reverse(). As in most cases for Guava, the former delegates to the latter if the argument is an ImmutableList, so you can use the former in all cases. These do not create new copies of the list but just "reversed views" of it.

Example

List reversed = ImmutableList.copyOf(myList).reverse();

jquery remove "selected" attribute of option?

Using jQuery 1.9 and above:

$("#mySelect :selected").prop('selected', false);

How to pip or easy_install tkinter on Windows

In python, Tkinter was a default package, you can repair the installation and select Tcl/Tk. repair When you run this, DDL should be installed like so: enter image description here

Java Scanner String input

When you read in the year month day hour minutes with something like nextInt() it leaves rest of the line in the parser/buffer (even if it is blank) so when you call nextLine() you are reading the rest of this first line.

I suggest you to use scan.next() instead of scan.nextLine().

CSS set li indent

I found that doing it in two relatively simple steps seemed to work quite well. The first css definition for ul sets the base indent that you want for the list as a whole. The second definition sets the indent value for each nested list item within it. In my case they are the same, but you can obviously pick whatever you want.

ul {
    margin-left: 1.5em;
}

ul > ul {
    margin-left: 1.5em;
}

Listview Scroll to the end of the list after updating the list

Using : Set the head of the list to it bottom lv.setStackFromBottom(true);

Worked for me and the list is scrolled to the bottom automatically when it is first brought into visibility. The list then scrolls as it should with TRANSCRIPT_MODE_ALWAYS_SCROLL.

printf %f with only 2 numbers after the decimal point?

System.out.printf("%.2f", number);

BUT, this will round the number to the nearest decimal point you have mentioned.(As in your case you will get 3.14 since rounding 3.14159 to 2 decimal points will be 3.14)

Since the function printf will round the numbers the answers for some other numbers may look like this,

System.out.printf("%.2f", 3.14136); -> 3.14
System.out.printf("%.2f", 3.14536); -> 3.15
System.out.printf("%.2f", 3.14836); -> 3.15

If you just need to cutoff the decimal numbers and limit it to a k decimal numbers without rounding,

lets say k = 2.

System.out.printf("%.2f", 3.14136 - 0.005); -> 3.14
System.out.printf("%.2f", 3.14536 - 0.005); -> 3.14
System.out.printf("%.2f", 3.14836 - 0.005); -> 3.14

Replace Div Content onclick

A Third Answer

Sorry, maybe I have it correct this time...

jsFiddle Demo

var savedBox1, savedBox2, state1=0, state2=0;

jQuery(document).ready(function() {
    jQuery(".rec1").click(function() {
        if (state1==0){
            savedBox1 = jQuery('#rec-box').html();
            jQuery('#rec-box').html(jQuery(this).next().html()); 
            state1 = 1;
        }else{
            jQuery('#rec-box').html(savedBox1); 
            state1 = 0;
        }
    });

    jQuery(".rec2").click(function() {
        if (state1==0){
            savedBox2 = jQuery('#rec-box2').html();
            jQuery('#rec-box2').html(jQuery(this).next().html()); 
            state2 = 1;
        }else{
            jQuery('#rec-box2').html(savedBox2); 
            state2 = 0;
        }
    });
});

Angular 4: How to include Bootstrap?

Step 1 : npm install bootstrap --save

Step : 2 : Paste below code in angular.json node_modules/bootstrap/dist/css/bootstrap.min.css

Step 3 : ng serve

enter image description here

How to change the blue highlight color of a UITableViewCell?

1- Add a view to the content view of your cell.
2- Right click your cell.
3- Make the added view as "selectedBackgroundView" enter image description here

How do I verify that a string only contains letters, numbers, underscores and dashes?

A regular expression will do the trick with very little code:

import re

...

if re.match("^[A-Za-z0-9_-]*$", my_little_string):
    # do something here

How can I validate a string to only allow alphanumeric characters in it?

Use the following expression:

^[a-zA-Z0-9]*$

ie:

using System.Text.RegularExpressions;

Regex r = new Regex("^[a-zA-Z0-9]*$");
if (r.IsMatch(SomeString)) {
  ...
}

HTML set image on browser tab

<link rel="SHORTCUT ICON" href="favicon.ico" type="image/x-icon" />
<link rel="ICON" href="favicon.ico" type="image/ico" />

Excellent tool for cross-browser favicon - http://www.convertico.com/

Setting up Gradle for api 26 (Android)

You could add google() to repositories block

allprojects {
    repositories {
        jcenter()
        maven {
            url 'https://github.com/uPhyca/stetho-realm/raw/master/maven-repo'

        }
        maven {
            url "https://jitpack.io"
        }
        google()
    }
}

Get file name from URI string in C#

The accepted answer is problematic for http urls. Moreover Uri.LocalPath does Windows specific conversions, and as someone pointed out leaves query strings in there. A better way is to use Uri.AbsolutePath

The correct way to do this for http urls is:

Uri uri = new Uri(hreflink);
string filename = System.IO.Path.GetFileName(uri.AbsolutePath);

AngularJS $http, CORS and http authentication

For making a CORS request one must add headers to the request along with the same he needs to check of mode_header is enabled in Apache.

For enabling headers in Ubuntu:

sudo a2enmod headers

For php server to accept request from different origin use:

Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

How to reload the current state?

$scope.reloadstat = function () { $state.go($state.current, {}, {reload: true}); };

How do I pick 2 random items from a Python set?

Use the random module: http://docs.python.org/library/random.html

import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)

This samples the two values without replacement (so the two values are different).

Writing to a file in a for loop

It's preferable to use context managers to close the files automatically

with open("new.txt", "r"), open('xyz.txt', 'w') as textfile, myfile:
    for line in textfile:
        var1, var2 = line.split(",");
        myfile.writelines(var1)

Difference between git checkout --track origin/branch and git checkout -b branch origin/branch

There is no difference at all!

1) git checkout -b branch origin/branch

If there is no --track and no --no-track, --track is assumed as default. The default can be changed with the setting branch.autosetupmerge.

In effect, 1) behaves like git checkout -b branch --track origin/branch.

2) git checkout --track origin/branch

“As a convenience”, --track without -b implies -b and the argument to -b is guessed to be “branch”. The guessing is driven by the configuration variable remote.origin.fetch.

In effect, 2) behaves like git checkout -b branch --track origin/branch.

As you can see: no difference.

But it gets even better:

3) git checkout branch

is also equivalent to git checkout -b branch --track origin/branch if “branch” does not exist yet but “origin/branch” does1.


All three commands set the “upstream” of “branch” to be “origin/branch” (or they fail).

Upstream is used as reference point of argument-less git status, git push, git merge and thus git pull (if configured like that (which is the default or almost the default)).

E.g. git status tells you how far behind or ahead you are of upstream, if one is configured.

git push is configured to push the current branch upstream by default2 since git 2.0.

1 ...and if “origin” is the only remote having “branch”
2 the default (named “simple”) also enforces for both branch names to be equal

How to supply value to an annotation from a Constant java

You can use enum and refer that enum in annotation field

How to convert a string from uppercase to lowercase in Bash?

Why not execute in backticks ?

 x=`echo "$y" | tr '[:upper:]' '[:lower:]'` 

This assigns the result of the command in backticks to the variable x. (i.e. it's not particular to tr but is a common pattern/solution for shell scripting)

You can use $(..) instead of the backticks. See here for more info.

Why use the params keyword?

It allows you to add as many base type parameters in your call as you like.

addTwoEach(10, 2, 4, 6)

whereas with the second form you have to use an array as parameter

addTwoEach(new int[] {10,2,4,6})

How to convert string to integer in UNIX

let d=d1-d2;echo $d;

This should help.

How long to brute force a salted SHA-512 hash? (salt provided)

There isn't a single answer to this question as there are too many variables, but SHA2 is not yet really cracked (see: Lifetimes of cryptographic hash functions) so it is still a good algorithm to use to store passwords in. The use of salt is good because it prevents attack from dictionary attacks or rainbow tables. Importance of a salt is that it should be unique for each password. You can use a format like [128-bit salt][512-bit password hash] when storing the hashed passwords.

The only viable way to attack is to actually calculate hashes for different possibilities of password and eventually find the right one by matching the hashes.

To give an idea about how many hashes can be done in a second, I think Bitcoin is a decent example. Bitcoin uses SHA256 and to cut it short, the more hashes you generate, the more bitcoins you get (which you can trade for real money) and as such people are motivated to use GPUs for this purpose. You can see in the hardware overview that an average graphic card that costs only $150 can calculate more than 200 million hashes/s. The longer and more complex your password is, the longer time it will take. Calculating at 200M/s, to try all possibilities for an 8 character alphanumberic (capital, lower, numbers) will take around 300 hours. The real time will most likely less if the password is something eligible or a common english word.

As such with anything security you need to look at in context. What is the attacker's motivation? What is the kind of application? Having a hash with random salt for each gives pretty good protection against cases where something like thousands of passwords are compromised.

One thing you can do is also add additional brute force protection by slowing down the hashing procedure. As you only hash passwords once, and the attacker has to do it many times, this works in your favor. The typical way to do is to take a value, hash it, take the output, hash it again and so forth for a fixed amount of iterations. You can try something like 1,000 or 10,000 iterations for example. This will make it that many times times slower for the attacker to find each password.

What command shows all of the topics and offsets of partitions in Kafka?

You might want to try kt. It's also quite faster than the bundled kafka-topics.

This is the current most complete info description you can get out of a topic with kt:

kt topic -brokers localhost:9092 -filter my_topic_name -partitions -leaders -replicas

It also outputs as JSON, so you can pipe it to jq for further flexibility.

Calculating the difference between two Java date instances

Using millisecond approach can cause problems in some locales.

Lets take, for example, the difference between the two dates 03/24/2007 and 03/25/2007 should be 1 day;

However, using the millisecond route, you'll get 0 days, if you run this in the UK!

/** Manual Method - YIELDS INCORRECT RESULTS - DO NOT USE**/  
/* This method is used to find the no of days between the given dates */  
public long calculateDays(Date dateEarly, Date dateLater) {  
   return (dateLater.getTime() - dateEarly.getTime()) / (24 * 60 * 60 * 1000);  
} 

Better way to implement this is to use java.util.Calendar

/** Using Calendar - THE CORRECT WAY**/  
public static long daysBetween(Calendar startDate, Calendar endDate) {  
  Calendar date = (Calendar) startDate.clone();  
  long daysBetween = 0;  
  while (date.before(endDate)) {  
    date.add(Calendar.DAY_OF_MONTH, 1);  
    daysBetween++;  
  }  
  return daysBetween;  
}  

In Postgresql, force unique on combination of two columns

CREATE TABLE someTable (
    id serial PRIMARY KEY,
    col1 int NOT NULL,
    col2 int NOT NULL,
    UNIQUE (col1, col2)
)

autoincrement is not postgresql. You want a serial.

If col1 and col2 make a unique and can't be null then they make a good primary key:

CREATE TABLE someTable (
    col1 int NOT NULL,
    col2 int NOT NULL,
    PRIMARY KEY (col1, col2)
)

JavaScript Infinitely Looping slideshow with delays?

Here:

window.onload = function start() {
    slide();
}
function slide() {
    var num = 0;
    for (num=0;num==10;) {
        setTimeout("document.getElementById('container').style.marginLeft='-600px'",3000);
        setTimeout("document.getElementById('container').style.marginLeft='-1200px'",6000);
        setTimeout("document.getElementById('container').style.marginLeft='-1800px'",9000);
        setTimeout("document.getElementById('container').style.marginLeft='0px'",12000);
    }
}

That makes it keep looping alright! That's why it isn't runnable here.

Is there a way to delete created variables, functions, etc from the memory of the interpreter?

This worked for me.

You need to run it twice once for globals followed by locals

for name in dir():
    if not name.startswith('_'):
        del globals()[name]

for name in dir():
    if not name.startswith('_'):
        del locals()[name]

How to loop through an array containing objects and access their properties

Looping through an array of objects is a pretty fundamental functionality. This is what works for me.

_x000D_
_x000D_
var person = [];_x000D_
person[0] = {_x000D_
  firstName: "John",_x000D_
  lastName: "Doe",_x000D_
  age: 60_x000D_
};_x000D_
_x000D_
var i, item;_x000D_
_x000D_
for (i = 0; i < person.length; i++) {_x000D_
  for (item in person[i]) {_x000D_
    document.write(item + ": " + person[i][item] + "<br>");_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

class method generates "TypeError: ... got multiple values for keyword argument ..."

Thanks for the instructive posts. I'd just like to keep a note that if you're getting "TypeError: foodo() got multiple values for keyword argument 'thing'", it may also be that you're mistakenly passing the 'self' as a parameter when calling the function (probably because you copied the line from the class declaration - it's a common error when one's in a hurry).

Multidimensional Lists in C#

Why don't you use a List<People> instead of a List<List<string>> ?

Why does adb return offline after the device string?

I've had a similar issue with one of my phones. I was unable to connect and use usb debugging on any of my computers. In the end, I had to restart the usb debugging on the phone manually [doing so using the Developer menu was not enough].

There's only one command you have to run on your phone [I did it using Terminal Emulator app]:

adb usb

And that was it.

Hope this helps someone in the future.

Create a hidden field in JavaScript

You can use jquery for create element on the fly

$('#form').append('<input type="hidden" name="fieldname" value="fieldvalue" />');

or other way

$('<input>').attr({
    type: 'hidden',
    id: 'fieldId',
    name: 'fieldname'
}).appendTo('form')

#include errors detected in vscode

The error message "Please update your includePath" does not necessarily mean there is actually a problem with the includePath. The problem may be that VSCode is using the wrong compiler or wrong IntelliSense mode. I have written instructions in this answer on how to troubleshoot and align your VSCode C++ configuration with your compiler and project.

What is the command to exit a Console application in C#?

You can use Environment.Exit(0) and Application.Exit.

Environment.Exit(): terminates this process and gives the underlying operating system the specified exit code.

How to insert an item into a key/value pair object?

Do you need to look up objects by the key? If not, consider using List<Tuple<string, string>> or List<KeyValuePair<string, string>> if you're not using .NET 4.

How can I check if given int exists in array?

I think you are looking for std::any_of, which will return a true/false answer to detect if an element is in a container (array, vector, deque, etc.)

int val = SOME_VALUE; // this is the value you are searching for
bool exists = std::any_of(std::begin(myArray), std::end(myArray), [&](int i)
{
    return i == val;
});

If you want to know where the element is, std::find will return an iterator to the first element matching whatever criteria you provide (or a predicate you give it).

int val = SOME_VALUE;
int* pVal = std::find(std::begin(myArray), std::end(myArray), val);
if (pVal == std::end(myArray))
{
    // not found
}
else
{
    // found
}

Composer: Command Not Found

This is for mac or ubuntu user, try this on terminal

curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

Generate SQL Create Scripts for existing tables with Query

Easiest way is to use the built-in feature of SQL Management Studio.

Right-click the database, go to tasks, Generate Scripts, and walk through the wizard. You can choose what objects to script, and it'll make it all for you.

Now if you are trying to make your OWN script to do the same thing, you're probably up for a lot of work...

Using awk to print all columns from the nth to the last

Perl:

@m=`ls -ltr dir | grep ^d | awk '{print \$6,\$7,\$8,\$9}'`;
foreach $i (@m)
{
        print "$i\n";

}

how to filter out a null value from spark dataframe

I use the following code to solve my question. It works. But as we all know, I work around a country's mile to solve it. So, is there a short cut for that? Thanks

def filter_null(field : Any) : Int = field match {
    case null => 0
    case _    => 1
}

val test = train_event_join.join(
    user_friends_pair,
    train_event_join("user_id") === user_friends_pair("user_id") &&
    train_event_join("event_owner") === user_friends_pair("friend_id"),
    "left"
).select(
    train_event_join("user_id"),
    train_event_join("event_id"),
    train_event_join("invited"),
    train_event_join("day_diff"),
    train_event_join("interested"),
    train_event_join("event_owner"),
    user_friends_pair("friend_id")
).rdd.map{
    line => (
        line(0).toString.toLong,
        line(1).toString.toLong,
        line(2).toString.toLong,
        line(3).toString.toLong,
        line(4).toString.toLong,
        line(5).toString.toLong,
        filter_null(line(6))
        )
    }.toDF("user_id", "event_id", "invited", "day_diff", "interested", "event_owner", "creator_is_friend")

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

Had to look it up in the specs:

Class's getResource() - documentation states the difference:

This method delegates the call to its class loader, after making these changes to the resource name: if the resource name starts with "/", it is unchanged; otherwise, the package name is prepended to the resource name after converting "." to "/". If this object was loaded by the bootstrap loader, the call is delegated to ClassLoader.getSystemResource.

What does "zend_mm_heap corrupted" mean

I had this error using the Mongo 2.2 driver for PHP:

$collection = $db->selectCollection('post');
$collection->ensureIndex(array('someField', 'someOtherField', 'yetAnotherField')); 

^^DOESN'T WORK

$collection = $db->selectCollection('post');
$collection->ensureIndex(array('someField', 'someOtherField')); 
$collection->ensureIndex(array('yetAnotherField')); 

^^ WORKS! (?!)

How can you search Google Programmatically Java API

In light of those TOS alterations last year we built an API that gives access to Google's search. It was for our own use only but after some requests we decided to open it up. We're planning to add additional search engines in the future!

Should anyone be looking for an easy way to implement / acquire search results you are free to sign up and give the REST API a try: https://searchapi.io

It returns JSON results and should be easy enough to implement with the detailed docs.

It's a shame that Bing and Yahoo are miles ahead on Google in this regard. Their APIs aren't cheap, but at least available.

How to read file with space separated values in pandas

add delim_whitespace=True argument, it's faster than regex.

jQuery: selecting each td in a tr

expanding on the answer above the 'each' function will return you the table-cell html object. wrapping that in $() will then allow you to perform jquery actions on it.

$(this).find('td').each (function( column, td) {
  $(td).blah
});  

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

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

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

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

kill a process in bash

It is not clear to me what you mean by "escape an executable which is running", but ctrl-z will put a process into the background and return control to the command line. You can then use the fg command to bring the program back into the foreground.

Using CSS td width absolute, position

Try to use

table {
  table-layout: auto;
}

If you use Bootstrap, class table has table-layout: fixed; by default.

Private vs Protected - Visibility Good-Practice Concern

I read an article a while ago that talked about locking down every class as much as possible. Make everything final and private unless you have an immediate need to expose some data or functionality to the outside world. It's always easy to expand the scope to be more permissible later on, but not the other way around. First consider making as many things as possible final which will make choosing between private and protected much easier.

  1. Make all classes final unless you need to subclass them right away.
  2. Make all methods final unless you need to subclass and override them right away.
  3. Make all method parameters final unless you need to change them within the body of the method, which is kinda awkward most of the times anyways.

Now if you're left with a final class, then make everything private unless something is absolutely needed by the world - make that public.

If you're left with a class that does have subclass(es), then carefully examine every property and method. First consider if you even want to expose that property/method to subclasses. If you do, then consider whether a subclass can wreak havoc on your object if it messed up the property value or method implementation in the process of overriding. If it's possible, and you want to protect your class' property/method even from subclasses (sounds ironic, I know), then make it private. Otherwise make it protected.

Disclaimer: I don't program much in Java :)

How do I print a double value without scientific notation using Java?

You can try it with DecimalFormat. With this class you are very flexible in parsing your numbers.
You can exactly set the pattern you want to use.
In your case for example:

double test = 12345678;
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(0);
System.out.println(df.format(test)); //12345678

Box shadow for bottom side only

You have to specify negative spread in the box shadow to remove side shadow

-webkit-box-shadow: 0 10px 10px -10px #000000;
   -moz-box-shadow: 0 10px 10px -10px #000000;
        box-shadow: 0 10px 10px -10px #000000;

Check out http://dabblet.com/gist/9532817 and try changing properties and know how it behaves

How to make a floated div 100% height of its parent?

A similar case when you need several child elements have the same height can be solved with flexbox:

https://css-tricks.com/using-flexbox/

Set display: flex; for parent and flex: 1; for child elements, they all will have the same height.

How to view the list of compile errors in IntelliJ?

the "problem view" mentioned in previous answers was helpful, but i saw it didn't catch all the errors in project. After running application, it began populating other classes that had issues but didn't appear at first in that problems view.

How to make exe files from a node.js app?

The best tool I know is NodeJS tool: zeit/pkg

It is very easy to use (much more than Nexe, just as an example), you can just install in globally: npm install -g pkg

to create executables for macOS, Linux and Windows:

pkg exampleApp.js

I had a bit of complicated code which used NodeJS socket server, I tried different applications, none of them created it properly, except zeit/pkg.

How to generate a random string in Ruby

Be aware: rand is predictable for an attacker and therefore probably insecure. You should definitely use SecureRandom if this is for generating passwords. I use something like this:

length = 10
characters = ('A'..'Z').to_a + ('a'..'z').to_a + ('0'..'9').to_a

password = SecureRandom.random_bytes(length).each_char.map do |char|
  characters[(char.ord % characters.length)]
end.join

How to get the latest record in each group using GROUP BY?

This is a standard problem.

Note that MySQL allows you to omit columns from the GROUP BY clause, which Standard SQL does not, but you do not get deterministic results in general when you use the MySQL facility.

SELECT *
  FROM Messages AS M
  JOIN (SELECT To_ID, From_ID, MAX(TimeStamp) AS Most_Recent
          FROM Messages
         WHERE To_ID = 12345678
         GROUP BY From_ID
       ) AS R
    ON R.To_ID = M.To_ID AND R.From_ID = M.From_ID AND R.Most_Recent = M.TimeStamp
 WHERE M.To_ID = 12345678

I've added a filter on the To_ID to match what you're likely to have. The query will work without it, but will return a lot more data in general. The condition should not need to be stated in both the nested query and the outer query (the optimizer should push the condition down automatically), but it can do no harm to repeat the condition as shown.

Set LIMIT with doctrine 2?

Your setMaxResults($limit) needs to be set on the object.

e.g.

$query_ids = $this->getEntityManager()
  ->createQuery(
    "SELECT e_.id
    FROM MuzichCoreBundle:Element e_
    WHERE [...]
    GROUP BY e_.id")
;
$query_ids->setMaxResults($limit);

whitespaces in the path of windows filepath

There is no problem with whitespaces in the path since you're not using the "shell" to open the file. Here is a session from the windows console to prove the point. You're doing something else wrong

Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on wi
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>>
>>> os.makedirs("C:/ABC/SEM 2/testfiles")
>>> open("C:/ABC/SEM 2/testfiles/all.txt","w")
<open file 'C:/ABC/SEM 2/testfiles/all.txt', mode 'w' at 0x0000000001D95420>
>>> exit()

C:\Users\Gnibbler>dir "C:\ABC\SEM 2\testfiles"
 Volume in drive C has no label.
 Volume Serial Number is 46A0-BB64

 Directory of c:\ABC\SEM 2\testfiles

13/02/2013  10:20 PM    <DIR>          .
13/02/2013  10:20 PM    <DIR>          ..
13/02/2013  10:20 PM                 0 all.txt
               1 File(s)              0 bytes
               2 Dir(s)  78,929,309,696 bytes free

C:\Users\Gnibbler>

Fit website background image to screen size

Try this:

background: url(../IMAGES/background.jpg) no-repeat;
background-size: auto auto;

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

INSERT INTO dbo.MyTable (ID, Name)
SELECT 123, 'Timmy'
UNION ALL
SELECT 124, 'Jonny'
UNION ALL
SELECT 125, 'Sally'

For SQL Server 2008, can do it in one VALUES clause exactly as per the statement in your question (you just need to add a comma to separate each values statement)...

Cannot authenticate into mongo, "auth fails"

This fixed my issue:

Go to terminal shell and type mongo.

Then type use db_name.

Then type:

 db.createUser(
   {
     user: "mongodb",
     pwd: "dogmeatsubparflavour1337",
     roles: [ { role: "dbOwner", db: "db_name" } ]
   }
 )

Also try: db.getUsers()

Quick sample:

const MongoClient = require('mongodb').MongoClient;

// MongoDB Connection Info
const url = 'mongodb://mongodb:[email protected]:27017/?authMechanism=DEFAULT&authSource=db_name';
// Additional options: https://docs.mongodb.com/manual/reference/connection-string/#connection-string-options

// Use Connect Method to connect to the Server
MongoClient.connect(url)
  .then((db) => {
    console.log(db);
    console.log('Casually connected correctly to server.');
    // Be careful with db.close() when working asynchronously
    db.close();
  })
  .catch((error) => {
    console.log(error);
  });

Volley JsonObjectRequest Post request not working

I had the same issue once, the empty POST array is caused due a redirection of the request (on your server side), fix the URL so it doesn't have to be redirected when it hits the server. For Example, if https is forced using the .htaccess file on your server side app, make sure your client request has the "https://" prefix. Usually when a redirect happens the POST array is lost. I Hope this helps!

What is an example of the Liskov Substitution Principle?

I see rectangles and squares in every answer, and how to violate the LSP.

I'd like to show how the LSP can be conformed to with a real-world example :

<?php

interface Database 
{
    public function selectQuery(string $sql): array;
}

class SQLiteDatabase implements Database
{
    public function selectQuery(string $sql): array
    {
        // sqlite specific code

        return $result;
    }
}

class MySQLDatabase implements Database
{
    public function selectQuery(string $sql): array
    {
        // mysql specific code

        return $result; 
    }
}

This design conforms to the LSP because the behaviour remains unchanged regardless of the implementation we choose to use.

And yes, you can violate LSP in this configuration doing one simple change like so :

<?php

interface Database 
{
    public function selectQuery(string $sql): array;
}

class SQLiteDatabase implements Database
{
    public function selectQuery(string $sql): array
    {
        // sqlite specific code

        return $result;
    }
}

class MySQLDatabase implements Database
{
    public function selectQuery(string $sql): array
    {
        // mysql specific code

        return ['result' => $result]; // This violates LSP !
    }
}

Now the subtypes cannot be used the same way since they don't produce the same result anymore.

Constructors in Go

There are some equivalents of constructors for when the zero values can't make sensible default values or for when some parameter is necessary for the struct initialization.

Supposing you have a struct like this :

type Thing struct {
    Name  string
    Num   int
}

then, if the zero values aren't fitting, you would typically construct an instance with a NewThing function returning a pointer :

func NewThing(someParameter string) *Thing {
    p := new(Thing)
    p.Name = someParameter
    p.Num = 33 // <- a very sensible default value
    return p
}

When your struct is simple enough, you can use this condensed construct :

func NewThing(someParameter string) *Thing {
    return &Thing{someParameter, 33}
}

If you don't want to return a pointer, then a practice is to call the function makeThing instead of NewThing :

func makeThing(name string) Thing {
    return Thing{name, 33}
}

Reference : Allocation with new in Effective Go.

What is the difference between Task.Run() and Task.Factory.StartNew()

In my application which calls two services, I compared both Task.Run and Task.Factory.StartNew. I found that in my case both of them work fine. However, the second one is faster.

How to get your Netbeans project into Eclipse

There's a very easy way if you were using a web application just follow this link.

just do in eclipse :

File > import > web > war file

Then select the war file of your app :)) very easy !!

Excel "External table is not in the expected format."

I was getting errors with third party and Oledb reading of a XLSX workbook. The issue appears to be a hidden worksheet that causes a error. Unhiding the worksheet enabled the workbook to import.

How to remove leading and trailing white spaces from a given html string?

var trim = your_string.replace(/^\s+|\s+$/g, '');

How to split elements of a list?

Try iterating through each element of the list, then splitting it at the tab character and adding it to a new list.

for i in list:
    newList.append(i.split('\t')[0])

Deny all, allow only one IP through htaccess

If you want to use mod_rewrite for access control you can use condition like user agent, http referrer, remote addr etc.

Example

RewriteCond %{REMOTE_ADDR} !=*.*.*.* #you ip address
RewriteRule ^$ - [F]

Refrences:

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

First convert LONG type column to CLOB type then use LIKE condition, for example:

CREATE TABLE tbl_clob AS
   SELECT to_lob(long_col) lob_col FROM tbl_long;

SELECT * FROM tbl_clob WHERE lob_col LIKE '%form%';

PostgreSQL naming conventions

Regarding tables names, case, etc, the prevalent convention is:

  • SQL keywords: UPPER CASE
  • names (identifiers): lower_case_with_underscores

For example:

UPDATE my_table SET name = 5;

This is not written in stone, but the bit about identifiers in lower case is highly recommended, IMO. Postgresql treats identifiers case insensitively when not quoted (it actually folds them to lowercase internally), and case sensitively when quoted; many people are not aware of this idiosyncrasy. Using always lowercase you are safe. Anyway, it's acceptable to use camelCase or PascalCase (or UPPER_CASE), as long as you are consistent: either quote identifiers always or never (and this includes the schema creation!).

I am not aware of many more conventions or style guides. Surrogate keys are normally made from a sequence (usually with the serial macro), it would be convenient to stick to that naming for those sequences if you create them by hand (tablename_colname_seq).

See also some discussion here, here and (for general SQL) here, all with several related links.

Note: Postgresql 10 introduced identity columns as an SQL-compliant replacement for serial.

What does InitializeComponent() do, and how does it work in WPF?

The call to InitializeComponent() (which is usually called in the default constructor of at least Window and UserControl) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).

This method locates a URI to the XAML for the Window/UserControl that is loading, and passes it to the System.Windows.Application.LoadComponent() static method. LoadComponent() loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.

In more detail, LoadComponent creates an instance of the XamlParser, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode(). This gets passed to the BamlRecordWriter class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.

Note: Interestingly, the InitializeComponent is a method on the System.Windows.Markup.IComponentConnector interface, of which Window/UserControl implement in the partial generated class.

Hope this helps!

Docker and securing passwords

Docker now (version 1.13 or 17.06 and higher) has support for managing secret information. Here's an overview and more detailed documentation

Similar feature exists in kubernetes and DCOS

How to get TimeZone from android mobile?

I needed the offset that not only included day light savings time but as a numerial. Here is the code that I used in case someone is looking for an example.

I get a response of "3.5" (3:30') which is what I would expect in Tehran , Iran in winter and "4.5" (4:30') for summer .

I also needed it as a string so I could post it to a server so you may not need the last line.

for getting currect time zone :

TimeZone tz = TimeZone.getDefault();
Date now = new Date();
//Import part : x.0 for double number
double offsetFromUtc = tz.getOffset(now.getTime()) / 3600000.0;
String m2tTimeZoneIs = Double.parseDouble(offsetFromUtc);

How do function pointers in C work?

Function pointers in C

Let's start with a basic function which we will be pointing to:

int addInt(int n, int m) {
    return n+m;
}

First thing, let's define a pointer to a function which receives 2 ints and returns an int:

int (*functionPtr)(int,int);

Now we can safely point to our function:

functionPtr = &addInt;

Now that we have a pointer to the function, let's use it:

int sum = (*functionPtr)(2, 3); // sum == 5

Passing the pointer to another function is basically the same:

int add2to3(int (*functionPtr)(int, int)) {
    return (*functionPtr)(2, 3);
}

We can use function pointers in return values as well (try to keep up, it gets messy):

// this is a function called functionFactory which receives parameter n
// and returns a pointer to another function which receives two ints
// and it returns another int
int (*functionFactory(int n))(int, int) {
    printf("Got parameter %d", n);
    int (*functionPtr)(int,int) = &addInt;
    return functionPtr;
}

But it's much nicer to use a typedef:

typedef int (*myFuncDef)(int, int);
// note that the typedef name is indeed myFuncDef

myFuncDef functionFactory(int n) {
    printf("Got parameter %d", n);
    myFuncDef functionPtr = &addInt;
    return functionPtr;
}

How to get a property value based on the name

In addition other guys answer, its Easy to get property value of any object by use Extension method like:

public static class Helper
    {
        public static object GetPropertyValue(this object T, string PropName)
        {
            return T.GetType().GetProperty(PropName) == null ? null : T.GetType().GetProperty(PropName).GetValue(T, null);
        }

    }

Usage is:

Car foo = new Car();
var balbal = foo.GetPropertyValue("Make");

Where does Git store files?

I'm on Windows and found my location by right clicking the Git Bash program in my Start menu and selecting Properties. The Shortcut tab shows the "Start in:" value. For me, it was %HOMEDRIVE%%HOMEPATH%, so I opened a CMD prompt and typed echo %HOMEDRIVE%%HOMEPATH% to see the actual location.

Read a file in Node.js

Use path.join(__dirname, '/start.html');

var fs = require('fs'),
    path = require('path'),    
    filePath = path.join(__dirname, 'start.html');

fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
    if (!err) {
        console.log('received data: ' + data);
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write(data);
        response.end();
    } else {
        console.log(err);
    }
});

How do I return a proper success/error message for JQuery .ajax() using PHP?

You need to provide the right content type if you're using JSON dataType. Before echo-ing the json, put the correct header.

<?php    
    header('Content-type: application/json');
    echo json_encode($response_array);
?>

Additional fix, you should check whether the query succeed or not.

if(mysql_query($query)){
    $response_array['status'] = 'success';  
}else {
    $response_array['status'] = 'error';  
}

On the client side:

success: function(data) {
    if(data.status == 'success'){
        alert("Thank you for subscribing!");
    }else if(data.status == 'error'){
        alert("Error on query!");
    }
},

Hope it helps.

Get filename from input [type='file'] using jQuery

You have to do this on the change event of the input type file this way:

$('#select_file').click(function() {
    $('#image_file').show();
    $('.btn').prop('disabled', false);
    $('#image_file').change(function() {
        var filename = $('#image_file').val();
        $('#select_file').html(filename);
    });
});?

Laravel migration table field's type change

The standard solution didn't work for me, when changing the type from TEXT to LONGTEXT.

I had to it like this:

public function up()
{
    DB::statement('ALTER TABLE mytable MODIFY mycolumn  LONGTEXT;');
}

public function down()
{
    DB::statement('ALTER TABLE mytable MODIFY mycolumn TEXT;');
}

This could be a Doctrine issue. More information here.

Another way to do it is to use the string() method, and set the value to the text type max length:

    Schema::table('mytable', function ($table) {
        // Will set the type to LONGTEXT.
        $table->string('mycolumn', 4294967295)->change();
    });

While loop to test if a file exists in bash

Like @zane-hooper, I've had a similar problem on NFS. On parallel / distributed filesystems the lag between you creating a file on one machine and the other machine "seeing" it can be very large, so I could wait up to a full minute after the creation of the file before the while loop exits (and there also is an aftereffect of it "seeing" an already deleted file).

This creates the illusion that the script "doesn't work", while in fact it is the filesystem that is dropping the ball.

This took me a while to figure out, hope it saves somebody some time.

PS This also causes an annoying number of "Stale file handler" errors.

In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?

Often used with/as a part of OOAD and business modeling. The definition by Neil is correct, but it is basically identical to MVC, but just abstracted for the business. The "Good summary" is well done so I will not copy it here as it is not my work, more detailed but inline with Neil's bullet points.

Good summary - Conceito: Entity-Control-Boundary Pattern

OOAD

How to use @Nullable and @Nonnull annotations more effectively?

Compiling the original example in Eclipse at compliance 1.8 and with annotation based null analysis enabled, we get this warning:

    directPathToA(y);
                  ^
Null type safety (type annotations): The expression of type 'Integer' needs unchecked conversion to conform to '@NonNull Integer'

This warning is worded in analogy to those warnings you get when mixing generified code with legacy code using raw types ("unchecked conversion"). We have the exact same situation here: method indirectPathToA() has a "legacy" signature in that it doesn't specify any null contract. Tools can easily report this, so they will chase you down all alleys where null annotations need to be propagated but aren't yet.

And when using a clever @NonNullByDefault we don't even have to say this every time.

In other words: whether or not null annotations "propagate very far" may depend on the tool you use, and on how rigorously you attend to all the warnings issued by the tool. With TYPE_USE null annotations you finally have the option to let the tool warn you about every possible NPE in your program, because nullness has become an intrisic property of the type system.

html select scroll bar

Horizontal scrollbars in a HTML Select are not natively supported. However, here's a way to create the appearance of a horizontal scrollbar:

1. First create a css class

<style type="text/css">
 .scrollable{
   overflow: auto;
   width: 70px; /* adjust this width depending to amount of text to display */
   height: 80px; /* adjust height depending on number of options to display */
   border: 1px silver solid;
 }
 .scrollable select{
   border: none;
 }
</style>

2. Wrap the SELECT inside a DIV - also, explicitly set the size to the number of options.

<div class="scrollable">
<select size="6" multiple="multiple">
    <option value="1" selected>option 1 The Long Option</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
    <option value="4">option 4</option>
    <option value="5">option 5 Another Longer than the Long Option ;)</option>
    <option value="6">option 6</option>
</select>
</div>

How do I get the total number of unique pairs of a set in the database?

I was solving this algorithm and get stuck with the pairs part.

This explanation help me a lot https://betterexplained.com/articles/techniques-for-adding-the-numbers-1-to-100/

So to calculate the sum of series of numbers:

n(n+1)/2

But you need to calculate this

1 + 2 + ... + (n-1)

So in order to get this you can use

n(n+1)/2 - n

that is equal to

n(n-1)/2

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

How do you create different variable names while in a loop?

for x in range(9):
    exec("string" + str(x) + " = 'hello'")

This should work.

Extension gd is missing from your system - laravel composer Update

The solution is quite simple.

In your php.ini, just uncomment the line extension=php_gd2.dll (or .so extension for unix systems.)

Hope it helps.

Delete the 'first' record from a table in SQL Server, without a WHERE condition

SQL-92:

DELETE Field FROM Table WHERE Field IN (SELECT TOP 1 Field FROM Table ORDER BY Field DESC)

jQuery select element in parent window

I looked for a solution to this problem, and came across the present page. I implemented the above solution:

$("#testdiv",opener.document) //doesn't work

But it doesn't work. Maybe it did work in previous jQuery versions, but it doesn't seem to work now.

I found this working solution on another stackoverflow page: how to access parent window object using jquery?

From which I got this working solution:

window.opener.$("#testdiv") //This works.

How to get the selected value from RadioButtonList?

string radioListValue = RadioButtonList.Text;

How to correctly use "section" tag in HTML5?

The answer is in the current spec:

The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading.

Examples of sections would be chapters, the various tabbed pages in a tabbed dialog box, or the numbered sections of a thesis. A Web site's home page could be split into sections for an introduction, news items, and contact information.

Authors are encouraged to use the article element instead of the section element when it would make sense to syndicate the contents of the element.

The section element is not a generic container element. When an element is needed for styling purposes or as a convenience for scripting, authors are encouraged to use the div element instead. A general rule is that the section element is appropriate only if the element's contents would be listed explicitly in the document's outline.

Reference:

Also see:

It looks like there's been a lot of confusion about this element's purpose, but the one thing that's agreed upon is that it is not a generic wrapper, like <div> is. It should be used for semantic purposes, and not a CSS or JavaScript hook (although it certainly can be styled or "scripted").

A better example, from my understanding, might look something like this:

<div id="content">
  <article>
     <h2>How to use the section tag</h2>
     <section id="disclaimer">
         <h3>Disclaimer</h3>
         <p>Don't take my word for it...</p>
     </section>
     <section id="examples">
       <h3>Examples</h3>
       <p>But here's how I would do it...</p>
     </section>
     <section id="closing_notes">
       <h3>Closing Notes</h3>
       <p>Well that was fun. I wonder if the spec will change next week?</p>
     </section>
  </article>
</div>

Note that <div>, being completely non-semantic, can be used anywhere in the document that the HTML spec allows it, but is not necessary.

invalid operands of types int and double to binary 'operator%'

Because % is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

How do I measure execution time of a command on the Windows command line?

If you are using Windows 2003 (note that windows server 2008 and later are not supported) you can use The Windows Server 2003 Resource Kit, which contains timeit.exe that displays detailed execution stats. Here is an example, timing the command "timeit -?":

C:\>timeit timeit -?
Invalid switch -?
Usage: TIMEIT [-f filename] [-a] [-c] [-i] [-d] [-s] [-t] [-k keyname | -r keyname] [-m mask] [commandline...]
where:        -f specifies the name of the database file where TIMEIT
                 keeps a history of previous timings.  Default is .\timeit.dat
              -k specifies the keyname to use for this timing run
              -r specifies the keyname to remove from the database.  If
                 keyname is followed by a comma and a number then it will
                 remove the slowest (positive number) or fastest (negative)
                 times for that keyname.
              -a specifies that timeit should display average of all timings
                 for the specified key.
              -i specifies to ignore non-zero return codes from program
              -d specifies to show detail for average
              -s specifies to suppress system wide counters
              -t specifies to tabular output
              -c specifies to force a resort of the data base
              -m specifies the processor affinity mask

Version Number:   Windows NT 5.2 (Build 3790)
Exit Time:        7:38 am, Wednesday, April 15 2009
Elapsed Time:     0:00:00.000
Process Time:     0:00:00.015
System Calls:     731
Context Switches: 299
Page Faults:      515
Bytes Read:       0
Bytes Written:    0
Bytes Other:      298

You can get TimeIt in the Windows 2003 Resource Kit. It's not available for direct download from the Microsoft Download Center, but one can still get it from the arhive.org - Windows Server 2003 Resource Kit Tools.

Get the difference between dates in terms of weeks, months, quarters, and years

what about this:

# get difference between dates `"01.12.2013"` and `"31.12.2013"`

# weeks
difftime(strptime("26.03.2014", format = "%d.%m.%Y"),
strptime("14.01.2013", format = "%d.%m.%Y"),units="weeks")
Time difference of 62.28571 weeks

# months
(as.yearmon(strptime("26.03.2014", format = "%d.%m.%Y"))-
as.yearmon(strptime("14.01.2013", format = "%d.%m.%Y")))*12
[1] 14

# quarters
(as.yearqtr(strptime("26.03.2014", format = "%d.%m.%Y"))-
as.yearqtr(strptime("14.01.2013", format = "%d.%m.%Y")))*4
[1] 4

# years
year(strptime("26.03.2014", format = "%d.%m.%Y"))-
year(strptime("14.01.2013", format = "%d.%m.%Y"))
[1] 1

as.yearmon() and as.yearqtr() are in package zoo. year() is in package lubridate. What do you think?

Angular - Use pipes in services and components

As usual in Angular, you can rely on dependency injection:

import { DatePipe } from '@angular/common';

class MyService {

  constructor(private datePipe: DatePipe) {}

  transformDate(date) {
    return this.datePipe.transform(date, 'yyyy-MM-dd');
  }
}

Add DatePipe to your providers list in your module; if you forget to do this you'll get an error no provider for DatePipe:

providers: [DatePipe,...]

Update Angular 6: Angular 6 now offers pretty much every formatting functions used by the pipes publicly. For example, you can now use the formatDate function directly.

import { formatDate } from '@angular/common';

class MyService {

  constructor(@Inject(LOCALE_ID) private locale: string) {}

  transformDate(date) {
    return formatDate(date, 'yyyy-MM-dd', this.locale);
  }
}

Before Angular 5: Be warned though that the DatePipe was relying on the Intl API until version 5, which is not supported by all browsers (check the compatibility table).

If you're using older Angular versions, you should add the Intl polyfill to your project to avoid any problem. See this related question for a more detailed answer.

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

util.component.ts

@Component({
    selector: 'app-logout',
    template: `<button class="btn btn-primary"(click)="logout()">Logout</button>`
})
export class LogoutComponent{}

util.module.ts

@NgModule({
    imports: [...],
    exports: [
        LogoutComponent
    ],
    declarations: [LogoutComponent]
})
export class AccountModule{};

LogoutComponent Needs to be exported

dashboard.module.ts
import AccountModule in module where we want to use <app-logout> import { AccountModule } from 'util.module';

@NgModule({
  imports: [
    CommonModule, AccountModule
  ],
  declarations: [DashboardComponent]
})
export class DashboardModule { }

dashboard.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-dashboard',
  template: `<div><app-logout></app-logout></div>`
})
export class DashboardComponent implements OnInit {
  constructor() {}
  ngOnInit() {}
}

I am not required to import and use CUSTOM_ELEMENTS_SCHEMA.
however its not working when dashboard.module is lazy loaded.
When using CUSTOM_ELEMENTS_SCHEMA in case of lazy loading, error is suppressed but the component is not added to dom.

How do I install the ext-curl extension with PHP 7?

We can install any PHP7 Extensions which we are needed at the time of install Magento just use related command which you get error at the time of installin Magento

sudo apt-get install php7.0-curl
sudo apt-get install php7.0-dom
sudo apt-get install php7.0-mcrypt
sudo apt-get install php7.0-simplexml
sudo apt-get install php7.0-spl
sudo apt-get install php7.0-xsl
sudo apt-get install php7.0-intl
sudo apt-get install php7.0-mbstring
sudo apt-get install php7.0-ctype
sudo apt-get install php7.0-hash
sudo apt-get install php7.0-openssl
sudo apt-get install php7.0-zip
sudo apt-get install php7.0-xmlwriter
sudo apt-get install php7.0-gd
sudo apt-get install php7.0-iconv

Thanks! Hope this will help you

python dict to numpy structured array

Let me propose an improved method when the values of the dictionnary are lists with the same lenght :

import numpy

def dctToNdarray (dd, szFormat = 'f8'):
    '''
    Convert a 'rectangular' dictionnary to numpy NdArray
    entry 
        dd : dictionnary (same len of list 
    retrun
        data : numpy NdArray 
    '''
    names = dd.keys()
    firstKey = dd.keys()[0]
    formats = [szFormat]*len(names)
    dtype = dict(names = names, formats=formats)
    values = [tuple(dd[k][0] for k in dd.keys())]
    data = numpy.array(values, dtype=dtype)
    for i in range(1,len(dd[firstKey])) :
        values = [tuple(dd[k][i] for k in dd.keys())]
        data_tmp = numpy.array(values, dtype=dtype)
        data = numpy.concatenate((data,data_tmp))
    return data

dd = {'a':[1,2.05,25.48],'b':[2,1.07,9],'c':[3,3.01,6.14]}
data = dctToNdarray(dd)
print data.dtype.names
print data

Using a BOOL property

Apple simply recommends declaring an isX getter for stylistic purposes. It doesn't matter whether you customize the getter name or not, as long as you use the dot notation or message notation with the correct name. If you're going to use the dot notation it makes no difference, you still access it by the property name:

@property (nonatomic, assign) BOOL working;

[self setWorking:YES];         // Or self.working = YES;
BOOL working = [self working]; // Or = self.working;

Or

@property (nonatomic, assign, getter=isWorking) BOOL working;

[self setWorking:YES];           // Or self.working = YES;, same as above
BOOL working = [self isWorking]; // Or = self.working;, also same as above

SQL Server Insert Example

Here are 4 ways to insert data into a table.

  1. Simple insertion when the table column sequence is known.

    INSERT INTO Table1 VALUES (1,2,...)

  2. Simple insertion into specified columns of the table.

    INSERT INTO Table1(col2,col4) VALUES (1,2)

  3. Bulk insertion when...

    1. You wish to insert every column of Table2 into Table1
    2. You know the column sequence of Table2
    3. You are certain that the column sequence of Table2 won't change while this statement is being used (perhaps you the statement will only be used once).

    INSERT INTO Table1 {Column sequence} SELECT * FROM Table2

  4. Bulk insertion of selected data into specified columns of Table2.

.

INSERT INTO Table1 (Column1,Column2 ....)
    SELECT Column1,Column2...
       FROM Table2

Customize list item bullets using CSS

Depending on the level of IE support needed, you could also use the :before selector with the bullet style set as the content property.

li {  
  list-style-type: none;
  font-size: small;
}

li:before {
  content: '\2022';
  font-size: x-large;
}

You may have to look up the HTML ASCII for the bullet style you want and use a converter for CSS Hex value.

Failed to connect to mailserver at "localhost" port 25

Change SMTP=localhost to SMTP=smtp.gmail.com

How would I extract a single file (or changes to a file) from a git stash?

The simplest concept to understand, although maybe not the best, is you have three files changed and you want to stash one file.

If you do git stash to stash them all, git stash apply to bring them back again and then git checkout f.c on the file in question to effectively reset it.

When you want to unstash that file run do a git reset --hard and then run git stash apply again, taking advantage ofthe fact that git stash apply doesn't clear the diff from the stash stack.

Get client IP address via third party web service

A more reliable REST endpoint would be http://freegeoip.net/json/

Returns the ip address along with the geo-location too. Also has cross-domain requests enabled (Access-Control-Allow-Origin: *) so you don't have to code around JSONP.

PHP's array_map including keys

This is probably the shortest and easiest to reason about:

$states = array('az' => 'Arizona', 'al' => 'Alabama');

array_map(function ($short, $long) {
    return array(
        'short' => $short,
        'long'  => $long
    );
}, array_keys($states), $states);

// produces:
array(
     array('short' => 'az', 'long' => 'Arizona'), 
     array('short' => 'al', 'long' => 'Alabama')
)

Get a worksheet name using Excel VBA

Function MySheet()

  ' uncomment the below line to make it Volatile
  'Application.Volatile
   MySheet = Application.Caller.Worksheet.Name

End Function

This should be the function you are looking for

SQL is null and = null

I think that equality is something that can be absolutely determined. The trouble with null is that it's inherently unknown. Null combined with any other value is null - unknown. Asking SQL "Is my value equal to null?" would be unknown every single time, even if the input is null. I think the implementation of IS NULL makes it clear.

Can we have multiple <tbody> in same <table>?

According to this example it can be done: w3-struct-tables.

UITextView that expands to text using auto layout

Obj C:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (nonatomic) UITextView *textView;
@end



#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize textView;

- (void)viewDidLoad{
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor grayColor]];
    self.textView = [[UITextView alloc] initWithFrame:CGRectMake(30,10,250,20)];
    self.textView.delegate = self;
    [self.view addSubview:self.textView];
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}

- (void)textViewDidChange:(UITextView *)txtView{
    float height = txtView.contentSize.height;
    [UITextView beginAnimations:nil context:nil];
    [UITextView setAnimationDuration:0.5];

    CGRect frame = txtView.frame;
    frame.size.height = height + 10.0; //Give it some padding
    txtView.frame = frame;
    [UITextView commitAnimations];
}

@end

Compare two different files line by line in python

I have just been faced with the same challenge, but I thought "Why programming this in Python if you can solve it with a simple "grep"?, which led to the following Python code:

import subprocess
from subprocess import PIPE

try:
  output1, errors1 = subprocess.Popen(["c:\\cygwin\\bin\\grep", "-Fvf" ,"c:\\file1.txt", "c:\\file2.txt"], shell=True, stdout=PIPE, stderr=PIPE).communicate();
  output2, errors2 = subprocess.Popen(["c:\\cygwin\\bin\\grep", "-Fvf" ,"c:\\file2.txt", "c:\\file1.txt"], shell=True, stdout=PIPE, stderr=PIPE).communicate();
  if (len(output1) + len(output2) + len(errors1) + len(errors2) > 0):
    print ("Compare result : There are differences:");
    if (len(output1) + len(output2) > 0):
      print ("  Output differences : ");
      print (output1);
      print (output2);
    if (len(errors1) + len(errors2) > 0):
      print (" Errors : ");
      print (errors1);
      print (errors2);
  else:
    print ("Compare result : Both files are equal");
except Exception as ex:
  print("Compare result : Exception during comparison");
  print(ex);
  raise;

The trick behind this is the following: grep -Fvf file1.txt file2.txt verifies if all entries in file2.txt are present in file1.txt. By doing this in both directions we can see if the content of both files are "equal". I put "equal" between quotes because duplicate lines are disregarded in this way of working.

Obviously, this is just an example: you can replace grep by any commandline file comparison tool.

How do I resolve git saying "Commit your changes or stash them before you can merge"?

If you are using Git Extensions you should be able to find your local changes in the Working directory as shown below:

enter image description here

If you don't see any changes, it's probably because you are on a wrong sub-module. So check all the items with a submarine icon as shown below:

enter image description here

When you found some uncommitted change:

Select the line with Working directory, navigate to Diff tab, Right click on rows with a pencil (or + or -) icon, choose Reset to first commit or commit or stash or whatever you want to do with it.

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

Node.js client for a socket.io server

Client side code: I had a requirement where my nodejs webserver should work as both server as well as client, so i added below code when i need it as client, It should work fine, i am using it and working fine for me!!!

const socket = require('socket.io-client')('http://192.168.0.8:5000', {
            reconnection: true,
            reconnectionDelay: 10000
          });
    
        socket.on('connect', (data) => {
            console.log('Connected to Socket');
        });
        
        socket.on('event_name', (data) => {
            console.log("-----------------received event data from the socket io server");
        });
    
        //either 'io server disconnect' or 'io client disconnect'
        socket.on('disconnect', (reason) => {
            console.log("client disconnected");
            if (reason === 'io server disconnect') {
              // the disconnection was initiated by the server, you need to reconnect manually
              console.log("server disconnected the client, trying to reconnect");
              socket.connect();
            }else{
                console.log("trying to reconnect again with server");
            }
            // else the socket will automatically try to reconnect
          });
    
        socket.on('error', (error) => {
            console.log(error);
        });

What is this Javascript "require"?

Necromancing.
IMHO, the existing answers leave much to be desired.

It's very simple:
Require is simply a (non-standard) function defined at global scope.
(window in browser, global in NodeJS).

Now, as such, to answer the question "what is require", we "simply" need to know what this function does.
This is perhaps best explained with code.

Here's a simple implementation by Michele Nasti, the code you can find on his github page.

Basically, let's call our minimalisc require function myRequire:

function myRequire(name) 
{
    console.log(`Evaluating file ${name}`);
    if (!(name in myRequire.cache)) {
        console.log(`${name} is not in cache; reading from disk`);
        let code = fs.readFileSync(name, 'utf8');
        let module = { exports: {} };
        myRequire.cache[name] = module;
        let wrapper = Function("require, exports, module", code);
        wrapper(myRequire, module.exports, module);
    }
    console.log(`${name} is in cache. Returning it...`);
    return myRequire.cache[name].exports;
}
myRequire.cache = Object.create(null);
window.require = myRequire;
const stuff = window.require('./main.js');
console.log(stuff);

Now you notice, the object "fs" is used here.
For simplicity's sake, Michele just imported the NodeJS fs module:

const fs = require('fs');

Which wouldn't be necessary.
So in the browser, you could make a simple implementation of require with a SYNCHRONOUS XmlHttpRequest:

const fs = {
    file: `
    // module.exports = \"Hello World\";
        
    module.exports = function(){ return 5*3;};
    
    `
    , getFile(fileName: string, encoding: string): string
    {
        // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
        let client = new XMLHttpRequest();
        // client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");

        // open(method, url, async)
        client.open("GET", fileName, false);
        client.send();
        if (client.status === 200)
            return client.responseText;

        return null;
    }


    , readFileSync: function (fileName: string, encoding: string): string
    {
        // this.getFile(fileName, encoding);
        return this.file; // Example, getFile would fetch this file 
    }
};

Basically, what require thus does, is download a JavaScript-file, eval it in an anonymous namespace (aka Function), with the global parameters "require", "exports" and "module", and return the exports, meaning an object's public functions and properties.

Note that this evaluation is recursive: you require files, which themselfs can require files.

This way, all "global" variables used in your module are variables in the require-wrapper-function namespace, and don't pollute the global scope with unwanted variables.

Also, this way, you can reuse code without depending on namespaces, so you get "modularity" in JavaScript. "modularity" in quotes, because this is not exactly true, though, because you can still write window.bla, and hence still pollute the global scope... Also, this establishes a separation between private and public functions, the public functions being the exports.

Now instead of saying

module.exports = function(){ return 5*3;};

You can also say:

function privateSomething()
{
    return 42:
}


function privateSomething2()
{
    return 21:
}


module.exports = {
      getRandomNumber: privateSomething
     ,getHalfRandomNumber: privateSomething2
};

and return an object.

Also, because your modules get evaluated in a function with parameters "require", "exports" and "module", your modules can use the undeclared variables "require", "exports" and "module", which might be startling at first. The require parameter there is of course a ByVal pointer to the require function saved into a variable.
Cool, right ?
Seen this way, require looses its magic, and becomes simple.
Now, the real require-function will do a few more checks and quirks, of course, but this is the essence of what that boils down to.

Also, in 2020, you should use the ECMA implementations instead of require:

import defaultExport from "module-name";
import * as name from "module-name";
import { export1 } from "module-name";
import { export1 as alias1 } from "module-name";
import { export1 , export2 } from "module-name";
import { foo , bar } from "module-name/path/to/specific/un-exported/file";
import { export1 , export2 as alias2 , [...] } from "module-name";
import defaultExport, { export1 [ , [...] ] } from "module-name";
import defaultExport, * as name from "module-name";
import "module-name";

And if you need a dynamic non-static import (e.g. load a polyfill based on browser-type), there is the ECMA-import function/keyword:

var promise = import("module-name");

note that import is not synchronous like require.
Instead, import is a promise, so

var something = require("something");

becomes

var something = await import("something");

because import returns a promise (asynchronous).

So basically, unlike require, import replaces fs.readFileSync with fs.readFileAsync.

async readFileAsync(fileName, encoding) 
{
    const textDecoder = new TextDecoder(encoding);
    // textDecoder.ignoreBOM = true;
    const response = await fetch(fileName);
    console.log(response.ok);
    console.log(response.status);
    console.log(response.statusText);
    // let json = await response.json();
    // let txt = await response.text();
    // let blo:Blob = response.blob();
    // let ab:ArrayBuffer = await response.arrayBuffer();
    // let fd = await response.formData()
    // Read file almost by line
    // https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader/read#Example_2_-_handling_text_line_by_line
    let buffer = await response.arrayBuffer();
    let file = textDecoder.decode(buffer);
    return file;
} // End Function readFileAsync

This of course requires the import-function to be async as well.

"use strict";
async function myRequireAsync(name) {
    console.log(`Evaluating file ${name}`);
    if (!(name in myRequireAsync.cache)) {
        console.log(`${name} is not in cache; reading from disk`);
        let code = await fs.readFileAsync(name, 'utf8');
        let module = { exports: {} };
        myRequireAsync.cache[name] = module;
        let wrapper = Function("asyncRequire, exports, module", code);
        await wrapper(myRequireAsync, module.exports, module);
    }
    console.log(`${name} is in cache. Returning it...`);
    return myRequireAsync.cache[name].exports;
}
myRequireAsync.cache = Object.create(null);
window.asyncRequire = myRequireAsync;
async () => {
    const asyncStuff = await window.asyncRequire('./main.js');
    console.log(asyncStuff);
};

Even better, right ?
Well yea, except that there is no ECMA-way to dynamically import synchronously (without promise).

Now, to understand the repercussions, you absolutely might want to read up on promises/async-await here, if you don't know what that is.

But very simply put, if a function returns a promise, it can be "awaited":

function sleep (fn, par) 
{
  return new Promise((resolve) => {
    // wait 3s before calling fn(par)
    setTimeout(() => resolve(fn(par)), 3000)
  })
}


var fileList = await sleep(listFiles, nextPageToken)

Which is nice way to make asynchronous code look synchronous.
Note that if you want to use async await in a function, that function must be declared async.

async function doSomethingAsync()
{
    var fileList = await sleep(listFiles, nextPageToken)
}

And also please note that in JavaScript, there is no way to call an async function (blockingly) from a synchronous one (the ones you know). So if you want to use await (aka ECMA-import), all your code needs to be async, which most likely is a problem, if everything isn't already async...

An example of where this simplified implementation of require fails, is when you require a file that is not valid JavaScript, e.g. when you require css, html, txt, svg and images or other binary files.
And it's easy to see why:
If you e.g. put HTML into a JavaScript function body, you of course rightfully get

SyntaxError: Unexpected token '<'

because of Function("bla", "<doctype...")

Now, if you wanted to extend this to for example include non-modules, you could just check the downloaded file-contents with for code.indexOf("module.exports") == -1, and then e.g. eval("jquery content") instead of Func (which works fine as long as you're in the browser). Since downloads with Fetch/XmlHttpRequests are subject to the same-origin-policy, and integrity is ensured by SSL/TLS, the use of eval here is rather harmless, provided you checked the JS files before you added them to your site, but that much should be standard-operating-procedure.

Note that there are several implementations of require-like functionality:

Can Mockito capture arguments of a method called multiple times?

With Java 8's lambdas, a convenient way is to use

org.mockito.invocation.InvocationOnMock

when(client.deleteByQuery(anyString(), anyString())).then(invocationOnMock -> {
    assertEquals("myCollection", invocationOnMock.getArgument(0));
    assertThat(invocationOnMock.getArgument(1), Matchers.startsWith("id:"));
}

Is it possible to use Java 8 for Android development?

I wrote a similar answer to a similar question on Stack Overflow, but here is part of that answer.

Android Studio 2.1:

The new version of Android Studio (2.1) has support for Java 8 features. Here is an extract from the Android Developers blogspot post:

... Android Studio 2.1 release includes support for the new Jack compiler and support for Java 8.

...

To use Java 8 language features when developing with the N Developer Preview, you need to use the Jack compiler. The New Project Wizard [File? New? Project] generates the correct configurations for projects targeting the N.


Prior to Android Studio 2.1:

Android does not support Java 1.8 yet (it only supports up to 1.7), so you cannot use Java 8 features like lambdas.

This answer gives more detail on Android Studio's compatibility; it states:

If you want to use lambdas, one of the major features of Java 8 in Android, you can use gradle-retrolamba

If you want to know more about using gradle-retrolambda, this answer gives a lot of detail on doing that.

How to get request URI without context path?

If you use request.getPathInfo() inside a Filter, you always seem to get null (at least with jetty).

This terse invalid bug + response alludes to the issue I think:

https://issues.apache.org/bugzilla/show_bug.cgi?id=28323

I suspect it is related to the fact that filters run before the servlet gets the request. It may be a container bug, or expected behaviour that I haven't been able to identify.

The contextPath is available though, so fforws solution works even in filters. I don't like having to do it by hand, but the implementation is broken or

How to check if String is null

You can check with null or Number.

First, add a reference to Microsoft.VisualBasic in your application.

Then, use the following code:

bool b = Microsoft.VisualBasic.Information.IsNumeric("null");
bool c = Microsoft.VisualBasic.Information.IsNumeric("abc");

In the above, b and c should both be false.

Deploying just HTML, CSS webpage to Tomcat

There is no real need to create a war to run it from Tomcat. You can follow these steps

  1. Create a folder in webapps folder e.g. MyApp

  2. Put your html and css in that folder and name the html file, which you want to be the starting page for your application, index.html

  3. Start tomcat and point your browser to url "http://localhost:8080/MyApp". Your index.html page will pop up in the browser

Grouped bar plot in ggplot

First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

Then you need to create a data frame out of it, melt it and plot it:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

Is this what you're after?

enter image description here

To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

> head(df)
  ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

LINQ to SQL - Left Outer Join with multiple join conditions

Another valid option is to spread the joins across multiple LINQ clauses, as follows:

public static IEnumerable<Announcementboard> GetSiteContent(string pageName, DateTime date)
{
    IEnumerable<Announcementboard> content = null;
    IEnumerable<Announcementboard> addMoreContent = null;
        try
        {
            content = from c in DB.Announcementboards
              // Can be displayed beginning on this date
              where c.Displayondate > date.AddDays(-1)
              // Doesn't Expire or Expires at future date
              && (c.Displaythrudate == null || c.Displaythrudate > date)
              // Content is NOT draft, and IS published
              && c.Isdraft == "N" && c.Publishedon != null
              orderby c.Sortorder ascending, c.Heading ascending
              select c;

            // Get the content specific to page names
            if (!string.IsNullOrEmpty(pageName))
            {
              addMoreContent = from c in content
                  join p in DB.Announceonpages on c.Announcementid equals p.Announcementid
                  join s in DB.Apppagenames on p.Apppagenameid equals s.Apppagenameid
                  where s.Apppageref.ToLower() == pageName.ToLower()
                  select c;
            }

            // Add the specified content using UNION
            content = content.Union(addMoreContent);

            // Exclude the duplicates using DISTINCT
            content = content.Distinct();

            return content;
        }
    catch (MyLovelyException ex)
    {
        // Add your exception handling here
        throw ex;
    }
}

How to get everything after last slash in a URL?

You don't need fancy things, just see the string methods in the standard library and you can easily split your url between 'filename' part and the rest:

url.rsplit('/', 1)

So you can get the part you're interested in simply with:

url.rsplit('/', 1)[-1]

Spring Boot Remove Whitelabel Error Page

I had a similar issue WhiteLabel Error message on my Angular SPA whenever I did a refresh.

The fix was to create a controller that implements ErrorController but instead of returning a String, I had to return a ModelAndView object that forwards to /

@CrossOrigin
@RestController
public class IndexController implements ErrorController {
    
    private static final String PATH = "/error";
    
    @RequestMapping(value = PATH)
    public ModelAndView saveLeadQuery() {           
        return new ModelAndView("forward:/");
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }
}

How to force reloading php.ini file?

To force a reload of the php.ini you should restart apache.

Try sudo service apache2 restart from the command line. Or sudo /etc/init.d/apache2 restart

How to use <md-icon> in Angular Material?

By Using like
use css and font same location

@font-face {
    font-family: 'Material-Design-Icons';
    src: url('Material-Design-Icons.eot');
    src: url('Material-Design-Icons.eot?#iefix') format('embedded-opentype'),
         url('Material-Design-Icons.woff2') format('woff2'),
         url('Material-Design-Icons.woff') format('woff'),
         url('Material-Design-Icons.ttf') format('truetype'),
         url('Material-Design-Icons.svg#ge_dinar_oneregular') format('svg');
    font-weight: normal;
    font-style: normal;
}

java.lang.IllegalArgumentException: No converter found for return value of type

Add below dependency in pom.xml:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.10.1</version>
    </dependency>

Was facing the same issue as the return type cannot be bind with the MediaType of Class Foo. After adding the dependency it worked.

Convert Rtf to HTML

You can try to upload it to google docs, and download it as HTML.

Convert RGB to Black & White in OpenCV

Simple binary threshold method is sufficient.

include

#include <string>
#include "opencv/highgui.h"
#include "opencv2/imgproc/imgproc.hpp"

using namespace std;
using namespace cv;

int main()
{
    Mat img = imread("./img.jpg",0);//loading gray scale image
    threshold(img, img, 128, 255, CV_THRESH_BINARY);//threshold binary, you can change threshold 128 to your convenient threshold
    imwrite("./black-white.jpg",img);
    return 0;
}

You can use GaussianBlur to get a smooth black and white image.

How can I start PostgreSQL on Windows?

If you have installed postgres via the Windows installer you can start it in Services like so:

enter image description here

Leaflet changing Marker color

Here is the SVG of the icon.

<svg width="28" height="41" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
 <defs>
  <linearGradient id="b">
   <stop stop-color="#2e6c97" offset="0"/>
   <stop stop-color="#3883b7" offset="1"/>
  </linearGradient>
  <linearGradient id="a">
   <stop stop-color="#126fc6" offset="0"/>
   <stop stop-color="#4c9cd1" offset="1"/>
  </linearGradient>
  <linearGradient y2="-0.004651" x2="0.498125" y1="0.971494" x1="0.498125" id="c" xlink:href="#a"/>
  <linearGradient y2="-0.004651" x2="0.415917" y1="0.490437" x1="0.415917" id="d" xlink:href="#b"/>
 </defs>
 <g>
  <title>Layer 1</title>
  <rect id="svg_1" fill="#fff" width="12.625" height="14.5" x="411.279" y="508.575"/>
  <path stroke="url(#d)" id="svg_2" stroke-linecap="round" stroke-width="1.1" fill="url(#c)" d="m14.095833,1.55c-6.846875,0 -12.545833,5.691 -12.545833,11.866c0,2.778 1.629167,6.308 2.80625,8.746l9.69375,17.872l9.647916,-17.872c1.177083,-2.438 2.852083,-5.791 2.852083,-8.746c0,-6.175 -5.607291,-11.866 -12.454166,-11.866zm0,7.155c2.691667,0.017 4.873958,2.122 4.873958,4.71s-2.182292,4.663 -4.873958,4.679c-2.691667,-0.017 -4.873958,-2.09 -4.873958,-4.679c0,-2.588 2.182292,-4.693 4.873958,-4.71z"/>
  <path id="svg_3" fill="none" stroke-opacity="0.122" stroke-linecap="round" stroke-width="1.1" stroke="#fff" d="m347.488007,453.719c-5.944,0 -10.938,5.219 -10.938,10.75c0,2.359 1.443,5.832 2.563,8.25l0.031,0.031l8.313,15.969l8.25,-15.969l0.031,-0.031c1.135,-2.448 2.625,-5.706 2.625,-8.25c0,-5.538 -4.931,-10.75 -10.875,-10.75zm0,4.969c3.168,0.021 5.781,2.601 5.781,5.781c0,3.18 -2.613,5.761 -5.781,5.781c-3.168,-0.02 -5.75,-2.61 -5.75,-5.781c0,-3.172 2.582,-5.761 5.75,-5.781z"/>
 </g>
</svg>

make bootstrap twitter dialog modal draggable

In my own case, i had to set backdrop and set the top and left properties before i could apply draggable function on the modal dialog. Maybe it might help someone ;)

if (!($('.modal.in').length)) {       
$('.modal-dialog').css({
     top: 0,
     left: 0
   });
}
$('#myModal').modal({
  backdrop: false,
   show: true
});

$('.modal-dialog').draggable({
  handle: ".modal-header"
});

How to convert string to string[]?

string[] is an array (vector) of strings string is just a string (a list/array of characters)

Depending on how you want to convert this, the canonical answer could be:

string[] -> string

return String.Join(" ", myStringArray);

string -> string[]

return new []{ myString };

Dropdown using javascript onchange

It does not work because your script in JSFiddle is running inside it's own scope (see the "OnLoad" drop down on the left?).

One way around this is to bind your event handler in javascript (where it should be):

document.getElementById('optionID').onchange = function () {
    document.getElementById("message").innerHTML = "Having a Baby!!";
};

Another way is to modify your code for the fiddle environment and explicitly declare your function as global so it can be found by your inline event handler:

window.changeMessage() {
    document.getElementById("message").innerHTML = "Having a Baby!!";
};

?

Bootstrap: Use .pull-right without having to hardcode a negative margin-top

just put #login-box before <h2>Welcome</h2> will be ok.

<div class='container'>
    <div class='hero-unit'>
        <div id='login-box' class='pull-right control-group'>
            <div class='clearfix'>
                <input type='text' placeholder='Username' />
            </div>
            <div class='clearfix'>
                <input type='password' placeholder='Password' />
            </div>
            <button type='button' class='btn btn-primary'>Log in</button>
        </div>
        <h2>Welcome</h2>

        <p>Please log in</p>

    </div>
</div>

here is jsfiddle http://jsfiddle.net/SyjjW/4/

How to cd into a directory with space in the name?

ok i spent some frustrating time with this problem too. My little guide.

Open desktop for example. If you didnt switch your disc in cmd, type:

cd desktop

Now if you want to display subfolders:

cd, make 1 spacebar, and press tab 2 times

Now if you want to enter directory/file with SPACE IN NAME. Lets open some file name f.g., to open it we need to type:

cd file\ name

p.s. notice this space after slash :)

iOS 6 apps - how to deal with iPhone 5 screen size?

@Pascal's comment on the OP's question is right. By simply adding the image, it removes the black borders and the app will use the full height.

You will need to make adjustments to any CGRects by determining that the device is using the bigger display. I.e. If you need something aligned to the bottom of the screen.

I am sure there is a built in method, but I haven't seen anything and a lot is still under NDA so the method we use in our apps is quite simply a global function. Add the following to your .pch file and then its a simple if( is4InchRetina() ) { ... } call to make adjustments to your CGRects etc.

static BOOL is4InchRetina()
{
    if (![UIApplication sharedApplication].statusBarHidden && (int)[[UIScreen mainScreen] applicationFrame].size.height == 548 || [UIApplication sharedApplication].statusBarHidden && (int)[[UIScreen mainScreen] applicationFrame].size.height == 568)
        return YES;

    return NO;
}

HTML <select> selected option background-color CSS style

You cannot rely on CSS for form elements. The results vary wildly across all the browsers. I don't think Safari lets you customize any form elements at all.

Your best bet is to use a plugin like jqTransform (uses jQuery).

EDIT: that page doesn't seem to be working at the moment. There is also Custom Form Elements which supports MooTools and may support jQuery in the future.

Interesting 'takes exactly 1 argument (2 given)' Python error

The call

e.extractAll("th")

for a regular method extractAll() is indeed equivalent to

Extractor.extractAll(e, "th")

These two calls are treated the same in all regards, including the error messages you get.

If you don't need to pass the instance to a method, you can use a staticmethod:

@staticmethod
def extractAll(tag):
    ...

which can be called as e.extractAll("th"). But I wonder why this is a method on a class at all if you don't need to access any instance.

Nullable property to entity field, Entity Framework through Code First

Just omit the [Required] attribute from the string somefield property. This will make it create a NULLable column in the db.

To make int types allow NULLs in the database, they must be declared as nullable ints in the model:

// an int can never be null, so it will be created as NOT NULL in db
public int someintfield { get; set; }

// to have a nullable int, you need to declare it as an int?
// or as a System.Nullable<int>
public int? somenullableintfield { get; set; }
public System.Nullable<int> someothernullableintfield { get; set; }

Rails Object to hash

If you are looking for only attributes, then you can get them by:

@post.attributes

Note that this calls ActiveModel::AttributeSet.to_hash every time you invoke it, so if you need to access the hash multiple times you should cache it in a local variable:

attribs = @post.attributes

Java equivalent to C# extension methods

Java does not have such feature. Instead you can either create regular subclass of your list implementation or create anonymous inner class:

List<String> list = new ArrayList<String>() {
   public String getData() {
       return ""; // add your implementation here. 
   }
};

The problem is to call this method. You can do it "in place":

new ArrayList<String>() {
   public String getData() {
       return ""; // add your implementation here. 
   }
}.getData();

Convert a PHP object to an associative array

Also you can use The Symfony Serializer Component

use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

$serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]);
$array = json_decode($serializer->serialize($object, 'json'), true);

Clang vs GCC - which produces faster binaries?

The fact that Clang compiles code faster may not be as important as the speed of the resulting binary. However, here is a series of benchmarks.

Shell Script: Execute a python program from within a shell script

Save the following program as print.py:

#!/usr/bin/python3
print('Hello World')

Then in the terminal type:

chmod +x print.py
./print.py

How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

Try surrounding the path in quotes. i.e "C:\Program Files\Appname\config.file"

String delimiter in string.split method

There is something wrong in your setDelimiter() function. You don't want to double quote the delimiters, do you?

public void setDelimiter(String delimiter) {
    char[] c = delimiter.toCharArray();
    this.delimiter = "\\" + c[0] + "\\" + c[1];
    System.out.println("Delimiter string is: " + this.delimiter);
}

However, as other users have said, it's better to use the Pattern.quote() method to escape your delimiter if your requirements permit.

Prevent any form of page refresh using jQuery/Javascript

Issue #2 now can be solved using BroadcastAPI.

At the moment it's only available in Chrome, Firefox, and Opera.

var bc = new BroadcastChannel('test_channel');

bc.onmessage = function (ev) { 
    if(ev.data && ev.data.url===window.location.href){
       alert('You cannot open the same page in 2 tabs');
    }
}

bc.postMessage(window.location.href);

Using ng-click vs bind within link function of Angular Directive

In this case, no need for a directive. This does the job :

<button ng-click="count = count + 1" ng-init="count=0">
  Increment
</button>
<span>
  count: {{count}}
</span>

Source: https://docs.angularjs.org/api/ng/directive/ngClick

decimal vs double! - Which one should I use and when?

System.Single / float - 7 digits
System.Double / double - 15-16 digits
System.Decimal / decimal - 28-29 significant digits

The way I've been stung by using the wrong type (a good few years ago) is with large amounts:

  • £520,532.52 - 8 digits
  • £1,323,523.12 - 9 digits

You run out at 1 million for a float.

A 15 digit monetary value:

  • £1,234,567,890,123.45

9 trillion with a double. But with division and comparisons it's more complicated (I'm definitely no expert in floating point and irrational numbers - see Marc's point). Mixing decimals and doubles causes issues:

A mathematical or comparison operation that uses a floating-point number might not yield the same result if a decimal number is used because the floating-point number might not exactly approximate the decimal number.

When should I use double instead of decimal? has some similar and more in depth answers.

Using double instead of decimal for monetary applications is a micro-optimization - that's the simplest way I look at it.