Programs & Examples On #War filedeployment

How to make a boolean variable switch between true and false every time a method is invoked?

Assuming your code above is the actual code, you have two problems:

1) your if statements need to be '==', not '='. You want to do comparison, not assignment.

2) The second if should be an 'else if'. Otherwise when it's false, you will set it to true, then the second if will be evaluated, and you'll set it back to false, as you describe

if (a == false) {
  a = true;
} else if (a == true) {
  a = false;
}

Another thing that would make it even simpler is the '!' operator:

a = !a;

will switch the value of a.

Drop shadow on a div container?

This works for me on all my browsers:

.shadow {
-moz-box-shadow: 0 0 30px 5px #999;
-webkit-box-shadow: 0 0 30px 5px #999;
}

then just give any div the shadow class, no jQuery required.

How to change the color of a CheckBox?

buttonTint worked for me try

android:buttonTint="@color/white"

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:id="@+id/agreeCheckBox"
    android:text="@string/i_agree_to_terms_s"
    android:buttonTint="@color/white"
    android:layout_below="@+id/avoid_spam_text"/>

Android Service Stops When App Is Closed

I'm in the same situation, so far I learned when the app is closed the service get closed also because they are in a one thread, so the service should be on another thread in order fot it not to be closed, look into that and look into keeping the service alive with alarm manager here an example http://www.vogella.com/articles/AndroidServices/article.html this way your service won't be shown in notification.

lastly, after all the research I've done I'm coming to realize that the best choice for a long running service is startForeground(), because it is made for that and the system actually deals with your service well.

plot different color for different categorical levels using matplotlib

Here's a succinct and generic solution to use a seaborn color palette.

First find a color palette you like and optionally visualize it:

sns.palplot(sns.color_palette("Set2", 8))

Then you can use it with matplotlib doing this:

# Unique category labels: 'D', 'F', 'G', ...
color_labels = df['color'].unique()

# List of RGB triplets
rgb_values = sns.color_palette("Set2", 8)

# Map label to RGB
color_map = dict(zip(color_labels, rgb_values))

# Finally use the mapped values
plt.scatter(df['carat'], df['price'], c=df['color'].map(color_map))

How to check if a URL exists or returns 404 with Java?

this worked for me:

URL u = new URL ( "http://www.example.com/");
HttpURLConnection huc =  ( HttpURLConnection )  u.openConnection (); 
huc.setRequestMethod ("GET");  //OR  huc.setRequestMethod ("HEAD"); 
huc.connect () ; 
int code = huc.getResponseCode() ;
System.out.println(code);

thanks for the suggestions above.

WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value

This kind of logic could be implemented using EXISTS:

CREATE TABLE tab(a INT, b VARCHAR(10));
INSERT INTO tab(a,b) VALUES(1,'a'),(1, NULL),(NULL, 'a'),(2,'b');

Query:

DECLARE @a INT;

--SET @a = 1;    -- specific NOT NULL value
--SET @a = NULL; -- NULL value
--SET @a = -1;   -- all values

SELECT *
FROM tab t
WHERE EXISTS(SELECT t.a INTERSECT SELECT @a UNION SELECT @a WHERE @a = '-1');

db<>fiddle demo

It could be extended to contain multiple params:

SELECT *
FROM tab t
WHERE EXISTS(SELECT t.a INTERSECT SELECT @a UNION SELECT @a WHERE @a = '-1')
  AND EXISTS(SELECT t.b INTERSECT SELECT @b UNION SELECT @a WHERE @b = '-1');

How Do I Replace/Change The Heading Text Inside <h3></h3>, Using jquery?

you don't - not like this. give an id to your tag , lets say it looks like this now :

<h3 id="myHeader"></h3>

then set the value like that :

myHeader.innerText = "public offers";

How to check if a radiobutton is checked in a radiogroup in Android?

I used the following and it worked for me. I used a boolean validation function where if any Radio Button in a Radio Group is checked, the validation function returns true and a submission is made. if returned false, no submission is made and a toast to "Select Gender" is shown:

  1. MainActivity.java

    public class MainActivity extends AppCompatActivity {
        private RadioGroup genderRadioGroup;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        //Initialize Radio Group And Submit Button
        genderRadioGroup=findViewById(R.id.gender_radiogroup);
        AppCompatButton submit = findViewById(R.id.btnSubmit);
    
        //Submit Radio Group using Submit Button
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Check Gender radio Group For Selected Radio Button
                if(genderRadioGroup.getCheckedRadioButtonId()==-1){//No Radio Button Is Checked
                    Toast.makeText(getApplicationContext(), "Please Select Gender", Toast.LENGTH_LONG).show();
                }else{//Radio Button Is Checked
                    RadioButton selectedRadioButton = findViewById(genderRadioGroup.getCheckedRadioButtonId());
                    gender = selectedRadioButton == null ? "" : selectedRadioButton.getText().toString().trim();
                }
                //Validate
                if (validateInputs()) {
                    //code to proceed when Radio button is checked
                }
            }
        }
        //Validation - No process is initialized if no Radio button is checked
        private boolean validateInputs() {
            if (genderRadioGroup.getCheckedRadioButtonId()==-1) {
                return false;
            }
            return true;
        }
    }
    
  2. In activity_main.xml:

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
    
        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/gender"/>
    
        <RadioGroup
                android:id="@+id/gender_radiogroup"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
    
            <RadioButton
                    android:id="@+id/male"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/male"/>
    
            <RadioButton
                    android:id="@+id/female"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/female""/>
    
        </RadioGroup>
    
        <android.support.v7.widget.AppCompatButton
            android:id="@+id/btnSubmit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/submit"/>
    
    </LinearLayout>
    

If no gender radio button is selected, then the code to proceed will not run.

I hope this helps.

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

When to use .First and when to use .FirstOrDefault with LINQ?

I found a website that apperars to explain the need for FirstOrDefault
http://thepursuitofalife.com/the-linq-firstordefault-method-and-null-resultsets/
If there are no results to a query, and you want to to call First() or Single() to get a single row... You will get an “Sequence contains no elements” exception.

Disclaimer: I have never used LINQ, so my apologies if this is way off the mark.

How to make the webpack dev server run on port 80 and on 0.0.0.0 to make it publicly accessible?

Following worked for me -

1) In Package.json add this:

"scripts": {
    "dev": "webpack-dev-server --progress --colors"
}

2) In webpack.config.js add this under config object that you export:

devServer: {
    host: "GACDTL001SS369k", // Your Computer Name
    port: 8080
}

3) Now on terminal type: npm run dev

4) After #3 compiles and ready just head over to your browser and key in address as http://GACDTL001SS369k:8080/

Your app should hopefully be working now with an external URL which others can access on the same network.

PS: GACDTL001SS369k was my Computer Name so do replace with whatever is yours on your machine.

Maximum length for MD5 input/output

A 128-bit MD5 hash is represented as a sequence of 32 hexadecimal digits.

How to set cache: false in jQuery.get call

Add the parameter yourself.

$.get(url,{ "_": $.now() }, function(rdata){
  console.log(rdata);
});

As of jQuery 3.0, you can now do this:

$.get({
  url: url, 
  cache: false
}).then(function(rdata){
  console.log(rdata);
});

How do I run a batch script from within a batch script?

huh, I don't know why, but call didn't do the trick
call script.bat didn't return to the original console.
cmd /k script.bat did return to the original console.

Refresh Page and Keep Scroll Position

I modified Sanoj Dushmantha's answer to use sessionStorage instead of localStorage. However, despite the documentation, browsers will still store this data even after the browser is closed. To fix this issue, I am removing the scroll position after it is reset.

<script>
    document.addEventListener("DOMContentLoaded", function (event) {
        var scrollpos = sessionStorage.getItem('scrollpos');
        if (scrollpos) {
            window.scrollTo(0, scrollpos);
            sessionStorage.removeItem('scrollpos');
        }
    });

    window.addEventListener("beforeunload", function (e) {
        sessionStorage.setItem('scrollpos', window.scrollY);
    });
</script>

Function to calculate R2 (R-squared) in R

You need a little statistical knowledge to see this. R squared between two vectors is just the square of their correlation. So you can define you function as:

rsq <- function (x, y) cor(x, y) ^ 2

Sandipan's answer will return you exactly the same result (see the following proof), but as it stands it appears more readable (due to the evident $r.squared).


Let's do the statistics

Basically we fit a linear regression of y over x, and compute the ratio of regression sum of squares to total sum of squares.

lemma 1: a regression y ~ x is equivalent to y - mean(y) ~ x - mean(x)

lemma 1

lemma 2: beta = cov(x, y) / var(x)

lemma 2

lemma 3: R.square = cor(x, y) ^ 2

lemma 3


Warning

R squared between two arbitrary vectors x and y (of the same length) is just a goodness measure of their linear relationship. Think twice!! R squared between x + a and y + b are identical for any constant shift a and b. So it is a weak or even useless measure on "goodness of prediction". Use MSE or RMSE instead:

I agree with 42-'s comment:

The R squared is reported by summary functions associated with regression functions. But only when such an estimate is statistically justified.

R squared can be a (but not the best) measure of "goodness of fit". But there is no justification that it can measure the goodness of out-of-sample prediction. If you split your data into training and testing parts and fit a regression model on the training one, you can get a valid R squared value on training part, but you can't legitimately compute an R squared on the test part. Some people did this, but I don't agree with it.

Here is very extreme example:

preds <- 1:4/4
actual <- 1:4

The R squared between those two vectors is 1. Yes of course, one is just a linear rescaling of the other so they have a perfect linear relationship. But, do you really think that the preds is a good prediction on actual??


In reply to wordsforthewise

Thanks for your comments 1, 2 and your answer of details.

You probably misunderstood the procedure. Given two vectors x and y, we first fit a regression line y ~ x then compute regression sum of squares and total sum of squares. It looks like you skip this regression step and go straight to the sum of square computation. That is false, since the partition of sum of squares does not hold and you can't compute R squared in a consistent way.

As you demonstrated, this is just one way for computing R squared:

preds <- c(1, 2, 3)
actual <- c(2, 2, 4)
rss <- sum((preds - actual) ^ 2)  ## residual sum of squares
tss <- sum((actual - mean(actual)) ^ 2)  ## total sum of squares
rsq <- 1 - rss/tss
#[1] 0.25

But there is another:

regss <- sum((preds - mean(preds)) ^ 2) ## regression sum of squares
regss / tss
#[1] 0.75

Also, your formula can give a negative value (the proper value should be 1 as mentioned above in the Warning section).

preds <- 1:4 / 4
actual <- 1:4
rss <- sum((preds - actual) ^ 2)  ## residual sum of squares
tss <- sum((actual - mean(actual)) ^ 2)  ## total sum of squares
rsq <- 1 - rss/tss
#[1] -2.375

Final remark

I had never expected that this answer could eventually be so long when I posted my initial answer 2 years ago. However, given the high views of this thread, I feel obliged to add more statistical details and discussions. I don't want to mislead people that just because they can compute an R squared so easily, they can use R squared everywhere.

Git error: src refspec master does not match any error: failed to push some refs

One classic root cause for this message is:

  • when the repo has been initialized (git init lis4368/assignments),
  • but no commit has ever been made

Ie, if you don't have added and committed at least once, there won't be a local master branch to push to.

Try first to create a commit:

  • either by adding (git add .) then git commit -m "first commit"
    (assuming you have the right files in place to add to the index)
  • or by create a first empty commit: git commit --allow-empty -m "Initial empty commit"

And then try git push -u origin master again.

See "Why do I need to explicitly push a new branch?" for more.

How do I get length of list of lists in Java?

Just use

int listCount = data.size();

That tells you how many lists there are (assuming none are null). If you want to find out how many strings there are, you'll need to iterate:

int total = 0;
for (List<String> sublist : data) {
    // TODO: Null checking
    total += sublist.size();
}
// total is now the total number of strings

Rails 4: assets not loading in production

I may be wrong but those who recommend changing

config.assets.compile = true

The comment on this line reads: #Do not fallback to assets pipeline if a precompiled asset is missed.

This suggests that by setting this to true you are not fixing the problem but rather bypassing it and running the pipeline every time. This must surely kill your performance and defeat the purpose of the pipeline?

I had this same error and it was due to the application running in a sub folder that rails didn't know about.

So my css file where in home/subfolder/app/public/.... but rails was looking in home/app/public/...

try either moving your app out of the subfolder or telling rails that it is in a subfolder.

How to create loading dialogs in Android?

It's a ProgressDialog, with setIndeterminate(true).

From http://developer.android.com/guide/topics/ui/dialogs.html#ProgressDialog

ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "", 
                    "Loading. Please wait...", true);

An indeterminate progress bar doesn't actually show a bar, it shows a spinning activity circle thing. I'm sure you know what I mean :)

Python script header

From the manpage for env (GNU coreutils 6.10):

env - run a program in a modified environment

In theory you could use env to reset the environment (removing many of the existing environment variables) or add additional environment variables in the script header. Practically speaking, the two versions you mentioned are identical. (Though others have mentioned a good point: specifying python through env lets you abstractly specify python without knowing its path.)

Check if a number is int or float

def is_int(x):
  absolute = abs(x)
  rounded = round(absolute)
  if absolute - rounded == 0:
    print str(x) + " is an integer"
  else:
    print str(x) +" is not an integer"


is_int(7.0) # will print 7.0 is an integer

SQL Query with Join, Count and Where

I have used sub-query and it worked great!

SELECT *,(SELECT count(*) FROM $this->tbl_news WHERE
$this->tbl_news.cat_id=$this->tbl_categories.cat_id) as total_news FROM
$this->tbl_categories

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

Here is an effective solution from didi to solve this problem, Since this bug is very common and difficult to find the cause, It looks more like a system problem, Why can't we ignore it directly?Of course we can ignore it, Here is the sample code:

final Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler = 
        Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        if (t.getName().equals("FinalizerWatchdogDaemon") && e instanceof TimeoutException) {
        } else {
            defaultUncaughtExceptionHandler.uncaughtException(t, e);
        }
    }
});

By setting a special default uncaught exception handler, application can change the way in which uncaught exceptions are handled for those threads that would already accept whatever default behavior the system provided. When an uncaught TimeoutException is thrown from a thread named FinalizerWatchdogDaemon, this special handler will block the handler chain, the system handler will not be called, so crash will be avoided.

Through practice, no other bad effects were found. The GC system is still working, timeouts are alleviated as CPU usage decreases.

For more details see: https://mp.weixin.qq.com/s/uFcFYO2GtWWiblotem2bGg

Loading cross-domain endpoint with AJAX

Figured it out. Used this instead.

$('.div_class').load('http://en.wikipedia.org/wiki/Cross-origin_resource_sharing #toctitle');

Android overlay a view ontop of everything?

I have tried the awnsers before but this did not work. Now I jsut used a LinearLayout instead of a TextureView, now it is working without any problem. Hope it helps some others who have the same problem. :)

    view = (LinearLayout) findViewById(R.id.view); //this is initialized in the constructor
    openWindowOnButtonClick();

