Programs & Examples On #Drupal domain access

The Domain Access module is a module for running a group of affiliated sites from one Drupal installation and a single shared database.

PHP function to generate v4 UUID

From tom, on http://www.php.net/manual/en/function.uniqid.php

$r = unpack('v*', fread(fopen('/dev/random', 'r'),16));
$uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
    $r[1], $r[2], $r[3], $r[4] & 0x0fff | 0x4000,
    $r[5] & 0x3fff | 0x8000, $r[6], $r[7], $r[8])

reCAPTCHA ERROR: Invalid domain for site key

I tried for almost 4 Hours with this and finally figuring it out with guidance from here, I thought I would share my solution with you.

Ok so my domain is an addon domain. I also got "ERROR for site owner: Invalid domain for site key" I had checked that everything was correct almost a thousand times and it looked right to me, until I thought of it in terms of a desktop shortcut.

Solution:

So for an addon domain make sure that the parent url is also in the list of domains i.e: [ADDON DOMAIN].[PARENT DOMAIN].com . The addon location will be the folder that you set on your host so when using addon domains ensure to name the root with something logical.

Hope this helps someone else and thanks for the suggestions people.

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

You have to create either another page or generic handler with the code to generate your pdf. Then that event gets triggered and the person is redirected to that page.

Calling a javascript function recursively

Here's one very simple example:

var counter = 0;

function getSlug(tokens) {
    var slug = '';

    if (!!tokens.length) {
        slug = tokens.shift();
        slug = slug.toLowerCase();
        slug += getSlug(tokens);

        counter += 1;
        console.log('THE SLUG ELEMENT IS: %s, counter is: %s', slug, counter);
    }

    return slug;
}

var mySlug = getSlug(['This', 'Is', 'My', 'Slug']);
console.log('THE SLUG IS: %s', mySlug);

Notice that the counter counts "backwards" in regards to what slug's value is. This is because of the position at which we are logging these values, as the function recurs before logging -- so, we essentially keep nesting deeper and deeper into the call-stack before logging takes place.

Once the recursion meets the final call-stack item, it trampolines "out" of the function calls, whereas, the first increment of counter occurs inside of the last nested call.

I know this is not a "fix" on the Questioner's code, but given the title I thought I'd generically exemplify Recursion for a better understanding of recursion, outright.

Reporting Services Remove Time from DateTime in Expression

In the format property of any textbox field you can use format strings:

e.g. D/M/Y, D, etc.

including parameters in OPENQUERY

You can execute a string with OPENQUERY once you build it up. If you go this route think about security and take care not to concatenate user-entered text into your SQL!

DECLARE @Sql VARCHAR(8000)
SET @Sql = 'SELECT * FROM Tbl WHERE Field1 < ''someVal'' AND Field2 IN '+ @valueList 
SET @Sql = 'SELECT * FROM OPENQUERY(SVRNAME, ''' + REPLACE(@Sql, '''', '''''') + ''')'
EXEC(@Sql)

Is there a naming convention for MySQL?

I would say that first and foremost: be consistent.

I reckon you are almost there with the conventions that you have outlined in your question. A couple of comments though:

Points 1 and 2 are good I reckon.

Point 3 - sadly this is not always possible. Think about how you would cope with a single table foo_bar that has columns foo_id and another_foo_id both of which reference the foo table foo_id column. You might want to consider how to deal with this. This is a bit of a corner case though!

Point 4 - Similar to Point 3. You may want to introduce a number at the end of the foreign key name to cater for having more than one referencing column.

Point 5 - I would avoid this. It provides you with little and will become a headache when you want to add or remove columns from a table at a later date.

Some other points are:

Index Naming Conventions

You may wish to introduce a naming convention for indexes - this will be a great help for any database metadata work that you might want to carry out. For example you might just want to call an index foo_bar_idx1 or foo_idx1 - totally up to you but worth considering.

Singular vs Plural Column Names

It might be a good idea to address the thorny issue of plural vs single in your column names as well as your table name(s). This subject often causes big debates in the DB community. I would stick with singular forms for both table names and columns. There. I've said it.

The main thing here is of course consistency!

Formatting dates on X axis in ggplot2

Can you use date as a factor?

Yes, but you probably shouldn't.

...or should you use as.Date on a date column?

Yes.

Which leads us to this:

library(scales)
df$Month <- as.Date(df$Month)
ggplot(df, aes(x = Month, y = AvgVisits)) + 
  geom_bar(stat = "identity") +
  theme_bw() +
  labs(x = "Month", y = "Average Visits per User") +
  scale_x_date(labels = date_format("%m-%Y"))

enter image description here

in which I've added stat = "identity" to your geom_bar call.

In addition, the message about the binwidth wasn't an error. An error will actually say "Error" in it, and similarly a warning will always say "Warning" in it. Otherwise it's just a message.

Latex - Change margins of only a few pages

I was struggling a lot with different solutions including \vspace{-Xmm} on the top and bottom of the page and dealing with warnings and errors. Finally I found this answer:

You can change the margins of just one or more pages and then restore it to its default:

\usepackage{geometry}
...
... 
...
\newgeometry{top=5mm, bottom=10mm}     % use whatever margins you want for left, right, top and bottom.
...
... %<The contents of enlarged page(s)>
...    
\restoregeometry     %so it does not affect the rest of the pages.
...
... 
...

PS:

1- This can also fix the following warning:

LaTeX Warning: Float too large for page by ...pt on input line ...

2- For more detailed answer look at this.

3- I just found that this is more elaboration on Kevin Chen's answer.

Reading an Excel file in PHP

I'm using below excel file url: https://github.com/inventorbala/Sample-Excel-files/blob/master/sample-excel-files.xlsx

Output:

Array
    (
        [0] => Array
            (
                [store_id] => 3716
                [employee_uid] => 664368
                [opus_id] => zh901j
                [item_description] => PRE ATT $75 PNLS 90EXP
                [opus_transaction_date] => 2019-10-18
                [opus_transaction_num] => X2MBV1DJKSLQW
                [opus_invoice_num] => O3716IN3409
                [customer_name] => BILL PHILLIPS
                [mobile_num] => 4052380136
                [opus_amount] => 75
                [rq4_amount] => 0
                [difference] => -75
                [ocomment] => Re-Upload: We need RQ4 transaction for October.  If you're unable to provide the October invoice, it will be counted as EPin shortage.
                [mark_delete] => 0
                [upload_date] => 2019-10-20
            )

        [1] => Array
            (
                [store_id] => 2710
                [employee_uid] => 75899
                [opus_id] => dc288t
                [item_description] => PRE ATT $50 PNLS 90EXP
                [opus_transaction_date] => 2019-10-18
                [opus_transaction_num] => XJ90419JKT9R9
                [opus_invoice_num] => M2710IN868
                [customer_name] => CALEB MENDEZ
                [mobile_num] => 6517672079
                [opus_amount] => 50
                [rq4_amount] => 0
                [difference] => -50
                [ocomment] => No Response.  Re-Upload
                [mark_delete] => 0
                [upload_date] => 2019-10-20
            )

        [2] => Array
            (
                [store_id] => 0136
                [employee_uid] => 70167
                [opus_id] => fv766x
                [item_description] => PRE ATT $50 PNLS 90EXP
                [opus_transaction_date] => 2019-10-18
                [opus_transaction_num] => XQ57316JKST1V
                [opus_invoice_num] => GONZABP25622
                [customer_name] => FAUSTINA CASTILLO
                [mobile_num] => 8302638628
                [opus_amount] => 100
                [rq4_amount] => 50
                [difference] => -50
                [ocomment] => Re-Upload: We have been charged in opus for $100. Provide RQ4 invoice number for remaining amount
                [mark_delete] => 0
                [upload_date] => 2019-10-20
            )

        [3] => Array
            (
                [store_id] => 3264
                [employee_uid] => 23723
                [opus_id] => aa297h
                [item_description] => PRE ATT $25 PNLS 90EXP
                [opus_transaction_date] => 2019-10-19
                [opus_transaction_num] => XR1181HJKW9MP
                [opus_invoice_num] => C3264IN1588
                [customer_name] => SOPHAT VANN
                [mobile_num] => 9494668372
                [opus_amount] => 70
                [rq4_amount] => 25
                [difference] => -45
                [ocomment] => No Response.  Re-Upload
                [mark_delete] => 0
                [upload_date] => 2019-10-20
            )

        [4] => Array
            (
                [store_id] => 4166
                [employee_uid] => 568494
                [opus_id] => ab7598
                [item_description] => PRE ATT $40 RTR
                [opus_transaction_date] => 2019-10-20
                [opus_transaction_num] => X8F58P3JL2RFU
                [opus_invoice_num] => I4166IN2481
                [customer_name] => KELLY MC GUIRE
                [mobile_num] => 6189468180
                [opus_amount] => 40
                [rq4_amount] => 0
                [difference] => -40
                [ocomment] => Re-Upload: The invoice number that you provided (I4166IN2481) belongs to September transaction.  We need RQ4 transaction for October.  If you're unable to provide the October invoice, it will be counted as EPin shortage.
                [mark_delete] => 0
                [upload_date] => 2019-10-21
            )

        [5] => Array
            (
                [store_id] => 4508
                [employee_uid] => 552502
                [opus_id] => ec850x
                [item_description] => $30 RTR
                [opus_transaction_date] => 2019-10-20
                [opus_transaction_num] => XPL7M1BJL1W5D
                [opus_invoice_num] => M4508IN6024
                [customer_name] => PREPAID CUSTOMER
                [mobile_num] => 6019109730
                [opus_amount] => 30
                [rq4_amount] => 0
                [difference] => -30
                [ocomment] => Re-Upload: The invoice number you provided (M4508IN7217) belongs to a different phone number.  We need RQ4 transaction for the phone number in question.  If you're unable to provide the RQ4 invoice for this transaction, it will be counted as EPin shortage.
                [mark_delete] => 0
                [upload_date] => 2019-10-21
            )

        [6] => Array
            (
                [store_id] => 3904
                [employee_uid] => 35818
                [opus_id] => tj539j
                [item_description] => PRE $45 PAYG PINLESS REFILL
                [opus_transaction_date] => 2019-10-20
                [opus_transaction_num] => XM1PZQSJL215F
                [opus_invoice_num] => N3904IN1410
                [customer_name] => DORTHY JONES
                [mobile_num] => 3365982631
                [opus_amount] => 90
                [rq4_amount] => 45
                [difference] => -45
                [ocomment] => Re-Upload: Please email the details to Treasury and confirm
                [mark_delete] => 0
                [upload_date] => 2019-10-21
            )

        [7] => Array
            (
                [store_id] => 1820
                [employee_uid] => 59883
                [opus_id] => cb9406
                [item_description] => PRE ATT $25 PNLS 90EXP
                [opus_transaction_date] => 2019-10-20
                [opus_transaction_num] => XTBJO14JL25OE
                [opus_invoice_num] => SEVIEIN19013
                [customer_name] => RON NELSON
                [mobile_num] => 8653821076
                [opus_amount] => 25
                [rq4_amount] => 5
                [difference] => -20
                [ocomment] => Re-Upload: We have been charged in opus for $25. Provide RQ4 invoice number for remaining amount
                [mark_delete] => 0
                [upload_date] => 2019-10-21
            )

        [8] => Array
            (
                [store_id] => 0178
                [employee_uid] => 572547
                [opus_id] => ms5674
                [item_description] => PRE $45 PAYG PINLESS REFILL
                [opus_transaction_date] => 2019-10-21
                [opus_transaction_num] => XT29916JL4S69
                [opus_invoice_num] => T0178BP1590
                [customer_name] => GABRIEL LONGORIA JR
                [mobile_num] => 4322133450
                [opus_amount] => 45
                [rq4_amount] => 0
                [difference] => -45
                [ocomment] => Re-Upload: Please email the details to Treasury and confirm
                [mark_delete] => 0
                [upload_date] => 2019-10-22
            )

        [9] => Array
            (
                [store_id] => 2180
                [employee_uid] => 7842
                [opus_id] => lm854y
                [item_description] => $30 RTR
                [opus_transaction_date] => 2019-10-21
                [opus_transaction_num] => XC9U712JL4LA4
                [opus_invoice_num] => KETERIN1836
                [customer_name] => PETE JABLONSKI
                [mobile_num] => 9374092680
                [opus_amount] => 30
                [rq4_amount] => 40
                [difference] => 10
                [ocomment] => Re-Upload: Credit the remaining balance to customers account in OPUS and email confirmation to Treasury
                [mark_delete] => 0
                [upload_date] => 2019-10-22
            )


      .
      .
      .
 [63] => Array
            (
                [store_id] => 0175
                [employee_uid] => 33738
                [opus_id] => ph5953
                [item_description] => PRE ATT $40 RTR
                [opus_transaction_date] => 2019-10-21
                [opus_transaction_num] => XE5N31DJL51RA
                [opus_invoice_num] => T0175IN4563
                [customer_name] => WILLIE TAYLOR
                [mobile_num] => 6822701188
                [opus_amount] => 40
                [rq4_amount] => 50
                [difference] => 10
                [ocomment] => Re-Upload: Credit the remaining balance to customers account in OPUS and email confirmation to Treasury
                [mark_delete] => 0
                [upload_date] => 2019-10-22
            ) 

    )

Getting Class type from String

You can use the forName method of Class:

Class cls = Class.forName(clsName);
Object obj = cls.newInstance();

Python 3 print without parenthesis

Although you need a pair of parentheses to print in Python 3, you no longer need a space after print, because it's a function. So that's only a single extra character.

If you still find typing a single pair of parentheses to be "unnecessarily time-consuming," you can do p = print and save a few characters that way. Because you can bind new references to functions but not to keywords, you can only do this print shortcut in Python 3.

Python 2:

>>> p = print
  File "<stdin>", line 1
    p = print
            ^
SyntaxError: invalid syntax

Python 3:

>>> p = print
>>> p('hello')
hello

It'll make your code less readable, but you'll save those few characters every time you print something.

Fastest way to write huge data in text file Java

try memory mapped files (takes 300 m/s to write 174MB in my m/c, core 2 duo, 2.5GB RAM) :

byte[] buffer = "Help I am trapped in a fortune cookie factory\n".getBytes();
int number_of_lines = 400000;

FileChannel rwChannel = new RandomAccessFile("textfile.txt", "rw").getChannel();
ByteBuffer wrBuf = rwChannel.map(FileChannel.MapMode.READ_WRITE, 0, buffer.length * number_of_lines);
for (int i = 0; i < number_of_lines; i++)
{
    wrBuf.put(buffer);
}
rwChannel.close();

What is useState() in React?

Thanks loelsonk, i did so

_x000D_
_x000D_
const [dataAction, setDataAction] = useState({name: '', description: ''});_x000D_
_x000D_
    const _handleChangeName = (data) => {_x000D_
        if(data.name)_x000D_
            setDataAction( prevState  => ({ ...prevState,   name : data.name }));_x000D_
        if(data.description)_x000D_
            setDataAction( prevState  => ({ ...prevState,   description : data.description }));_x000D_
    };_x000D_
    _x000D_
    ....return (_x000D_
    _x000D_
          <input onChange={(event) => _handleChangeName({name: event.target.value})}/>_x000D_
          <input onChange={(event) => _handleChangeName({description: event.target.value})}/>_x000D_
    )
_x000D_
_x000D_
_x000D_

How to uninstall Apache with command line

If Apache was installed using NSIS installer it should have left an uninstaller. You should search inside Apache installation directory for executable named unistaller.exe or something like that. NSIS uninstallers support /S flag by default for silent uninstall. So you can run something like "C:\Program Files\<Apache installation dir here>\uninstaller.exe" /S

From NSIS documentation:

3.2.1 Common Options

/NCRC disables the CRC check, unless CRCCheck force was used in the script. /S runs the installer or uninstaller silently. See section 4.12 for more information. /D sets the default installation directory ($INSTDIR), overriding InstallDir and InstallDirRegKey. It must be the last parameter used in the command line and must not contain any quotes, even if the path contains spaces. Only absolute paths are supported.

How to change users in TortoiseSVN

After struggling with this and trying all the answers on this page, I finally realized I had the incorrect credentials stored by windows for the server that hosts our subversion. I cleared this stored value from windows credentials and all is well.

https://web.archive.org/web/20160614002053/http://windows.microsoft.com/en-us/windows7/remove-stored-passwords-certificates-and-other-credentials

How to select a directory and store the location using tkinter in Python

This code may be helpful for you.

from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()

Remove leading comma from a string

You can use directly replace function on javascript with regex or define a help function as in php ltrim(left) and rtrim(right):

1) With replace:

var myArray = ",'first string','more','even more'".replace(/^\s+/, '').split(/'?,?'/);

2) Help functions:

if (!String.prototype.ltrim) String.prototype.ltrim = function() {
    return this.replace(/^\s+/, '');
};
if (!String.prototype.rtrim) String.prototype.rtrim = function() {
    return this.replace(/\s+$/, '');
};
var myArray = ",'first string','more','even more'".ltrim().split(/'?,?'/).filter(function(el) {return el.length != 0});;

You can do and other things to add parameter to the help function with what you want to replace the char, etc.

How to import existing Android project into Eclipse?

You can also use Make new > General > Project, then import the project to that project directory

How to pass values between Fragments

// In Fragment_1.java

Bundle bundle = new Bundle();
bundle.putString("key","abc"); // Put anything what you want

Fragment_2 fragment2 = new Fragment_2();
fragment2.setArguments(bundle);

getFragmentManager()
      .beginTransaction()
      .replace(R.id.content, fragment2)
      .commit();

// In Fragment_2.java

Bundle bundle = this.getArguments();

if(bundle != null){
     // handle your code here.
}

Hope this help you.

Pick a random value from an enum?

Simple Kotlin Solution

MyEnum.values().random()

random() is a default extension function included in base Kotlin on the Collection object. Kotlin Documentation Link

If you'd like to simplify it with an extension function, try this:

inline fun <reified T : Enum<T>> random(): T = enumValues<T>().random()

// Then call
random<MyEnum>()

To make it static on your enum class. Make sure to import my.package.random in your enum file

MyEnum.randomValue()

// Add this to your enum class
companion object {
    fun randomValue(): MyEnum {
        return random()
    }
}

If you need to do it from an instance of the enum, try this extension

inline fun <reified T : Enum<T>> T.random() = enumValues<T>().random()

// Then call
MyEnum.VALUE.random() // or myEnumVal.random() 

How to write inside a DIV box with javascript

I would suggest Jquery:

$("#log").html("Type what you want to be shown to the user");   

How do I use LINQ Contains(string[]) instead of Contains(string)

Try the following.

string input = "someString";
string[] toSearchFor = GetSearchStrings();
var containsAll = toSearchFor.All(x => input.Contains(x));

How can I rollback a git repository to a specific commit?

When doing branch updates from master, I notice that I sometimes over-click, and cause the branch to merge into the master, too. Found a way to undo that.

If your last commit was a merge, a little more love is needed:

git revert -m 1 HEAD

basic authorization command for curl

curl -D- -X GET -H "Authorization: Basic ZnJlZDpmcmVk" -H "Content-Type: application/json" http://localhost:7990/rest/api/1.0/projects

--note

base46 encode =ZnJlZDpmcmVk

How to output to the console in C++/Windows

Since you mentioned stdout.txt I google'd it to see what exactly would create a stdout.txt; normally, even with a Windows app, console output goes to the allocated console, or nowhere if one is not allocated.

So, assuming you are using SDL (which is the only thing that brought up stdout.txt), you should follow the advice here. Either freopen stdout and stderr with "CON", or do the other linker/compile workarounds there.

In case the link gets broken again, here is exactly what was referenced from libSDL:

How do I avoid creating stdout.txt and stderr.txt?

"I believe inside the Visual C++ project that comes with SDL there is a SDL_nostdio target > you can build which does what you want(TM)."

"If you define "NO_STDIO_REDIRECT" and recompile SDL, I think it will fix the problem." > > (Answer courtesy of Bill Kendrick)

Get row-index values of Pandas DataFrame as list?

If you're only getting these to manually pass into df.set_index(), that's unnecessary. Just directly do df.set_index['your_col_name', drop=False], already.

It's very rare in pandas that you need to get an index as a Python list (unless you're doing something pretty funky, or else passing them back to NumPy), so if you're doing this a lot, it's a code smell that you're doing something wrong.

Android: checkbox listener

If you are looking to do this in Kotlin with the interface implementation.

class MainActivity: AppCompatActivity(),CompoundButton.OnCheckedChangeListener{

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

      val yourCheckBox = findViewById<CheckBox>(R.id.check_box)
      yourCheckBox.setOnCheckedChangeListener(this)

    }

 override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        when(buttonView?.id){
            R.id.check_box -> Log.d("Checked: ","$isChecked")
        }
    }

}

Retrieving a Foreign Key value with django-rest-framework serializers

Simple solution source='category.name' where category is foreign key and .name it's attribute.

from rest_framework.serializers import ModelSerializer, ReadOnlyField
from my_app.models import Item

class ItemSerializer(ModelSerializer):
    category_name = ReadOnlyField(source='category.name')

    class Meta:
        model = Item
        fields = "__all__"

Entity Framework .Remove() vs. .DeleteObject()

It's not generally correct that you can "remove an item from a database" with both methods. To be precise it is like so:

  • ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

  • EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:

    • If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL values, this foreign will be set to null and if you call SaveChanges this NULL value for the childEntity will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE statement. No DELETE statement occurs.

    • If the relationship is required (the FK doesn't allow NULL values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges - the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.

    • If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL) EF will mark the childEntity as Deleted as well. If you call SaveChanges a SQL DELETE statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: "If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.". This seems unprecise or even wrong to me because all three cases above have a "referential integrity constraint" but only in the last case the child is in fact deleted. (Unless they mean with "dependent object" an object that participates in an identifying relationship which would be an unusual terminology though.)

Using an if statement to check if a div is empty

You can use .is().

if( $('#leftmenu').is(':empty') ) {
    // ...

Or you could just test the length property to see if one was found.

if( $('#leftmenu:empty').length ) {
    // ...

Keep in mind that empty means no white space either. If there's a chance that there will be white space, then you can use $.trim() and check for the length of the content.

if( !$.trim( $('#leftmenu').html() ).length ) {
    // ...

Easiest way to split a string on newlines in .NET?

using System.IO;

string textToSplit;

if (textToSplit != null)
{
    List<string> lines = new List<string>();
    using (StringReader reader = new StringReader(textToSplit))
    {
        for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
        {
            lines.Add(line);
        }
    }
}

How to prevent auto-closing of console after the execution of batch file

besides pause.

set /p=

can be used .It will expect user input and will release the flow when enter is pressed.

or

runas /user:# "" >nul 2>&1

which will do the same except nothing from the user input will be displayed nor will remain in the command history.

Why split the <script> tag when writing it with document.write()?

I think is for prevent the browser's HTML parser from interpreting the <script>, and mainly the </script> as the closing tag of the actual script, however I don't think that using document.write is a excellent idea for evaluating script blocks, why don't use the DOM...

var newScript = document.createElement("script");
...

Wipe data/Factory reset through ADB

After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.

 * The arguments which may be supplied in the recovery.command file:
 *   --send_intent=anystring - write the text out to recovery.intent
 *   --update_package=path - verify install an OTA package file
 *   --wipe_data - erase user data (and cache), then reboot
 *   --wipe_cache - wipe cache (but not user data), then reboot
 *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs

Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:

adb shell
recovery --wipe_data

Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.

EDIT:

For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command

For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c

Why doesn't the height of a container element increase if it contains floated elements?

You are encountering the float bug (though I'm not sure if it's technically a bug due to how many browsers exhibit this behaviour). Here is what is happening:

Under normal circumstances, assuming that no explicit height has been set, a block level element such as a div will set its height based on its content. The bottom of the parent div will extend beyond the last element. Unfortunately, floating an element stops the parent from taking the floated element into account when determining its height. This means that if your last element is floated, it will not "stretch" the parent in the same way a normal element would.

Clearing

There are two common ways to fix this. The first is to add a "clearing" element; that is, another element below the floated one that will force the parent to stretch. So add the following html as the last child:

<div style="clear:both"></div>

It shouldn't be visible, and by using clear:both, you make sure that it won't sit next to the floated element, but after it.

Overflow:

The second method, which is preferred by most people (I think) is to change the CSS of the parent element so that the overflow is anything but "visible". So setting the overflow to "hidden" will force the parent to stretch beyond the bottom of the floated child. This is only true if you haven't set a height on the parent, of course.

Like I said, the second method is preferred as it doesn't require you to go and add semantically meaningless elements to your markup, but there are times when you need the overflow to be visible, in which case adding a clearing element is more than acceptable.

Set color of TextView span in Android

From the developer docs, to change the color and size of a spannable:

1- create a class:

    class RelativeSizeColorSpan(size: Float,@ColorInt private val color: Int): RelativeSizeSpan(size) {

    override fun updateDrawState(textPaint: TextPaint?) {
        super.updateDrawState(textPaint)
        textPaint?.color = color
    } 
}

2 Create your spannable using that class:

    val spannable = SpannableStringBuilder(titleNames)
spannable.setSpan(
    RelativeSizeColorSpan(1.5f, Color.CYAN), // Increase size by 50%
    titleNames.length - microbe.name.length, // start
    titleNames.length, // end
    Spannable.SPAN_EXCLUSIVE_INCLUSIVE
)

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

Well, I can think of a CSS hack that will resolve this issue.

You could add the following line in your CSS file:

* html .blog_list div.postbody img { width:75px; height: SpecifyHeightHere; } 

The above code will only be seen by IE6. The aspect ratio won't be perfect, but you could make it look somewhat normal. If you really wanted to make it perfect, you would need to write some javascript that would read the original picture width, and set the ratio accordingly to specify a height.

Equivalent of "continue" in Ruby

Yes, it's called next.

for i in 0..5
   if i < 2
     next
   end
   puts "Value of local variable is #{i}"
end

This outputs the following:

Value of local variable is 2
Value of local variable is 3
Value of local variable is 4
Value of local variable is 5
 => 0..5 

How can I get the data type of a variable in C#?

One option would be to use a helper extension method like follows:

public static class MyExtensions
{
    public static System.Type Type<T>(this T v)=>typeof(T);
}

var i=0;
console.WriteLine(i.Type().FullName);

What is the purpose of Node.js module.exports and how do you use it?

the refer link is like this:

exports = module.exports = function(){
    //....
}

the properties of exports or module.exports ,such as functions or variables , will be exposed outside

there is something you must pay more attention : don't override exports .

why ?

because exports just the reference of module.exports , you can add the properties onto the exports ,but if you override the exports , the reference link will be broken .

good example :

exports.name = 'william';

exports.getName = function(){
   console.log(this.name);
}

bad example :

exports = 'william';

exports = function(){
     //...
}

If you just want to exposed only one function or variable , like this:

// test.js
var name = 'william';

module.exports = function(){
    console.log(name);
}   

// index.js
var test = require('./test');
test();

this module only exposed one function and the property of name is private for the outside .

Magento: get a static block as html in a phtml file

I think this will work for you

$block = Mage::getModel('cms/block')->setStoreId(Mage::app()->getStore()->getId())->load('newest_product');
echo $block->getTitle();
echo $block->getContent();

It does work but now the variables in CMS block are not parsing anymore :(

How to stop (and restart) the Rails Server?

In case that doesn't work there is another way that works especially well in Windows: Kill localhost:3000 process from Windows command line

Unable to open debugger port in IntelliJ

This one worked for me-- If the issue still persists (in case you are not using a glassFish server), then close your JIdea and stop the server. This will disable the ports connectivity. Then start your server and JIdea, this will start fresh connectivity with the ports, resolving the issue.

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

Just add autofocus in first input or textarea.

<input type="text" name="name" id="xax" autofocus="autofocus" />

Example of Mockito's argumentCaptor

Here I am giving you a proper example of one callback method . so suppose we have a method like method login() :

 public void login() {
    loginService = new LoginService();
    loginService.login(loginProvider, new LoginListener() {
        @Override
        public void onLoginSuccess() {
            loginService.getresult(true);
        }

        @Override
        public void onLoginFaliure() {
            loginService.getresult(false);

        }
    });
    System.out.print("@@##### get called");
}

I also put all the helper class here to make the example more clear: loginService class

public class LoginService implements Login.getresult{
public void login(LoginProvider loginProvider,LoginListener callback){

    String username  = loginProvider.getUsername();
    String pwd  = loginProvider.getPassword();
    if(username != null && pwd != null){
        callback.onLoginSuccess();
    }else{
        callback.onLoginFaliure();
    }

}

@Override
public void getresult(boolean value) {
    System.out.print("login success"+value);
}}

and we have listener LoginListener as :

interface LoginListener {
void onLoginSuccess();

void onLoginFaliure();

}

now I just wanted to test the method login() of class Login

 @Test
public void loginTest() throws Exception {
    LoginService service = mock(LoginService.class);
    LoginProvider provider = mock(LoginProvider.class);
    whenNew(LoginProvider.class).withNoArguments().thenReturn(provider);
    whenNew(LoginService.class).withNoArguments().thenReturn(service);
    when(provider.getPassword()).thenReturn("pwd");
    when(provider.getUsername()).thenReturn("username");
    login.getLoginDetail("username","password");

    verify(provider).setPassword("password");
    verify(provider).setUsername("username");

    verify(service).login(eq(provider),captor.capture());

    LoginListener listener = captor.getValue();

    listener.onLoginSuccess();

    verify(service).getresult(true);

also dont forget to add annotation above the test class as

@RunWith(PowerMockRunner.class)
@PrepareForTest(Login.class)

JQuery post JSON object to a server

To send json to the server, you first have to create json

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            name:"Bob",
            ...
        }),
        dataType: 'json'
    });
}