public void openWindowOnButtonClick()
{
    view.setAlpha((float)0.5);
    FloatingActionButton fb = (FloatingActionButton) findViewById(R.id.floatingActionButton);
    final InputMethodManager keyboard = (InputMethodManager) getSystemService(getBaseContext().INPUT_METHOD_SERVICE);
    fb.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            // check if the Overlay should be visible. If this value is false, it is not shown -> show it.
            if(view.getVisibility() == View.INVISIBLE)
            {
                view.setVisibility(View.VISIBLE);
                keyboard.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
                Log.d("Overlay", "Klick");
            }
            else if(view.getVisibility() == View.VISIBLE)
            {
                view.setVisibility(View.INVISIBLE);
                keyboard.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
            }

Table columns, setting both min and max width with css

Tables work differently; sometimes counter-intuitively.

The solution is to use width on the table cells instead of max-width.

Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.

I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.

_x000D_
_x000D_
table {_x000D_
  width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  border: 0;_x000D_
  border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
  background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
  min-width: 10px;_x000D_
  width: 20px;_x000D_
  max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
  min-width: 40px;_x000D_
  width: 45px;_x000D_
  max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td class="a">A</td>_x000D_
    <td class="b">B</td>_x000D_
    <td class="c">C</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

CRON job to run on the last day of the month

Set up a cron job to run on the first day of the month. Then change the system's clock to be one day ahead.

How do you automatically set the focus to a textbox when a web page loads?

As a general advice, I would recommend not stealing the focus from the address bar. (Jeff already talked about that.)

Web page can take some time to load, which means that your focus change can occur some long time after the user typed the pae URL. Then he could have changed his mind and be back to url typing while you will be loading your page and stealing the focus to put it in your textbox.

That's the one and only reason that made me remove Google as my start page.

Of course, if you control the network (local network) or if the focus change is to solve an important usability issue, forget all I just said :)

How to check if a process is in hang state (Linux)

Is there any command in Linux through which i can know if the process is in hang state.

There is no command, but once I had to do a very dumb hack to accomplish something similar. I wrote a Perl script which periodically (every 30 seconds in my case):

  • run ps to find list of PIDs of the watched processes (along with exec time, etc)
  • loop over the PIDs
  • start gdb attaching to the process using its PID, dumping stack trace from it using thread apply all where, detaching from the process
  • a process was declared hung if:
    • its stack trace didn't change and time didn't change after 3 checks
    • its stack trace didn't change and time was indicating 100% CPU load after 3 checks
  • hung process was killed to give a chance for a monitoring application to restart the hung instance.

But that was very very very very crude hack, done to reach an about-to-be-missed deadline and it was removed a few days later, after a fix for the buggy application was finally installed.

Otherwise, as all other responders absolutely correctly commented, there is no way to find whether the process hung or not: simply because the hang might occur for way to many reasons, often bound to the application logic.

The only way is for application itself being capable of indicating whether it is alive or not. Simplest way might be for example a periodic log message "I'm alive".

Difference between "enqueue" and "dequeue"

These are terms usually used when describing a "FIFO" queue, that is "first in, first out". This works like a line. You decide to go to the movies. There is a long line to buy tickets, you decide to get into the queue to buy tickets, that is "Enqueue". at some point you are at the front of the line, and you get to buy a ticket, at which point you leave the line, that is "Dequeue".

Android Lint contentDescription warning

Non textual widgets need a content description in some ways to describe textually the image so that screens readers to be able to describe the user interface. You can ignore the property xmlns:tools="http://schemas.android.com/tools"
tools:ignore="contentDescription"
or define the property android:contentDescription="your description"

SQL Server: Is it possible to insert into two tables at the same time?

Before being able to do a multitable insert in Oracle, you could use a trick involving an insert into a view that had an INSTEAD OF trigger defined on it to perform the inserts. Can this be done in SQL Server?

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

I recently faced the issue and here's the solution.

No need to change the screen orientation parameter which you set at android manifest file.

Just add two folders in

res>values
as  res>values-v26 
and res>values-v27

Then copy your styles.xml and themes.xml file there.

and change the following parameters from TRUE to FALSE.

<item name="android:windowIsTranslucent">true</item>

<item name="android:windowIsTranslucent">false</item>

It will work.

A common bug of Android 8.0

Android Studio - Device is connected but 'offline'

Step 1: Turn off USB DEBUGGING in Developer Options

Step 2: Remove USB Cable

Step 3: Turn on USB Debugging(This rests USB Configurations)

Step 4: on Command Prompt enter adb kill-server and then adb start-server

Step 5: Connect the USB Cable

Step 6: Check Devices connected in Run in Android Studio(you should be able to see your device listed)

Step 7: If you want to continue running using the cable this would be good enough

(If you want to do Wireless Debugging continue with below step)

Step 8: type adb tcpip 5555. If no error is displayed remove USB Cable

Step 9: Look up IP Address of your phone from About abd then type adb connect xxx.vvv.b.n(your phone's IP)

Step 10: Check in Devices in Android Studio again and you shud see you r device in List of devices. If yes,

org.apache.jasper.JasperException: Unable to compile class for JSP:

This maybe caused by jar conflict. Remove the servlet-api.jar in your servlet/WEB-INF/ directory, %Tomcat home%/lib already have this lib.

Twitter Bootstrap dropdown menu

It's also possible to customise your bootstrap build by using:

http://twitter.github.com/bootstrap/customize.html

All the plugins are included by default.

Executing a batch script on Windows shutdown

Programatically this can be achieved with SCHTASKS:

SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=1074)]]" /EC Security /tn on_shutdown_normal /tr "c:\some.bat" 

SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=6006)]]" /EC Security /tn on_shutdown_6006 /tr "c:\some.bat" 

SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=6008)]]" /EC Security /tn on_shutdown_6008 /tr "c:\some.bat" 

Does Python have an ordered set?

So i also had a small list where i clearly had the possibility of introducing non-unique values.

I searched for the existence of a unique list of some sort, but then realized that testing the existence of the element before adding it works just fine.

if(not new_element in my_list):
    my_list.append(new_element)

I don't know if there are caveats to this simple approach, but it solves my problem.

Border around each cell in a range

I have a set of 15 subroutines I add to every Coded Excel Workbook I create and this is one of them. The following routine clears the area and creates a border.

Sample Call:

Call BoxIt(Range("A1:z25"))

Subroutine:

Sub BoxIt(aRng As Range)
On Error Resume Next

    With aRng

        'Clear existing
        .Borders.LineStyle = xlNone

        'Apply new borders
        .BorderAround xlContinuous, xlThick, 0
        With .Borders(xlInsideVertical)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .Weight = xlMedium
        End With
        With .Borders(xlInsideHorizontal)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .Weight = xlMedium
        End With
    End With

End Sub

Import regular CSS file in SCSS file?

If I am correct css is compatible with scss so you can change the extension of a css to scss and it should continue to work. Once you change the extension you can import it and it will be included in the file.

If you don't do that sass will use the css @import which is something you don't want.

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

Solution for Eclipse Luna:

  1. Right Click on maven web project
  2. Click 'Properties'menu
  3. Select 'Deployment Assembly' in left side of the popped window
  4. Click 'Add...' Button in right side of the popped up window
  5. Now appear one more popup window(New Assembly Directivies)
  6. Click 'Java Build path entries'
  7. Click 'Next' Button
  8. Click 'Finish' Button, now atomatically close New Assemby Directivies popup window
  9. Now click 'Apply' Button and Ok Button
  10. Run your webapplication

What are intent-filters in Android?

An intent filter is an expression in an app's manifest file that specifies the type of intents that the component would like to receive.

When you create an implicit intent, the Android system finds the appropriate component to start by comparing the contents of the intent to the intent filters declared in the manifest file of other apps on the device. If the intent matches an intent filter, the system starts that component and delivers it the Intent object.

AndroidManifest.xml

<activity android:name=".HelloWorld"
    android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <data android:scheme="http" android:host="androidium.org"/>
    </intent-filter>
</activity>

Launch HelloWorld

Intent intent = new Intent (Intent.ACTION_VIEW, Uri.parse("http://androidium.org"));
startActivity(intent);

What are the differences between type() and isinstance()?

Here's an example where isinstance achieves something that type cannot:

class Vehicle:
    pass

class Truck(Vehicle):
    pass

in this case, a truck object is a Vehicle, but you'll get this:

isinstance(Vehicle(), Vehicle)  # returns True
type(Vehicle()) == Vehicle      # returns True
isinstance(Truck(), Vehicle)    # returns True
type(Truck()) == Vehicle        # returns False, and this probably won't be what you want.

In other words, isinstance is true for subclasses, too.

Also see: How to compare type of an object in Python?

Change :hover CSS properties with JavaScript

I'd recommend to replace all :hover properties to :active when you detect that device supports touch. Just call this function when you do so as touch()

   function touch() {
      if ('ontouchstart' in document.documentElement) {
        for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
          var sheet = document.styleSheets[sheetI];
          if (sheet.cssRules) {
            for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
              var rule = sheet.cssRules[ruleI];

              if (rule.selectorText) {
                rule.selectorText = rule.selectorText.replace(':hover', ':active');
              }
            }
          }
        }
      }
    }

How do I convert datetime.timedelta to minutes, hours in Python?

datetime.timedelta(hours=1, minutes=10)
#python 2.7

How to automatically insert a blank row after a group of data

Select your array, including column labels, DATA > Outline -Subtotal, At each change in: column1, Use function: Count, Add subtotal to: column3, check Replace current subtotals and Summary below data, OK.

Filter and select for Column1, Text Filters, Contains..., Count, OK. Select all visible apart from the labels and delete contents. Remove filter and, if desired, ungroup rows.

How to prevent tensorflow from allocating the totality of a GPU memory?

Tensorflow 2.0 Beta and (probably) beyond

The API changed again. It can be now found in:

tf.config.experimental.set_memory_growth(
    device,
    enable
)

Aliases:

  • tf.compat.v1.config.experimental.set_memory_growth
  • tf.compat.v2.config.experimental.set_memory_growth

References:

See also: Tensorflow - Use a GPU: https://www.tensorflow.org/guide/gpu

for Tensorflow 2.0 Alpha see: this answer

Cannot start MongoDB as a service

Check if your mongod.cfg file has tabs in it. Removing tabs solved it for me!

Put content in HttpResponseMessage object?

For a string specifically, the quickest way is to use the StringContent constructor

response.Content = new StringContent("Your response text");

There are a number of additional HttpContent class descendants for other common scenarios.

Javascript - validation, numbers only

This one worked for me :

function validateForm(){

  var z = document.forms["myForm"]["num"].value;

  if(!/^[0-9]+$/.test(z)){
    alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
  }

}

Regex: match word that ends with "Id"

I would use
\b[A-Za-z]*Id\b
The \b matches the beginning and end of a word i.e. space, tab or newline, or the beginning or end of a string.

The [A-Za-z] will match any letter, and the * means that 0+ get matched. Finally there is the Id.

Note that this will match words that have capital letters in the middle such as 'teStId'.

I use http://www.regular-expressions.info/ for regex reference

How to implement a binary search tree in Python?

The problem, or at least one problem with your code is here:-

def insert(self,node,someNumber):
    if node is None:
        node = Node(someNumber)
    else:
        if node.data > someNumber:
            self.insert(node.rchild,someNumber)
        else:
            self.insert(node.rchild, someNumber)
    return

You see the statement "if node.data > someNumber:" and the associated "else:" statement both have the same code after them. i.e you do the same thing whether the if statement is true or false.

I'd suggest you probably intended to do different things here, perhaps one of these should say self.insert(node.lchild, someNumber) ?

Which Radio button in the group is checked?

The GroupBox has a Validated event for this purpose, if you are using WinForms.

private void grpBox_Validated(object sender, EventArgs e)
    {
        GroupBox g = sender as GroupBox;
        var a = from RadioButton r in g.Controls
                 where r.Checked == true select r.Name;
        strChecked = a.First();
     }

Why should C++ programmers minimize use of 'new'?

To a great extent, that's someone elevating their own weaknesses to a general rule. There's nothing wrong per se with creating objects using the new operator. What there is some argument for is that you have to do so with some discipline: if you create an object you need to make sure it's going to be destroyed.

The easiest way of doing that is to create the object in automatic storage, so C++ knows to destroy it when it goes out of scope:

 {
    File foo = File("foo.dat");

    // do things

 }

Now, observe that when you fall off that block after the end-brace, foo is out of scope. C++ will call its dtor automatically for you. Unlike Java, you don't need to wait for the GC to find it.

Had you written

 {
     File * foo = new File("foo.dat");

you would want to match it explicitly with

     delete foo;
  }

or even better, allocate your File * as a "smart pointer". If you aren't careful about that it can lead to leaks.

The answer itself makes the mistaken assumption that if you don't use new you don't allocate on the heap; in fact, in C++ you don't know that. At most, you know that a small amout of memory, say one pointer, is certainly allocated on the stack. However, consider if the implementation of File is something like

  class File {
    private:
      FileImpl * fd;
    public:
      File(String fn){ fd = new FileImpl(fn);}

then FileImpl will still be allocated on the stack.

And yes, you'd better be sure to have

     ~File(){ delete fd ; }

in the class as well; without it, you'll leak memory from the heap even if you didn't apparently allocate on the heap at all.

GET and POST methods with the same Action name in the same Controller

To answer your specific question, you cannot have two methods with the same name and the same arguments in a single class; using the HttpGet and HttpPost attributes doesn't distinguish the methods.

To address this, I'd typically include the view model for the form you're posting:

public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        Some Code--Some Code---Some Code
        return View();
    }

    [HttpPost]
    public ActionResult Index(formViewModel model)
    {
        do work on model --
        return View();
    }

}

How do I update pip itself from inside my virtual environment?

Open Command Prompt with Administrator Permissions, and repeat the command:

python -m pip install --upgrade pip

Comparing two strings in C?

You need to use strcmp:

strcmp(namet2, nameIt2)

How does the Spring @ResponseBody annotation work?

Further to this, the return type is determined by

  1. What the HTTP Request says it wants - in its Accept header. Try looking at the initial request as see what Accept is set to.

  2. What HttpMessageConverters Spring sets up. Spring MVC will setup converters for XML (using JAXB) and JSON if Jackson libraries are on he classpath.

If there is a choice it picks one - in this example, it happens to be JSON.

This is covered in the course notes. Look for the notes on Message Convertors and Content Negotiation.

How to make a div with a circular shape?

By using a border-radius of 50% you can make a circle. Here is an example:

CSS:

#exampleCircle{
    width: 500px;
    height: 500px;
    background: red;
    border-radius: 50%;
}

HTML:

<div id = "exampleCircle"></div>

How can I easily add storage to a VirtualBox machine with XP installed?

The problem is that the file system on that disk was created when the disk had a certain geometry and you must modify it (while your OS is running on it).

So yes, making the virtual hard disk bigger is not a big issue. The issue is to make the new space available to your OS. To do that, you need tools like parted (Linux) or Partition Magic (Windows).

How to delete an SVN project from SVN repository

Disposing of a Working Copy

Subversion doesn't track either the state or the existence of working copies on the server, so there's no server overhead to keeping working copies around. Likewise, there's no need to let the server know that you're going to delete a working copy.

If you're likely to use a working copy again, there's nothing wrong with just leaving it on disk until you're ready to use it again, at which point all it takes is an svn update to bring it up to date and ready for use.

However, if you're definitely not going to use a working copy again, you can safely delete the entire thing using whatever directory removal capabilities your operating system offers. We recommend that before you do so you run svn status and review any files listed in its output that are prefixed with a ? to make certain that they're not of importance.

from: http://svnbook.red-bean.com/en/1.7/svn.tour.cleanup.html

CSS content property: is it possible to insert HTML instead of Text?

Unfortunately, this is not possible. Per the spec:

Generated content does not alter the document tree. In particular, it is not fed back to the document language processor (e.g., for reparsing).

In other words, for string values this means the value is always treated literally. It is never interpreted as markup, regardless of the document language in use.

As an example, using the given CSS with the following HTML:

<h1 class="header">Title</h1>

... will result in the following output:

<a href="#top">Back</a>Title

Inconsistent Accessibility: Parameter type is less accessible than method

Constructor of public class clients is public but it has a parameter of type ACTInterface that is private (it is nested in a class?). You can't do that. You need to make ACTInterface at least as accessible as clients.

How to change default language for SQL Server?

Using SQL Server Management Studio

To configure the default language option

  1. In Object Explorer, right-click a server and select Properties.
  2. Click the Misc server settings node.
  3. In the Default language for users box, choose the language in which Microsoft SQL Server should display system messages. The default language is English.

Using Transact-SQL

To configure the default language option

  1. Connect to the Database Engine.
  2. From the Standard bar, click New Query.
  3. Copy and paste the following example into the query window and click Execute.

This example shows how to use sp_configure to configure the default language option to French

USE AdventureWorks2012 ;
GO
EXEC sp_configure 'default language', 2 ;
GO
RECONFIGURE ;
GO

The 33 languages of SQL Server