This is how you would structure the ajax request to send the json as a post var.

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        data: { json: JSON.stringify({
            name:"Bob",
            ...
        })},
        dataType: 'json'
    });
}

The json will now be in the json post var.

How do I resolve a HTTP 414 "Request URI too long" error?

An excerpt from the RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1:

The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions:

  • Annotation of existing resources;
  • Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
  • Providing a block of data, such as the result of submitting a form, to a data-handling process;
  • Extending a database through an append operation.

How to make a <ul> display in a horizontal row

Set the display property to inline for the list you want this to apply to. There's a good explanation of displaying lists on A List Apart.

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.

100% width background image with an 'auto' height

Tim S. was much closer to a "correct" answer then the currently accepted one. If you want to have a 100% width, variable height background image done with CSS, instead of using cover (which will allow the image to extend out from the sides) or contain (which does not allow the image to extend out at all), just set the CSS like so:

body {
    background-image: url(img.jpg);
    background-position: center top;
    background-size: 100% auto;
}

This will set your background image to 100% width and allow the height to overflow. Now you can use media queries to swap out that image instead of relying on JavaScript.

EDIT: I just realized (3 months later) that you probably don't want the image to overflow; you seem to want the container element to resize based on it's background-image (to preserve it's aspect ratio), which is not possible with CSS as far as I know.

Hopefully soon you'll be able to use the new srcset attribute on the img element. If you want to use img elements now, the currently accepted answer is probably best.

However, you can create a responsive background-image element with a constant aspect ratio using purely CSS. To do this, you set the height to 0 and set the padding-bottom to a percentage of the element's own width, like so:

.foo {
    height: 0;
    padding: 0; /* remove any pre-existing padding, just in case */
    padding-bottom: 75%; /* for a 4:3 aspect ratio */
    background-image: url(foo.png);
    background-position: center center;
    background-size: 100%;
    background-repeat: no-repeat;
}

In order to use different aspect ratios, divide the height of the original image by it's own width, and multiply by 100 to get the percentage value. This works because padding percentage is always calculated based on width, even if it's vertical padding.

PHP - iterate on string characters

For those who are looking for the fastest way to iterate over strings in php, Ive prepared a benchmark testing.
The first method in which you access string characters directly by specifying its position in brackets and treating string like an array:

$string = "a sample string for testing";
$char = $string[4] // equals to m

I myself thought the latter is the fastest method, but I was wrong.
As with the second method (which is used in the accepted answer):

$string = "a sample string for testing";
$string = str_split($string);
$char = $string[4] // equals to m

This method is going to be faster cause we are using a real array and not assuming one to be an array.

Calling the last line of each of the above methods for 1000000 times lead to these benchmarking results:

Using string[i]
0.24960017204285 Seconds

Using str_split
0.18720006942749 Seconds

Which means the second method is way faster.

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

Adapted from Timmmm to PYQT5

from PyQt5.QtGui import QPixmap
from PyQt5.QtGui import QResizeEvent
from PyQt5.QtWidgets import QLabel


class Label(QLabel):

    def __init__(self):
        super(Label, self).__init__()
        self.pixmap_width: int = 1
        self.pixmapHeight: int = 1

    def setPixmap(self, pm: QPixmap) -> None:
        self.pixmap_width = pm.width()
        self.pixmapHeight = pm.height()

        self.updateMargins()
        super(Label, self).setPixmap(pm)

    def resizeEvent(self, a0: QResizeEvent) -> None:
        self.updateMargins()
        super(Label, self).resizeEvent(a0)

    def updateMargins(self):
        if self.pixmap() is None:
            return
        pixmapWidth = self.pixmap().width()
        pixmapHeight = self.pixmap().height()
        if pixmapWidth <= 0 or pixmapHeight <= 0:
            return
        w, h = self.width(), self.height()
        if w <= 0 or h <= 0:
            return

        if w * pixmapHeight > h * pixmapWidth:
            m = int((w - (pixmapWidth * h / pixmapHeight)) / 2)
            self.setContentsMargins(m, 0, m, 0)
        else:
            m = int((h - (pixmapHeight * w / pixmapWidth)) / 2)
            self.setContentsMargins(0, m, 0, m)

Updating the value of data attribute using jQuery

$('.toggle img').data('block', 'something').attr('src', 'something.jpg');

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

How does one capture a Mac's command key via JavaScript?

Basing on Ilya's data, I wrote a Vanilla JS library for supporting modifier keys on Mac: https://github.com/MichaelZelensky/jsLibraries/blob/master/macKeys.js

Just use it like this, e.g.:

document.onclick = function (event) {
  if (event.shiftKey || macKeys.shiftKey) {
    //do something interesting
  }
}

Tested on Chrome, Safari, Firefox, Opera on Mac. Please check if it works for you.

How to draw circle in html page?

Here's a circle that I used for a CS 1.6 stats website. A beautiful four colors circle.

_x000D_
_x000D_
#circle {
      border-top: 8px ridge #d11967;
      border-right: 8px ridge #d32997;
      border-bottom: 8px ridge #5246eb;
      border-left: 8px ridge #fc2938;
      border-radius: 50%; width: 440px; height: 440px;
}
_x000D_
<div id="circle"></div>
_x000D_
_x000D_
_x000D_ Adjust the circle diameter by chaging the width and height.

You can also rotate and skew by using skewY(), skewX() and rotate():

  transform: rotate(60deg);
  transform: skewY(-5deg);
  transform: skewX(-15deg);

How do I clear a search box with an 'x' in bootstrap 3?

Do not bind to element id, just use the 'previous' input element to clear.

CSS:

.clear-input > span {
    position: absolute;
    right: 24px;
    top: 10px;
    height: 14px;
    margin: auto;
    font-size: 14px;
    cursor: pointer;
    color: #AAA;
}

Javascript:

function $(document).ready(function() {
    $(".clear-input>span").click(function(){
        // Clear the input field before this clear button
        // and give it focus.

        $(this).prev().val('').focus();
    });
});

HTML Markup, use as much as you like:

<div class="clear-input">
    Pizza: <input type="text" class="form-control">
    <span class="glyphicon glyphicon-remove-circle"></span>
</div>

<div class="clear-input">
    Pasta: <input type="text" class="form-control">
    <span class="glyphicon glyphicon-remove-circle"></span>
</div>

AngularJs - ng-model in a SELECT

Select's default value should be one of its value in the list. In order to load the select with default value you can use ng-options. A scope variable need to be set in the controller and that variable is assigned as ng-model in HTML's select tag.

View this plunker for any references:

http://embed.plnkr.co/hQiYqaQXrtpxQ96gcZhq/preview

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

A picture is worth a thousand words:

PHP Double Equals == equality chart:

enter image description here

PHP Triple Equals === Equality chart:

enter image description here

Source code to create these images:

https://github.com/sentientmachine/php_equality_charts

Guru Meditation

Those who wish to keep their sanity, read no further because none of this will make any sense, except to say that this is how the insanity-fractal, of PHP was designed.

  1. NAN != NAN but NAN == true.

  2. == will convert left and right operands to numbers if left is a number. So 123 == "123foo", but "123" != "123foo"

  3. A hex string in quotes is occasionally a float, and will be surprise cast to float against your will, causing a runtime error.

  4. == is not transitive because "0"== 0, and 0 == "" but "0" != ""

  5. PHP Variables that have not been declared yet are false, even though PHP has a way to represent undefined variables, that feature is disabled with ==.

  6. "6" == " 6", "4.2" == "4.20", and "133" == "0133" but 133 != 0133. But "0x10" == "16" and "1e3" == "1000" exposing that surprise string conversion to octal will occur both without your instruction or consent, causing a runtime error.

  7. False == 0, "", [] and "0".

  8. If you add 1 to number and they are already holding their maximum value, they do not wrap around, instead they are cast to infinity.

  9. A fresh class is == to 1.

  10. False is the most dangerous value because False is == to most of the other variables, mostly defeating it's purpose.

Hope:

If you are using PHP, Thou shalt not use the double equals operator because if you use triple equals, the only edge cases to worry about are NAN and numbers so close to their datatype's maximum value, that they are cast to infinity. With double equals, anything can be surprise == to anything or, or can be surprise casted against your will and != to something of which it should obviously be equal.

Anywhere you use == in PHP is a bad code smell because of the 85 bugs in it exposed by implicit casting rules that seem designed by millions of programmers programming by brownian motion.

Send Message in C#

It doesn't sound like a good idea to use send message. I think you should try to work around the problem that the DLLs can't reference each other...

Laravel Controller Subfolder routing

In Laravel 5.6, assuming the name of your subfolder' is Api:

In your controller, you need these two lines:

namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;

And in your route file api.php, you need:

Route::resource('/myapi', 'Api\MyController');

Create an array of strings

You need to use cell-arrays:

names = cell(10,1);
for i=1:10
    names{i} = ['Sample Text ' num2str(i)];
end

Laravel blank white screen

The following steps solved blank white screen problem on my Laravel 5.

  • Go to your Laravel root folder
  • Give write permission to bootstrap/cache and storage directories

sudo chmod -R 777 bootstrap/cache storage

  • Rename .env.example to .env
  • Generate application key with the following command in terminal/command-prompt from Laravel root:

php artisan key:generate

This will generate the encryption key and update the value of APP_KEY in .env file

This should solve the problem.

If the problem still exists, then update config/app.php with the new key generated from the above artisan key generate command:

'key' => env('APP_KEY', 'SomeRandomString'),

to

'key' => env('APP_KEY', 'KEY_GENERATED_FROM_ABOVE_COMMAND'),

Cannot read property 'push' of undefined when combining arrays

This error occurs in angular when you didn't intialise the array blank.
For an example:

userlist: any[ ];
this.userlist = [ ]; 

or

userlist: any = [ ];

Launch an event when checking a checkbox in Angular2

Check Demo: https://stackblitz.com/edit/angular-6-checkbox?embed=1&file=src/app/app.component.html

  CheckBox: use change event to call the function and pass the event.

<label class="container">    
   <input type="checkbox" [(ngModel)]="theCheckbox"  data-md-icheck 
    (change)="toggleVisibility($event)"/>
      Checkbox is <span *ngIf="marked">checked</span><span 
     *ngIf="!marked">unchecked</span>
     <span class="checkmark"></span>
</label>
 <div>And <b>ngModel</b> also works, it's value is <b>{{theCheckbox}}</b></div>

Java: Why is the Date constructor deprecated, and what do I use instead?

Date itself is not deprecated. It's just a lot of its methods are. See here for details.

Use java.util.Calendar instead.

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

Improve subplot size/spacing with many subplots in matplotlib

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(10,60))
plt.subplots_adjust( ... )

The plt.subplots_adjust method:

def subplots_adjust(*args, **kwargs):
    """
    call signature::

      subplots_adjust(left=None, bottom=None, right=None, top=None,
                      wspace=None, hspace=None)

    Tune the subplot layout via the
    :class:`matplotlib.figure.SubplotParams` mechanism.  The parameter
    meanings (and suggested defaults) are::

      left  = 0.125  # the left side of the subplots of the figure
      right = 0.9    # the right side of the subplots of the figure
      bottom = 0.1   # the bottom of the subplots of the figure
      top = 0.9      # the top of the subplots of the figure
      wspace = 0.2   # the amount of width reserved for blank space between subplots
      hspace = 0.2   # the amount of height reserved for white space between subplots

    The actual defaults are controlled by the rc file
    """
    fig = gcf()
    fig.subplots_adjust(*args, **kwargs)
    draw_if_interactive()

or

fig = plt.figure(figsize=(10,60))
fig.subplots_adjust( ... )

The size of the picture matters.

"I've tried messing with hspace, but increasing it only seems to make all of the graphs smaller without resolving the overlap problem."

Thus to make more white space and keep the sub plot size the total image needs to be bigger.

Converting java date to Sql timestamp

Take a look at SimpleDateFormat:

java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());  

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
System.out.println(sdf.format(sq));

How can I remove an element from a list?

There's the rlist package (http://cran.r-project.org/web/packages/rlist/index.html) to deal with various kinds of list operations.

Example (http://cran.r-project.org/web/packages/rlist/vignettes/Filtering.html):

library(rlist)
devs <- 
  list(
    p1=list(name="Ken",age=24,
      interest=c("reading","music","movies"),
      lang=list(r=2,csharp=4,python=3)),
    p2=list(name="James",age=25,
      interest=c("sports","music"),
      lang=list(r=3,java=2,cpp=5)),
    p3=list(name="Penny",age=24,
      interest=c("movies","reading"),
      lang=list(r=1,cpp=4,python=2)))

list.remove(devs, c("p1","p2"))

Results in:

# $p3
# $p3$name
# [1] "Penny"
# 
# $p3$age
# [1] 24
# 
# $p3$interest
# [1] "movies"  "reading"
# 
# $p3$lang
# $p3$lang$r
# [1] 1
# 
# $p3$lang$cpp
# [1] 4
# 
# $p3$lang$python
# [1] 2

Sites not accepting wget user agent header

It seems Yahoo server does some heuristic based on User-Agent in a case Accept header is set to */*.

Accept: text/html

did the trick for me.

e.g.

wget  --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0"  http://yahoo.com

Note: if you don't declare Accept header then wget automatically adds Accept:*/* which means give me anything you have.

Jar mismatch! Fix your dependencies

In my case there was another directory within my workspace, having the same jar file as the one in my project. I hadn't created that directory or anything in it. It was created by Eclipse I believe. I just erased that directory and it just runs ok.

How to iterate over each string in a list of strings and operate on it's elements

The reason is that in your second example i is the word itself, not the index of the word. So

for w1 in words:
     if w1[0] == w1[len(w1) - 1]:
       c += 1
     print c

would the equivalent of your code.

Does Python's time.time() return the local or UTC timestamp?

I eventually settled for:

>>> import time
>>> time.mktime(time.gmtime())
1509467455.0

How do I check whether a file exists without exceptions?

It isn't needed probably but if it is, here's some code

import os

def file_exists(path, filename):
    for file_or_folder in os.listdir(path):
        if file_or_folder == filename:
            return True
    return False

AngularJS: Service vs provider vs factory

All the good answers already. I would like to add few more points on Service and Factory. Along with the difference between service/factory. And one can also have questions like:

  1. Should I use service or factory? What’s the difference?
  2. Is they do same or have same behaviour?

Lets start with the difference between Service and factory:

  1. Both are Singletons: Whenever Angular find these as a dependency first time,it create a single instance of service/factory. Once the instance is created, same instance is used forever.

  2. Can be used to model an object with behavior: They can both have methods, internal state variables, and so on. Though the way you write that code will differ.

Services:

A service is a constructor function, and Angular will instantiate it by calling new yourServiceName(). This means a couple of things.

  1. Functions and instance variables will be properties of this.
  2. You don’t need to return a value. When Angular calls new yourServiceName(), it’ll receive the this object with all the properties you put on it.

Sample Example:

angular.service('MyService', function() {
  this.aServiceVariable = "Ved Prakash"
  this.aServiceMethod = function() {
    return //code
  };
});

When Angular injects this MyService service into a controller that depends on it, that controller will get a MyService that it can call functions on, e.g. MyService.aServiceMethod ().

Be careful with this:

Since the constructed service is an object, the methods inside it can refer to this when they’re called:

angular.service('ScoreKeeper', function($http) {
  this.score = 0;

  this.getScore = function() {
    return this.score;
  };

  this.setScore = function(newScore) {
    this.score = newScore;
  };

  this.addOne = function() {
    this.score++;
  };
});

You might be tempted to call ScoreKeeper.setScore in a promise chain, for instance if you initialized the score by grabbing it from the server: $http.get('/score').then(ScoreKeeper.setScore). The trouble with this is that ScoreKeeper.setScore will be called with this bound to null and you’ll get errors. The better way would be $http.get('/score').then(ScoreKeeper.setScore.bind(ScoreKeeper)). Whether you choose to use this in your service methods or not, be careful how you call them.

Returning a Value from a Service:

Due to how JavaScript constructors work, if you return a complex value (i.e., an Object) from a constructor function, the caller will get that Object instead of the this instance.

This means that you can basically copy-paste the factory example from below, replace factory with service, and it’ll work:

angular.service('MyService', function($http) {
  var api = {};

  api.aServiceMethod= function() {
    return $http.get('/users');
  };
  return api;
});

So when Angular constructs your service with new MyService(), it’ll get that api object instead of the MyService instance.

This is the behavior for any complex values (objects, functions) but not for primitive types.

Factories:

A factory is a plain old function that returns a value. The return value is what gets injected into things that depend on the factory. A typical factory pattern in Angular is to return an object with functions as properties, like this:

angular.factory('MyFactory', function($http) {
  var api = {};

  api.aFactoryMethod= function() {
    return $http.get('/users');
  };

  return api;
});

The injected value for a factory dependency is the factory’s return value, and it doesn’t have to be an object. It could be a function

Answers for above 1 and 2 questions:

For the most part, just stick with using factories for everything. Their behavior is easier to understand. There’s no choice to make about whether to return a value or not, and furthermore, no bugs to be introduced if you do the wrong thing.

I still refer to them as “services” when I’m talking about injecting them as dependencies, though.

Service/Factory behavior is very similar, and some people will say that either one is fine. That’s somewhat true, but I find it easier to follow the advice of John Papa’s style guide and just stick with factories.**

How can I change CSS display none or block property using jQuery?

In javascript:

document.getElementById("myDIV").style.display = "none";

and in jquery:

$("#myDIV").css({display: "none"});
$("#myDIV").css({display: "block"});

and you can use:

$('#myDIV').hide();
$('#myDIV').show();

WRONGTYPE Operation against a key holding the wrong kind of value php

Redis supports 5 data types. You need to know what type of value that a key maps to, as for each data type, the command to retrieve it is different.

Here are the commands to retrieve key value:

  • if value is of type string -> GET <key>
  • if value is of type hash -> HGETALL <key>
  • if value is of type lists -> lrange <key> <start> <end>
  • if value is of type sets -> smembers <key>
  • if value is of type sorted sets -> ZRANGEBYSCORE <key> <min> <max>

Use the TYPE command to check the type of value a key is mapping to:

  • type <key>

How / can I display a console window in Intellij IDEA?

  1. Press the left corner button
  2. Choose debug
  3. Click console

enter image description here

enter image description here

How do I run all Python unit tests in a directory?

You could use a test runner that would do this for you. nose is very good for example. When run, it will find tests in the current tree and run them.

Updated:

Here's some code from my pre-nose days. You probably don't want the explicit list of module names, but maybe the rest will be useful to you.

testmodules = [
    'cogapp.test_makefiles',
    'cogapp.test_whiteutils',
    'cogapp.test_cogapp',
    ]

suite = unittest.TestSuite()

for t in testmodules:
    try:
        # If the module defines a suite() function, call it to get the suite.
        mod = __import__(t, globals(), locals(), ['suite'])
        suitefn = getattr(mod, 'suite')
        suite.addTest(suitefn())
    except (ImportError, AttributeError):
        # else, just load all the test cases from the module.
        suite.addTest(unittest.defaultTestLoader.loadTestsFromName(t))

unittest.TextTestRunner().run(suite)

How to close jQuery Dialog within the dialog?

Using $(this).dialog('close'); only works inside the click function of a button within the modal. If your button is not within the dialog box, as in this example, specify a selector:

$('#form-dialog').dialog('close');

For more information, see the documentation

How to set user environment variables in Windows Server 2008 R2 as a normal user?

Under "Start" enter "environment" in the search field. That will list the option to change the system variables directly in the start menu.

How to run server written in js with Node.js

You don't need to go in node.js prompt, you just need to use standard command promt and write

node c:/node/server.js

this also works:

node c:\node\server.js

and then in your browser:

http://localhost:1337

Accept server's self-signed ssl certificate in Java client

If 'they' are using a self-signed certificate it is up to them to take the steps required to make their server usable. Specifically that means providing their certificate to you offline in a trustworthy way. So get them to do that. You then import that into your truststore using the keytool as described in the JSSE Reference Guide. Don't even think about the insecure TrustManager posted here.

EDIT For the benefit of the seventeen (!) downvoters, and numerous commenters below, who clearly have not actually read what I have written here, this is not a jeremiad against self-signed certificates. There is nothing wrong with self-signed certificates when implemented correctly. But, the correct way to implement them is to have the certificate delivered securely via an offline process, rather than via the unauthenticated channel they are going to be used to authenticate. Surely this is obvious? It is certainly obvious to every security-aware organization I have ever worked for, from banks with thousands of branches to my own companies. The client-side code-base 'solution' of trusting all certificates, including self-signed certificates signed by absolutely anybody, or any arbitary body setting itself up as a CA, is ipso facto not secure. It is just playing at security. It is pointless. You are having a private, tamperproof, reply-proof, injection-proof conversation with ... somebody. Anybody. A man in the middle. An impersonator. Anybody. You may as well just use plaintext.

The equivalent of wrap_content and match_parent in flutter?

I used this solution, you have to define the height and width of your screen using MediaQuery:

 Container(
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width
  )

Running AMP (apache mysql php) on Android

On Google Play, PAW Server is the typical PHP server package ( contain Beanshell code ). You can put your webpages in the "html" folder. However, typical Beanshell code is not very familiar to be edited. On Android device, I recommend you to use SL4A and phpforandroid to build up Perl and PHP Server. Yet, they do not use MySQL as DATA base. You should be familiar with the Scripting Layer for Android (SL4A) platform. See this link for reference

Putting images with options in a dropdown list

I have found a crossbrowser compatible JQuery plugin here.

http://designwithpc.com/Plugins/ddSlick

probably useful in this scenario.

Set element width or height in Standards Mode

The style property lets you specify values for CSS properties.

The CSS width property takes a length as its value.

Lengths require units. In quirks mode, browsers tend to assume pixels if provided with an integer instead of a length. Specify units.

e1.style.width = "400px";

gridview data export to excel in asp.net

Instead of doing all these.. cant you use a simpler approach as shown below.

Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
            Response.ContentType = "application/excel";
            System.IO.StringWriter sw = new System.IO.StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gv.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();

You can get the entire walkthrough here

Check if string contains only letters in javascript

try to add \S at your pattern

^[A-Za-z]\S*$

Why do I get the error "Unsafe code may only appear if compiling with /unsafe"?

To use unsafe code blocks, the project has to be compiled with the /unsafe switch on.

Open the properties for the project, go to the Build tab and check the Allow unsafe code checkbox.

Regular expression to match characters at beginning of line only

Regex symbol to match at beginning of a line:

^

Add the string you're searching for (CTR) to the regex like this:

^CTR

Example: regex

That should be enough!

However, if you need to get the text from the whole line in your language of choice, add a "match anything" pattern .*:

^CTR.*

Example: more regex

If you want to get crazy, use the end of line matcher

$

Add that to the growing regex pattern:

^CTR.*$

Example: lets get crazy

Note: Depending on how and where you're using regex, you might have to use a multi-line modifier to get it to match multiple lines. There could be a whole discussion on the best strategy for picking lines out of a file to process them, and some of the strategies would require this:

Multi-line flag m (this is specified in various ways in various languages/contexts)

/^CTR.*/gm

Example: we had to use m on regex101

How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

With Java 8 and later, use the java.time package.

ZonedDateTime.now().getYear();
ZonedDateTime.now().getMonthValue();
ZonedDateTime.now().getDayOfMonth();
ZonedDateTime.now().getHour();
ZonedDateTime.now().getMinute();
ZonedDateTime.now().getSecond();

ZonedDateTime.now() is a static method returning the current date-time from the system clock in the default time-zone. All the get methods return an int value.

jquery function val() is not equivalent to "$(this).value="?

You want:

this.value = ''; // straight JS, no jQuery

or

$(this).val(''); // jQuery

With $(this).value = '' you're assigning an empty string as the value property of the jQuery object that wraps this -- not the value of this itself.

Is it possible to print a variable's type in standard C++?

Very ugly but does the trick if you only want compile time info (e.g. for debugging):

auto testVar = std::make_tuple(1, 1.0, "abc");
decltype(testVar)::foo= 1;

Returns:

Compilation finished with errors:
source.cpp: In function 'int main()':
source.cpp:5:19: error: 'foo' is not a member of 'std::tuple<int, double, const char*>'

Failed to load ApplicationContext (with annotation)

Your test requires a ServletContext: add @WebIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT

...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

UPDATE In Spring Boot 1.4.x and above @WebIntegrationTest is no longer preferred. @SpringBootTest or @WebMvcTest

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

There's also workaround doing disjunction of your array, worked for me as other solutions were hard to implement using some old framework.

select * from tableA where id = 1 or id = 2 or id = 3 ...

But for better perfo, I would use Nikolai Nechai's solution with unions, if possible.

use current date as default value for a column

I have also come across this need for my database project. I decided to share my findings here.

1) There is no way to a NOT NULL field without a default when data already exists (Can I add a not null column without DEFAULT value)

2) This topic has been addressed for a long time. Here is a 2008 question (Add a column with a default value to an existing table in SQL Server)

3) The DEFAULT constraint is used to provide a default value for a column. The default value will be added to all new records IF no other value is specified. (https://www.w3schools.com/sql/sql_default.asp)

4) The Visual Studio Database Project that I use for development is really good about generating change scripts for you. This is the change script created for my DB promotion:

GO
PRINT N'Altering [dbo].[PROD_WHSE_ACTUAL]...';

GO
ALTER TABLE [dbo].[PROD_WHSE_ACTUAL]
    ADD [DATE] DATE DEFAULT getdate() NOT NULL;

-

Here are the steps I took to update my database using Visual Studio for development.

1) Add default value (Visual Studio SSDT: DB Project: table designer) enter image description here

2) Use the Schema Comparison tool to generate the change script.

code already provided above

3) View the data BEFORE applying the change. enter image description here

4) View the data AFTER applying the change. enter image description here

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

In Java/Android, to test a password with at least one number, one letter, one special character in following pattern:

"^(?=.*[A-Za-z])(?=.*\\d)(?=.*[$@$!%*#?&])[A-Za-z\\d$@$!%*#?&]{8,}$"

Python: Assign print output to a variable

To answer the question more generaly how to redirect standard output to a variable ?

do the following :

from io import StringIO
import sys