| LANGID |        ALIAS        |
|--------|---------------------|
|    0   | English             |
|    1   | German              |
|    2   | French              |
|    3   | Japanese            |
|    4   | Danish              |
|    5   | Spanish             |
|    6   | Italian             |
|    7   | Dutch               |
|    8   | Norwegian           |
|    9   | Portuguese          |
|   10   | Finnish             |
|   11   | Swedish             |
|   12   | Czech               |
|   13   | Hungarian           |
|   14   | Polish              |
|   15   | Romanian            |
|   16   | Croatian            |
|   17   | Slovak              |
|   18   | Slovenian           |
|   19   | Greek               |
|   20   | Bulgarian           |
|   21   | Russian             |
|   22   | Turkish             |
|   23   | British English     |
|   24   | Estonian            |
|   25   | Latvian             |
|   26   | Lithuanian          |
|   27   | Brazilian           |
|   28   | Traditional Chinese |
|   29   | Korean              |
|   30   | Simplified Chinese  |
|   31   | Arabic              |
|   32   | Thai                |
|   33   | Bokmål              |

Java Scanner String input

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

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

Hiding an Excel worksheet with VBA

To hide from the UI, use Format > Sheet > Hide

To hide programatically, use the Visible property of the Worksheet object. If you do it programatically, you can set the sheet as "very hidden", which means it cannot be unhidden through the UI.

ActiveWorkbook.Sheets("Name").Visible = xlSheetVeryHidden 
' or xlSheetHidden or xlSheetVisible

You can also set the Visible property through the properties pane for the worksheet in the VBA IDE (ALT+F11).

Functions are not valid as a React child. This may happen if you return a Component instead of from render

You are using it as a regular component, but it's actually a function that returns a component.

Try doing something like this:

const NewComponent = NewHOC(Movie)

And you will use it like this:

<NewComponent someProp="someValue" />

Here is a running example:

_x000D_
_x000D_
const NewHOC = (PassedComponent) => {
  return class extends React.Component {
    render() {
      return (
        <div>
          <PassedComponent {...this.props} />
        </div>
      )
    }
  }
}

const Movie = ({name}) => <div>{name}</div>

const NewComponent = NewHOC(Movie);

function App() {
  return (
    <div>
      <NewComponent name="Kill Bill" />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"/>
_x000D_
_x000D_
_x000D_

So basically NewHOC is just a function that accepts a component and returns a new component that renders the component passed in. We usually use this pattern to enhance components and share logic or data.

You can read about HOCS in the docs and I also recommend reading about the difference between react elements and components

I wrote an article about the different ways and patterns of sharing logic in react.

Windows git "warning: LF will be replaced by CRLF", is that warning tail backward?

--Update on 9th July---

Removed "It is correct and accurate" as commented by @mgiuca

======

NO. It is NOT talking about your files currently with CRLF. It is instead talking about files with LF.

It should read:

warning: (If you check it out/or clone to another folder with your current core.autocrlf configuration,)LF will be replaced by CRLF

The file will have its original line endings in your (current) working directory.

This picture should explain what it means. enter image description here

How do I use method overloading in Python?

I just came across overloading.py (function overloading for Python 3) for anybody who may be interested.

From the linked repository's README file:

overloading is a module that provides function dispatching based on the types and number of runtime arguments.

When an overloaded function is invoked, the dispatcher compares the supplied arguments to available function signatures and calls the implementation that provides the most accurate match.

Features

Function validation upon registration and detailed resolution rules guarantee a unique, well-defined outcome at runtime. Implements function resolution caching for great performance. Supports optional parameters (default values) in function signatures. Evaluates both positional and keyword arguments when resolving the best match. Supports fallback functions and execution of shared code. Supports argument polymorphism. Supports classes and inheritance, including classmethods and staticmethods.

Specify JDK for Maven to use

compile:compile has a user property that allows you to specify a path to the javac.

Note that this user property only works when fork is true which is false by default.

$ mvn -Dmaven.compiler.fork=true -Dmaven.compiler.executable=/path/to/the/javac compile

You might have to double quote the value if it contains spaces.

> mvn -Dmaven.compiler.fork=true -Dmaven.compiler.executable="C:\...\javac" compile

See also Maven custom properties precedence.

PHP convert date format dd/mm/yyyy => yyyy-mm-dd

Here's another solution not using date(). not so smart:)

$var = '20/04/2012';
echo implode("-", array_reverse(explode("/", $var)));

CSS Input field text color of inputted text

I always do input prompts, like this:

    <input style="color: #C0C0C0;" value="[email protected]" 
    onfocus="this.value=''; this.style.color='#000000'">

Of course, if your user fills in the field, changes focus and comes back to the field, the field will once again be cleared. If you do it like that, be sure that's what you want. You can make it a one time thing by setting a semaphore, like this:

    <script language = "text/Javascript"> 
    cleared[0] = cleared[1] = cleared[2] = 0; //set a cleared flag for each field
    function clearField(t){                   //declaring the array outside of the
    if(! cleared[t.id]){                      // function makes it static and global
        cleared[t.id] = 1;  // you could use true and false, but that's more typing
        t.value='';         // with more chance of typos
        t.style.color='#000000';
        }
    }
    </script>

Your <input> field then looks like this:

    <input id = 0; style="color: #C0C0C0;" value="[email protected]" 
    onfocus=clearField(this)>

Read file-contents into a string in C++

There should be no \0 in text files.

#include<iostream>
#include<fstream>

using namespace std;

int main(){
  fstream f(FILENAME, fstream::in );
  string s;
  getline( f, s, '\0');

  cout << s << endl;
  f.close();
}

Convert a char to upper case using regular expressions (EditPad Pro)

You can also capitalize the first letter of the match using \I1 and \I2 etc instead of $1 and $2.

What is the list of supported languages/locales on Android?

List of locales supported as of API 22 (Android 5.1). Obtained from a Nexus 5 with locale set to "English (United States)" (locale affects the DisplayName output).

for (Locale locale : Locale.getAvailableLocales()) {
    Log.d("LOCALES", locale.getLanguage() + "_" + locale.getCountry() + " [" + locale.getDisplayName() + "]");
}


    af_ [Afrikaans]
    af_NA [Afrikaans (Namibia)]
    af_ZA [Afrikaans (South Africa)]
    agq_ [Aghem]
    agq_CM [Aghem (Cameroon)]
    ak_ [Akan]
    ak_GH [Akan (Ghana)]
    am_ [Amharic]
    am_ET [Amharic (Ethiopia)]
    ar_ [Arabic]
    ar_001 [Arabic (World)]
    ar_AE [Arabic (United Arab Emirates)]
    ar_BH [Arabic (Bahrain)]
    ar_DJ [Arabic (Djibouti)]
    ar_DZ [Arabic (Algeria)]
    ar_EG [Arabic (Egypt)]
    ar_EH [Arabic (Western Sahara)]
    ar_ER [Arabic (Eritrea)]
    ar_IL [Arabic (Israel)]
    ar_IQ [Arabic (Iraq)]
    ar_JO [Arabic (Jordan)]
    ar_KM [Arabic (Comoros)]
    ar_KW [Arabic (Kuwait)]
    ar_LB [Arabic (Lebanon)]
    ar_LY [Arabic (Libya)]
    ar_MA [Arabic (Morocco)]
    ar_MR [Arabic (Mauritania)]
    ar_OM [Arabic (Oman)]
    ar_PS [Arabic (Palestine)]
    ar_QA [Arabic (Qatar)]
    ar_SA [Arabic (Saudi Arabia)]
    ar_SD [Arabic (Sudan)]
    ar_SO [Arabic (Somalia)]
    ar_SS [Arabic (South Sudan)]
    ar_SY [Arabic (Syria)]
    ar_TD [Arabic (Chad)]
    ar_TN [Arabic (Tunisia)]
    ar_YE [Arabic (Yemen)]
    as_ [Assamese]
    as_IN [Assamese (India)]
    asa_ [Asu]
    asa_TZ [Asu (Tanzania)]
    az_ [Azerbaijani]
    az_ [Azerbaijani (Cyrillic)]
    az_AZ [Azerbaijani (Cyrillic,Azerbaijan)]
    az_ [Azerbaijani (Latin)]
    az_AZ [Azerbaijani (Latin,Azerbaijan)]
    bas_ [Basaa]
    bas_CM [Basaa (Cameroon)]
    be_ [Belarusian]
    be_BY [Belarusian (Belarus)]
    bem_ [Bemba]
    bem_ZM [Bemba (Zambia)]
    bez_ [Bena]
    bez_TZ [Bena (Tanzania)]
    bg_ [Bulgarian]
    bg_BG [Bulgarian (Bulgaria)]
    bm_ [Bambara]
    bm_ML [Bambara (Mali)]
    bn_ [Bengali]
    bn_BD [Bengali (Bangladesh)]
    bn_IN [Bengali (India)]
    bo_ [Tibetan]
    bo_CN [Tibetan (China)]
    bo_IN [Tibetan (India)]
    br_ [Breton]
    br_FR [Breton (France)]
    brx_ [Bodo]
    brx_IN [Bodo (India)]
    bs_ [Bosnian]
    bs_ [Bosnian (Cyrillic)]
    bs_BA [Bosnian (Cyrillic,Bosnia and Herzegovina)]
    bs_ [Bosnian (Latin)]
    bs_BA [Bosnian (Latin,Bosnia and Herzegovina)]
    ca_ [Catalan]
    ca_AD [Catalan (Andorra)]
    ca_ES [Catalan (Spain)]
    ca_FR [Catalan (France)]
    ca_IT [Catalan (Italy)]
    cgg_ [Chiga]
    cgg_UG [Chiga (Uganda)]
    chr_ [Cherokee]
    chr_US [Cherokee (United States)]
    cs_ [Czech]
    cs_CZ [Czech (Czech Republic)]
    cy_ [Welsh]
    cy_GB [Welsh (United Kingdom)]
    da_ [Danish]
    da_DK [Danish (Denmark)]
    da_GL [Danish (Greenland)]
    dav_ [Taita]
    dav_KE [Taita (Kenya)]
    de_ [German]
    de_AT [German (Austria)]
    de_BE [German (Belgium)]
    de_CH [German (Switzerland)]
    de_DE [German (Germany)]
    de_LI [German (Liechtenstein)]
    de_LU [German (Luxembourg)]
    dje_ [Zarma]
    dje_NE [Zarma (Niger)]
    dua_ [Duala]
    dua_CM [Duala (Cameroon)]
    dyo_ [Jola-Fonyi]
    dyo_SN [Jola-Fonyi (Senegal)]
    dz_ [Dzongkha]
    dz_BT [Dzongkha (Bhutan)]
    ebu_ [Embu]
    ebu_KE [Embu (Kenya)]
    ee_ [Ewe]
    ee_GH [Ewe (Ghana)]
    ee_TG [Ewe (Togo)]
    el_ [Greek]
    el_CY [Greek (Cyprus)]
    el_GR [Greek (Greece)]
    en_ [English]
    en_001 [English (World)]
    en_150 [English (Europe)]
    en_AG [English (Antigua and Barbuda)]
    en_AI [English (Anguilla)]
    en_AS [English (American Samoa)]
    en_AU [English (Australia)]
    en_BB [English (Barbados)]
    en_BE [English (Belgium)]
    en_BM [English (Bermuda)]
    en_BS [English (Bahamas)]
    en_BW [English (Botswana)]
    en_BZ [English (Belize)]
    en_CA [English (Canada)]
    en_CC [English (Cocos (Keeling) Islands)]
    en_CK [English (Cook Islands)]
    en_CM [English (Cameroon)]
    en_CX [English (Christmas Island)]
    en_DG [English (Diego Garcia)]
    en_DM [English (Dominica)]
    en_ER [English (Eritrea)]
    en_FJ [English (Fiji)]
    en_FK [English (Falkland Islands (Islas Malvinas))]
    en_FM [English (Micronesia)]
    en_GB [English (United Kingdom)]
    en_GD [English (Grenada)]
    en_GG [English (Guernsey)]
    en_GH [English (Ghana)]
    en_GI [English (Gibraltar)]
    en_GM [English (Gambia)]
    en_GU [English (Guam)]
    en_GY [English (Guyana)]
    en_HK [English (Hong Kong)]
    en_IE [English (Ireland)]
    en_IM [English (Isle of Man)]
    en_IN [English (India)]
    en_IO [English (British Indian Ocean Territory)]
    en_JE [English (Jersey)]
    en_JM [English (Jamaica)]
    en_KE [English (Kenya)]
    en_KI [English (Kiribati)]
    en_KN [English (Saint Kitts and Nevis)]
    en_KY [English (Cayman Islands)]
    en_LC [English (Saint Lucia)]
    en_LR [English (Liberia)]
    en_LS [English (Lesotho)]
    en_MG [English (Madagascar)]
    en_MH [English (Marshall Islands)]
    en_MO [English (Macau)]
    en_MP [English (Northern Mariana Islands)]
    en_MS [English (Montserrat)]
    en_MT [English (Malta)]
    en_MU [English (Mauritius)]
    en_MW [English (Malawi)]
    en_NA [English (Namibia)]
    en_NF [English (Norfolk Island)]
    en_NG [English (Nigeria)]
    en_NR [English (Nauru)]
    en_NU [English (Niue)]
    en_NZ [English (New Zealand)]
    en_PG [English (Papua New Guinea)]
    en_PH [English (Philippines)]
    en_PK [English (Pakistan)]
    en_PN [English (Pitcairn Islands)]
    en_PR [English (Puerto Rico)]
    en_PW [English (Palau)]
    en_RW [English (Rwanda)]
    en_SB [English (Solomon Islands)]
    en_SC [English (Seychelles)]
    en_SD [English (Sudan)]
    en_SG [English (Singapore)]
    en_SH [English (Saint Helena)]
    en_SL [English (Sierra Leone)]
    en_SS [English (South Sudan)]
    en_SX [English (Sint Maarten)]
    en_SZ [English (Swaziland)]
    en_TC [English (Turks and Caicos Islands)]
    en_TK [English (Tokelau)]
    en_TO [English (Tonga)]
    en_TT [English (Trinidad and Tobago)]
    en_TV [English (Tuvalu)]
    en_TZ [English (Tanzania)]
    en_UG [English (Uganda)]
    en_UM [English (U.S. Outlying Islands)]
    en_US [English (United States)]
    en_US [English (United States,Computer)]
    en_VC [English (St. Vincent & Grenadines)]
    en_VG [English (British Virgin Islands)]
    en_VI [English (U.S. Virgin Islands)]
    en_VU [English (Vanuatu)]
    en_WS [English (Samoa)]
    en_ZA [English (South Africa)]
    en_ZM [English (Zambia)]
    en_ZW [English (Zimbabwe)]
    eo_ [Esperanto]
    es_ [Spanish]
    es_419 [Spanish (Latin America)]
    es_AR [Spanish (Argentina)]
    es_BO [Spanish (Bolivia)]
    es_CL [Spanish (Chile)]
    es_CO [Spanish (Colombia)]
    es_CR [Spanish (Costa Rica)]
    es_CU [Spanish (Cuba)]
    es_DO [Spanish (Dominican Republic)]
    es_EA [Spanish (Ceuta and Melilla)]
    es_EC [Spanish (Ecuador)]
    es_ES [Spanish (Spain)]
    es_GQ [Spanish (Equatorial Guinea)]
    es_GT [Spanish (Guatemala)]
    es_HN [Spanish (Honduras)]
    es_IC [Spanish (Canary Islands)]
    es_MX [Spanish (Mexico)]
    es_NI [Spanish (Nicaragua)]
    es_PA [Spanish (Panama)]
    es_PE [Spanish (Peru)]
    es_PH [Spanish (Philippines)]
    es_PR [Spanish (Puerto Rico)]
    es_PY [Spanish (Paraguay)]
    es_SV [Spanish (El Salvador)]
    es_US [Spanish (United States)]
    es_UY [Spanish (Uruguay)]
    es_VE [Spanish (Venezuela)]
    et_ [Estonian]
    et_EE [Estonian (Estonia)]
    eu_ [Basque]
    eu_ES [Basque (Spain)]
    ewo_ [Ewondo]
    ewo_CM [Ewondo (Cameroon)]
    fa_ [Persian]
    fa_AF [Persian (Afghanistan)]
    fa_IR [Persian (Iran)]
    ff_ [Fulah]
    ff_SN [Fulah (Senegal)]
    fi_ [Finnish]
    fi_FI [Finnish (Finland)]
    fil_ [Filipino]
    fil_PH [Filipino (Philippines)]
    fo_ [Faroese]
    fo_FO [Faroese (Faroe Islands)]
    fr_ [French]
    fr_BE [French (Belgium)]
    fr_BF [French (Burkina Faso)]
    fr_BI [French (Burundi)]
    fr_BJ [French (Benin)]
    fr_BL [French (Saint Barthélemy)]
    fr_CA [French (Canada)]
    fr_CD [French (Congo (DRC))]
    fr_CF [French (Central African Republic)]
    fr_CG [French (Congo (Republic))]
    fr_CH [French (Switzerland)]
    fr_CI [French (Côte d’Ivoire)]
    fr_CM [French (Cameroon)]
    fr_DJ [French (Djibouti)]
    fr_DZ [French (Algeria)]
    fr_FR [French (France)]
    fr_GA [French (Gabon)]
    fr_GF [French (French Guiana)]
    fr_GN [French (Guinea)]
    fr_GP [French (Guadeloupe)]
    fr_GQ [French (Equatorial Guinea)]
    fr_HT [French (Haiti)]
    fr_KM [French (Comoros)]
    fr_LU [French (Luxembourg)]
    fr_MA [French (Morocco)]
    fr_MC [French (Monaco)]
    fr_MF [French (Saint Martin)]
    fr_MG [French (Madagascar)]
    fr_ML [French (Mali)]
    fr_MQ [French (Martinique)]
    fr_MR [French (Mauritania)]
    fr_MU [French (Mauritius)]
    fr_NC [French (New Caledonia)]
    fr_NE [French (Niger)]
    fr_PF [French (French Polynesia)]
    fr_PM [French (Saint Pierre and Miquelon)]
    fr_RE [French (Réunion)]
    fr_RW [French (Rwanda)]
    fr_SC [French (Seychelles)]
    fr_SN [French (Senegal)]
    fr_SY [French (Syria)]
    fr_TD [French (Chad)]
    fr_TG [French (Togo)]
    fr_TN [French (Tunisia)]
    fr_VU [French (Vanuatu)]
    fr_WF [French (Wallis and Futuna)]
    fr_YT [French (Mayotte)]
    ga_ [Irish]
    ga_IE [Irish (Ireland)]
    gl_ [Galician]
    gl_ES [Galician (Spain)]
    gsw_ [Swiss German]
    gsw_CH [Swiss German (Switzerland)]
    gsw_LI [Swiss German (Liechtenstein)]
    gu_ [Gujarati]
    gu_IN [Gujarati (India)]
    guz_ [Gusii]
    guz_KE [Gusii (Kenya)]
    gv_ [Manx]
    gv_IM [Manx (Isle of Man)]
    ha_ [Hausa]
    ha_ [Hausa (Latin)]
    ha_GH [Hausa (Latin,Ghana)]
    ha_NE [Hausa (Latin,Niger)]
    ha_NG [Hausa (Latin,Nigeria)]
    haw_ [Hawaiian]
    haw_US [Hawaiian (United States)]
    iw_ [Hebrew]
    iw_IL [Hebrew (Israel)]
    hi_ [Hindi]
    hi_IN [Hindi (India)]
    hr_ [Croatian]
    hr_BA [Croatian (Bosnia and Herzegovina)]
    hr_HR [Croatian (Croatia)]
    hu_ [Hungarian]
    hu_HU [Hungarian (Hungary)]
    hy_ [Armenian]
    hy_AM [Armenian (Armenia)]
    in_ [Indonesian]
    in_ID [Indonesian (Indonesia)]
    ig_ [Igbo]
    ig_NG [Igbo (Nigeria)]
    ii_ [Sichuan Yi]
    ii_CN [Sichuan Yi (China)]
    is_ [Icelandic]
    is_IS [Icelandic (Iceland)]
    it_ [Italian]
    it_CH [Italian (Switzerland)]
    it_IT [Italian (Italy)]
    it_SM [Italian (San Marino)]
    ja_ [Japanese]
    ja_JP [Japanese (Japan)]
    jgo_ [Ngomba]
    jgo_CM [Ngomba (Cameroon)]
    jmc_ [Machame]
    jmc_TZ [Machame (Tanzania)]
    ka_ [Georgian]
    ka_GE [Georgian (Georgia)]
    kab_ [Kabyle]
    kab_DZ [Kabyle (Algeria)]
    kam_ [Kamba]
    kam_KE [Kamba (Kenya)]
    kde_ [Makonde]
    kde_TZ [Makonde (Tanzania)]
    kea_ [Kabuverdianu]
    kea_CV [Kabuverdianu (Cape Verde)]
    khq_ [Koyra Chiini]
    khq_ML [Koyra Chiini (Mali)]
    ki_ [Kikuyu]
    ki_KE [Kikuyu (Kenya)]
    kk_ [Kazakh]
    kk_ [Kazakh (Cyrillic)]
    kk_KZ [Kazakh (Cyrillic,Kazakhstan)]
    kkj_ [Kako]
    kkj_CM [Kako (Cameroon)]
    kl_ [Kalaallisut]
    kl_GL [Kalaallisut (Greenland)]
    kln_ [Kalenjin]
    kln_KE [Kalenjin (Kenya)]
    km_ [Khmer]
    km_KH [Khmer (Cambodia)]
    kn_ [Kannada]
    kn_IN [Kannada (India)]
    ko_ [Korean]
    ko_KP [Korean (North Korea)]
    ko_KR [Korean (South Korea)]
    kok_ [Konkani]
    kok_IN [Konkani (India)]
    ks_ [Kashmiri]
    ks_ [Kashmiri (Arabic)]
    ks_IN [Kashmiri (Arabic,India)]
    ksb_ [Shambala]
    ksb_TZ [Shambala (Tanzania)]
    ksf_ [Bafia]
    ksf_CM [Bafia (Cameroon)]
    kw_ [Cornish]
    kw_GB [Cornish (United Kingdom)]
    ky_ [Kyrgyz]
    ky_ [Kyrgyz (Cyrillic)]
    ky_KG [Kyrgyz (Cyrillic,Kyrgyzstan)]
    lag_ [Langi]
    lag_TZ [Langi (Tanzania)]
    lg_ [Ganda]
    lg_UG [Ganda (Uganda)]
    lkt_ [Lakota]
    lkt_US [Lakota (United States)]
    ln_ [Lingala]
    ln_AO [Lingala (Angola)]
    ln_CD [Lingala (Congo (DRC))]
    ln_CF [Lingala (Central African Republic)]
    ln_CG [Lingala (Congo (Republic))]
    lo_ [Lao]
    lo_LA [Lao (Laos)]
    lt_ [Lithuanian]
    lt_LT [Lithuanian (Lithuania)]
    lu_ [Luba-Katanga]
    lu_CD [Luba-Katanga (Congo (DRC))]
    luo_ [Luo]
    luo_KE [Luo (Kenya)]
    luy_ [Luyia]
    luy_KE [Luyia (Kenya)]
    lv_ [Latvian]
    lv_LV [Latvian (Latvia)]
    mas_ [Masai]
    mas_KE [Masai (Kenya)]
    mas_TZ [Masai (Tanzania)]
    mer_ [Meru]
    mer_KE [Meru (Kenya)]
    mfe_ [Morisyen]
    mfe_MU [Morisyen (Mauritius)]
    mg_ [Malagasy]
    mg_MG [Malagasy (Madagascar)]
    mgh_ [Makhuwa-Meetto]
    mgh_MZ [Makhuwa-Meetto (Mozambique)]
    mgo_ [Meta']
    mgo_CM [Meta' (Cameroon)]
    mk_ [Macedonian]
    mk_MK [Macedonian (Macedonia (FYROM))]
    ml_ [Malayalam]
    ml_IN [Malayalam (India)]
    mn_ [Mongolian]
    mn_ [Mongolian (Cyrillic)]
    mn_MN [Mongolian (Cyrillic,Mongolia)]
    mr_ [Marathi]
    mr_IN [Marathi (India)]
    ms_ [Malay]
    ms_ [Malay (Latin)]
    ms_BN [Malay (Latin,Brunei)]
    ms_MY [Malay (Latin,Malaysia)]
    ms_SG [Malay (Latin,Singapore)]
    mt_ [Maltese]
    mt_MT [Maltese (Malta)]
    mua_ [Mundang]
    mua_CM [Mundang (Cameroon)]
    my_ [Burmese]
    my_MM [Burmese (Myanmar (Burma))]
    naq_ [Nama]
    naq_NA [Nama (Namibia)]
    nb_ [Norwegian Bokmål]
    nb_NO [Norwegian Bokmål (Norway)]
    nb_SJ [Norwegian Bokmål (Svalbard and Jan Mayen)]
    nd_ [North Ndebele]
    nd_ZW [North Ndebele (Zimbabwe)]
    ne_ [Nepali]
    ne_IN [Nepali (India)]
    ne_NP [Nepali (Nepal)]
    nl_ [Dutch]
    nl_AW [Dutch (Aruba)]
    nl_BE [Dutch (Belgium)]
    nl_BQ [Dutch (Caribbean Netherlands)]
    nl_CW [Dutch (Curaçao)]
    nl_NL [Dutch (Netherlands)]
    nl_SR [Dutch (Suriname)]
    nl_SX [Dutch (Sint Maarten)]
    nmg_ [Kwasio]
    nmg_CM [Kwasio (Cameroon)]
    nn_ [Norwegian Nynorsk]
    nn_NO [Norwegian Nynorsk (Norway)]
    nnh_ [Ngiemboon]
    nnh_CM [Ngiemboon (Cameroon)]
    nus_ [Nuer]
    nus_SD [Nuer (Sudan)]
    nyn_ [Nyankole]
    nyn_UG [Nyankole (Uganda)]
    om_ [Oromo]
    om_ET [Oromo (Ethiopia)]
    om_KE [Oromo (Kenya)]
    or_ [Oriya]
    or_IN [Oriya (India)]
    pa_ [Punjabi]
    pa_ [Punjabi (Arabic)]
    pa_PK [Punjabi (Arabic,Pakistan)]
    pa_ [Punjabi (Gurmukhi)]
    pa_IN [Punjabi (Gurmukhi,India)]
    pl_ [Polish]
    pl_PL [Polish (Poland)]
    ps_ [Pashto]
    ps_AF [Pashto (Afghanistan)]
    pt_ [Portuguese]
    pt_AO [Portuguese (Angola)]
    pt_BR [Portuguese (Brazil)]
    pt_CV [Portuguese (Cape Verde)]
    pt_GW [Portuguese (Guinea-Bissau)]
    pt_MO [Portuguese (Macau)]
    pt_MZ [Portuguese (Mozambique)]
    pt_PT [Portuguese (Portugal)]
    pt_ST [Portuguese (São Tomé and Príncipe)]
    pt_TL [Portuguese (Timor-Leste)]
    rm_ [Romansh]
    rm_CH [Romansh (Switzerland)]
    rn_ [Rundi]
    rn_BI [Rundi (Burundi)]
    ro_ [Romanian]
    ro_MD [Romanian (Moldova)]
    ro_RO [Romanian (Romania)]
    rof_ [Rombo]
    rof_TZ [Rombo (Tanzania)]
    ru_ [Russian]
    ru_BY [Russian (Belarus)]
    ru_KG [Russian (Kyrgyzstan)]
    ru_KZ [Russian (Kazakhstan)]
    ru_MD [Russian (Moldova)]
    ru_RU [Russian (Russia)]
    ru_UA [Russian (Ukraine)]
    rw_ [Kinyarwanda]
    rw_RW [Kinyarwanda (Rwanda)]
    rwk_ [Rwa]
    rwk_TZ [Rwa (Tanzania)]
    saq_ [Samburu]
    saq_KE [Samburu (Kenya)]
    sbp_ [Sangu]
    sbp_TZ [Sangu (Tanzania)]
    seh_ [Sena]
    seh_MZ [Sena (Mozambique)]
    ses_ [Koyraboro Senni]
    ses_ML [Koyraboro Senni (Mali)]
    sg_ [Sango]
    sg_CF [Sango (Central African Republic)]
    shi_ [Tachelhit]
    shi_ [Tachelhit (Latin)]
    shi_MA [Tachelhit (Latin,Morocco)]
    shi_ [Tachelhit (Tifinagh)]
    shi_MA [Tachelhit (Tifinagh,Morocco)]
    si_ [Sinhala]
    si_LK [Sinhala (Sri Lanka)]
    sk_ [Slovak]
    sk_SK [Slovak (Slovakia)]
    sl_ [Slovenian]
    sl_SI [Slovenian (Slovenia)]
    sn_ [Shona]
    sn_ZW [Shona (Zimbabwe)]
    so_ [Somali]
    so_DJ [Somali (Djibouti)]
    so_ET [Somali (Ethiopia)]
    so_KE [Somali (Kenya)]
    so_SO [Somali (Somalia)]
    sq_ [Albanian]
    sq_AL [Albanian (Albania)]
    sq_MK [Albanian (Macedonia (FYROM))]
    sq_XK [Albanian (Kosovo)]
    sr_ [Serbian]
    sr_ [Serbian (Cyrillic)]
    sr_BA [Serbian (Cyrillic,Bosnia and Herzegovina)]
    sr_ME [Serbian (Cyrillic,Montenegro)]
    sr_RS [Serbian (Cyrillic,Serbia)]
    sr_XK [Serbian (Cyrillic,Kosovo)]
    sr_ [Serbian (Latin)]
    sr_BA [Serbian (Latin,Bosnia and Herzegovina)]
    sr_ME [Serbian (Latin,Montenegro)]
    sr_RS [Serbian (Latin,Serbia)]
    sr_XK [Serbian (Latin,Kosovo)]
    sv_ [Swedish]
    sv_AX [Swedish (Åland Islands)]
    sv_FI [Swedish (Finland)]
    sv_SE [Swedish (Sweden)]
    sw_ [Swahili]
    sw_KE [Swahili (Kenya)]
    sw_TZ [Swahili (Tanzania)]
    sw_UG [Swahili (Uganda)]
    swc_ [Congo Swahili]
    swc_CD [Congo Swahili (Congo (DRC))]
    ta_ [Tamil]
    ta_IN [Tamil (India)]
    ta_LK [Tamil (Sri Lanka)]
    ta_MY [Tamil (Malaysia)]
    ta_SG [Tamil (Singapore)]
    te_ [Telugu]
    te_IN [Telugu (India)]
    teo_ [Teso]
    teo_KE [Teso (Kenya)]
    teo_UG [Teso (Uganda)]
    th_ [Thai]
    th_TH [Thai (Thailand)]
    ti_ [Tigrinya]
    ti_ER [Tigrinya (Eritrea)]
    ti_ET [Tigrinya (Ethiopia)]
    to_ [Tongan]
    to_TO [Tongan (Tonga)]
    tr_ [Turkish]
    tr_CY [Turkish (Cyprus)]
    tr_TR [Turkish (Turkey)]
    twq_ [Tasawaq]
    twq_NE [Tasawaq (Niger)]
    tzm_ [Central Atlas Tamazight]
    tzm_ [Central Atlas Tamazight (Latin)]
    tzm_MA [Central Atlas Tamazight (Latin,Morocco)]
    ug_ [Uyghur]
    ug_ [Uyghur (Arabic)]
    ug_CN [Uyghur (Arabic,China)]
    uk_ [Ukrainian]
    uk_UA [Ukrainian (Ukraine)]
    ur_ [Urdu]
    ur_IN [Urdu (India)]
    ur_PK [Urdu (Pakistan)]
    uz_ [Uzbek]
    uz_ [Uzbek (Arabic)]
    uz_AF [Uzbek (Arabic,Afghanistan)]
    uz_ [Uzbek (Cyrillic)]
    uz_UZ [Uzbek (Cyrillic,Uzbekistan)]
    uz_ [Uzbek (Latin)]
    uz_UZ [Uzbek (Latin,Uzbekistan)]
    vai_ [Vai]
    vai_ [Vai (Latin)]
    vai_LR [Vai (Latin,Liberia)]
    vai_ [Vai (Vai)]
    vai_LR [Vai (Vai,Liberia)]
    vi_ [Vietnamese]
    vi_VN [Vietnamese (Vietnam)]
    vun_ [Vunjo]
    vun_TZ [Vunjo (Tanzania)]
    xog_ [Soga]
    xog_UG [Soga (Uganda)]
    yav_ [Yangben]
    yav_CM [Yangben (Cameroon)]
    yo_ [Yoruba]
    yo_BJ [Yoruba (Benin)]
    yo_NG [Yoruba (Nigeria)]
    zgh_ [Standard Moroccan Tamazight]
    zgh_MA [Standard Moroccan Tamazight (Morocco)]
    zh_ [Chinese]
    zh_ [Chinese (Simplified Han)]
    zh_CN [Chinese (Simplified Han,China)]
    zh_HK [Chinese (Simplified Han,Hong Kong)]
    zh_MO [Chinese (Simplified Han,Macau)]
    zh_SG [Chinese (Simplified Han,Singapore)]
    zh_ [Chinese (Traditional Han)]
    zh_HK [Chinese (Traditional Han,Hong Kong)]
    zh_MO [Chinese (Traditional Han,Macau)]
    zh_TW [Chinese (Traditional Han,Taiwan)]
    zu_ [Zulu]
    zu_ZA [Zulu (South Africa)]

Enter key in textarea

You need to consider the case where the user presses enter in the middle of the text, not just at the end. I'd suggest detecting the enter key in the keyup event, as suggested, and use a regular expression to ensure the value is as you require:

<textarea id="t" rows="4" cols="80"></textarea>
<script type="text/javascript">
    function formatTextArea(textArea) {
        textArea.value = textArea.value.replace(/(^|\r\n|\n)([^*]|$)/g, "$1*$2");
    }

    window.onload = function() {
        var textArea = document.getElementById("t");
        textArea.onkeyup = function(evt) {
            evt = evt || window.event;

            if (evt.keyCode == 13) {
                formatTextArea(this);
            }
        };
    };
</script>

excel delete row if column contains value from to-remove-list

Given sheet 2:

ColumnA
-------
apple
orange

You can flag the rows in sheet 1 where a value exists in sheet 2:

ColumnA  ColumnB
-------  --------------
pear     =IF(ISERROR(VLOOKUP(A1,Sheet2!A:A,1,FALSE)),"Keep","Delete")
apple    =IF(ISERROR(VLOOKUP(A2,Sheet2!A:A,1,FALSE)),"Keep","Delete")
cherry   =IF(ISERROR(VLOOKUP(A3,Sheet2!A:A,1,FALSE)),"Keep","Delete")
orange   =IF(ISERROR(VLOOKUP(A4,Sheet2!A:A,1,FALSE)),"Keep","Delete")
plum     =IF(ISERROR(VLOOKUP(A5,Sheet2!A:A,1,FALSE)),"Keep","Delete")

The resulting data looks like this:

ColumnA  ColumnB
-------  --------------
pear     Keep
apple    Delete
cherry   Keep
orange   Delete
plum     Keep

You can then easily filter or sort sheet 1 and delete the rows flagged with 'Delete'.

Searching a string in eclipse workspace

Goto Search->File

You will get an window, you can give either simple search text or regx pattern. Once you enter your search keyword click Search and make sure that Scope is Workspace.

You may use this for Replace as well.

MySQL - count total number of rows in php

for PHP 5.3 using PDO

<?php
    $staff=$dbh->prepare("SELECT count(*) FROM staff_login");
    $staff->execute();
    $staffrow = $staff->fetch(PDO::FETCH_NUM);
    $staffcount = $staffrow[0];


    echo $staffcount;
?>

How to resolve cURL Error (7): couldn't connect to host?

This issue can also be caused by making curl calls to https when it is not configured on the remote device. Calling over http can resolve this problem in these situations, at least until you configure ssl on the remote.

Remove Server Response Header IIS7

Try setting the HKLM\SYSTEM\CurrentControlSet\Services\HTTP\Parameters\DisableServerHeader registry entry to a REG_DWORD of 1.

React Native Responsive Font Size

A slightly different approach worked for me :-

const normalize = (size: number): number => {
  const scale = screenWidth / 320;
  const newSize = size * scale;
  let calculatedSize = Math.round(PixelRatio.roundToNearestPixel(newSize))

  if (PixelRatio.get() < 3)
    return calculatedSize - 0.5
  return calculatedSize
};

Do refer Pixel Ratio as this allows you to better set up the function based on the device density.

shift a std_logic_vector of n bit to right or left

There are two ways that you can achieve this. Concatenation, and shift/rotate functions.

  • Concatenation is the "manual" way of doing things. You specify what part of the original signal that you want to "keep" and then concatenate on data to one end or the other. For example: tmp <= tmp(14 downto 0) & '0';

  • Shift functions (logical, arithmetic): These are generic functions that allow you to shift or rotate a vector in many ways. The functions are: sll (shift left logical), srl (shift right logical). A logical shift inserts zeros. Arithmetric shifts (sra/sla) insert the left most or right most bit, but work in the same way as logical shift. Note that for all of these operations you specify what you want to shift (tmp), and how many times you want to perform the shift (n bits)

  • Rotate functions: rol (rotate left), ror (rotate right). Rotating does just that, the MSB ends up in the LSB and everything shifts left (rol) or the other way around for ror.

Here is a handy reference I found (see the first page).

400 BAD request HTTP error code meaning?

From w3.org

10.4.1 400 Bad Request

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

How to grep a text file which contains some binary data?

You can also try Word Extractor tool. Word Extractor can be used with any file in your computer to separate the strings that contain human text / words from binary code (exe applications, DLLs).

Get current rowIndex of table in jQuery

Try this,

$('td').click(function(){
   var row_index = $(this).parent().index();
   var col_index = $(this).index();
});

If you need the index of table contain td then you can change it to

var row_index = $(this).parent('table').index(); 

Single line if statement with 2 actions

Sounds like you really want a Dictionary<int, string> or possibly a switch statement...

You can do it with the conditional operator though:

userType = user.Type == 0 ? "Admin"
         : user.Type == 1 ? "User"
         : user.Type == 2 ? "Employee"
         : "The default you didn't specify";

While you could put that in one line, I'd strongly urge you not to.

I would normally only do this for different conditions though - not just several different possible values, which is better handled in a map.

how to add value to a tuple?

As other people have answered, tuples in python are immutable and the only way to 'modify' one is to create a new one with the appended elements included.

But the best solution is a list. When whatever function or method that requires a tuple needs to be called, create a tuple by using tuple(list).

How to beautifully update a JPA entity in Spring Data?

Even better then @Tanjim Rahman answer you can using Spring Data JPA use the method T getOne(ID id)

Customer customerToUpdate = customerRepository.getOne(id);
customerToUpdate.setName(customerDto.getName);
customerRepository.save(customerToUpdate);

Is's better because getOne(ID id) gets you only a reference (proxy) object and does not fetch it from the DB. On this reference you can set what you want and on save() it will do just an SQL UPDATE statement like you expect it. In comparsion when you call find() like in @Tanjim Rahmans answer spring data JPA will do an SQL SELECT to physically fetch the entity from the DB, which you dont need, when you are just updating.

Init array of structs in Go

You can have it this way:

It is important to mind the commas after each struct item or set of items.

earnings := []LineItemsType{

        LineItemsType{

            TypeName: "Earnings",

            Totals: 0.0,

            HasTotal: true,

            items: []LineItems{

                LineItems{

                    name: "Basic Pay",

                    amount: 100.0,
                },

                LineItems{

                    name: "Commuter Allowance",

                    amount: 100.0,
                },
            },
        },
        LineItemsType{

            TypeName: "Earnings",

            Totals: 0.0,

            HasTotal: true,

            items: []LineItems{

                LineItems{

                    name: "Basic Pay",

                    amount: 100.0,
                },

                LineItems{

                    name: "Commuter Allowance",

                    amount: 100.0,
                },
            },
        },
    }

Conditionally ignoring tests in JUnit 4

A quick note: Assume.assumeTrue(condition) ignores rest of the steps but passes the test. To fail the test, use org.junit.Assert.fail() inside the conditional statement. Works same like Assume.assumeTrue() but fails the test.

Multiple radio button groups in one form

To create a group of inputs you can create a custom html element

window.customElements.define('radio-group', RadioGroup);

https://gist.github.com/robdodson/85deb2f821f9beb2ed1ce049f6a6ed47

to keep selected option in each group, you need to add name attribute to inputs in group, if you not add it then all is one group.

Get current category ID of the active page

If it is a category page,you can get id of current category by:

$category = get_category( get_query_var( 'cat' ) );
$cat_id = $category->cat_ID;

If you want to get category id of any particular category on any page, try using :

$category_id = get_cat_ID('Category Name');

Python SQLite: database is locked

I had the same problem: sqlite3.IntegrityError

As mentioned in many answers, the problem is that a connection has not been properly closed.

In my case I had try except blocks. I was accessing the database in the try block and when an exception was raised I wanted to do something else in the except block.

try:
    conn = sqlite3.connect(path)
    cur = conn.cursor()
    cur.execute('''INSERT INTO ...''')
except:
    conn = sqlite3.connect(path)
    cur = conn.cursor()
    cur.execute('''DELETE FROM ...''')
    cur.execute('''INSERT INTO ...''')

However, when the exception was being raised the connection from the try block had not been closed.

I solved it using with statements inside the blocks.

try:
    with sqlite3.connect(path) as conn:
        cur = conn.cursor()
        cur.execute('''INSERT INTO ...''')
except:
    with sqlite3.connect(path) as conn:
        cur = conn.cursor()
        cur.execute('''DELETE FROM ...''')
        cur.execute('''INSERT INTO ...''')

How do I post form data with fetch api?

?These can help you:

let formData = new FormData();
            formData.append("name", "John");
            formData.append("password", "John123");
            fetch("https://yourwebhook", {
              method: "POST",
              mode: "no-cors",
              cache: "no-cache",
              credentials: "same-origin",
              headers: {
                "Content-Type": "form-data"
              },
              body: formData
            });
            //router.push("/registro-completado");
          } else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
          }
        })
        .catch(function(error) {
          console.log("Error getting document:", error);
        });