result = StringIO()
sys.stdout = result
result_string = result.getvalue()

If you need to do that only in some function do the following :

old_stdout = sys.stdout  

# your function containing the previous lines
my_function()

sys.stdout = old_stdout

R - test if first occurrence of string1 is followed by string2

I think it's worth answering the generic question "R - test if string contains string" here.

For that, use the grep function.

# example:
> if(length(grep("ab","aacd"))>0) print("found") else print("Not found")
[1] "Not found"
> if(length(grep("ab","abcd"))>0) print("found") else print("Not found")
[1] "found"

(Deep) copying an array using jQuery

I've come across this "deep object copy" function that I've found handy for duplicating objects by value. It doesn't use jQuery, but it certainly is deep.

http://www.overset.com/2007/07/11/javascript-recursive-object-copy-deep-object-copy-pass-by-value/

What's the purpose of the LEA instruction?

LEA : just an "arithmetic" instruction..

MOV transfers data between operands but lea is just calculating

Possible heap pollution via varargs parameter

Heap pollution is a technical term. It refers to references which have a type that is not a supertype of the object they point to.

List<A> listOfAs = new ArrayList<>();
List<B> listOfBs = (List<B>)(Object)listOfAs; // points to a list of As

This can lead to "unexplainable" ClassCastExceptions.

// if the heap never gets polluted, this should never throw a CCE
B b = listOfBs.get(0); 

@SafeVarargs does not prevent this at all. However, there are methods which provably will not pollute the heap, the compiler just can't prove it. Previously, callers of such APIs would get annoying warnings that were completely pointless but had to be suppressed at every call site. Now the API author can suppress it once at the declaration site.

However, if the method actually is not safe, users will no longer be warned.

How to set underline text on textview?

Simple and easy way to display underline in TextView is:

yourTextView.getPaint().setUnderlineText(true);

And if you want to remove underlining for that view, you can write below code:

yourTextView.getPaint().setUnderlineText(false);

It will work even though you set android:textAllCaps="true"

How to check if directory exist using C++ and winAPI

If linking to the shell Lightweight API (shlwapi.dll) is ok for you, you can use the PathIsDirectory function

How to add List<> to a List<> in asp.net

Try using list.AddRange(VTSWeb.GetDailyWorktimeViolations(VehicleID2));

Add/Delete table rows dynamically using JavaScript

You could just clone the first row that has the inputs, then get the nested inputs and update their ID to add the row number (and do the same with the first cell).

function deleteRow(row)
{
    var i=row.parentNode.parentNode.rowIndex;
    document.getElementById('POITable').deleteRow(i);
}


function insRow()
{
    var x=document.getElementById('POITable');
       // deep clone the targeted row
    var new_row = x.rows[1].cloneNode(true);
       // get the total number of rows
    var len = x.rows.length;
       // set the innerHTML of the first row 
    new_row.cells[0].innerHTML = len;

       // grab the input from the first cell and update its ID and value
    var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
    inp1.id += len;
    inp1.value = '';

       // grab the input from the first cell and update its ID and value
    var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
    inp2.id += len;
    inp2.value = '';

       // append the new row to the table
    x.appendChild( new_row );
}

Demo below

_x000D_
_x000D_
function deleteRow(row) {_x000D_
  var i = row.parentNode.parentNode.rowIndex;_x000D_
  document.getElementById('POITable').deleteRow(i);_x000D_
}_x000D_
_x000D_
_x000D_
function insRow() {_x000D_
  console.log('hi');_x000D_
  var x = document.getElementById('POITable');_x000D_
  var new_row = x.rows[1].cloneNode(true);_x000D_
  var len = x.rows.length;_x000D_
  new_row.cells[0].innerHTML = len;_x000D_
_x000D_
  var inp1 = new_row.cells[1].getElementsByTagName('input')[0];_x000D_
  inp1.id += len;_x000D_
  inp1.value = '';_x000D_
  var inp2 = new_row.cells[2].getElementsByTagName('input')[0];_x000D_
  inp2.id += len;_x000D_
  inp2.value = '';_x000D_
  x.appendChild(new_row);_x000D_
}
_x000D_
<div id="POItablediv">_x000D_
  <input type="button" id="addPOIbutton" value="Add POIs" /><br/><br/>_x000D_
  <table id="POITable" border="1">_x000D_
    <tr>_x000D_
      <td>POI</td>_x000D_
      <td>Latitude</td>_x000D_
      <td>Longitude</td>_x000D_
      <td>Delete?</td>_x000D_
      <td>Add Rows?</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>1</td>_x000D_
      <td><input size=25 type="text" id="latbox" /></td>_x000D_
      <td><input size=25 type="text" id="lngbox" readonly=true/></td>_x000D_
      <td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)" /></td>_x000D_
      <td><input type="button" id="addmorePOIbutton" value="Add More POIs" onclick="insRow()" /></td>_x000D_
    </tr>_x000D_
  </table>
_x000D_
_x000D_
_x000D_

XSD - how to allow elements in any order any number of times?

If none of the above is working, you are probably working on EDI trasaction where you need to validate your result against an HIPPA schema or any other complex xsd for that matter. The requirement is that, say there 8 REF segments and any of them have to appear in any order and also not all are required, means to say you may have them in following order 1st REF, 3rd REF , 2nd REF, 9th REF. Under default situation EDI receive will fail, beacause default complex type is

<xs:sequence>
  <xs:element.../>
</xs:sequence>

The situation is even complex when you are calling your element by refrence and then that element in its original spot is quite complex itself. for example:

<xs:element>
<xs:complexType>
<xs:sequence>
<element name="REF1"  ref= "REF1_Mycustomelment" minOccurs="0" maxOccurs="1">
<element name="REF2"  ref= "REF2_Mycustomelment" minOccurs="0" maxOccurs="1">
<element name="REF3"  ref= "REF3_Mycustomelment" minOccurs="0" maxOccurs="1">
</xs:sequence>
</xs:complexType>
</xs:element>

Solution:

Here simply replacing "sequence" with "all" or using "choice" with min/max combinations won't work!

First thing replace "xs:sequence" with "<xs:all>" Now,You need to make some changes where you are Referring the element from, There go to:

<xs:annotation>
  <xs:appinfo>
    <b:recordinfo structure="delimited" field.........Biztalk/2003">

***Now in the above segment add trigger point in the end like this trigger_field="REF01_...complete name.." trigger_value = "38" Do the same for other REF segments where trigger value will be different like say "18", "XX" , "YY" etc..so that your record info now looks like:b:recordinfo structure="delimited" field.........Biztalk/2003" trigger_field="REF01_...complete name.." trigger_value="38">


This will make each element unique, reason being All REF segements (above example) have same structure like REF01, REF02, REF03. And during validation the structure validation is ok but it doesn't let the values repeat because it tries to look for remaining values in first REF itself. Adding triggers will make them all unique and they will pass in any order and situational cases (like use 5 out 9 and not all 9/9).

Hope it helps you, for I spent almost 20 hrs on this.

Good Luck

Getting msbuild.exe without installing Visual Studio

Download MSBuild with the link from @Nicodemeus answer was OK, yet the installation was broken until I've added these keys into a register:

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSBuild\ToolsVersions\12.0]
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))" 

Call parent method from child class c#

To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:

In child add:

public Action UpdateProgress;  // In place of event handler declaration
                               // declare an Action delegate
.
.
.
private LoadData() {
    this.UpdateProgress();    // call to Action delegate - MyMethod in
                              // parent
}

In parent add:

// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod;  // assigns MyMethod to child delegate

Get month and year from date cells Excel

You could right click on those cells, go to format, select custom, then type mm yyyy.

What is the reason for a red exclamation mark next to my project in Eclipse?

There is a Problems view (try Window->Show View) which shows this kind of thing.

It's usually missing Jars (eg your project configuration references a jar that isn't there), and that kind of thing, in the case of JDT, but obviously these days Eclipse can be used in so many ways, it could be anything.

How to bind Events on Ajax loaded Content?

Important step for Event binding on Ajax loading content...

01. First of all unbind or off the event on selector

$(".SELECTOR").off();

02. Add event listener on document level

$(document).on("EVENT", '.SELECTOR', function(event) { 
    console.log("Selector event occurred");
});

Getting list of items inside div using Selenium Webdriver

I'm not sure if your findElements statement gets you all the divs. I would try the following:

List<WebElement> elementsRoot = driver.findElements(By.xpath("//div[@class=\"facetContainerDiv\"]/div));

for(int i = 0; i < elementsRoot.size(); ++i) {
     WebElement checkbox = elementsRoot.get(i).findElement(By.xpath("./label/input"));
     checkbox.click();
     blah blah blah
}

The idea here is that you get the root element then use another a 'sub' xpath or any selector you like to find the node element. Of course the xpath or selector may need to be adjusted to properly find the element you want.

Declare global variables in Visual Studio 2010 and VB.NET

A global variable could be accessible in all your forms in your project if you use the keyword public shared if it is in a class. It will also work if you use the keyword "public" if it is under a Module, but it is not the best practice for many reasons.

(... Yes, I somewhat repeating what "Cody Gray" and "RBarryYoung" said.)

One of the problems is when you have two threads that call the same global variable at the same time. You will have some surprises. You might have unexpected reactions if you don't know their limitations. Take a look at the post Global Variables in Visual Basic .NET and download the sample project!

Random numbers with Math.random() in Java

There's a small problem with the formula that you found on Google. It should be:
(int)(Math.random() * (max - min + 1) + min)
not
(int)(Math.random() * (max - min) + min) .

max - min + 1 is the range in which random numbers can be generated

how to convert a string to an array in php

here, Use explode() function to convert string into array, by a string

click here to know more about explode()

$str = "this is string";
$delimiter = ' ';  // use any string / character by which, need to split string into Array
$resultArr = explode($delimiter, $str);  
var_dump($resultArr);

Output :

Array
(
    [0] => "this",
    [1] => "is",
    [2] => "string "
)

it is same as the requirements:

  arr[0]="this";
  arr[1]="is";
  arr[2]="string";

Cut Corners using CSS

If you need a transparent cut out edge, you can use a rotated pseudo element as a background for the div and position it to cut out the desired corner:

Transprent cut out edge on a div

_x000D_
_x000D_
body {_x000D_
  background: url(http://i.imgur.com/k8BtMvj.jpg);_x000D_
  background-size: cover;_x000D_
}_x000D_
div {_x000D_
  position: relative;_x000D_
  width: 50%;_x000D_
  margin: 0 auto;_x000D_
  overflow: hidden;_x000D_
  padding: 20px;_x000D_
  text-align: center;_x000D_
}_x000D_
div:after {_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  width: 1100%; height: 1100%;_x000D_
  top: 20px; right: -500%;_x000D_
  background: rgba(255,255,255,.8);_x000D_
  transform-origin: 54% 0;_x000D_
  transform: rotate(45deg);_x000D_
  z-index: -1;_x000D_
}
_x000D_
<div>_x000D_
  ... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note that this solution uses transforms and you need to add the required vendor prefixes. For more info see canIuse.

To cut the bottom right edge, you can change the top, transform and transform-origin properties of the pseudo element to:

_x000D_
_x000D_
body {_x000D_
  background: url(http://i.imgur.com/k8BtMvj.jpg);_x000D_
  background-size: cover;_x000D_
}_x000D_
div {_x000D_
  position: relative;_x000D_
  width: 50%;_x000D_
  margin: 0 auto;_x000D_
  overflow: hidden;_x000D_
  padding: 20px;_x000D_
  text-align: center;_x000D_
}_x000D_
div:after {_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  width: 1100%; height: 1100%;_x000D_
  bottom: 20px; right: -500%;_x000D_
  background: rgba(255,255,255,.8);_x000D_
  transform-origin: 54% 100%;_x000D_
  transform: rotate(-45deg);_x000D_
  z-index: -1;_x000D_
}
_x000D_
<div>_x000D_
  ... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations

declare @cur cursor
declare @idx int       
declare @Approval_No varchar(50) 

declare @ReqNo varchar(100)
declare @M_Id  varchar(100)
declare @Mail_ID varchar(100)
declare @temp  table
(
val varchar(100)
)
declare @temp2  table
(
appno varchar(100),
mailid varchar(100),
userod varchar(100)
)


    declare @slice varchar(8000)       
    declare @String varchar(100)
    --set @String = '1200096,1200095,1200094,1200093,1200092,1200092'
set @String = '20131'


    select @idx = 1       
        if len(@String)<1 or @String is null  return       

    while @idx!= 0       
    begin       
        set @idx = charindex(',',@String)       
        if @idx!=0       
            set @slice = left(@String,@idx - 1)       
        else       
            set @slice = @String

            --select @slice       
            insert into @temp values(@slice)
        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break


    end
    -- select distinct(val) from @temp


SET @cur = CURSOR FOR select distinct(val) from @temp


--open cursor    
OPEN @cur    
--fetchng id into variable    
FETCH NEXT    
    FROM @cur into @Approval_No 

      --
    --loop still the end    
     while @@FETCH_STATUS = 0  
    BEGIN   


select distinct(Approval_Sr_No) as asd, @ReqNo=Approval_Sr_No,@M_Id=AM_ID,@Mail_ID=Mail_ID from WFMS_PRAO,WFMS_USERMASTER where  WFMS_PRAO.AM_ID=WFMS_USERMASTER.User_ID
and Approval_Sr_No=@Approval_No

   insert into @temp2 values(@ReqNo,@M_Id,@Mail_ID)  

FETCH NEXT    
      FROM @cur into @Approval_No    
 end  
    --close cursor    
    CLOSE @cur    

select * from @tem

How to get 0-padded binary representation of an integer in java?

for(int i=0;i<n;i++)
{
  for(int j=str[i].length();j<4;j++)
  str[i]="0".concat(str[i]);
}

str[i].length() is length of number say 2 in binary is 01 which is length 2 change 4 to desired max length of number. This can be optimized to O(n). by using continue.

Cannot access wamp server on local network

If you are using wamp stack, it will be fixed by open port in Firewall (Control Pannel). It work for my case (detail how to open port 80: https://tips.alocentral.com/open-tcp-port-80-in-windows-firewall/)

How to get Latitude and Longitude of the mobile device in android?

you can got Current latlng using this

`

  public class MainActivity extends ActionBarActivity {
  private LocationManager locationManager;
  private String provider;
  private MyLocationListener mylistener;
  private Criteria criteria;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


             locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
              // Define the criteria how to select the location provider
              criteria = new Criteria();
              criteria.setAccuracy(Criteria.ACCURACY_COARSE);   //default

              // user defines the criteria

              criteria.setCostAllowed(false); 
              // get the best provider depending on the criteria
              provider = locationManager.getBestProvider(criteria, false);

              // the last known location of this provider
              Location location = locationManager.getLastKnownLocation(provider);

              mylistener = new MyLocationListener();

              if (location != null) {
                  mylistener.onLocationChanged(location);
              } else {
                  // leads to the settings because there is no last known location
                  Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                  startActivity(intent);
              }
              // location updates: at least 1 meter and 200millsecs change
              locationManager.requestLocationUpdates(provider, 200, 1, mylistener);
            String a=""+location.getLatitude();
            Toast.makeText(getApplicationContext(), a, 222).show();

}

private class MyLocationListener implements LocationListener {

      @Override
      public void onLocationChanged(Location location) {
        // Initialize the location fields



          Toast.makeText(MainActivity.this,  ""+location.getLatitude()+location.getLongitude(),
                    Toast.LENGTH_SHORT).show()  

      }

      @Override
      public void onStatusChanged(String provider, int status, Bundle extras) {
          Toast.makeText(MainActivity.this, provider + "'s status changed to "+status +"!",
                    Toast.LENGTH_SHORT).show();
      }

      @Override
      public void onProviderEnabled(String provider) {
          Toast.makeText(MainActivity.this, "Provider " + provider + " enabled!",
            Toast.LENGTH_SHORT).show();

      }

      @Override
      public void onProviderDisabled(String provider) {
          Toast.makeText(MainActivity.this, "Provider " + provider + " disabled!",
            Toast.LENGTH_SHORT).show();
      }
  }         

`

how to use "tab space" while writing in text file

You can use \t to create a tab in a file.

Are one-line 'if'/'for'-statements good Python style?

I've found that in the majority of cases doing block clauses on one line is a bad idea.

It will, again as a generality, reduce the quality of the form of the code. High quality code form is a key language feature for python.

In some cases python will offer ways todo things on one line that are definitely more pythonic. Things such as what Nick D mentioned with the list comprehension:

newlist = [splitColon.split(a) for a in someList]

although unless you need a reusable list specifically you may want to consider using a generator instead

listgen = (splitColon.split(a) for a in someList)

note the biggest difference between the two is that you can't reiterate over a generator, but it is more efficient to use.

There is also a built in ternary operator in modern versions of python that allow you to do things like

string_to_print = "yes!" if "exam" in "example" else ""
print string_to_print

or

iterator = max_value if iterator > max_value else iterator

Some people may find these more readable and usable than the similar if (condition): block.

When it comes down to it, it's about code style and what's the standard with the team you're working on. That's the most important, but in general, i'd advise against one line blocks as the form of the code in python is so very important.

Select objects based on value of variable in object using jq

Just try this one as a full copy paste in the shell and you will grasp it

# create the example file to  be working on .. 
cat << EOF > tmp.json
[  
 { "card_id": "id-00", "card_id_type": "card_id_type-00"},
 {"card_id": "id-01", "card_id_type": "card_id_type-01"},
 {  "card_id": "id-02", "card_id_type": "card_id_type-02"}
]
EOF


# pipe the content of the file to the  jq query, which gets the array of objects
# and select the attribute named "card_id" ONLY if it's neighbour attribute
# named "card_id_type" has the "card_id_type-01" value
# jq -r means give me ONLY the value of the jq query no quotes aka raw
cat tmp.json | jq -r '.[]| select (.card_id_type == "card_id_type-01")|.card_id'

id-01

or with an aws cli command

 # list my vpcs or
 # list the values of the tags which names are "Name" 
 aws ec2 describe-vpcs | jq -r '.| .Vpcs[].Tags[]|select (.Key == "Name") | .Value'|sort  -nr

How to increment an iterator by 2?

We can use both std::advance as well as std::next, but there's a difference between the two.

advance modifies its argument and returns nothing. So it can be used as:

vector<int> v;
v.push_back(1);
v.push_back(2);
auto itr = v.begin();
advance(itr, 1);          //modifies the itr
cout << *itr<<endl        //prints 2

next returns a modified copy of the iterator:

vector<int> v;
v.push_back(1);
v.push_back(2);
cout << *next(v.begin(), 1) << endl;    //prints 2

How do I use Spring Boot to serve static content located in Dropbox folder?

For the current Spring-Boot Version 1.5.3 the parameter is

spring.resources.static-locations

Update I configured

`spring.resources.static-locations=file:/opt/x/y/z/static``

and expected to get my index.html living in this folder when calling

http://<host>/index.html

This did not work. I had to include the folder name in the URL:

http://<host>/static/index.html

How to count days between two dates in PHP?

In case your DateTime has also hour:minutes:seconds and you still want to have the number of days..

   /**
     * Returns the total number of days between to DateTimes, 
     * if it is within the same year
     * @param $start
     * @param $end
     */
    public function dateTimesToDays($start,$end){
       return intval($end->format('z')) - intval($start->format('z')) + 1;
    }

https://github.com/dukeatcoding/timespan-converter

Import functions from another js file. Javascript

By default, scripts can't handle imports like that directly. You're probably getting another error about not being able to get Course or not doing the import.

If you add type="module" to your <script> tag, and change the import to ./course.js (because browsers won't auto-append the .js portion), then the browser will pull down course for you and it'll probably work.

import './course.js';

function Student() {
    this.firstName = '';
    this.lastName = '';
    this.course = new Course();
}

<html>
    <head>
        <script src="./models/student.js" type="module"></script>
    </head>
    <body>
        <div id="myDiv">
        </div>
        <script>
        window.onload= function() {
            var x = new Student();
            x.course.id = 1;
            document.getElementById('myDiv').innerHTML = x.course.id;
        }
        </script>
    </body>
</html>

If you're serving files over file://, it likely won't work. Some IDEs have a way to run a quick sever.

You can also write a quick express server to serve your files (install Node if you don't have it):

//package.json
{
  "scripts": { "start": "node server" },
  "dependencies": { "express": "latest" }
}

// server/index.js
const express = require('express');
const app = express();

app.use('/', express.static('PATH_TO_YOUR_FILES_HERE');
app.listen(8000);

With those two files, run npm install, then npm start and you'll have a server running over http://localhost:8000 which should point to your files.

Is there a way to automatically generate getters and setters in Eclipse?

Bring up the context menu (i.e. right click) in the source code window of the desired class. Then select the Source submenu; from that menu selecting Generate Getters and Setters... will cause a wizard window to appear.

Source -> Generate Getters and Setters...

Select the variables you wish to create getters and setters for and click OK.

How do I print a double value with full precision using cout?

In C++20 you'll be able to use std::format to do this:

std::cout << std::format("{}", M_PI);

Output (assuming IEEE754 double):

3.141592653589793

The default floating-point format is the shortest decimal representation with a round-trip guarantee. The advantage of this method compared to the setprecision I/O manipulator is that it doesn't print unnecessary digits.

In the meantime you can use the {fmt} library, std::format is based on. {fmt} also provides the print function that makes this even easier and more efficient (godbolt):

fmt::print("{}", M_PI);

Disclaimer: I'm the author of {fmt} and C++20 std::format.

How to Lock the data in a cell in excel using vba

You can first choose which cells you don't want to be protected (to be user-editable) by setting the Locked status of them to False:

Worksheets("Sheet1").Range("B2:C3").Locked = False

Then, you can protect the sheet, and all the other cells will be protected. The code to do this, and still allow your VBA code to modify the cells is:

Worksheets("Sheet1").Protect UserInterfaceOnly:=True

or

Call Worksheets("Sheet1").Protect(UserInterfaceOnly:=True)

OS detecting makefile

I had a case where I had to detect the difference between two versions of Fedora, to tweak the command-line options for inkscape:
- in Fedora 31, the default inkscape is 1.0beta which uses --export-file
- in Fedora < 31, the default inkscape is 0.92 which uses --export-pdf

My Makefile contains the following

# set VERSION_ID from /etc/os-release

$(eval $(shell grep VERSION_ID /etc/os-release))

# select the inkscape export syntax

ifeq ($(VERSION_ID),31)
EXPORT = export-file
else
EXPORT = export-pdf
endif

# rule to convert inkscape SVG (drawing) to PDF

%.pdf : %.svg
    inkscape --export-area-drawing $< --$(EXPORT)=$@

This works because /etc/os-release contains a line

VERSION_ID=<value>

so the shell command in the Makefile returns the string VERSION_ID=<value>, then the eval command acts on this to set the Makefile variable VERSION_ID. This can obviously be tweaked for other OS's depending how the metadata is stored. Note that in Fedora there is not a default environment variable that gives the OS version, otherwise I would have used that!

How to select option in drop down using Capybara

For some reason it didn't work for me. So I had to use something else.

select "option_name_here", :from => "organizationSelect"

worked for me.

Difference between session affinity and sticky session?

Sticky session means to route the requests of particular session to the same physical machine who served the first request for that session.

How to SELECT the last 10 rows of an SQL table which has no ID field?

You can use the "ORDER BY DESC" option, then put it back in the original order:

(SELECT * FROM tablename ORDER BY id DESC LIMIT 10) ORDER BY id;

Converting a year from 4 digit to 2 digit and back again in C#

Even if a builtin way existed, it wouldn't validate it as greater than today and it would differ very little from a substring call. I wouldn't worry about it.

How to unzip a file using the command line?

As other have alluded, 7-zip is great.

Note: I am going to zip and then unzip a file. Unzip is at the bottom.

My contribution:

Get the

7-Zip Command Line Version

Current URL

http://www.7-zip.org/download.html

The syntax?

You can put the following into a .bat file

"C:\Program Files\7-Zip\7z.exe" a MySuperCoolZipFile.zip "C:\MyFiles\*.jpg" -pmypassword -r -w"C:\MyFiles\" -mem=AES256

I've shown a few options.

-r is recursive. Usually what you want with zip functionality.

a is for "archive". That's the name of the output zip file.

-p is for a password (optional)

-w is a the source directory. This will nest your files correctly in the zip file, without extra folder information.

-mem is the encryption strength.

There are others. But the above will get you running.

NOTE: Adding a password will make the zip file unfriendly when it comes to viewing the file through Windows Explorer. The client may need their own copy of 7-zip (or winzip or other) to view the contents of the file.

EDIT::::::::::::(just extra stuff).

There is a "command line" version which is probably better suited for this: http://www.7-zip.org/download.html

(current (at time of writing) direct link) http://sourceforge.net/projects/sevenzip/files/7-Zip/9.20/7za920.zip/download

So the zip command would be (with the command line version of the 7 zip tool).

"C:\WhereIUnzippedCommandLineStuff\7za.exe" a MySuperCoolZipFile.zip "C:\MyFiles\*.jpg" -pmypassword -r -w"C:\MyFiles\" -mem=AES256

Now the unzip portion: (to unzip the file you just created)

"C:\WhereIUnzippedCommandLineStuff\7zipCommandLine\7za.exe" e MySuperCoolZipFile.zip "*.*" -oC:\SomeOtherFolder\MyUnzippedFolder -pmypassword -y -r

As an alternative to the "e" argument, there is a x argument.

  e: Extract files from archive (without using directory names)
  x: eXtract files with full paths

Documentation here:

http://sevenzip.sourceforge.jp/chm/cmdline/commands/extract.htm

C# ASP.NET MVC Return to Previous Page

I am assuming (please correct me if I am wrong) that you want to re-display the edit page if the edit fails and to do this you are using a redirect.

You may have more luck by just returning the view again rather than trying to redirect the user, this way you will be able to use the ModelState to output any errors too.

Edit:

Updated based on feedback. You can place the previous URL in the viewModel, add it to a hidden field then use it again in the action that saves the edits.

For instance:

public ActionResult Index()
{
    return View();
}

[HttpGet] // This isn't required
public ActionResult Edit(int id)
{
   // load object and return in view
   ViewModel viewModel = Load(id);

   // get the previous url and store it with view model
   viewModel.PreviousUrl = System.Web.HttpContext.Current.Request.UrlReferrer;

   return View(viewModel);
}

[HttpPost]
public ActionResult Edit(ViewModel viewModel)
{
   // Attempt to save the posted object if it works, return index if not return the Edit view again

   bool success = Save(viewModel);
   if (success)
   {
       return Redirect(viewModel.PreviousUrl);
   }
   else
   {
      ModelState.AddModelError("There was an error");
      return View(viewModel);
   }
}

The BeginForm method for your view doesn't need to use this return URL either, you should be able to get away with:

@model ViewModel

@using (Html.BeginForm())
{
    ...
    <input type="hidden" name="PreviousUrl" value="@Model.PreviousUrl" />
}

Going back to your form action posting to an incorrect URL, this is because you are passing a URL as the 'id' parameter, so the routing automatically formats your URL with the return path.

This won't work because your form will be posting to an controller action that won't know how to save the edits. You need to post to your save action first, then handle the redirect within it.

Python Pandas : group by in group by and average?

I would simply do this, which literally follows what your desired logic was:

df.groupby(['org']).mean().groupby(['cluster']).mean()

How can I check Drupal log files?

To view entries in Drupal's own internal log system (the watchdog database table), go to http://example.com/admin/reports/dblog. These can include Drupal-specific errors as well as general PHP or MySQL errors that have been thrown.

Use the watchdog() function to add an entry to this log from your own custom module.

When Drupal bootstraps it uses the PHP function set_error_handler() to set its own error handler for PHP errors. Therefore, whenever a PHP error occurs within Drupal it will be logged through the watchdog() call at admin/reports/dblog. If you look for PHP fatal errors, for example, in /var/log/apache/error.log and don't see them, this is why. Other errors, e.g. Apache errors, should still be logged in /var/log, or wherever you have it configured to log to.

Build a basic Python iterator

There are four ways to build an iterative function:

Examples:

# generator
def uc_gen(text):
    for char in text.upper():
        yield char

# generator expression
def uc_genexp(text):
    return (char for char in text.upper())

# iterator protocol
class uc_iter():
    def __init__(self, text):
        self.text = text.upper()
        self.index = 0
    def __iter__(self):
        return self
    def __next__(self):
        try:
            result = self.text[self.index]
        except IndexError:
            raise StopIteration
        self.index += 1
        return result

# getitem method
class uc_getitem():
    def __init__(self, text):
        self.text = text.upper()
    def __getitem__(self, index):
        return self.text[index]

To see all four methods in action:

for iterator in uc_gen, uc_genexp, uc_iter, uc_getitem:
    for ch in iterator('abcde'):
        print(ch, end=' ')
    print()

Which results in:

A B C D E
A B C D E
A B C D E
A B C D E

Note:

The two generator types (uc_gen and uc_genexp) cannot be reversed(); the plain iterator (uc_iter) would need the __reversed__ magic method (which, according to the docs, must return a new iterator, but returning self works (at least in CPython)); and the getitem iteratable (uc_getitem) must have the __len__ magic method:

    # for uc_iter we add __reversed__ and update __next__
    def __reversed__(self):
        self.index = -1
        return self
    def __next__(self):
        try:
            result = self.text[self.index]
        except IndexError:
            raise StopIteration
        self.index += -1 if self.index < 0 else +1
        return result

    # for uc_getitem
    def __len__(self)
        return len(self.text)

To answer Colonel Panic's secondary question about an infinite lazily evaluated iterator, here are those examples, using each of the four methods above:

# generator
def even_gen():
    result = 0
    while True:
        yield result
        result += 2


# generator expression
def even_genexp():
    return (num for num in even_gen())  # or even_iter or even_getitem
                                        # not much value under these circumstances

# iterator protocol
class even_iter():
    def __init__(self):
        self.value = 0
    def __iter__(self):
        return self
    def __next__(self):
        next_value = self.value
        self.value += 2
        return next_value

# getitem method
class even_getitem():
    def __getitem__(self, index):
        return index * 2

import random
for iterator in even_gen, even_genexp, even_iter, even_getitem:
    limit = random.randint(15, 30)
    count = 0
    for even in iterator():
        print even,
        count += 1
        if count >= limit:
            break
    print

Which results in (at least for my sample run):

0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32

How to choose which one to use? This is mostly a matter of taste. The two methods I see most often are generators and the iterator protocol, as well as a hybrid (__iter__ returning a generator).

Generator expressions are useful for replacing list comprehensions (they are lazy and so can save on resources).

If one needs compatibility with earlier Python 2.x versions use __getitem__.

SQL Server 2008: How to query all databases sizes?

A better and quite simpler one

SELECT [Database Name] = DB_NAME(database_id),
     [Type] = CASE WHEN Type_Desc = 'ROWS' THEN 'Data File(s)'
               WHEN Type_Desc = 'LOG'  THEN 'Log File(s)'
               ELSE Type_Desc END,
     [Size in MB] = CAST( ((SUM(Size)* 8) / 1024.0) AS DECIMAL(18,2) )
FROM   sys.master_files
--Uncomment if you need to query for a particular database
--WHERE      database_id = DB_ID(‘Database Name’) 
GROUP BY  GROUPING SETS
        (
               (DB_NAME(database_id), Type_Desc),
               (DB_NAME(database_id))
        ) ORDER BY      DB_NAME(database_id), Type_Desc DESC

It will give you size of Data File(s) and Log File(s) separately like below

DatabaseName    Type            Size in MB
-------------------------------------------
FMS             Data File(s)    23.00
FMS             Log File(s)     1.50
PointOfSale     Data File(s)    4.00
PointOfSale     Log File(s)     1.25
Union2          Data File(s)    336.00
Union2          Log File(s)     1191.13
SurveyProject   Data File(s)    4.00
SurveyProject   Log File(s)     1.00

How to install PostgreSQL's pg gem on Ubuntu?

Simple solution for ubuntu users...

First uninstall all postgres packages, then run these commads...

sudo apt-get install postgresql
sudo apt-get install postgresql-client libpq5 libpq-dev

# for rvm (single user)
mv ~/.rvm/usr/lib ~/.rvm/usr/lib_rvm 

# for rvm (multi-user)
mv /usr/local/rvm/usr/lib /usr/local/rvm/usr/lib_rvm

gem install pg  --   --with-pg-lib=/usr/lib

Then run 'bundle install'. Every thing will be fine. Have a good day!

In Powershell what is the idiomatic way of converting a string to an int?

You can use the -as operator. If casting succeed you get back a number:

$numberAsString -as [int]

How to delete an element from a Slice in Golang

Maybe you can try this method:

// DelEleInSlice delete an element from slice by index
//  - arr: the reference of slice
//  - index: the index of element will be deleted
func DelEleInSlice(arr interface{}, index int) {
    vField := reflect.ValueOf(arr)
    value := vField.Elem()
    if value.Kind() == reflect.Slice || value.Kind() == reflect.Array {
        result := reflect.AppendSlice(value.Slice(0, index), value.Slice(index+1, value.Len()))
        value.Set(result)
    }
}

Usage:

arrInt := []int{0, 1, 2, 3, 4, 5}
arrStr := []string{"0", "1", "2", "3", "4", "5"}
DelEleInSlice(&arrInt, 3)
DelEleInSlice(&arrStr, 4)
fmt.Println(arrInt)
fmt.Println(arrStr)

Result:

0, 1, 2, 4, 5
"0", "1", "2", "3", "5"

Differences between Oracle JDK and OpenJDK

Both OpenJDK and Oracle JDK are created and maintained currently by Oracle only.

OpenJDK and Oracle JDK are implementations of the same Java specification passed the TCK (Java Technology Certification Kit).

Most of the vendors of JDK are written on top of OpenJDK by doing a few tweaks to [mostly to replace licensed proprietary parts / replace with more high-performance items that only work on specific OS] components without breaking the TCK compatibility.

Many vendors implemented the Java specification and got TCK passed. For example, IBM J9, Azul Zulu, Azul Zing, and Oracle JDK.

Almost every existing JDK is derived from OpenJDK.

As suggested by many, licensing is a change between JDKs.

Starting with JDK 11 accessing the long time support Oracle JDK/Java SE will now require a commercial license. You should now pay attention to which JDK you're installing as Oracle JDK without subscription could stop working. source

Ref: List of Java virtual machines

Verify External Script Is Loaded

Merging several answers from above into an easy to use function

function GetScriptIfNotLoaded(scriptLocationAndName)
{
  var len = $('script[src*="' + scriptLocationAndName +'"]').length;

  //script already loaded!
  if (len > 0)
      return;

  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = scriptLocationAndName;
  head.appendChild(script);
}

Declare and initialize a Dictionary in Typescript

Here is a more general Dictionary implementation inspired by this from @dmck

    interface IDictionary<T> {
      add(key: string, value: T): void;
      remove(key: string): void;
      containsKey(key: string): boolean;
      keys(): string[];
      values(): T[];
    }

    class Dictionary<T> implements IDictionary<T> {

      _keys: string[] = [];
      _values: T[] = [];

      constructor(init?: { key: string; value: T; }[]) {
        if (init) {
          for (var x = 0; x < init.length; x++) {
            this[init[x].key] = init[x].value;
            this._keys.push(init[x].key);
            this._values.push(init[x].value);
          }
        }
      }

      add(key: string, value: T) {
        this[key] = value;
        this._keys.push(key);
        this._values.push(value);
      }

      remove(key: string) {
        var index = this._keys.indexOf(key, 0);
        this._keys.splice(index, 1);
        this._values.splice(index, 1);

        delete this[key];
      }

      keys(): string[] {
        return this._keys;
      }

      values(): T[] {
        return this._values;
      }

      containsKey(key: string) {
        if (typeof this[key] === "undefined") {
          return false;
        }

        return true;
      }

      toLookup(): IDictionary<T> {
        return this;
      }
    }

Round a floating-point number down to the nearest integer?

Just make round(x-0.5) this will always return the next rounded down Integer value of your Float. You can also easily round up by do round(x+0.5)

Why does an image captured using camera intent gets rotated on some devices on Android?

If somebody experiences problems with ExifInterface on Android 4.4 (KitKat) for getting the orientation, it might be because of wrong path got from the URI. See a solution for propoer getPath in Stack Overflow question Get real path from URI, Android KitKat new storage access framework

Configuration with name 'default' not found. Android Studio

I am facing same problem, I was fixed it by generating gradle project and then adding lib project to android studio

First, See build.gradle file is present in project root directory

if not then, Create gradle project,

  1. export your required lib project from eclipse then (File->Export->Android->generate Gradle build file
  2. Click on Next->Next->Select your lib project from project listing->Next->Next->Finish
  3. See build.gradle file present in your project root directory
  4. Move this project to Android Studio

Java: Literal percent sign in printf statement

You can use StringEscapeUtils from Apache Commons Logging utility or escape manually using code for each character.

Nullable type as a generic parameter possible?

Change the return type to Nullable<T>, and call the method with the non nullable parameter

static void Main(string[] args)
{
    int? i = GetValueOrNull<int>(null, string.Empty);
}


public static Nullable<T> GetValueOrNull<T>(DbDataRecord reader, string columnName) where T : struct
{
    object columnValue = reader[columnName];

    if (!(columnValue is DBNull))
        return (T)columnValue;

    return null;
}

Copy Notepad++ text with formatting?

Select the text.

Right Click.

Plugin Commands -> Copy Text with Syntax Highlighting

Paste it into Word or whatever.

How to check compiler log in sql developer?

control-shift-L should open the log(s) for you. this will by default be the messages log, but if you create the item that is creating the error the Compiler Log will show up (for me the box shows up in the bottom middle left).

if the messages log is the only log that shows up, simply re-execute the item that was causing the failure and the compiler log will show up

for instance, hit Control-shift-L then execute this

CREATE OR REPLACE FUNCTION TEST123() IS
BEGIN
VAR := 2;
end TEST123;

and you will see the message "Error(1,18): PLS-00103: Encountered the symbol ")" when expecting one of the following: current delete exists prior "

(You can also see this in "View--Log")

One more thing, if you are having a problem with a (function || package || procedure) if you do the coding via the SQL Developer interface (by finding the object in question on the connections tab and editing it the error will be immediately displayed (and even underlined at times)

How to read HDF5 files in Python

from keras.models import load_model 

h= load_model('FILE_NAME.h5')

How to fix apt-get: command not found on AWS EC2?

please, be sure your connected to a ubuntu server, I Had the same problem but I was connected to other distro, check the AMI value in your details instance, it should be something like

AMI: ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1 

hope it helps

How to preview selected image in input type="file" in popup using jQuery?

Demo

HTML:

 <form id="form1" runat="server">
   <input type='file' id="imgInp" />
   <img id="blah" src="#" alt="your image" />
</form>

jQuery

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#imgInp").change(function(){
    readURL(this);
});

Reference

How to set different colors in HTML in one statement?

You could use CSS for this and create classes for the elements. So you'd have something like this

p.detail { color:#4C4C4C;font-weight:bold;font-family:Calibri;font-size:20 }
span.name { color:#FF0000;font-weight:bold;font-family:Tahoma;font-size:20 }

Then your HTML would read:

<p class="detail">My Name is: <span class="name">Tintinecute</span> </p>

It's a lot neater then inline stylesheets, is easier to maintain and provides greater reuse.

Here's the complete HTML to demonstrate what I mean:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <style type="text/css">
    p.detail { color:#4C4C4C;font-weight:bold;font-family:Calibri;font-size:20 }
    span.name { color:#FF0000;font-weight:bold;font-family:Tahoma;font-size:20 }
    </style>
</head>
<body>
    <p class="detail">My Name is: <span class="name">Tintinecute</span> </p>
</body>
</html>     

You'll see that I have the stylesheet classes in a style tag in the header, and then I only apply those classes in the code such as <p class="detail"> ... </p>. Go through the w3schools tutorial, it will only take a couple of hours and will really turn you around when it comes to styling your HTML elements. If you cut and paste that into an HTML document you can edit the styles and see what effect they have when you open the file in a browser. Experimenting like this is a great way to learn.

How do I implement Cross Domain URL Access from an Iframe using Javascript?

You might want to take a look at these questions/answers ; they could give you some informations concerning your problem :

To make things short : accessing iframe from another domain is not possible, for security reasons -- which explains the error message you are getting.


The Same origin policy page on wikipedia brings some informations about that security measure :

In a nutshell, the policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions — but prevents access to most methods and properties across pages on different sites.

A strict separation between content provided by unrelated sites must be maintained on client side to prevent the loss of data confidentiality or integrity.

Use of Java's Collections.singletonList()?

From the javadoc

@param  the sole object to be stored in the returned list.
@return an immutable list containing only the specified object.

example

import java.util.*;

public class HelloWorld {
    public static void main(String args[]) {
        // create an array of string objs
        String initList[] = { "One", "Two", "Four", "One",};

        // create one list
        List list = new ArrayList(Arrays.asList(initList));

        System.out.println("List value before: "+list);

        // create singleton list
        list = Collections.singletonList("OnlyOneElement");
        list.add("five"); //throws UnsupportedOperationException
        System.out.println("List value after: "+list);
    }
}

Use it when code expects a read-only list, but you only want to pass one element in it. singletonList is (thread-)safe and fast.

how to append a css class to an element by javascript?

classList is a convenient alternative to accessing an element's list of classes.. see http://developer.mozilla.org/en-US/docs/Web/API/Element.classList.

Not supported in IE < 10

Two HTML tables side by side, centered on the page

Unfortunately, all of these solutions rely on specifying a fixed width. Since the tables are generated dynamically (statistical results pulled from a database), the width can not be known in advance.

The desired result can be achieved by wrapping the two tables within another table:

<table align="center"><tr><td>
//code for table on the left
</td><td>
//code for table on the right
</td></tr></table>

and the result is a perfectly centered pair of tables that responds fluidly to arbitrary widths and page (re)sizes (and the align="center" table attribute could be hoisted out into an outer div with margin autos).

I conclude that there are some layouts that can only be achieved with tables.

How to call a Python function from Node.js

You could take your python, transpile it, and then call it as if it were javascript. I have done this succesfully for screeps and even got it to run in the browser a la brython.

Maximum number of threads in a .NET app?

Mitch is right. It depends on resources (memory).

Although Raymond's article is dedicated to Windows threads, not to C# threads, the logic applies the same (C# threads are mapped to Windows threads).

However, as we are in C#, if we want to be completely precise, we need to distinguish between "started" and "non started" threads. Only started threads actually reserve stack space (as we could expect). Non started threads only allocate the information required by a thread object (you can use reflector if interested in the actual members).

You can actually test it for yourself, compare:

    static void DummyCall()
    {
        Thread.Sleep(1000000000);
    }

    static void Main(string[] args)
    {
        int count = 0;
        var threadList = new List<Thread>();
        try
        {
            while (true)
            {
                Thread newThread = new Thread(new ThreadStart(DummyCall), 1024);
                newThread.Start();
                threadList.Add(newThread);
                count++;
            }
        }
        catch (Exception ex)
        {
        }
    }

with:

   static void DummyCall()
    {
        Thread.Sleep(1000000000);
    }

    static void Main(string[] args)
    {
        int count = 0;
        var threadList = new List<Thread>();
        try
        {
            while (true)
            {
                Thread newThread = new Thread(new ThreadStart(DummyCall), 1024);
                threadList.Add(newThread);
                count++;
            }
        }
        catch (Exception ex)
        {
        }
    }

Put a breakpoint in the exception (out of memory, of course) in VS to see the value of counter. There is a very significant difference, of course.

Spring Boot and how to configure connection details to MongoDB?

spring.data.mongodb.host and spring.data.mongodb.port are not supported if you’re using the Mongo 3.0 Java driver. In such cases, spring.data.mongodb.uri should be used to provide all of the configuration, like this:

spring.data.mongodb.uri=mongodb://user:[email protected]:12345

How unique is UUID?

Quoting from Wikipedia:

Thus, anyone can create a UUID and use it to identify something with reasonable confidence that the identifier will never be unintentionally used by anyone for anything else

It goes on to explain in pretty good detail on how safe it actually is. So to answer your question: Yes, it's safe enough.

Entity Framework and Connection Pooling

Below code helped my object to be refreshed with fresh database values. The Entry(object).Reload() command forces the object to recall database values

GM_MEMBERS member = DatabaseObjectContext.GM_MEMBERS.FirstOrDefault(p => p.Username == username && p.ApplicationName == this.ApplicationName);
DatabaseObjectContext.Entry(member).Reload();

Removing "http://" from a string

$new_website = substr($str, ($pos = strrpos($str, '//')) !== false ? $pos + 2 : 0); 

This would remove everything before the '//'.

EDIT

This one is tested. Using strrpos() instead or strpos().

Facebook Callback appends '#_=_' to Return URL

For those who are looking for simple answer

if (window.location.hash === "#_=_"){
    history.replaceState 
        ? history.replaceState(null, null, window.location.href.split("#")[0])
        : window.location.hash = "";
}

How to call shell commands from Ruby

I'm definitely not a Ruby expert, but I'll give it a shot:

$ irb 
system "echo Hi"
Hi
=> true

You should also be able to do things like:

cmd = 'ls'
system(cmd)

How to get the selected item of a combo box to a string variable in c#

Try this:

string selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
MessageBox.Show(selected);

Oracle Date datatype, transformed to 'YYYY-MM-DD HH24:MI:SS TMZ' through SQL

to convert a TimestampTZ in oracle, you do

TO_TIMESTAMP_TZ('2012-10-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') 
  at time zone 'region'

see here: http://docs.oracle.com/cd/E11882_01/server.112/e10729/ch4datetime.htm#NLSPG264

and here for regions: http://docs.oracle.com/cd/E11882_01/server.112/e10729/applocaledata.htm#NLSPG0141

eg:

SQL> select a, sys_extract_utc(a), a at time zone '-05:00' from (select TO_TIMESTAMP_TZ('2013-04-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'-05:00'
---------------------------------------------------------------------------
09-APR-13 01.10.21.000000000 CST
09-APR-13 06.10.21.000000000
09-APR-13 01.10.21.000000000 -05:00


SQL> select a, sys_extract_utc(a), a at time zone '-05:00' from (select TO_TIMESTAMP_TZ('2013-03-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'-05:00'
---------------------------------------------------------------------------
09-MAR-13 01.10.21.000000000 CST
09-MAR-13 07.10.21.000000000
09-MAR-13 02.10.21.000000000 -05:00

SQL> select a, sys_extract_utc(a), a at time zone 'America/Los_Angeles' from (select TO_TIMESTAMP_TZ('2013-04-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'AMERICA/LOS_ANGELES'
---------------------------------------------------------------------------
09-APR-13 01.10.21.000000000 CST
09-APR-13 06.10.21.000000000
08-APR-13 23.10.21.000000000 AMERICA/LOS_ANGELES

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

This problem is generally caused by the website/intranet URL being placed in one of:

  • Compatibility Mode List
  • Internet Explorer Intranet Zone
    (with Display intranet sites in Compatibility View setting enabled)
  • Enterprise Mode List

On corporate networks, these compatibility view settings are often controlled centrally via group policy. In your case, Enterprise Mode appears to be the culprit.

IE 11 Enterprise Mode

Unfortunately setting META X-UA-Compatible will not override this.

For End-Users

Sometimes the only way for end-users to override this is to press F12 and change the Document Mode under the Emulation Tab. However this setting is not permanent and may revert once Developer Tools is closed.

You can also try to exclude your site from the Intranet zone. But the list of domains which belong to the Intranet zone is usually also controlled by the group policy, so the chance of this working is slim.

To see the list of domains that belong to the Intranet zone, go to:

Tools -> Internet Options -> Security -> Sites -> Advanced

If the list contains your subdomain and is greyed out, then you will not be able to override compatibility view until your network admin allows it.

You really need to contact your network administrator to allow changing the compatibility view settings in the group policy.

For Network Admins

Loading the website with Developer Tools open (F12) will often report the reason that IE is switching to an older mode.

All 3 settings mentioned above are generally controlled via Group Policy, although can sometimes be overridden on user machines.

If Enterprise Mode is the issue (as appears to be the case for the original poster), the following two articles might be helpful:

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

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

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

Resize on div element

For a google maps integration I was looking for a way to detect when a div has changed in size. Since google maps always require proper dimensions e.g. width and height in order to render properly.

The solution I came up with is a delegation of an event, in my case a tab click. This could be a window resize of course, the idea remains the same:

if (parent.is(':visible')) {
    w = parent.outerWidth(false);
    h = w * mapRatio /*9/16*/;
    this.map.css({ width: w, height: h });
} else {
    this.map.closest('.tab').one('click', function() {
        this.activate();
    }.bind(this));
}

this.map in this case is my map div. Since my parent is invisible on load, the computed width and height are 0 or don't match. By using .bind(this) I can delegate the script execution (this.activate) to an event (click).

Now I'm confident the same applies for resize events.

$(window).one('resize', function() {
    this.div.css({ /*whatever*/ });
}.bind(this));

Hope it helps anyone!

How to Replace Multiple Characters in SQL?

I don't know why Charles Bretana deleted his answer, so I'm adding it back in as a CW answer, but a persisted computed column is a REALLY good way to handle these cases where you need cleansed or transformed data almost all the time, but need to preserve the original garbage. His suggestion is relevant and appropriate REGARDLESS of how you decide to cleanse your data.

Specifically, in my current project, I have a persisted computed column which trims all the leading zeros (luckily this is realtively easily handled in straight T-SQL) from some particular numeric identifiers stored inconsistently with leading zeros. This is stored in persisted computed columns in the tables which need it and indexed because that conformed identifier is often used in joins.

How to get JavaScript variable value in PHP

You will need to use JS to send the URL back with a variable in it such as: http://www.site.com/index.php?uid=1

by using something like this in JS:

window.location.href=”index.php?uid=1";

Then in the PHP code use $_GET:

$somevar = $_GET["uid"]; //puts the uid varialbe into $somevar

Appending an element to the end of a list in Scala

We can append or prepend two lists or list&array
Append:

var l = List(1,2,3)    
l = l :+ 4 
Result : 1 2 3 4  
var ar = Array(4, 5, 6)    
for(x <- ar)    
{ l = l :+ x }  
  l.foreach(println)

Result:1 2 3 4 5 6

Prepending:

var l = List[Int]()  
   for(x <- ar)  
    { l= x :: l } //prepending    
     l.foreach(println)   

Result:6 5 4 1 2 3

Single huge .css file vs. multiple smaller specific .css files?

I prefer multiple CSS files. That way it is easier to swap "skins" in and out as you desire. The problem with one monolithic file is that it can get out of control and hard to manage. What if you want blue backgrounds but don't want the buttons to change? Just alter your backgrounds file. Etc.

regex error - nothing to repeat

It seems to be a python bug (that works perfectly in vim). The source of the problem is the (\s*...)+ bit. Basically , you can't do (\s*)+ which make sense , because you are trying to repeat something which can be null.

>>> re.compile(r"(\s*)+")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py", line 180, in compile
    return _compile(pattern, flags)
  File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py", line 233, in _compile
    raise error, v # invalid expression
sre_constants.error: nothing to repeat

However (\s*\1) should not be null, but we know it only because we know what's in \1. Apparently python doesn't ... that's weird.

C# Switch-case string starting with

Try this and tell my if it works hope it help you:

string value = Convert.ToString(Console.ReadLine());

Switch(value)
{
    Case "abc":

    break;

    default:

    break;
}       

Right way to split an std::string into a vector<string>

You can use getline with delimiter:

string s, tmp; 
stringstream ss(s);
vector<string> words;

while(getline(ss, tmp, ',')){
    words.push_back(tmp);
    .....
}

ProgressDialog in AsyncTask

This question is already answered and most of the answers here are correct but they don't solve one major issue with config changes. Have a look at this article https://androidresearch.wordpress.com/2013/05/10/dealing-with-asynctask-and-screen-orientation/ if you would like to write a async task in a better way.

How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

In recent kernels (not sure since when) you can list the contents of /dev/serial to get a list of the serial ports on your system. They are actually symlinks pointing to the correct /dev/ node:

flu0@laptop:~$ ls /dev/serial/
total 0
drwxr-xr-x 2 root root 60 2011-07-20 17:12 by-id/
drwxr-xr-x 2 root root 60 2011-07-20 17:12 by-path/
flu0@laptop:~$ ls /dev/serial/by-id/
total 0
lrwxrwxrwx 1 root root 13 2011-07-20 17:12 usb-Prolific_Technology_Inc._USB-Serial_Controller-if00-port0 -> ../../ttyUSB0
flu0@laptop:~$ ls /dev/serial/by-path/
total 0
lrwxrwxrwx 1 root root 13 2011-07-20 17:12 pci-0000:00:0b.0-usb-0:3:1.0-port0 -> ../../ttyUSB0

This is a USB-Serial adapter, as you can see. Note that when there are no serial ports on the system, the /dev/serial/ directory does not exists. Hope this helps :).

endsWith in JavaScript

If you're using lodash:

_.endsWith('abc', 'c'); // true

If not using lodash, you can borrow from its source.

Compilation error - missing zlib.h

You are missing zlib.h header file, on Linux install it via:

sudo apt-get install libz-dev

As a matter of fact, the module presents as zlib1g-dev in the apt repo, so this is the up-to-date call (Feb 2019):

sudo apt install zlib1g-dev

On Fedora: sudo dnf install zlib-devel (in older versions: sudo dnf install libz-devel).

This will provide the development support files for a library implementing the deflate compression method found in gzip and PKZIP.

If you've already zlib library, make sure you're compiling your code sources with -lz. See: How to fix undefined references to inflate/deflate functions?.

WCF - How to Increase Message Size Quota

If you are creating your WCF bindings dynamically here's the code to use:

BasicHttpBinding httpBinding = new BasicHttpBinding();
httpBinding.MaxReceivedMessageSize = Int32.MaxValue;
httpBinding.MaxBufferSize = Int32.MaxValue;
// Commented next statement since it is not required
// httpBinding.MaxBufferPoolSize = Int32.MaxValue;

LINQ select in C# dictionary

var res = exitDictionary
            .Select(p => p.Value).Cast<Dictionary<string, object>>()
            .SelectMany(d => d)
            .Where(p => p.Key == "fieldname1")
            .Select(p => p.Value).Cast<List<Dictionary<string,string>>>()
            .SelectMany(l => l)
            .SelectMany(d=> d)
            .Where(p => p.Key == "valueTitle")
            .Select(p => p.Value)
            .ToList();

This also works, and easy to understand.

Pandas DataFrame to List of Lists

You could access the underlying array and call its tolist method:

>>> df = pd.DataFrame([[1,2,3],[3,4,5]])
>>> lol = df.values.tolist()
>>> lol
[[1L, 2L, 3L], [3L, 4L, 5L]]

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

A great substitute for np.isnan() and pd.isnull() is

for i in range(0,a.shape[0]):
    if(a[i]!=a[i]):
       //do something here
       //a[i] is nan

since only nan is not equal to itself.

Converting from signed char to unsigned char and back again?

Yes this is safe.

The c language uses a feature called integer promotion to increase the number of bits in a value before performing calculations. Therefore your CLAMP255 macro will operate at integer (probably 32 bit) precision. The result is assigned to a jbyte, which reduces the integer precision back to 8 bits fit in to the jbyte.

how to pass list as parameter in function

public void SomeMethod(List<DateTime> dates)
{
    // do something
}

Regex matching beginning AND end strings

\bdbo\..*fn

I was looking through a ton of java code for a specific library: car.csclh.server.isr.businesslogic.TypePlatform (although I only knew car and Platform at the time). Unfortunately, none of the other suggestions here worked for me, so I figured I'd post this.

Here's the regex I used to find it:

\bcar\..*Platform