Asynchronous shell exec in PHP

In Linux, you can start a process in a new independent thread by appending an ampersand at the end of the command

mycommand -someparam somevalue &

In Windows, you can use the "start" DOS command

start mycommand -someparam somevalue

How to check if a DateTime field is not null or empty?

DateTime is not standard nullable type. If you want assign null to DateTime type of variable, you have to use DateTime? type which supports null value.

If you only want test your variable to be set (e.g. variable holds other than default value), you can use keyword "default" like in following code:

if (dateTimeVariable == default(DateTime))
{
    //do work for dateTimeVariable == null situation
}

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

I was experiencing this problem while using Alamofire. My mistake was that I was sending an empty dictionary [:] for the parameters on a GET request, rather than sending nil parameters.

Hope this helps!

How to add facebook share button on my website?

For Facebook share with an image without an API and using a # to deep link into a sub page, the trick was to share the image as picture=

The variable mainUrl would be http://yoururl.com/

var d1 = $('.targ .t1').text();
var d2 = $('.targ .t2').text();
var d3 = $('.targ .t3').text();
var d4 = $('.targ .t4').text();
var descript_ = d1 + ' ' + d2 + ' ' + d3 + ' ' + d4;
var descript = encodeURIComponent(descript_);

var imgUrl_ = 'path/to/mypic_'+id+'.jpg';
var imgUrl = mainUrl + encodeURIComponent(imgUrl_);

var shareLink = mainUrl + encodeURIComponent('mypage.html#' + id);

var fbShareLink = shareLink + '&picture=' + imgUrl + '&description=' + descript;
var twShareLink = 'text=' + descript + '&url=' + shareLink;

// facebook
$(".my-btn .facebook").off("tap click").on("tap click",function(){
  var fbpopup = window.open("https://www.facebook.com/sharer/sharer.php?u=" + fbShareLink, "pop", "width=600, height=400, scrollbars=no");
  return false;
});

// twitter
$(".my-btn .twitter").off("tap click").on("tap click",function(){
  var twpopup = window.open("http://twitter.com/intent/tweet?" + twShareLink , "pop", "width=600, height=400, scrollbars=no");
  return false;
});

Sql query to insert datetime in SQL Server

If you are storing values via any programming language

Here is an example in C#

To store date you have to convert it first and then store it

insert table1 (foodate)
   values (FooDate.ToString("MM/dd/yyyy"));

FooDate is datetime variable which contains your date in your format.

Using switch statement with a range of value in each case?

For input number in range 0..100

int n1 = 75; // input value
String res; int n=0; 
int[] a ={0,20,35,55,70,85,101};

for(; n1>=a[n]; n++);
switch(6-n+1) {
  case 1: res="A"; break;
  case 2: res="B"; break;
  case 3: res="C"; break;
  case 4: res="D"; break;
  case 5: res="E"; break;
  default:res="F";
}
System.out.println(res);

Matrix Transpose in Python

`

_x000D_
_x000D_
def transpose(m):_x000D_
    return(list(map(list,list(zip(*m)))))
_x000D_
_x000D_
_x000D_

`This function will return the transpose

Python Linked List

The following is what I came up with. It's similer to Riccardo C.'s, in this thread, except it prints the numbers in order instead of in reverse. I also made the LinkedList object a Python Iterator in order to print the list out like you would a normal Python list.

class Node:

    def __init__(self, data=None):
        self.data = data
        self.next = None

    def __str__(self):
        return str(self.data)


class LinkedList:

    def __init__(self):
        self.head = None
        self.curr = None
        self.tail = None

    def __iter__(self):
        return self

    def next(self):
        if self.head and not self.curr:
            self.curr = self.head
            return self.curr
        elif self.curr.next:
            self.curr = self.curr.next
            return self.curr
        else:
            raise StopIteration

    def append(self, data):
        n = Node(data)
        if not self.head:
            self.head = n
            self.tail = n
        else:
            self.tail.next = n
            self.tail = self.tail.next


# Add 5 nodes
ll = LinkedList()
for i in range(1, 6):
    ll.append(i)

# print out the list
for n in ll:
    print n

"""
Example output:
$ python linked_list.py
1
2
3
4
5
"""

Convert string to binary then back again using PHP

Why you are using PHP for the conversion. Now, there are so many front end languages available, Why you are still including a server? You can convert the password into the binary number in the front-end and send the converted string in the Database. According to my point of view, this would be convenient.

var bintext, textresult="", binlength;
    this.aaa = this.text_value;
    bintext = this.aaa.replace(/[^01]/g, "");
        binlength = bintext.length-(bintext.length%8);
        for(var z=0; z<binlength; z=z+8) {
            textresult += String.fromCharCode(parseInt(bintext.substr(z,8),2));
                            this.ans = textresult;

This is a Javascript code which I have found here: http://binarytotext.net/, they have used this code with Vue.js. In the code, this.aaa is the v-model dynamic value. To convert the binary into the text values, they have used big numbers. You need to install an additional package and convert it back into the text field. In my point of view, it would be easy.

How to leave space in HTML

To add non-breaking space or real space to your text in html, you can use the &nbsp; character entity.

How to use a WSDL file to create a WCF service (not make a call)

Use svcutil.exe with the /sc switch to generate the WCF contracts. This will create a code file that you can add to your project. It will contain all interfaces and data types you need to create your service. Change the output location using the /o switch, or you can find the file in the folder where you ran svcutil.exe. The default language is C# but I think (I've never tried it) you should be able to change this using /l:vb.

svcutil /sc "WSDL file path"

If your WSDL has any supporting XSD files pass those in as arguments after the WSDL.

svcutil /sc "WSDL file path" "XSD 1 file path" "XSD 2 file path" ... "XSD n file path"

Then create a new class that is your service and implement the contract interface you just created.

How do I center list items inside a UL element?

I added the div line and it did the trick:

<div style="text-align:center">
<ul>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
</ul>
</div>

favicon not working in IE

this seems to be an ASPX pages problem, I have never been able to show a favicon in any page for IE (all others yes Chrome, FF and safari) the only sites that I've seen that are the exception to that rule are bing.com, msdn.com and others that belong to MS and run on asp.net, there is something that they are not telling us! even world-known sites cant show in IE eg: manu.com (most browsed sports team in the world) aspx site and fails to dislplay the favicon on IE. http://www.manutd.com/favicon.ico does show the icon.

Please prove me wrong.

Tomcat 8 is not able to handle get request with '|' in query parameters?

The URI is encoded as UTF-8, but Tomcat is decoding them as ISO-8859-1. You need to edit the connector settings in the server.xml and add the URIEncoding="UTF-8" attribute.

or edit this parameter on your application.properties

server.tomcat.uri-encoding=utf-8

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

After trial and error comparing the using statements of my controller and the Asp.Net Template controller

using System.Web;

Solved the problem for me. You are also going to need to add:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

To use GetUserManager method.

Microsoft couldn't find a way to resolve this automatically with right click and resolve like other missing using statements?

How to set the opacity/alpha of a UIImage?

Based on Alexey Ishkov's answer, but in Swift

I used an extension of the UIImage class.

Swift 2:

UIImage Extension:

extension UIImage {
    func imageWithAlpha(alpha: CGFloat) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        drawAtPoint(CGPointZero, blendMode: .Normal, alpha: alpha)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
}

To use:

let image = UIImage(named: "my_image")
let transparentImage = image.imageWithAlpha(0.5)

Swift 3/4/5:

Note that this implementation returns an optional UIImage. This is because in Swift 3 UIGraphicsGetImageFromCurrentImageContext now returns an optional. This value could be nil if the context is nil or what not created with UIGraphicsBeginImageContext.

UIImage Extension:

extension UIImage {
    func image(alpha: CGFloat) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        draw(at: .zero, blendMode: .normal, alpha: alpha)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
}

To use:

let image = UIImage(named: "my_image")
let transparentImage = image?.image(alpha: 0.5)

How to affect other elements when one element is hovered

If the cube is directly inside the container:

#container:hover > #cube { background-color: yellow; }

If cube is next to (after containers closing tag) the container:

#container:hover + #cube { background-color: yellow; }

If the cube is somewhere inside the container:

#container:hover #cube { background-color: yellow; }

If the cube is a sibling of the container:

#container:hover ~ #cube { background-color: yellow; }

Username and password in https url

When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.

With Basic Auth, the HTTP request from the question will look something like this:

GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk

The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password).

To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl, the username and password will be clearly visible on the process list and might turn up in the bash history file.

When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.

Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.

When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.

Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.

vertical & horizontal lines in matplotlib

This may be a common problem for new users of Matplotlib to draw vertical and horizontal lines. In order to understand this problem, you should be aware that different coordinate systems exist in Matplotlib.

The method axhline and axvline are used to draw lines at the axes coordinate. In this coordinate system, coordinate for the bottom left point is (0,0), while the coordinate for the top right point is (1,1), regardless of the data range of your plot. Both the parameter xmin and xmax are in the range [0,1].

On the other hand, method hlines and vlines are used to draw lines at the data coordinate. The range for xmin and xmax are the in the range of data limit of x axis.

Let's take a concrete example,

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 5, 100)
y = np.sin(x)

fig, ax = plt.subplots()

ax.plot(x, y)
ax.axhline(y=0.5, xmin=0.0, xmax=1.0, color='r')
ax.hlines(y=0.6, xmin=0.0, xmax=1.0, color='b')

plt.show()

It will produce the following plot: enter image description here

The value for xmin and xmax are the same for the axhline and hlines method. But the length of produced line is different.

How do I make a dictionary with multiple keys to one value?

It is simple. The first thing that you have to understand the design of the Python interpreter. It doesn't allocate memory for all the variables basically if any two or more variable has the same value it just map to that value.

let's go to the code example,

In [6]: a = 10

In [7]: id(a)
Out[7]: 10914656

In [8]: b = 10

In [9]: id(b)
Out[9]: 10914656

In [10]: c = 11

In [11]: id(c)
Out[11]: 10914688

In [12]: d = 21

In [13]: id(d)
Out[13]: 10915008

In [14]: e = 11

In [15]: id(e)
Out[15]: 10914688

In [16]: e = 21

In [17]: id(e)
Out[17]: 10915008

In [18]: e is d
Out[18]: True
In [19]: e = 30

In [20]: id(e)
Out[20]: 10915296

From the above output, variables a and b shares the same memory, c and d has different memory when I create a new variable e and store a value (11) which is already present in the variable c so it mapped to that memory location and doesn't create a new memory when I change the value present in the variable e to 21 which is already present in the variable d so now variables d and e share the same memory location. At last, I change the value in the variable e to 30 which is not stored in any other variable so it creates a new memory for e.

so any variable which is having same value shares the memory.

Not for list and dictionary objects

let's come to your question.

when multiple keys have same value then all shares same memory so the thing that you expect is already there in python.

you can simply use it like this

In [49]: dictionary = {
    ...:     'k1':1,
    ...:     'k2':1,
    ...:     'k3':2,
    ...:     'k4':2}
    ...:     
    ...:     

In [50]: id(dictionary['k1'])
Out[50]: 10914368

In [51]: id(dictionary['k2'])
Out[51]: 10914368

In [52]: id(dictionary['k3'])
Out[52]: 10914400

In [53]: id(dictionary['k4'])
Out[53]: 10914400

From the above output, the key k1 and k2 mapped to the same address which means value one stored only once in the memory which is multiple key single value dictionary this is the thing you want. :P

How to save a dictionary to a file?

I would suggest saving your data using the JSON format instead of pickle format as JSON's files are human-readable which makes your debugging easier since your data is small. JSON files are also used by other programs to read and write data. You can read more about it here

You'll need to install the JSON module, you can do so with pip:

pip install json


# To save the dictionary into a file:
json.dump( data, open( "myfile.json", 'w' ) )

This creates a json file with the name myfile.

# To read data from file:
data = json.load( open( "myfile.json" ) )

This reads and stores the myfile.json data in a data object.

Oracle SQL Where clause to find date records older than 30 days

Use:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= TRUNC(SYSDATE) - 30

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date that is 30 days previous including the current time.

Depending on your needs, you could also look at using ADD_MONTHS:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)

What are best practices for multi-language database design?

I'm using next approach:

Product

ProductID OrderID,...

ProductInfo

ProductID Title Name LanguageID

Language

LanguageID Name Culture,....

How to create id with AUTO_INCREMENT on Oracle?

FUNCTION UNIQUE2(
 seq IN NUMBER
) RETURN VARCHAR2
AS
 i NUMBER := seq;
 s VARCHAR2(9);
 r NUMBER(2,0);
BEGIN
  WHILE i > 0 LOOP
    r := MOD( i, 36 );
    i := ( i - r ) / 36;
    IF ( r < 10 ) THEN
      s := TO_CHAR(r) || s;
    ELSE
      s := CHR( 55 + r ) || s;
    END IF;
  END LOOP;
  RETURN 'ID'||LPAD( s, 14, '0' );
END;

How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?

i got the same problem and i notice that my security config has diferent TAGS like the @Xenolion answer says

<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
    </domain-config>
</network-security-config>

so i change the TAGS "domain-config" for "base-config" and works, like this:

<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
    </base-config>
</network-security-config>

Running Bash commands in Python

According to the error you are missing a package named swap on the server. This /usr/bin/cwm requires it. If you're on Ubuntu/Debian, install python-swap using aptitude.

Sending message through WhatsApp

Tested on Marshmallow S5 and it works!

    Uri uri = Uri.parse("smsto:" + "phone number with country code");
    Intent sendIntent = new Intent(Intent.ACTION_SENDTO, uri);
    sendIntent.setPackage("com.whatsapp");
    startActivity(sendIntent); 

This will open a direct chat with a person, if whatsapp not installed this will throw exception, if phone number not known to whatsapp they will offer to send invite via sms or simple sms message

Jackson enum Serializing and DeSerializer

I've found a very nice and concise solution, especially useful when you cannot modify enum classes as it was in my case. Then you should provide a custom ObjectMapper with a certain feature enabled. Those features are available since Jackson 1.6. So you only need to write toString() method in your enum.

public class CustomObjectMapper extends ObjectMapper {
    @PostConstruct
    public void customConfiguration() {
        // Uses Enum.toString() for serialization of an Enum
        this.enable(WRITE_ENUMS_USING_TO_STRING);
        // Uses Enum.toString() for deserialization of an Enum
        this.enable(READ_ENUMS_USING_TO_STRING);
    }
}

There are more enum-related features available, see here:

https://github.com/FasterXML/jackson-databind/wiki/Serialization-Features https://github.com/FasterXML/jackson-databind/wiki/Deserialization-Features

Sorting Python list based on the length of the string

I Would like to add how the pythonic key function works while sorting :

Decorate-Sort-Undecorate Design Pattern :

Python’s support for a key function when sorting is implemented using what is known as the decorate-sort-undecorate design pattern.

It proceeds in 3 steps:

  1. Each element of the list is temporarily replaced with a “decorated” version that includes the result of the key function applied to the element.

  2. The list is sorted based upon the natural order of the keys.

  3. The decorated elements are replaced by the original elements.

Key parameter to specify a function to be called on each list element prior to making comparisons. docs

Explicit Return Type of Lambda

You can have more than one statement when still return:

[]() -> your_type {return (
        your_statement,
        even_more_statement = just_add_comma,
        return_value);}

http://www.cplusplus.com/doc/tutorial/operators/#comma

Truncating a table in a stored procedure

You should know that it is not possible to directly run a DDL statement like you do for DML from a PL/SQL block because PL/SQL does not support late binding directly it only support compile time binding which is fine for DML. hence to overcome this type of problem oracle has provided a dynamic SQL approach which can be used to execute the DDL statements.The dynamic sql approach is about parsing and binding of sql string at the runtime. Also you should rememder that DDL statements are by default auto commit hence you should be careful about any of the DDL statement using the dynamic SQL approach incase if you have some DML (which needs to be commited explicitly using TCL) before executing the DDL in the stored proc/function.

You can use any of the following dynamic sql approach to execute a DDL statement from a pl/sql block.

1) Execute immediate

2) DBMS_SQL package

3) DBMS_UTILITY.EXEC_DDL_STATEMENT (parse_string IN VARCHAR2);

Hope this answers your question with explanation.

Get the (last part of) current directory name in C#

You could try:

var path = @"/Users/smcho/filegen_from_directory/AIRPassthrough/";
var dirName = new DirectoryInfo(path).Name;

How to add image for button in android?

Put your Image in drawable folder. Here my image file name is left.png

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_x="118dp"
    android:layout_y="95dp"
    android:background="@drawable/left"
    android:onClick="toast"
    android:text=" " />

How can I declare a global variable in Angular 2 / Typescript?

See for example Angular 2 - Implementation of shared services

@Injectable() 
export class MyGlobals {
  readonly myConfigValue:string = 'abc';
}

@NgModule({
  providers: [MyGlobals],
  ...
})

class MyComponent {
  constructor(private myGlobals:MyGlobals) {
    console.log(myGlobals.myConfigValue);
  }
}

or provide individual values

@NgModule({
  providers: [{provide: 'myConfigValue', useValue: 'abc'}],
  ...
})

class MyComponent {
  constructor(@Inject('myConfigValue') private myConfigValue:string) {
    console.log(myConfigValue);
  }
}

Select last row in MySQL

on tables with many rows are two queries probably faster...

SELECT @last_id := MAX(id) FROM table;

SELECT * FROM table WHERE id = @last_id;

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

Your Custom AuthenticationProvider class should be annotated with the following:

@Transactional

This will make sure the presence of the hibernate session there as well.

regex to match a single character that is anything but a space

The following should suffice:

[^ ]

If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):

[^\s]

or

\S  # Note this is a CAPITAL 'S'!

Difference between Iterator and Listiterator?

the following is that the difference between iterator and listIterator

iterator :

boolean hasNext();
E next();
void remove();

listIterator:

boolean hasNext();
E next();
boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
void remove();
void set(E e);
void add(E e);

throwing exceptions out of a destructor

Everyone else has explained why throwing destructors are terrible... what can you do about it? If you're doing an operation that may fail, create a separate public method that performs cleanup and can throw arbitrary exceptions. In most cases, users will ignore that. If users want to monitor the success/failure of the cleanup, they can simply call the explicit cleanup routine.

For example:

class TempFile {
public:
    TempFile(); // throws if the file couldn't be created
    ~TempFile() throw(); // does nothing if close() was already called; never throws
    void close(); // throws if the file couldn't be deleted (e.g. file is open by another process)
    // the rest of the class omitted...
};

Display tooltip on Label's hover?

Are you find with using standard tooltip? You could use title attribute like

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

You could add the title attribute of same value to the element that label is for as well.

Android, canvas: How do I clear (delete contents of) a canvas (= bitmaps), living in a surfaceView?

mBitmap.eraseColor(Color.TRANSPARENT);

canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

Because XMLHttpReponse synchronous operation is deprecated I came up with the following solution that wraps XMLHttpRequest. This allows ordered AJAX queries while still being asycnronous in nature, which is very useful for single use CSRF tokens.

It is also transparent so libraries such as jQuery will operate seamlessly.

/* wrap XMLHttpRequest for synchronous operation */
var XHRQueue = [];
var _XMLHttpRequest = XMLHttpRequest;
XMLHttpRequest = function()
{
  var xhr   = new _XMLHttpRequest();
  var _send = xhr.send;

  xhr.send = function()
  {
    /* queue the request, and if it's the first, process it */
    XHRQueue.push([this, arguments]);
    if (XHRQueue.length == 1)
      this.processQueue();
  };

  xhr.processQueue = function()
  {
    var call = XHRQueue[0];
    var xhr  = call[0];
    var args = call[1];

    /* you could also set a CSRF token header here */

    /* send the request */
    _send.apply(xhr, args);
  };

  xhr.addEventListener('load', function(e)
  {
    /* you could also retrieve a CSRF token header here */

    /* remove the completed request and if there is more, trigger the next */
    XHRQueue.shift();
    if (XHRQueue.length)
      this.processQueue();
  });

  return xhr;
};

Using OpenSSL what does "unable to write 'random state'" mean?

I know this question is on Linux, but on windows I had the same issue. Turns out you have to start the command prompt in "Run As Administrator" mode for it to work. Otherwise you get the same: unable to write 'random state' error.

Conditional formatting based on another cell's value

change the background color of cell B5 based on the value of another cell - C5. If C5 is greater than 80% then the background color is green but if it's below, it will be amber/red.

There is no mention that B5 contains any value so assuming 80% is .8 formatted as percentage without decimals and blank counts as "below":

Select B5, colour "amber/red" with standard fill then Format - Conditional formatting..., Custom formula is and:

=C5>0.8

with green fill and Done.

CF rule example

How to use SVN, Branch? Tag? Trunk?

Just to add another set of answers:

  • I commit whenever I finish a piece of work. Sometimes it's a tiny bugfix that just changed one line and took me 2 minutes to do; other times it's two weeks worth of sweat. Also, as a rule of thumb, you don't commit anything that breaks the build. Thus if it has taken you a long time to do something, take the latest version before committing, and see if your changes break the build. Of course, if I go a long time without committing, it makes me uneasy because I don't want to loose that work. In TFS I use this nice thing as "shelvesets" for this. In SVN you'll have to work around in another way. Perhaps create your own branch or backup these files manually to another machine.
  • Branches are copies of your whole project. The best illustration for their use is perhaps the versioning of products. Imagine that you are working at a large project (say, the Linux kernel). After months of sweat you've finally arrived at version 1.0 that you release to the public. After that you start to work on version 2.0 of you product which is going to be way better. But in the mean time there are also a lot of people out there which are using version 1.0. And these people find bugs that you have to fix. Now, you can't fix the bug in the upcoming 2.0 version and ship that to the clients - it's not ready at all. Instead you have to pull out an old copy of 1.0 source, fix the bug there, and ship that to the people. This is what branches are for. When you released the 1.0 version you made a branch in SVN which made a copy of the source code at that point. This branch was named "1.0". You then continued work on the next version in your main source copy, but the 1.0 copy remained there as it was at the moment of the release. And you can continue fixing bugs there. Tags are just names attached to specific revisions for ease of use. You could say "Revision 2342 of the source code", but it's easier to refer to it as "First stable revision". :)
  • I usually put everything in the source control that relates directly to the programming. For example, since I'm making webpages, I also put images and CSS files in source control, not to mention config files etc. Project documentation does not go in there, however that is actually just a matter of preference.

Bootstrap Dropdown menu is not working

For Bootstrap 4 you need an additional library. If you read your browser console, Bootstrap will actually print an error message telling you that you need it for drop down to work.

Error: Bootstrap dropdown require Popper.js (https://popper.js.org)

Label axes on Seaborn Barplot

Seaborn's barplot returns an axis-object (not a figure). This means you can do the following:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
ax = sns.barplot(x = 'val', y = 'cat', 
              data = fake, 
              color = 'black')
ax.set(xlabel='common xlabel', ylabel='common ylabel')
plt.show()

How to extract custom header value in Web API message handler?

Try something like this:

IEnumerable<string> headerValues = request.Headers.GetValues("MyCustomID");
var id = headerValues.FirstOrDefault();

There's also a TryGetValues method on Headers you can use if you're not always guaranteed to have access to the header.

How to set a reminder in Android?

Nope, it is more complicated than just calling a method, if you want to transparently add it into the user's calendar.

You've got a couple of choices;

  1. Calling the intent to add an event on the calendar
    This will pop up the Calendar application and let the user add the event. You can pass some parameters to prepopulate fields:

    Calendar cal = Calendar.getInstance();              
    Intent intent = new Intent(Intent.ACTION_EDIT);
    intent.setType("vnd.android.cursor.item/event");
    intent.putExtra("beginTime", cal.getTimeInMillis());
    intent.putExtra("allDay", false);
    intent.putExtra("rrule", "FREQ=DAILY");
    intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
    intent.putExtra("title", "A Test Event from android app");
    startActivity(intent);
    

    Or the more complicated one:

  2. Get a reference to the calendar with this method
    (It is highly recommended not to use this method, because it could break on newer Android versions):

    private String getCalendarUriBase(Activity act) {
    
        String calendarUriBase = null;
        Uri calendars = Uri.parse("content://calendar/calendars");
        Cursor managedCursor = null;
        try {
            managedCursor = act.managedQuery(calendars, null, null, null, null);
        } catch (Exception e) {
        }
        if (managedCursor != null) {
            calendarUriBase = "content://calendar/";
        } else {
            calendars = Uri.parse("content://com.android.calendar/calendars");
            try {
                managedCursor = act.managedQuery(calendars, null, null, null, null);
            } catch (Exception e) {
            }
            if (managedCursor != null) {
                calendarUriBase = "content://com.android.calendar/";
            }
        }
        return calendarUriBase;
    }
    

    and add an event and a reminder this way:

    // get calendar
    Calendar cal = Calendar.getInstance();     
    Uri EVENTS_URI = Uri.parse(getCalendarUriBase(this) + "events");
    ContentResolver cr = getContentResolver();
    
    // event insert
    ContentValues values = new ContentValues();
    values.put("calendar_id", 1);
    values.put("title", "Reminder Title");
    values.put("allDay", 0);
    values.put("dtstart", cal.getTimeInMillis() + 11*60*1000); // event starts at 11 minutes from now
    values.put("dtend", cal.getTimeInMillis()+60*60*1000); // ends 60 minutes from now
    values.put("description", "Reminder description");
    values.put("visibility", 0);
    values.put("hasAlarm", 1);
    Uri event = cr.insert(EVENTS_URI, values);
    
    // reminder insert
    Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(this) + "reminders");
    values = new ContentValues();
    values.put( "event_id", Long.parseLong(event.getLastPathSegment()));
    values.put( "method", 1 );
    values.put( "minutes", 10 );
    cr.insert( REMINDERS_URI, values );
    

    You'll also need to add these permissions to your manifest for this method:

    <uses-permission android:name="android.permission.READ_CALENDAR" />
    <uses-permission android:name="android.permission.WRITE_CALENDAR" />
    

Update: ICS Issues

The above examples use the undocumented Calendar APIs, new public Calendar APIs have been released for ICS, so for this reason, to target new android versions you should use CalendarContract.

More infos about this can be found at this blog post.

Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

No library, one line, properly padded

const str = (new Date()).toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");

It uses the built-in function Date.toISOString(), chops off the ms, replaces the hyphens with slashes, and replaces the T with a space to go from say '2019-01-05T09:01:07.123' to '2019/01/05 09:01:07'.

Local time instead of UTC

const now = new Date();
const offsetMs = now.getTimezoneOffset() * 60 * 1000;
const dateLocal = new Date(now.getTime() - offsetMs);
const str = dateLocal.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");

Get IFrame's document, from JavaScript in main document

In case you get a cross-domain error:

If you have control over the content of the iframe - that is, if it is merely loaded in a cross-origin setup such as on Amazon Mechanical Turk - you can circumvent this problem with the <body onload='my_func(my_arg)'> attribute for the inner html.

For example, for the inner html, use the this html parameter (yes - this is defined and it refers to the parent window of the inner body element):

<body onload='changeForm(this)'>

In the inner html :

    function changeForm(window) {
        console.log('inner window loaded: do whatever you want with the inner html');
        window.document.getElementById('mturk_form').style.display = 'none';
    </script>

How to get object size in memory?

In debug mode

load SOS

and execute dumpheap command.

How to get cookie expiration date / creation date from javascript?

If you are using Chrome you can goto the "Resources" tab and find the item "Cookies" in the left sidebar. From there select the domain you are checking the set cookie for and it will give you a list of cookies associated with that domain, along with their expiration date.

Add vertical whitespace using Twitter Bootstrap?

I know this is old and there are several good solutions already posted, but a simple solution that worked for me is the following CSS

<style>
  .divider{
    margin: 0cm 0cm .5cm 0cm;
  }
</style>

and then create a div in your html

<div class="divider"></div>

Converting a string to a date in DB2

I know its old post but still I want to contribute
Above will not work if you have data format like this
'YYYMMDD'

For example:

Dt
20151104

So I tried following in order to get the desired result.

select cast(Left('20151104', 4)||'-'||substring('20151104',5,2)||'-'||substring('20151104', 7,2) as date) from SYSIBM.SYSDUMMY1;

Additionally, If you want to run the query from MS SQL linked server to DB2(To display only 100 rows).

    SELECT top 100 * from OPENQUERY([Linked_Server_Name],
    'select cast(Left(''20151104'', 4)||''-''||substring(''20151104'',5,2)||''-''||substring(''20151104'', 7,2) as date) AS Dt 
    FROM SYSIBM.SYSDUMMY1')

Result after above query:

Dt
2015-11-04

Hope this helps for others.

How to specify a min but no max decimal using the range data annotation attribute?

I was going to try something like this:

[Range(typeof(decimal), ((double)0).ToString(), ((double)decimal.MaxValue).ToString(), ErrorMessage = "Amount must be greater than or equal to zero.")]

The problem with doing this, though, is that the compiler wants a constant expression, which disallows ((double)0).ToString(). The compiler will take

[Range(0d, (double)decimal.MaxValue, ErrorMessage = "Amount must be greater than zero.")]

Fast way to get the min/max values among properties of object

For nested structures of different depth, i.e. {node: {leaf: 4}, leaf: 1}, this will work (using lodash or underscore):

function getMaxValue(d){
    if(typeof d === "number") {
        return d;
    } else if(typeof d === "object") {
        return _.max(_.map(_.keys(d), function(key) {
            return getMaxValue(d[key]);
        }));
    } else {
        return false;
    }
}

Does it make sense to use Require.js with Angular.js?

Here is the approach I use: http://thaiat.github.io/blog/2014/02/26/angularjs-and-requirejs-for-very-large-applications/

The page shows a possible implementation of AngularJS + RequireJS, where the code is split by features and then component type.

How to access the request body when POSTing using Node.js and Express?

Express 4.0 and above:

$ npm install --save body-parser

And then in your node app:

const bodyParser = require('body-parser');
app.use(bodyParser);

Express 3.0 and below:

Try passing this in your cURL call:

--header "Content-Type: application/json"

and making sure your data is in JSON format:

{"user":"someone"}

Also, you can use console.dir in your node.js code to see the data inside the object as in the following example:

var express = require('express');
var app = express.createServer();

app.use(express.bodyParser());

app.post('/', function(req, res){
    console.dir(req.body);
    res.send("test");
}); 

app.listen(3000);

This other question might also help: How to receive JSON in express node.js POST request?

If you don't want to use the bodyParser check out this other question: https://stackoverflow.com/a/9920700/446681

FileNotFoundError: [Errno 2] No such file or directory

You are using a relative path, which means that the program looks for the file in the working directory. The error is telling you that there is no file of that name in the working directory.

Try using the exact, or absolute, path.

How do I set up Visual Studio Code to compile C++ code?

A makefile task example for new 2.0.0 tasks.json version.

In the snippet below some comments I hope they will be useful.

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "<TASK_NAME>",
            "type": "shell",
            "command": "make",
            // use options.cwd property if the Makefile is not in the project root ${workspaceRoot} dir
            "options": {
                "cwd": "${workspaceRoot}/<DIR_WITH_MAKEFILE>"
            },
            // start the build without prompting for task selection, use "group": "build" otherwise
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                "echo": true,
                "reveal": "always",
                "focus": false,
                "panel": "shared"
            },
            // arg passing example: in this case is executed make QUIET=0
            "args": ["QUIET=0"],
            // Use the standard less compilation problem matcher.
            "problemMatcher": {
                "owner": "cpp",
                "fileLocation": ["absolute"],
                "pattern": {
                    "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        }
    ]
}

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

Hendry's answer is 100% correct. I had the same problem with my application, where there is repository project dealing with database with use of methods encapsulating EF db context operation. Other projects use this repository, and I don't want to reference EF in those projects. Somehow I don't feel it's proper, I need EF only in repository project. Anyway, copying EntityFramework.SqlServer.dll to other project output directory solves the problem. To avoid problems, when you forget to copy this dll, you can change repository build directory. Go to repository project's properties, select Build tab, and in output section you can set output directory to other project's build directory. Sure, it's just workaround. Maybe the hack, mentioned in some placec, is better:

var instance = System.Data.Entity.SqlServer.SqlProviderServices.Instance;

Still, for development purposes it is enough. Later, when preparing install or publish, you can add this file to package.

I'm quite new to EF. Is there any better method to solve this issue? I don't like "hack" - it makes me feel that there is something that is "not secure".

Best way to integrate Python and JavaScript?

There's a bridge based on JavaScriptCore (from WebKit), but it's pretty incomplete: http://code.google.com/p/pyjscore/

Convert string to variable name in python

This is the best way, I know of to create dynamic variables in python.

my_dict = {}
x = "Buffalo"
my_dict[x] = 4

I found a similar, but not the same question here Creating dynamically named variables from user input

Command /usr/bin/codesign failed with exit code 1

If you're using phonegap/cordova:

I got this when building from Cordova but the solution for me was much simpler. A permissions issue.

Just set the files to correct permissions

chmod -R 774 ./projectfolder

And then set ownership

chown -R youraccname:staff ./projectfolder 

MySQL Select all columns from one table and some from another table

Using alias for referencing the tables to get the columns from different tables after joining them.

Select tb1.*, tb2.col1, tb2.col2 from table1 tb1 JOIN table2 tb2 on tb1.Id = tb2.Id

What is the simplest way to SSH using Python?

I have written Python bindings for libssh2. Libssh2 is a client-side library implementing the SSH2 protocol.

import socket
import libssh2

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('exmaple.com', 22))

session = libssh2.Session()
session.startup(sock)
session.userauth_password('john', '******')

channel = session.channel()
channel.execute('ls -l')

print channel.read(1024)

Git pushing to remote branch

Simply push this branch to a different branch name

 git push -u origin localBranch:remoteBranch

Adding a right click menu to an item

Having just messed around with this, it's useful to kjnow that the e.X / e.Y points are relative to the control, so if (as I was) you are adding a context menu to a listview or something similar, you will want to adjust it with the form's origin. In the example below I've added 20 to the x/y so that the menu appears slightly to the right and under the cursor.

cmDelete.Show(this, new Point(e.X + ((Control)sender).Left+20, e.Y + ((Control)sender).Top+20));

text box input height

Just use CSS to increase it's height:

<input type="text" style="height:30px;" name="item" align="left" />

Or, often times, you want to increase it's height by using padding instead of specifying an exact height:

<input type="text" style="padding: 5px;" name="item" align="left" />

WebSockets protocol vs HTTP

You seem to assume that WebSocket is a replacement for HTTP. It is not. It's an extension.

The main use-case of WebSockets are Javascript applications which run in the web browser and receive real-time data from a server. Games are a good example.

Before WebSockets, the only method for Javascript applications to interact with a server was through XmlHttpRequest. But these have a major disadvantage: The server can't send data unless the client has explicitly requested it.

But the new WebSocket feature allows the server to send data whenever it wants. This allows to implement browser-based games with a much lower latency and without having to use ugly hacks like AJAX long-polling or browser plugins.

So why not use normal HTTP with streamed requests and responses

In a comment to another answer you suggested to just stream the client request and response body asynchronously.

In fact, WebSockets are basically that. An attempt to open a WebSocket connection from the client looks like a HTTP request at first, but a special directive in the header (Upgrade: websocket) tells the server to start communicating in this asynchronous mode. First drafts of the WebSocket protocol weren't much more than that and some handshaking to ensure that the server actually understands that the client wants to communicate asynchronously. But then it was realized that proxy servers would be confused by that, because they are used to the usual request/response model of HTTP. A potential attack scenario against proxy servers was discovered. To prevent this it was necessary to make WebSocket traffic look unlike any normal HTTP traffic. That's why the masking keys were introduced in the final version of the protocol.

How do I prevent a parent's onclick event from firing when a child anchor is clicked?

Use stopPropagation method, see an example:

$("#clickable a").click(function(e) {
   e.stopPropagation();
});

As said by jQuery Docs:

stopPropagation method prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

Keep in mind that it does not prevent others listeners to handle this event(ex. more than one click handler for a button), if it is not the desired effect, you must use stopImmediatePropagation instead.

How to add items to a spinner in Android?

Add this code after updating the list

Suppose:

The ArrayAdapter<String> variable name is dataAdapter, and the List variable name is keys.

  • dataAdapter.addAll(keys);
  • dataAdapter.notifyDataSetChanged();

How to create a video from images with FFmpeg?

See the Create a video slideshow from images – FFmpeg

If your video does not show the frames correctly If you encounter problems, such as the first image is skipped or only shows for one frame, then use the fps video filter instead of -r for the output framerate

ffmpeg -r 1/5 -i img%03d.png -c:v libx264 -vf fps=25 -pix_fmt yuv420p out.mp4

Alternatively the format video filter can be added to the filter chain to replace -pix_fmt yuv420p like "fps=25,format=yuv420p". The advantage of this method is that you can control which filter goes first

ffmpeg -r 1/5 -i img%03d.png -c:v libx264 -vf "fps=25,format=yuv420p" out.mp4

I tested below parameters, it worked for me

"e:\ffmpeg\ffmpeg.exe" -r 1/5 -start_number 0 -i "E:\images\01\padlock%3d.png" -c:v libx264 -vf "fps=25,format=yuv420p" e:\out.mp4

below parameters also worked but it always skips the first image

"e:\ffmpeg\ffmpeg.exe" -r 1/5 -start_number 0 -i "E:\images\01\padlock%3d.png" -c:v libx264 -r 30 -pix_fmt yuv420p e:\out.mp4

making a video from images placed in different folders

First, add image paths to imagepaths.txt like below.

# this is a comment details https://trac.ffmpeg.org/wiki/Concatenate

file 'E:\images\png\images__%3d.jpg'
file 'E:\images\jpg\images__%3d.jpg'

Sample usage as follows;

"h:\ffmpeg\ffmpeg.exe" -y -r 1/5 -f concat -safe 0 -i "E:\images\imagepaths.txt" -c:v libx264 -vf "fps=25,format=yuv420p" "e:\out.mp4"

-safe 0 parameter prevents Unsafe file name error

Related links

FFmpeg making a video from images placed in different folders

FFMPEG An Intermediate Guide/image sequence

Concatenate – FFmpeg

CSS change button style after click

Each link has five different states: link, hover, active, focus and visited.

Link is the normal appearance, hover is when you mouse over, active is the state when it's clicked, focus follows active and visited is the state you end up when you unfocus the recently clicked link.

I'm guessing you want to achieve a different style on either focus or visited, then you can add the following CSS:

a { color: #00c; }
a:visited { #ccc; }
a:focus { #cc0; }

A recommended order in your CSS to not cause any trouble is the following:

a
a:visited { ... }
a:focus { ... }
a:hover { ... }
a:active { ... }

You can use your web browser's developer tools to force the states of the element like this (Chrome->Developer Tools/Inspect Element->Style->Filter :hov): Force state in Chrome Developer Tools

How do I to insert data into an SQL table using C# as well as implement an upload function?

using System;
using System.Data;
using System.Data.SqlClient;

namespace InsertingData
{
    class sqlinsertdata
    {
        static void Main(string[] args)
        {
            try
            { 
            SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
            conn.Open();
                SqlCommand cmd = new SqlCommand("insert into <Table Name>values(1,'nagendra',10000);",conn);
                cmd.ExecuteNonQuery();
                Console.WriteLine("Inserting Data Successfully");
                conn.Close();
        }
            catch(Exception e)
            {
                Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t"  + e.GetType());
            }
            Console.ReadKey();

    }
    }
}

How to list all methods for an object in Ruby?

The following will list the methods that the User class has that the base Object class does not have...

>> User.methods - Object.methods
=> ["field_types", "maximum", "create!", "active_connections", "to_dropdown",
    "content_columns", "su_pw?", "default_timezone", "encode_quoted_value", 
    "reloadable?", "update", "reset_sequence_name", "default_timezone=", 
    "validate_find_options", "find_on_conditions_without_deprecation", 
    "validates_size_of", "execute_simple_calculation", "attr_protected", 
    "reflections", "table_name_prefix", ...

Note that methods is a method for Classes and for Class instances.

Here's the methods that my User class has that are not in the ActiveRecord base class:

>> User.methods - ActiveRecord::Base.methods
=> ["field_types", "su_pw?", "set_login_attr", "create_user_and_conf_user", 
    "original_table_name", "field_type", "authenticate", "set_default_order",
    "id_name?", "id_name_column", "original_locking_column", "default_order",
    "subclass_associations",  ... 
# I ran the statements in the console.

Note that the methods created as a result of the (many) has_many relationships defined in the User class are not in the results of the methods call.

Added Note that :has_many does not add methods directly. Instead, the ActiveRecord machinery uses the Ruby method_missing and responds_to techniques to handle method calls on the fly. As a result, the methods are not listed in the methods method result.

how to iterate through dictionary in a dictionary in django template?

This answer didn't work for me, but I found the answer myself. No one, however, has posted my question. I'm too lazy to ask it and then answer it, so will just put it here.

This is for the following query:

data = Leaderboard.objects.filter(id=custom_user.id).values(
    'value1',
    'value2',
    'value3')

In template:

{% for dictionary in data %}
  {% for key, value in dictionary.items %}
    <p>{{ key }} : {{ value }}</p>
  {% endfor %}
{% endfor %}

How to get every first element in 2 dimensional list

You can get the index [0] from each element in a list comprehension

>>> [i[0] for i in a]
[4.0, 3.0, 3.5]

Also just to be pedantic, you don't have a list of list, you have a tuple of tuple.

unsigned APK can not be installed

I cannot install an apk build with "Export Unsigned Application Package" Android SDK feature, but i can install an apk browsing the bin directory of my project after the project buid. I put this apk on my sd on my HTC Wildfire phone, select it and the application install correctly. You need to allow your phone to install unsigned apk. Good Luck.

Android device chooser - My device seems offline

fastest way is

Settings -> Developer Options -> Android Debugging

turn off and then on again (tested on CyanogenMod 11)

Interface vs Base class

I've found that a pattern of Interface > Abstract > Concrete works in the following use-case:

1.  You have a general interface (eg IPet)
2.  You have a implementation that is less general (eg Mammal)
3.  You have many concrete members (eg Cat, Dog, Ape)

The abstract class defines default shared attributes of the concrete classes, yet enforces the interface. For example:

public interface IPet{

    public boolean hasHair();

    public boolean walksUprights();

    public boolean hasNipples();
}

Now, since all mammals have hair and nipples (AFAIK, I'm not a zoologist), we can roll this into the abstract base class

public abstract class Mammal() implements IPet{

     @override
     public walksUpright(){
         throw new NotSupportedException("Walks Upright not implemented");
     }

     @override
     public hasNipples(){return true}

     @override
     public hasHair(){return true}

And then the concrete classes merely define that they walk upright.

public class Ape extends Mammal(){

    @override
    public walksUpright(return true)
}

public class Catextends Mammal(){

    @override
    public walksUpright(return false)
}

This design is nice when there are lots of concrete classes, and you don't want to maintain boilerplate just to program to an interface. If new methods were added to the interface, it would break all of the resulting classes, so you are still getting the advantages of the interface approach.

In this case, the abstract could just as well be concrete; however, the abstract designation helps to emphasize that this pattern is being employed.

How to convert image into byte array and byte array to base64 String in android?

They have wrapped most stuff need to solve your problem, one of the tests looks like this:

String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " ");
String code = "background: url(folder.png);";

StringWriter writer = new StringWriter();
embedder = new CSSURLEmbedder(new StringReader(code), true);
embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1));

String result = writer.toString();
assertEquals("background: url(" + folderDataURI + ");", result);

Http Get using Android HttpURLConnection

URL url = new URL("https://www.google.com");

//if you are using

URLConnection conn =url.openConnection();

//change it to

HttpURLConnection conn =(HttpURLConnection )url.openConnection();

No module named MySQLdb

You need to use one of the following commands. Which one depends on what OS and software you have and use.

  1. easy_install mysql-python (mix os)
  2. pip install mysql-python (mix os/ python 2)
  3. pip install mysqlclient (mix os/ python 3)
  4. apt-get install python-mysqldb (Linux Ubuntu, ...)
  5. cd /usr/ports/databases/py-MySQLdb && make install clean (FreeBSD)
  6. yum install MySQL-python (Linux Fedora, CentOS ...)

For Windows, see this answer: Install mysql-python (Windows)

concat scope variables into string in angular directive expression

I've created a working CodePen example demonstrating how to do this.

Relevant HTML:

<section ng-app="app" ng-controller="MainCtrl">
  <a href="#" ng-click="doSomething('#/path/{{obj.val1}}/{{obj.val2}}')">Click Me</a><br>
  debug: {{debug.val}}
</section>

Relevant javascript:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.obj = {
    val1: 'hello',
    val2: 'world'
  };

  $scope.debug = {
    val: ''
  };

  $scope.doSomething = function(input) {
    $scope.debug.val = input;
  };
});

How do I include a pipe | in my linux find -exec command?

The job of interpreting the pipe symbol as an instruction to run multiple processes and pipe the output of one process into the input of another process is the responsibility of the shell (/bin/sh or equivalent).

In your example you can either choose to use your top level shell to perform the piping like so:

find -name 'file_*' -follow -type f -exec zcat {} \; | agrep -dEOE 'grep'

In terms of efficiency this results costs one invocation of find, numerous invocations of zcat, and one invocation of agrep.

This would result in only a single agrep process being spawned which would process all the output produced by numerous invocations of zcat.

If you for some reason would like to invoke agrep multiple times, you can do:

find . -name 'file_*' -follow -type f \
    -printf "zcat %p | agrep -dEOE 'grep'\n" | sh

This constructs a list of commands using pipes to execute, then sends these to a new shell to actually be executed. (Omitting the final "| sh" is a nice way to debug or perform dry runs of command lines like this.)

In terms of efficiency this results costs one invocation of find, one invocation of sh, numerous invocations of zcat and numerous invocations of agrep.

The most efficient solution in terms of number of command invocations is the suggestion from Paul Tomblin:

find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep'

... which costs one invocation of find, one invocation of xargs, a few invocations of zcat and one invocation of agrep.

Creating a new ArrayList in Java

Material please go through this Link And also try this

 ArrayList<Class> myArray= new ArrayList<Class>();

tell pip to install the dependencies of packages listed in a requirement file

simplifily, use:

pip install -r requirement.txt

it can install all listed in requirement file.

How to overcome root domain CNAME restrictions?

I don't know how they are getting away with it, or what negative side effects their may be, but I'm using Hover.com to host some of my domains, and recently setup the apex of my domain as a CNAME there. Their DNS editing tool did not complain at all, and my domain happily resolves via the CNAME assigned.

Here is what Dig shows me for this domain (actual domain obfuscated as mydomain.com):

; <<>> DiG 9.8.3-P1 <<>> mydomain.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 2056
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;mydomain.com.          IN  A

;; ANSWER SECTION:
mydomain.com.       394 IN  CNAME   myapp.parseapp.com.
myapp.parseapp.com. 300 IN  CNAME   parseapp.com.
parseapp.com.       60  IN  A   54.243.93.102

How to change the bootstrap primary color?

Bootstrap 4

This is what worked for me:

I created my own _custom_theme.scss file with content similar to:

/* To simplify I'm only changing the primary color */
$theme-colors: ( "primary":#ffd800);

Added it to the top of the file bootstrap.scss and recompiled (In my case I had it in a folder called !scss)

@import "../../../!scss/_custom_theme.scss";
@import "functions";
@import "variables";
@import "mixins";

How do I Merge two Arrays in VBA?

Here's a version that uses a collection object to combine two 1-d arrays and pass them to a 3rd array. Doesn't work for multi-dimensional arrays.

Function joinArrays(arr1 As Variant, arr2 As Variant) As Variant
 Dim arrToReturn() As Variant, myCollection As New Collection
 For Each x In arr1: myCollection.Add x: Next
 For Each y In arr2: myCollection.Add y: Next

 ReDim arrToReturn(1 To myCollection.Count)
 For i = 1 To myCollection.Count: arrToReturn(i) = myCollection.Item(i): Next
 joinArrays = arrToReturn
End Function

How to disable or enable viewpager swiping in android

In your custom view pager adapter, override those methods in ViewPager.

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    // Never allow swiping to switch between pages
    return false;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    // Never allow swiping to switch between pages
    return false;
}

And to enable, just return each super method:

super.onInterceptTouchEvent(event) and super.onTouchEvent(event).

Foreign Key to multiple tables

The first option in @Nathan Skerl's list is what was implemented in a project I once worked with, where a similar relationship was established between three tables. (One of them referenced two others, one at a time.)

So, the referencing table had two foreign key columns, and also it had a constraint to guarantee that exactly one table (not both, not neither) was referenced by a single row.

Here's how it could look when applied to your tables:

CREATE TABLE dbo.[Group]
(
    ID int NOT NULL CONSTRAINT PK_Group PRIMARY KEY,
    Name varchar(50) NOT NULL
);

CREATE TABLE dbo.[User]
(
    ID int NOT NULL CONSTRAINT PK_User PRIMARY KEY,
    Name varchar(50) NOT NULL
);

CREATE TABLE dbo.Ticket
(
    ID int NOT NULL CONSTRAINT PK_Ticket PRIMARY KEY,
    OwnerGroup int NULL
      CONSTRAINT FK_Ticket_Group FOREIGN KEY REFERENCES dbo.[Group] (ID),
    OwnerUser int NULL
      CONSTRAINT FK_Ticket_User  FOREIGN KEY REFERENCES dbo.[User]  (ID),
    Subject varchar(50) NULL,
    CONSTRAINT CK_Ticket_GroupUser CHECK (
      CASE WHEN OwnerGroup IS NULL THEN 0 ELSE 1 END +
      CASE WHEN OwnerUser  IS NULL THEN 0 ELSE 1 END = 1
    )
);

As you can see, the Ticket table has two columns, OwnerGroup and OwnerUser, both of which are nullable foreign keys. (The respective columns in the other two tables are made primary keys accordingly.) The CK_Ticket_GroupUser check constraint ensures that only one of the two foreign key columns contains a reference (the other being NULL, that's why both have to be nullable).

(The primary key on Ticket.ID is not necessary for this particular implementation, but it definitely wouldn't harm to have one in a table like this.)

Revert to a commit by a SHA hash in Git?

This might work:

git checkout 56e05f
echo ref: refs/heads/master > .git/HEAD
git commit

How to find encoding of a file via script on Linux?

If you're talking about XML-files (ISO-8859-1), the XML-declaration inside them specifies the encoding: <?xml version="1.0" encoding="ISO-8859-1" ?>
So, you can use regular expressions (e.g. with perl) to check every file for such specification.
More information can be found here: How to Determine Text File Encoding.

PHP decoding and encoding json with unicode characters

A hacky way of doing JSON_UNESCAPED_UNICODE in PHP 5.3. Really disappointed by PHP json support. Maybe this will help someone else.

$array = some_json();
// Encode all string children in the array to html entities.
array_walk_recursive($array, function(&$item, $key) {
    if(is_string($item)) {
        $item = htmlentities($item);
    }
});
$json = json_encode($array);

// Decode the html entities and end up with unicode again.
$json = html_entity_decode($rson);

tsconfig.json: Build:No inputs were found in config file

When using Visual Studio Code, building the project (i.e. pressing Ctrl + Shift + B), moves your .ts file into the .vscode folder (I don't know why it does this), then generates the TS18003 error. What I did was move my .ts file out of the .vscode folder, back into the root folder and build the project again.

The project built successfully!

apache not accepting incoming connections from outside of localhost

this is what worked for us to get the apache accessible from outside:

sudo iptables -I INPUT 4 -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
sudo service iptables restart

How can I specify a [DllImport] path at runtime?

As long as you know the directory where your C++ libraries could be found at run time, this should be simple. I can clearly see that this is the case in your code. Your myDll.dll would be present inside myLibFolder directory inside temporary folder of the current user.

string str = Path.GetTempPath() + "..\\myLibFolder\\myDLL.dll"; 

Now you can continue using the DllImport statement using a const string as shown below:

[DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int DLLFunction(int Number1, int Number2);

Just at run time before you call the DLLFunction function (present in C++ library) add this line of code in C# code:

string assemblyProbeDirectory = Path.GetTempPath() + "..\\myLibFolder\\myDLL.dll"; 
Directory.SetCurrentDirectory(assemblyProbeDirectory);

This simply instructs the CLR to look for the unmanaged C++ libraries at the directory path which you obtained at run time of your program. Directory.SetCurrentDirectory call sets the application's current working directory to the specified directory. If your myDLL.dll is present at path represented by assemblyProbeDirectory path then it will get loaded and the desired function will get called through p/invoke.

C++ - Decimal to binary converting

My way of converting decimal to binary in C++. But since we are using mod, this function will work in case of hexadecimal or octal also. You can also specify bits. This function keeps calculating the lowest significant bit and place it on the end of the string. If you are not so similar to this method than you can vist: https://www.wikihow.com/Convert-from-Decimal-to-Binary

#include <bits/stdc++.h>
using namespace std;

string itob(int bits, int n) {
    int c;
    char s[bits+1]; // +1 to append NULL character.

    s[bits] = '\0'; // The NULL character in a character array flags the end of the string, not appending it may cause problems.

    c = bits - 1; // If the length of a string is n, than the index of the last character of the string will be n - 1. Cause the index is 0 based not 1 based. Try yourself.

    do {
        if(n%2) s[c] = '1';
        else s[c] = '0';
        n /= 2;
        c--;
    } while (n>0);

    while(c > -1) {
        s[c] = '0';
        c--;
}

    return s;
}

int main() {
    cout << itob(1, 0) << endl; // 0 in 1 bit binary.
    cout << itob(2, 1) << endl; // 1 in 2 bit binary.
    cout << itob(3, 2) << endl; // 2 in 3 bit binary.
    cout << itob(4, 4) << endl; // 4 in 4 bit binary.
    cout << itob(5, 15) << endl; // 15 in 5 bit binary.
    cout << itob(6, 30) << endl; // 30 in 6 bit binary.
    cout << itob(7, 61) << endl; // 61 in 7 bit binary.
    cout << itob(8, 127) << endl; // 127 in 8 bit binary.
    return 0;
}

The Output:

0
01
010
0100
01111
011110
0111101
01111111