Programs & Examples On #Gps.net

How to check if a list is empty in Python?

Empty lists evaluate to False in boolean contexts (such as if some_list:).

How can I tell where mongoDB is storing data? (its not in the default /data/db!)

mongod defaults the database location to /data/db/.

If you run ps -xa | grep mongod and you don't see a --dbpath which explicitly tells mongod to look at that parameter for the db location and you don't have a dbpath in your mongodb.conf, then the default location will be: /data/db/ and you should look there.

What ports need to be open for TortoiseSVN to authenticate (clear text) and commit?

What's the first part of your Subversion repository URL?

  • If your URL looks like: http://subversion/repos/, then you're probably going over Port 80.
  • If your URL looks like: https://subversion/repos/, then you're probably going over Port 443.
  • If your URL looks like: svn://subversion/, then you're probably going over Port 3690.
  • If your URL looks like: svn+ssh://subversion/repos/, then you're probably going over Port 22.
  • If your URL contains a port number like: http://subversion/repos:8080, then you're using that port.

I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.

If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.

The only way around that is to log into a local machine over the VPN, and then do everything from that system.

String compare in Perl with "eq" vs "=="

Did you try to chomp the $str1 and $str2?

I found a similar issue with using (another) $str1 eq 'Y' and it only went away when I first did:

chomp($str1);
if ($str1 eq 'Y') {
....
}

works after that.

Hope that helps.

How to get hex color value rather than RGB value?

This one looks a bit nicer:

var rgb = $('#selector').css('backgroundColor').match(/\d+/g);
var r   = parseInt(rgb[0], 10);
var g   = parseInt(rgb[1], 10);
var b   = parseInt(rgb[2], 10);
var hex = '#'+ r.toString(16) + g.toString(16) + b.toString(16);

a more succinct one-liner:

var rgb = $('#selector').css('backgroundColor').match(/\d+/g);
var hex = '#'+ Number(rgb[0]).toString(16) + Number(rgb[1]).toString(16) + Number(rgb[2]).toString(16);

forcing jQuery to always return hex:

$.cssHooks.backgroundColor = {
    get: function(elem) {
        if (elem.currentStyle)
            var bg = elem.currentStyle["backgroundColor"];
        else if (window.getComputedStyle) {
            var bg = document.defaultView.getComputedStyle(elem,
                null).getPropertyValue("background-color");
        }
        if (bg.search("rgb") == -1) {
            return bg;
        } else {
            bg = bg.match(/\d+/g);
            function hex(x) {
                return ("0" + parseInt(x).toString(16)).slice(-2);
            }
            return "#" + hex(bg[0]) + hex(bg[1]) + hex(bg[2]);
        }
    }
}

Uppercase first letter of variable

Use the .replace[MDN] function to replace the lowercase letters that begin a word with the capital letter.

_x000D_
_x000D_
var str = "hello world";_x000D_
str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {_x000D_
    return letter.toUpperCase();_x000D_
});_x000D_
alert(str); //Displays "Hello World"
_x000D_
_x000D_
_x000D_


Edit: If you are dealing with word characters other than just a-z, then the following (more complicated) regular expression might better suit your purposes.

_x000D_
_x000D_
var str = "???? ????????? björn über ñaque a?fa";_x000D_
str = str.toLowerCase().replace(/^[\u00C0-\u1FFF\u2C00-\uD7FF\w]|\s[\u00C0-\u1FFF\u2C00-\uD7FF\w]/g, function(letter) {_x000D_
    return letter.toUpperCase();_x000D_
});_x000D_
alert(str); //Displays "???? ????????? Björn Über Ñaque ??fa"
_x000D_
_x000D_
_x000D_

Why should the static field be accessed in a static way?

Because ... it (MILLISECONDS) is a static field (hiding in an enumeration, but that's what it is) ... however it is being invoked upon an instance of the given type (but see below as this isn't really true1).

javac will "accept" that, but it should really be MyUnits.MILLISECONDS (or non-prefixed in the applicable scope).

1 Actually, javac "rewrites" the code to the preferred form -- if m happened to be null it would not throw an NPE at run-time -- it is never actually invoked upon the instance).

Happy coding.


I'm not really seeing how the question title fits in with the rest :-) More accurate and specialized titles increase the likely hood the question/answers can benefit other programmers.

A weighted version of random.choice

If your list of weighted choices is relatively static, and you want frequent sampling, you can do one O(N) preprocessing step, and then do the selection in O(1), using the functions in this related answer.

# run only when `choices` changes.
preprocessed_data = prep(weight for _,weight in choices)

# O(1) selection
value = choices[sample(preprocessed_data)][0]

Configure Log4net to write to multiple files

I wanted to log all messages to root logger, and to have a separate log with errors, here is how it can be done:

<log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
        <file value="allMessages.log" />
        <appendToFile value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date  %-5level %logger  - %message%newline" />
        </layout>
    </appender>

    <appender name="ErrorsFileAppender" type="log4net.Appender.FileAppender">
        <file value="errorsLog.log" />
        <appendToFile value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date  %-5level %logger  - %message%newline" />
        </layout>
        <filter type="log4net.Filter.LevelRangeFilter">
            <levelMin value="ERROR" />
            <levelMax value="FATAL" />
        </filter>
    </appender>

    <root>
        <level value="ALL" />
        <appender-ref ref="FileAppender" />
        <appender-ref ref="ErrorsFileAppender" />
    </root>
</log4net>

Notice the use of filter element.

GitHub: invalid username or password

Since you probably want to keep 2FA enabled for your account, you can set up a ssh key and that way you won't need to type your Github credentials every time you want to push work to Github.

You can find all the ssh setup steps in the documentation. First, make sure you don't currently have any ssh keys (id_rsa.pub, etc.) with $ ls -al ~/.ssh

How to add Python to Windows registry

I faced to the same problem. I solved it by

  1. navigate to HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstallPath and edit the default key with the output of C:\> where python.exe command.
  2. navigate to HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstallPath\InstallGroup and edit the default key with Python 3.4

Note: My python version is 3.4 and you need to replace 3.4 with your python version.

Normally you can find Registry entries for Python in HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\<version>. You just need to copy those entries to HKEY_CURRENT_USER\Software\Python\PythonCore\<version>

ContractFilter mismatch at the EndpointDispatcher exception

I had this error because I have an old version of the DLL in the GAC of my server. So make sure everything is referenced correctly and that the assembly/GAC is up to date with the good dll.

ArrayAdapter in android to create simple listview

The TextView resource id it needs is for a TextView layout file, so it won't be in the same activity.

You can create it by going to File > New > XML > XML Layout File, and enter the widget type, which is 'TextView' in the root tag field.

Source: https://www.kompulsa.com/the-simplest-way-to-implement-an-android-listview/

Why powershell does not run Angular commands?

I solved my problem by running below command

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

How to parse a JSON string to an array using Jackson

The complete example with an array. Replace "constructArrayType()" by "constructCollectionType()" or any other type you need.

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

public class Sorting {

    private String property;

    private String direction;

    public Sorting() {

    }

    public Sorting(String property, String direction) {
        this.property = property;
        this.direction = direction;
    }

    public String getProperty() {
        return property;
    }

    public void setProperty(String property) {
        this.property = property;
    }

    public String getDirection() {
        return direction;
    }

    public void setDirection(String direction) {
        this.direction = direction;
    }

    public static void main(String[] args) throws JsonParseException, IOException {
        final String json = "[{\"property\":\"title1\", \"direction\":\"ASC\"}, {\"property\":\"title2\", \"direction\":\"DESC\"}]";
        ObjectMapper mapper = new ObjectMapper();
        Sorting[] sortings = mapper.readValue(json, TypeFactory.defaultInstance().constructArrayType(Sorting.class));
        System.out.println(sortings);
    }
}

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

Plotting in a non-blocking way with Matplotlib

The Python package drawnow allows to update a plot in real time in a non blocking way.
It also works with a webcam and OpenCV for example to plot measures for each frame.
See the original post.

Adding a new array element to a JSON object

First we need to parse the JSON object and then we can add an item.

var str = '{"theTeam":[{"teamId":"1","status":"pending"},
{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';

var obj = JSON.parse(str);
obj['theTeam'].push({"teamId":"4","status":"pending"});
str = JSON.stringify(obj);

Finally we JSON.stringify the obj back to JSON

Extract only right most n letters from a string

Use this:

string mystr = "PER 343573"; int number = Convert.ToInt32(mystr.Replace("PER ",""));

Spring @ContextConfiguration how to put the right location for the xml

Loading the file from: {project}/src/main/webapp/WEB-INF/spring-dispatcher-servlet.xml

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring-dispatcher-servlet.xml" })     
@WebAppConfiguration
public class TestClass {
    @Test
    public void test() {
         // test definition here..          
    }
}

How to get the path of the batch script in Windows?

%~dp0 - return the path from where script executed

But, important to know also below one:

%CD% - return the current path in runtime, for example if you get into other folders using "cd folder1", and then "cd folder2", it will return the full path until folder2 and not the original path where script located

MySQL INNER JOIN Alias

Use a seperate column to indicate the join condition

SELECT  t.importid, 
        case 
            when t.importid = g.home 
            then 'home' 
            else 'away' 
        end as join_condition, 
        g.network, 
        g.date_start 
FROM    game g
INNER JOIN team t ON (t.importid = g.home OR t.importid = g.away)
ORDER BY date_start DESC 
LIMIT 7

No module named 'pymysql'

Just a note: for Anaconda install packages command:

  1. python setup.py install

Understanding dict.copy() - shallow or deep?

It's not a matter of deep copy or shallow copy, none of what you're doing is deep copy.

Here:

>>> new = original 

you're creating a new reference to the the list/dict referenced by original.

while here:

>>> new = original.copy()
>>> # or
>>> new = list(original) # dict(original)

you're creating a new list/dict which is filled with a copy of the references of objects contained in the original container.

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

You don't need both hibernate.cfg.xml and persistence.xml in this case. Have you tried removing hibernate.cfg.xml and mapping everything in persistence.xml only?

But as the other answer also pointed out, this is not okay like this:

@Id
@JoinColumn(name = "categoria") 
private String id;

Didn't you want to use @Column instead?

How do I convert speech to text?

.NET can do it with its System.Speech namespace.

You would have to convert to .wav first or capture the audio live from the mic.

Details on implementation can be found here: Transcribing Audio with .NET

Create a sample login page using servlet and JSP?

As I can see, you are comparing the message with the empty string using ==.

Its very hard to write the full code, but I can tell the flow of code - first, create db class & method inide that which will return the connection. second, create a servelet(ex-login.java) & import that db class onto that servlet. third, create instance of imported db class with the help of new operator & call the connection method of that db class. fourth, creaet prepared statement & execute statement & put this code in try catch block for exception handling.Use if-else condition in the try block to navigate your login page based on success or failure.

I hope, it will help you. If any problem, then please revert.

Nikhil Pahariya

How to convert Java String into byte[]?

The object your method decompressGZIP() needs is a byte[].

So the basic, technical answer to the question you have asked is:

byte[] b = string.getBytes();
byte[] b = string.getBytes(Charset.forName("UTF-8"));
byte[] b = string.getBytes(StandardCharsets.UTF_8); // Java 7+ only

However the problem you appear to be wrestling with is that this doesn't display very well. Calling toString() will just give you the default Object.toString() which is the class name + memory address. In your result [B@38ee9f13, the [B means byte[] and 38ee9f13 is the memory address, separated by an @.

For display purposes you can use:

Arrays.toString(bytes);

But this will just display as a sequence of comma-separated integers, which may or may not be what you want.

To get a readable String back from a byte[], use:

String string = new String(byte[] bytes, Charset charset);

The reason the Charset version is favoured, is that all String objects in Java are stored internally as UTF-16. When converting to a byte[] you will get a different breakdown of bytes for the given glyphs of that String, depending upon the chosen charset.

Python Traceback (most recent call last)

In Python2, input is evaluated, input() is equivalent to eval(raw_input()). When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.

Use raw_input to get a string from the user in Python2.

Demo 1: klj is not defined:

>>> input()
klj
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'klj' is not defined

Demo 2: klj is defined:

>>> klj = 'hi'
>>> input()
klj
'hi'

Demo 3: getting a string with raw_input:

>>> raw_input()
klj
'klj'

Django DB Settings 'Improperly Configured' Error

You can't just fire up Python and check things, Django doesn't know what project you want to work on. You have to do one of these things:

  • Use python manage.py shell
  • Use django-admin.py shell --settings=mysite.settings (or whatever settings module you use)
  • Set DJANGO_SETTINGS_MODULE environment variable in your OS to mysite.settings
  • (This is removed in Django 1.6) Use setup_environ in the python interpreter:

    from django.core.management import setup_environ
    from mysite import settings
    
    setup_environ(settings)
    

Naturally, the first way is the easiest.

How to create a label inside an <input> element?

I think its good to keep the Label and not to use placeholder as mentioned above. Its good for UX as explain here: https://www.smashingmagazine.com/2018/03/ux-contact-forms-essentials-conversions/

Here example with Label inside Input fields: codepen.io/jdax/pen/mEBJNa

How to get a tab character?

As mentioned, for efficiency reasons sequential spaces are consolidated into one space the browser actually displays. Remember what the ML in HTML stand for. It's a Mark-up Language, designed to control how text is displayed.. not whitespace :p

Still, you can pretend the browser respects tabs since all the TAB does is prepend 4 spaces, and that's easy with CSS. either in line like ...

 <div style="padding-left:4.00em;">Indenented text </div>

Or as a regular class in a style sheet

.tabbed {padding-left:4.00em;}

Then the HTML might look like

<p>regular paragraph regular paragraph regular paragraph</p>
<p class="tabbed">Indented text Indented text Indented text</p>
<p>regular paragraph regular paragraph regular paragraph</p>

OS X Terminal Colors

If you are using tcsh, then edit your ~/.cshrc file to include the lines:

setenv CLICOLOR 1
setenv LSCOLORS dxfxcxdxbxegedabagacad

Where, like Martin says, LSCOLORS specifies the color scheme you want to use.

To generate the LSCOLORS you want to use, checkout this site

How to get the seconds since epoch from the time + date output of gmtime()?

There are two ways, depending on your original timestamp:

mktime() and timegm()

http://docs.python.org/library/time.html

Should I use "camel case" or underscores in python?

for everything related to Python's style guide: i'd recommend you read PEP8.

To answer your question:

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

How to test android apps in a real device with Android Studio?

I have a Nexus 4 and own a Thinkpad L430 Windows 8.1

My errors: "Waiting for device. USB device not found"

I went to: Device Manager > View > Drop to "Acer Device" > Right click on Acer Composite ADB Interface > Update it

Afterward, Reboot/Restart your computer. Once it turned on Plug Your USB Device onto the computer.

Go to: Setting > Enable "Developer options" > Check the "USB debugging" option > Check "Allow mock locations" > Check "Verify apps over USB".

Swipe down from the drop down menu of your phone where it Shows the USB Connection Icon. Tap on USB Computer Connection > Select the Check box "Camera (PTP)"

Run your Android Studio App and it should work

RunAs A different user when debugging in Visual Studio

I'm using the following method based on @Watki02's answer:

  1. Shift r-click the application to debug
  2. Run as different user
  3. Attach the debugger to the application

That way you can keep your visual studio instance as your own user whilst debugging from the other.

How do I get row id of a row in sql server

SQL Server does not track the order of inserted rows, so there is no reliable way to get that information given your current table structure. Even if employee_id is an IDENTITY column, it is not 100% foolproof to rely on that for order of insertion (since you can fill gaps and even create duplicate ID values using SET IDENTITY_INSERT ON). If employee_id is an IDENTITY column and you are sure that rows aren't manually inserted out of order, you should be able to use this variation of your query to select the data in sequence, newest first:

SELECT 
   ROW_NUMBER() OVER (ORDER BY EMPLOYEE_ID DESC) AS ID, 
   EMPLOYEE_ID,
   EMPLOYEE_NAME 
FROM dbo.CSBCA1_5_FPCIC_2012_EES207201222743
ORDER BY ID;

You can make a change to your table to track this information for new rows, but you won't be able to derive it for your existing data (they will all me marked as inserted at the time you make this change).

ALTER TABLE dbo.CSBCA1_5_FPCIC_2012_EES207201222743 
-- wow, who named this?
  ADD CreatedDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;

Note that this may break existing code that just does INSERT INTO dbo.whatever SELECT/VALUES() - e.g. you may have to revisit your code and define a proper, explicit column list.

Android textview outline text

You can put a shadow behind the text, which can often help readability. Try experimenting with 50% translucent black shadows on your green text. Details on how to do this are over here: Android - shadow on text?

To really add a stroke around the text, you need to do something a bit more involved, like this: How do you draw text with a border on a MapView in Android?

How to let an ASMX file output JSON

Alternative: Use a generic HTTP handler (.ashx) and use your favorite json library to manually serialize and deserialize your JSON.

I've found that complete control over the handling of a request and generating a response beats anything else .NET offers for simple, RESTful web services.

How to use andWhere and orWhere in Doctrine?

Why not just

$q->where("a = 1");
$q->andWhere("b = 1 OR b = 2");
$q->andWhere("c = 1 OR d = 2");

EDIT: You can also use the Expr class (Doctrine2).

What does the variable $this mean in PHP?

This is long detailed explanation. I hope this will help the beginners. I will make it very simple.

First, let's create a class

<?php 

class Class1
{
    
}

You can omit the php closing tag ?> if you are using php code only.

Now let's add properties and a method inside Class1.

<?php 

class Class1
{
    public $property1 = "I am property 1";
    public $property2 = "I am property 2";

    public function Method1()
    {
        return "I am Method 1";
    }
}

The property is just a simple variable , but we give it the name property cuz its inside a class.

The method is just a simple function , but we say method cuz its also inside a class.

The public keyword mean that the method or a property can be accessed anywhere in the script.

Now, how we can use the properties and the method inside Class1 ?

The answer is creating an instance or an object, think of an object as a copy of the class.

<?php 

class Class1
{
    public $property1 = "I am property 1";
    public $property2 = "I am property 2";

    public function Method1()
    {
        return "I am Method 1";
    }
}

$object1 = new Class1;
var_dump($object1);

We created an object, which is $object1 , which is a copy of Class1 with all its contents. And we dumped all the contents of $object1 using var_dump() .

This will give you

object(Class1)#1 (2) { ["property1"]=> string(15) "I am property 1" ["property2"]=> string(15) "I am property 2" }

So all the contents of Class1 are in $object1 , except Method1 , i don't know why methods doesn't show while dumping objects.

Now what if we want to access $property1 only. Its simple , we do var_dump($object1->property1); , we just added ->property1 , we pointed to it.

we can also access Method1() , we do var_dump($object1->Method1());.

Now suppose i want to access $property1 from inside Method1() , i will do this

<?php 

class Class1
{
    public $property1 = "I am property 1";
    public $property2 = "I am property 2";

    public function Method1()
    {   
        $object2 = new Class1;
        return $object2->property1;
    }
}

$object1 = new Class1;
var_dump($object1->Method1()); 

we created $object2 = new Class1; which is a new copy of Class1 or we can say an instance. Then we pointed to property1 from $object2

return $object2->property1;

This will print string(15) "I am property 1" in the browser.

Now instead of doing this inside Method1()

$object2 = new Class1;
return $object2->property1;

We do this

return $this->property1;

The $this object is used inside the class to refer to the class itself.

It is an alternative for creating new object and then returning it like this

$object2 = new Class1;
return $object2->property1;

Another example

<?php 

class Class1
{
    public $property1 = 119;
    public $property2 = 666;
    public $result;

    public function Method1()
    {   
        $this->result = $this->property1 + $this->property2;
        return $this->result;
    }
}

$object1 = new Class1;
var_dump($object1->Method1());

We created 2 properties containing integers and then we added them and put the result in $this->result.

Do not forget that

$this->property1 = $property1 = 119

they have that same value .. etc

I hope that explains the idea.

This series of videos will help you a lot in OOP

https://www.youtube.com/playlist?list=PLe30vg_FG4OSEHH6bRF8FrA7wmoAMUZLv

What design patterns are used in Spring framework?

Spring is a collection of best-practise API patterns, you can write up a shopping list of them as long as your arm. The way that the API is designed encourages you (but doesn't force you) to follow these patterns, and half the time you follow them without knowing you are doing so.

Move the mouse pointer to a specific position?

You cannot move the mousepointer with javascript.

Just think about the implications for a second, if you could ;)

  1. User thinks: "hey I'd like to click this link"
  2. Javascript moves mousecursor to another link
  3. User clicks wrong link and inadvertently downloads malware that formats his c-drive and eats his candy

Detecting arrow key presses in JavaScript

Use keydown, not keypress for non-printable keys such as arrow keys:

function checkKey(e) {
    e = e || window.event;
    alert(e.keyCode);
}

document.onkeydown = checkKey;

The best JavaScript key event reference I've found (beating the pants off quirksmode, for example) is here: http://unixpapa.com/js/key.html

"Could not get any response" response when using postman with subdomain

Postman for Linux Version 6.7.1 - Ubuntu 18.04 - linux 4.15.0-43-generic / x64

I had the same problem and by chance I replaced http://localhost with http://127.0.0.1 and everything worked.

My etc/hosts had the proper entries for localhost and https://localhost requests always worked as expected.

I have no clue why changing localhost for http with 127.0.0.1 solved the issue.

Can one do a for each loop in java in reverse order?

AFAIK there isn't a standard "reverse_iterator" sort of thing in the standard library that supports the for-each syntax which is already a syntactic sugar they brought late into the language.

You could do something like for(Item element: myList.clone().reverse()) and pay the associated price.

This also seems fairly consistent with the apparent phenomenon of not giving you convenient ways to do expensive operations - since a list, by definition, could have O(N) random access complexity (you could implement the interface with a single-link), reverse iteration could end up being O(N^2). Of course, if you have an ArrayList, you don't pay that price.

How to print the contents of RDD?

You can also save as a file: rdd.saveAsTextFile("alicia.txt")

Run an OLS regression with Pandas Data Frame

B is not statistically significant. The data is not capable of drawing inferences from it. C does influence B probabilities

 df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]})

 avg_c=df['C'].mean()
 sumC=df['C'].apply(lambda x: x if x<avg_c else 0).sum()
 countC=df['C'].apply(lambda x: 1 if x<avg_c else None).count()
 avg_c2=sumC/countC
 df['C']=df['C'].apply(lambda x: avg_c2 if x >avg_c else x)
 
 print(df)

 model_ols = smf.ols("A ~ B+C",data=df).fit()

 print(model_ols.summary())

 df[['B','C']].plot()
 plt.show()


 df2=pd.DataFrame()
 df2['B']=np.linspace(10,50,10)
 df2['C']=30

 df3=pd.DataFrame()
 df3['B']=np.linspace(10,50,10)
 df3['C']=100

 predB=model_ols.predict(df2)
 predC=model_ols.predict(df3)
 plt.plot(df2['B'],predB,label='predict B C=30')
 plt.plot(df3['B'],predC,label='predict B C=100')
 plt.legend()
 plt.show()

 print("A change in the probability of C affects the probability of B")

 intercept=model_ols.params.loc['Intercept']
 B_slope=model_ols.params.loc['B']
 C_slope=model_ols.params.loc['C']
 #Intercept    11.874252
 #B             0.760859
 #C            -0.060257

 print("Intercept {}\n B slope{}\n C    slope{}\n".format(intercept,B_slope,C_slope))


 #lower_conf,upper_conf=np.exp(model_ols.conf_int())
 #print(lower_conf,upper_conf)
 #print((1-(lower_conf/upper_conf))*100)

 model_cov=model_ols.cov_params()
 std_errorB = np.sqrt(model_cov.loc['B', 'B'])
 std_errorC = np.sqrt(model_cov.loc['C', 'C'])
 print('SE: ', round(std_errorB, 4),round(std_errorC, 4))
 #check for statistically significant
 print("B z value {} C z value {}".format((B_slope/std_errorB),(C_slope/std_errorC)))
 print("B feature is more statistically significant than C")


 Output:

 A change in the probability of C affects the probability of B
 Intercept 11.874251554067563
 B slope0.7608594144571961
 C slope-0.060256845997223814

 Standard Error:  0.4519 0.0793
 B z value 1.683510336937001 C z value -0.7601036314930376
 B feature is more statistically significant than C

 z>2 is statistically significant     

How to get the last N records in mongodb?

Last function should be sort, not limit.

Example:

db.testcollection.find().limit(3).sort({timestamp:-1}); 

HTML CSS Button Positioning

as I expected, yeah, it's because the whole DOM element is being pushed down. You have multiple options. You can put the buttons in separate divs, and float them so that they don't affect each other. the simpler solution is to just set the :active button to position:relative; and use top instead of margin or line-height. example fiddle: http://jsfiddle.net/5CZRP/

How to change value for innodb_buffer_pool_size in MySQL on Mac OS?

In the earlier versions of MySQL ( < 5.7.5 ) the only way to set

'innodb_buffer_pool_size'

variable was by writing it to my.cnf (for linux) and my.ini (for windows) under [mysqld] section :

[mysqld]

innodb_buffer_pool_size = 2147483648

You need to restart your mysql server to have it's effect in action.

UPDATE :

As of MySQL 5.7.5, the innodb_buffer_pool_size configuration option can be set dynamically using a SET statement, allowing you to resize the buffer pool without restarting the server. For example:

mysql> SET GLOBAL innodb_buffer_pool_size=402653184;

Reference : https://dev.mysql.com/doc/refman/5.7/en/innodb-buffer-pool-resize.html

React Modifying Textarea Values

I think you want something along the line of:

Parent:

<Editor name={this.state.fileData} />

Editor:

var Editor = React.createClass({
  displayName: 'Editor',
  propTypes: {
    name: React.PropTypes.string.isRequired
  },
  getInitialState: function() { 
    return {
      value: this.props.name
    };
  },
  handleChange: function(event) {
    this.setState({value: event.target.value});
  },
  render: function() {
    return (
      <form id="noter-save-form" method="POST">
        <textarea id="noter-text-area" name="textarea" value={this.state.value} onChange={this.handleChange} />
        <input type="submit" value="Save" />
      </form>
    );
  }
});

This is basically a direct copy of the example provided on https://facebook.github.io/react/docs/forms.html

Update for React 16.8:

import React, { useState } from 'react';

const Editor = (props) => {
    const [value, setValue] = useState(props.name);

    const handleChange = (event) => {
        setValue(event.target.value);
    };

    return (
        <form id="noter-save-form" method="POST">
            <textarea id="noter-text-area" name="textarea" value={value} onChange={handleChange} />
            <input type="submit" value="Save" />
        </form>
    );
}

Editor.propTypes = {
    name: PropTypes.string.isRequired
};

How to round a numpy array?

It is worth noting that the accepted answer will round small floats down to zero.

>>> import numpy as np 
>>> arr = np.asarray([2.92290007e+00, -1.57376965e-03, 4.82011728e-08, 1.92896977e-12])
>>> print(arr)
[ 2.92290007e+00 -1.57376965e-03  4.82011728e-08  1.92896977e-12]
>>> np.round(arr, 2)
array([ 2.92, -0.  ,  0.  ,  0.  ]) 

You can use set_printoptions and a custom formatter to fix this and get a more numpy-esque printout with fewer decimal places:

>>> np.set_printoptions(formatter={'float': "{0:0.2e}".format})
>>> print(arr)
[2.92e+00 -1.57e-03 4.82e-08 1.93e-12]  

This way, you get the full versatility of format and maintain the full precision of numpy's datatypes.

Also note that this only affects printing, not the actual precision of the stored values used for computation.

How to delete row based on cell value

You could copy down a formula like the following in a new column...

=IF(ISNUMBER(FIND("-",A1)),1,0)

... then sort on that column, highlight all the rows where the value is 1 and delete them.

How to get MD5 sum of a string using python?

You can Try with

#python3
import hashlib
rawdata = "put your data here"
sha = hashlib.sha256(str(rawdata).encode("utf-8")).hexdigest() #For Sha256 hash
print(sha)
mdpass = hashlib.md5(str(sha).encode("utf-8")).hexdigest() #For MD5 hash
print(mdpass)

Concatenate a NumPy array to another NumPy array

I found this link while looking for something slightly different, how to start appending array objects to an empty numpy array, but tried all the solutions on this page to no avail.

Then I found this question and answer: How to add a new row to an empty numpy array

The gist here:

The way to "start" the array that you want is:

arr = np.empty((0,3), int)

Then you can use concatenate to add rows like so:

arr = np.concatenate( ( arr, [[x, y, z]] ) , axis=0)

See also https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html

How can I schedule a daily backup with SQL Server Express?

Eduardo Molteni had a great answer:

Using Windows Scheduled Tasks:

In the batch file

"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE" -S 
(local)\SQLExpress -i D:\dbbackups\SQLExpressBackups.sql

In SQLExpressBackups.sql

BACKUP DATABASE MyDataBase1 TO  DISK = N'D:\DBbackups\MyDataBase1.bak' 
WITH NOFORMAT, INIT,  NAME = N'MyDataBase1 Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10

BACKUP DATABASE MyDataBase2 TO  DISK = N'D:\DBbackups\MyDataBase2.bak' 
WITH NOFORMAT, INIT,  NAME = N'MyDataBase2 Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10

GO

How to list files in an android directory?

Your path is not within the assets folder. Either you enumerate files within the assets folder by means of AssetManager.list() or you enumerate files on your SD card by means of File.list()

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

I got openCV installed smoothly in my mac by:

$ brew install opencv
$ brew link --overwrite --dry-run opencv // to force linking
$ pip3 install opencv-contrib-python

I got it at windows 10 using:

c:\> pip3 install opencv-python
c:\> pip3 install opencv-contrib-python

Then I got it tested by

$ python3
Python 3.7.3 (default, Mar 27 2019, 09:23:15) 
[Clang 10.0.1 (clang-1001.0.46.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> cv2.__version__
'4.1.0'
>>> exit()

What is the difference between visibility:hidden and display:none?

display:none will hide the element and collapse the space is was taking up, whereas visibility:hidden will hide the element and preserve the elements space. display:none also effects some of the properties available from javascript in older versions of IE and Safari.

How do you use a variable in a regular expression?

As Eric Wendelin mentioned, you can do something like this:

str1 = "pattern"
var re = new RegExp(str1, "g");
"pattern matching .".replace(re, "regex");

This yields "regex matching .". However, it will fail if str1 is ".". You'd expect the result to be "pattern matching regex", replacing the period with "regex", but it'll turn out to be...

regexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregex

This is because, although "." is a String, in the RegExp constructor it's still interpreted as a regular expression, meaning any non-line-break character, meaning every character in the string. For this purpose, the following function may be useful:

 RegExp.quote = function(str) {
     return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
 };

Then you can do:

str1 = "."
var re = new RegExp(RegExp.quote(str1), "g");
"pattern matching .".replace(re, "regex");

yielding "pattern matching regex".

placeholder for select tag

Yes it is possible

You can do this using only HTML You need to set default select option disabled="" and selected="" and select tag required="". Browser doesn't allow user to submit the form without selecting an option.

<form action="" method="POST">
    <select name="in-op" required="">
        <option disabled="" selected="">Select Option</option>
        <option>Option 1</option>
        <option>Option 2</option>
        <option>Option 3</option>
    </select>
    <input type="submit" value="Submit">
</form>

How to automatically import data from uploaded CSV or XLS file into Google Sheets

(Mar 2017) The accepted answer is not the best solution. It relies on manual translation using Apps Script, and the code may not be resilient, requiring maintenance. If your legacy system autogenerates CSV files, it's best they go into another folder for temporary processing (importing [uploading to Google Drive & converting] to Google Sheets files).

My thought is to let the Drive API do all the heavy-lifting. The Google Drive API team released v3 at the end of 2015, and in that release, insert() changed names to create() so as to better reflect the file operation. There's also no more convert flag -- you just specify MIMEtypes... imagine that!

The documentation has also been improved: there's now a special guide devoted to uploads (simple, multipart, and resumable) that comes with sample code in Java, Python, PHP, C#/.NET, Ruby, JavaScript/Node.js, and iOS/Obj-C that imports CSV files into Google Sheets format as desired.

Below is one alternate Python solution for short files ("simple upload") where you don't need the apiclient.http.MediaFileUpload class. This snippet assumes your auth code works where your service endpoint is DRIVE with a minimum auth scope of https://www.googleapis.com/auth/drive.file.

# filenames & MIMEtypes
DST_FILENAME = 'inventory'
SRC_FILENAME = DST_FILENAME + '.csv'
SHT_MIMETYPE = 'application/vnd.google-apps.spreadsheet'
CSV_MIMETYPE = 'text/csv'

# Import CSV file to Google Drive as a Google Sheets file
METADATA = {'name': DST_FILENAME, 'mimeType': SHT_MIMETYPE}
rsp = DRIVE.files().create(body=METADATA, media_body=SRC_FILENAME).execute()
if rsp:
    print('Imported %r to %r (as %s)' % (SRC_FILENAME, DST_FILENAME, rsp['mimeType']))

Better yet, rather than uploading to My Drive, you'd upload to one (or more) specific folder(s), meaning you'd add the parent folder ID(s) to METADATA. (Also see the code sample on this page.) Finally, there's no native .gsheet "file" -- that file just has a link to the online Sheet, so what's above is what you want to do.

If not using Python, you can use the snippet above as pseudocode to port to your system language. Regardless, there's much less code to maintain because there's no CSV parsing. The only thing remaining is to blow away the CSV file temp folder your legacy system wrote to.

R Apply() function on specific dataframe columns

lapply is probably a better choice than apply here, as apply first coerces your data.frame to an array which means all the columns must have the same type. Depending on your context, this could have unintended consequences.

The pattern is:

df[cols] <- lapply(df[cols], FUN)

The 'cols' vector can be variable names or indices. I prefer to use names whenever possible (it's robust to column reordering). So in your case this might be:

wifi[4:9] <- lapply(wifi[4:9], A)

An example of using column names:

wifi <- data.frame(A=1:4, B=runif(4), C=5:8)
wifi[c("B", "C")] <- lapply(wifi[c("B", "C")], function(x) -1 * x)

Postgres ERROR: could not open file for reading: Permission denied

I resolved the same issue with a recursive chown on the parent folder:

sudo chown -R postgres:postgres /home/my_user/export_folder

(my export being in /home/my_user/export_folder/export_1.csv)

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

If you used a raw socket (SOCK_RAW) and re-implemented TCP in userland, I think the answer is limited in this case only by the number of (local address, source port, destination address, destination port) tuples (~2^64 per local address).

It would of course take a lot of memory to keep the state of all those connections, and I think you would have to set up some iptables rules to keep the kernel TCP stack from getting upset &/or responding on your behalf.

Parenthesis/Brackets Matching using Stack algorithm

Algorithm to use for checking well balanced parenthesis -

  1. Declare a map matchingParenMap and initialize it with closing and opening bracket of each type as the key-value pair respectively.
  2. Declare a set openingParenSet and initialize it with the values of matchingParenMap.
  3. Declare a stack parenStack which will store the opening brackets '{', '(', and '['.
  4. Now traverse the string expression input.

    1. If the current character is an opening bracket ( '{', '(', '[' ) then push it to the parenStack.

    2. If the current character is a closing bracket ( '}', ')', ']' ) then pop from parenStack and if the popped character is equal to the matching starting bracket in matchingParenMap then continue looping else return false.

  5. After complete traversal if no opening brackets are left in parenStack it means it is a well balanced expression.

I have explained the code snippet of the algorithm used on my blog. Check link - http://hetalrachh.home.blog/2019/12/25/stack-data-structure/

The EntityManager is closed

Same problem, solved with a simple code refactoring. The problem is sometime present when a required field is null, before do anithing, try to refactor your code. A better workflow can solve the problem.

Django - Did you forget to register or load this tag?

{% load static %}

Please add this template tag on top of the HTML or base HTML file

jQuery Combobox/select autocomplete?

This works great for me and I'm doing more, writing less with jQuery's example modified.

I defined the select object on my page, just like the jQuery ex. I took the text and pushed it to an array. Then I use the array as my source to my input autocomplete. tadaa.

$(function() {
   var mySource = [];
   $("#mySelect").children("option").map(function() {
      mySource.push($(this).text());
   });

   $("#myInput").autocomplete({
      source: mySource,
      minLength: 3
   });
}

Turn off constraints temporarily (MS SQL)

You can disable FK and CHECK constraints only in SQL 2005+. See ALTER TABLE

ALTER TABLE foo NOCHECK CONSTRAINT ALL

or

ALTER TABLE foo NOCHECK CONSTRAINT CK_foo_column

Primary keys and unique constraints can not be disabled, but this should be OK if I've understood you correctly.

How to access static resources when mapping a global front controller servlet on /*

With Spring 3.0.4.RELEASE and higher you can use

<mvc:resources mapping="/resources/**" location="/public-resources/"/>

As seen in Spring Reference.

java build path problems

  1. Right click on project, Properties, Java Build Path.
  2. Remove the current JRE library.
  3. Click Add library > JRE System Library > Workspace default JRE.

Are the decimal places in a CSS width respected?

The width will be rounded to an integer number of pixels.

I don't know if every browser will round it the same way though. They all seem to have a different strategy when rounding sub-pixel percentages. If you're interested in the details of sub-pixel rounding in different browsers, there's an excellent article on ElastiCSS.

edit: I tested @Skilldrick's demo in some browsers for the sake of curiosity. When using fractional pixel values (not percentages, they work as suggested in the article I linked) IE9p7 and FF4b7 seem to round to the nearest pixel, while Opera 11b, Chrome 9.0.587.0 and Safari 5.0.3 truncate the decimal places. Not that I hoped that they had something in common after all...

Which ORM should I use for Node.js and MySQL?

I would choose Sequelize because of it's excellent documentation. It's just a honest opinion (I never really used MySQL with Node that much).

How to sort an array of objects by multiple fields?

A dynamic way to do that with MULTIPLE keys:

  • filter unique values from each col/key of sort
  • put in order or reverse it
  • add weights width zeropad for each object based on indexOf(value) keys values
  • sort using caclutated weights

enter image description here

Object.defineProperty(Array.prototype, 'orderBy', {
value: function(sorts) { 
    sorts.map(sort => {            
        sort.uniques = Array.from(
            new Set(this.map(obj => obj[sort.key]))
        );

        sort.uniques = sort.uniques.sort((a, b) => {
            if (typeof a == 'string') {
                return sort.inverse ? b.localeCompare(a) : a.localeCompare(b);
            }
            else if (typeof a == 'number') {
                return sort.inverse ? (a < b) : (a > b ? 1 : 0);
            }
            else if (typeof a == 'boolean') {
                let x = sort.inverse ? (a === b) ? 0 : a? -1 : 1 : (a === b) ? 0 : a? 1 : -1;
                return x;
            }
            return 0;
        });
    });

    const weightOfObject = (obj) => {
        let weight = "";
        sorts.map(sort => {
            let zeropad = `${sort.uniques.length}`.length;
            weight += sort.uniques.indexOf(obj[sort.key]).toString().padStart(zeropad, '0');
        });
        //obj.weight = weight; // if you need to see weights
        return weight;
    }

    this.sort((a, b) => {
        return weightOfObject(a).localeCompare( weightOfObject(b) );
    });

    return this;
}
});

Use:

// works with string, number and boolean
let sortered = your_array.orderBy([
    {key: "type", inverse: false}, 
    {key: "title", inverse: false},
    {key: "spot", inverse: false},
    {key: "internal", inverse: true}
]);

enter image description here

How to Iterate over a Set/HashSet without an Iterator?

There are at least six additional ways to iterate over a set. The following are known to me:

Method 1

// Obsolete Collection
Enumeration e = new Vector(movies).elements();
while (e.hasMoreElements()) {
  System.out.println(e.nextElement());
}

Method 2

for (String movie : movies) {
  System.out.println(movie);
}

Method 3

String[] movieArray = movies.toArray(new String[movies.size()]);
for (int i = 0; i < movieArray.length; i++) {
  System.out.println(movieArray[i]);
}

Method 4

// Supported in Java 8 and above
movies.stream().forEach((movie) -> {
  System.out.println(movie);
});

Method 5

// Supported in Java 8 and above
movies.stream().forEach(movie -> System.out.println(movie));

Method 6

// Supported in Java 8 and above
movies.stream().forEach(System.out::println);

This is the HashSet which I used for my examples:

Set<String> movies = new HashSet<>();
movies.add("Avatar");
movies.add("The Lord of the Rings");
movies.add("Titanic");

Formula to convert date to number

The Excel number for a modern date is most easily calculated as the number of days since 12/30/1899 on the Gregorian calendar.

Excel treats the mythical date 01/00/1900 (i.e., 12/31/1899) as corresponding to 0, and incorrectly treats year 1900 as a leap year. So for dates before 03/01/1900, the Excel number is effectively the number of days after 12/31/1899.

However, Excel will not format any number below 0 (-1 gives you ##########) and so this only matters for "01/00/1900" to 02/28/1900, making it easier to just use the 12/30/1899 date as a base.

A complete function in DB2 SQL that accounts for the leap year 1900 error:

SELECT
   DAYS(INPUT_DATE)                 
   - DAYS(DATE('1899-12-30'))
   - CASE                       
        WHEN INPUT_DATE < DATE('1900-03-01')  
           THEN 1               
           ELSE 0               
     END

C++, What does the colon after a constructor mean?

As others have said, it's an initialisation list. You can use it for two things:

  1. Calling base class constructors
  2. Initialising member variables before the body of the constructor executes.

For case #1, I assume you understand inheritance (if that's not the case, let me know in the comments). So you are simply calling the constructor of your base class.

For case #2, the question may be asked: "Why not just initialise it in the body of the constructor?" The importance of the initialisation lists is particularly evident for const members. For instance, take a look at this situation, where I want to initialise m_val based on the constructor parameter:

class Demo
{
    Demo(int& val) 
     {
         m_val = val;
     }
private:
    const int& m_val;
};

By the C++ specification, this is illegal. We cannot change the value of a const variable in the constructor, because it is marked as const. So you can use the initialisation list:

class Demo
{
    Demo(int& val) : m_val(val)
     {
     }
private:
    const int& m_val;
};

That is the only time that you can change a const member variable. And as Michael noted in the comments section, it is also the only way to initialise a reference that is a class member.

Outside of using it to initialise const member variables, it seems to have been generally accepted as "the way" of initialising variables, so it's clear to other programmers reading your code.

AttributeError: 'list' object has no attribute 'encode'

You need to do encode on tmp[0], not on tmp.

tmp is not a string. It contains a (Unicode) string.

Try running type(tmp) and print dir(tmp) to see it for yourself.

How can I compile a Java program in Eclipse without running it?

You can un-check the build automatically in Project menu and then build by hand by type Ctrl + B, or clicking an icon the appears to the right of the printer icon.

Split a string by another string in C#

As of .NET Core 2.0, there is an override that takes a string.

So now you can do "THExxQUICKxxBROWNxxFOX".Split("xx").

See https://docs.microsoft.com/en-us/dotnet/api/system.string.split?view=netcore-2.0#System_String_Split_System_String_System_StringSplitOptions_

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

As a counter point to the general thrust of the other answers. See The Many Benefits of Money…Data Type! in SQLCAT's Guide to Relational Engine

Specifically I would point out the following

Working on customer implementations, we found some interesting performance numbers concerning the money data type. For example, when Analysis Services was set to the currency data type (from double) to match the SQL Server money data type, there was a 13% improvement in processing speed (rows/sec). To get faster performance within SQL Server Integration Services (SSIS) to load 1.18 TB in under thirty minutes, as noted in SSIS 2008 - world record ETL performance, it was observed that changing the four decimal(9,2) columns with a size of 5 bytes in the TPC-H LINEITEM table to money (8 bytes) improved bulk inserting speed by 20% ... The reason for the performance improvement is because of SQL Server’s Tabular Data Stream (TDS) protocol, which has the key design principle to transfer data in compact binary form and as close as possible to the internal storage format of SQL Server. Empirically, this was observed during the SSIS 2008 - world record ETL performance test using Kernrate; the protocol dropped significantly when the data type was switched to money from decimal. This makes the transfer of data as efficient as possible. A complex data type needs additional parsing and CPU cycles to handle than a fixed-width type.

So the answer to the question is "it depends". You need to be more careful with certain arithmetical operations to preserve precision but you may find that performance considerations make this worthwhile.

How to detect IE11?

Use !(window.ActiveXObject) && "ActiveXObject" in window to detect IE11 explicitly.

To detect any IE (pre-Edge, "Trident") version, use "ActiveXObject" in window instead.

Max length UITextField

Since delegates are a 1-to-1 relationship and I might want to use it elsewhere for other reasons, I like to restrict textfield length adding this code within their setup:

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        setup()
    }

    required override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    func setup() {

        // your setup...

        setMaxLength()
    }

    let maxLength = 10

    private func setMaxLength() {
            addTarget(self, action: #selector(textfieldChanged(_:)), for: UIControlEvents.editingChanged)
        }

        @objc private func textfieldChanged(_ textField: UITextField) {
            guard let text = text else { return }
            let trimmed = text.characters.prefix(maxLength)
            self.text = String(trimmed)

        }

javascript - replace dash (hyphen) with a space

Imagine you end up with double dashes, and want to replace them with a single character and not doubles of the replace character. You can just use array split and array filter and array join.

var str = "This-is---a--news-----item----";

Then to replace all dashes with single spaces, you could do this:

var newStr = str.split('-').filter(function(item) {
  item = item ? item.replace(/-/g, ''): item
  return item;
}).join(' ');

Now if the string contains double dashes, like '----' then array split will produce an element with 3 dashes in it (because it split on the first dash). So by using this line:

item = item ? item.replace(/-/g, ''): item

The filter method removes those extra dashes so the element will be ignored on the filter iteration. The above line also accounts for if item is already an empty element so it doesn't crash on item.replace.

Then when your string join runs on the filtered elements, you end up with this output:

"This is a news item"

Now if you were using something like knockout.js where you can have computer observables. You could create a computed observable to always calculate "newStr" when "str" changes so you'd always have a version of the string with no dashes even if you change the value of the original input string. Basically they are bound together. I'm sure other JS frameworks can do similar things.

Java Comparator class to sort arrays

Just tried this solution, we don't have to even write int.

int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };
Arrays.sort(twoDim, (a1,a2) -> a2[0] - a1[0]);

This thing will also work, it automatically detects the type of string.

iOS 7.0 No code signing identities found

I just had this problem with Jenkins.

The solution was to copy the certificate and paste it into the system keychain otherwise Jenkins couldn't read the certificate.

How to add a TextView to LinearLayout in Android

You need to access the layout via it's layout resource, not an id resource which is not guaranteed unique. The resource reference should look like R.layout.my_cool_layout where your above XML layout is stored in res/layout/my_cool_layout.xml.

composer laravel create project

make sure that your composer is up to date. write in the cmd

composer create-project –-prefer-dist laravel/laravel NameOfProject "Version" 

Exit a Script On Error

Are you looking for exit?

This is the best bash guide around. http://tldp.org/LDP/abs/html/

In context:

if jarsigner -verbose -keystore $keyst -keystore $pass $jar_file $kalias
then
    echo $jar_file signed sucessfully
else
    echo ERROR: Failed to sign $jar_file. Please recheck the variables 1>&2
    exit 1 # terminate and indicate error
fi

...

how to display none through code behind

I believe this should work:

login_div.Attributes.Add("style","display:none");

UITableView, Separator color where to set?

Try + (instancetype)appearance of UITableView:

Objective-C:

[[UITableView appearance] setSeparatorColor:[UIColor blackColor]]; // set your desired colour in place of "[UIColor blackColor]"

Swift 3.0:

UITableView.appearance().separatorColor = UIColor.black // set your desired colour in place of "UIColor.black"

Note: Change will reflect to all tables used in application.

Adding machineKey to web.config on web-farm sites

This should answer:

How To: Configure MachineKey in ASP.NET 2.0 - Web Farm Deployment Considerations

Web Farm Deployment Considerations

If you deploy your application in a Web farm, you must ensure that the configuration files on each server share the same value for validationKey and decryptionKey, which are used for hashing and decryption respectively. This is required because you cannot guarantee which server will handle successive requests.

With manually generated key values, the settings should be similar to the following example.

<machineKey  
validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7
               AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"       

decryptionKey="ABAA84D7EC4BB56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
validation="SHA1"
decryption="AES"
/>

If you want to isolate your application from other applications on the same server, place the in the Web.config file for each application on each server in the farm. Ensure that you use separate key values for each application, but duplicate each application's keys across all servers in the farm.

In short, to set up the machine key refer the following link: Setting Up a Machine Key - Orchard Documentation.

Setting Up the Machine Key Using IIS Manager

If you have access to the IIS management console for the server where Orchard is installed, it is the easiest way to set-up a machine key.

Start the management console and then select the web site. Open the machine key configuration: The IIS web site configuration panel

The machine key control panel has the following settings:

The machine key configuration panel

Uncheck "Automatically generate at runtime" for both the validation key and the decryption key.

Click "Generate Keys" under "Actions" on the right side of the panel.

Click "Apply".

and add the following line to the web.config file in all the webservers under system.web tag if it does not exist.

<machineKey  
    validationKey="21F0SAMPLEKEY9C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7
                   AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"           
    decryptionKey="ABAASAMPLEKEY56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
    validation="SHA1"
    decryption="AES"
/>

Please make sure that you have a permanent backup of the machine keys and web.config file

How to write some data to excel file(.xlsx)

Try this code

Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
object misvalue = System.Reflection.Missing.Value;
try
{
    //Start Excel and get Application object.
    oXL = new Microsoft.Office.Interop.Excel.Application();
    oXL.Visible = true;

    //Get a new workbook.
    oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
    oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;

    //Add table headers going cell by cell.
    oSheet.Cells[1, 1] = "First Name";
    oSheet.Cells[1, 2] = "Last Name";
    oSheet.Cells[1, 3] = "Full Name";
    oSheet.Cells[1, 4] = "Salary";

    //Format A1:D1 as bold, vertical alignment = center.
    oSheet.get_Range("A1", "D1").Font.Bold = true;
    oSheet.get_Range("A1", "D1").VerticalAlignment =
        Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;

    // Create an array to multiple values at once.
    string[,] saNames = new string[5, 2];

    saNames[0, 0] = "John";
    saNames[0, 1] = "Smith";
    saNames[1, 0] = "Tom";

    saNames[4, 1] = "Johnson";

    //Fill A2:B6 with an array of values (First and Last Names).
    oSheet.get_Range("A2", "B6").Value2 = saNames;

    //Fill C2:C6 with a relative formula (=A2 & " " & B2).
    oRng = oSheet.get_Range("C2", "C6");
    oRng.Formula = "=A2 & \" \" & B2";

    //Fill D2:D6 with a formula(=RAND()*100000) and apply format.
    oRng = oSheet.get_Range("D2", "D6");
    oRng.Formula = "=RAND()*100000";
    oRng.NumberFormat = "$0.00";

    //AutoFit columns A:D.
    oRng = oSheet.get_Range("A1", "D1");
    oRng.EntireColumn.AutoFit();

    oXL.Visible = false;
    oXL.UserControl = false;
    oWB.SaveAs("c:\\test\\test505.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
        false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    oWB.Close();
    oXL.Quit();

    //...

How do you use subprocess.check_output() in Python?

The right answer (using Python 2.7 and later, since check_output() was introduced then) is:

py2output = subprocess.check_output(['python','py2.py','-i', 'test.txt'])

To demonstrate, here are my two programs:

py2.py:

import sys
print sys.argv

py3.py:

import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)

Running it:

$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"

Here's what's wrong with each of your versions:

py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt'])

First, str('python py2.py') is exactly the same thing as 'python py2.py'—you're taking a str, and calling str to convert it to an str. This makes the code harder to read, longer, and even slower, without adding any benefit.

More seriously, python py2.py can't be a single argument, unless you're actually trying to run a program named, say, /usr/bin/python\ py2.py. Which you're not; you're trying to run, say, /usr/bin/python with first argument py2.py. So, you need to make them separate elements in the list.

Your second version fixes that, but you're missing the ' before test.txt'. This should give you a SyntaxError, probably saying EOL while scanning string literal.

Meanwhile, I'm not sure how you found documentation but couldn't find any examples with arguments. The very first example is:

>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'

That calls the "echo" command with an additional argument, "Hello World!".

Also:

-i is a positional argument for argparse, test.txt is what the -i is

I'm pretty sure -i is not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.

Java: Integer equals vs. ==

"==" always compare the memory location or object references of the values. equals method always compare the values. But equals also indirectly uses the "==" operator to compare the values.

Integer uses Integer cache to store the values from -128 to +127. If == operator is used to check for any values between -128 to 127 then it returns true. for other than these values it returns false .

Refer the link for some additional info

Check if a string is palindrome

// The below C++ function checks for a palindrome and 
// returns true if it is a palindrome and returns false otherwise

bool checkPalindrome ( string s )
{
    // This calculates the length of the string

    int n = s.length();

    // the for loop iterates until the first half of the string
    // and checks first element with the last element,
    // second element with second last element and so on.
    // if those two characters are not same, hence we return false because
    // this string is not a palindrome 

    for ( int i = 0; i <= n/2; i++ ) 
    {
        if ( s[i] != s[n-1-i] )
            return false;
    }
    
    // if the above for loop executes completely , 
    // this implies that the string is palindrome, 
    // hence we return true and exit

    return true;
}

NVIDIA NVML Driver/library version mismatch

So I was having this problem, none of the other remedies worked. The error message was opaque, but checking dmesg was key:

[   10.118255] NVRM: API mismatch: the client has the version 410.79, but
           NVRM: this kernel module has the version 384.130.  Please
           NVRM: make sure that this kernel module and all NVIDIA driver
           NVRM: components have the same version.

However I had completely removed the 384 version, and removed any remaining kernel drivers nvidia-384*. But even after reboot, I was still getting this. Seeing this meant that the kernel was still compiled to reference 384, but was only finding 410. So I recompiled my kernel:

# uname -a # find the kernel it's using
Linux blah 4.13.0-43-generic #48~16.04.1-Ubuntu SMP Thu May 17 12:56:46 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
# update-initramfs -c -k 4.13.0-43-generic #recompile it
# reboot

And then it worked.

After removing 384, I still had 384 files in: /var/lib/dkms/nvidia-XXX/XXX.YY/4.13.0-43-generic/x86_64/module /lib/modules/4.13.0-43-generic/kernel/drivers

I recommend using the locate command (not installed by default) rather than searching the filesystem every time.

How is Pythons glob.glob ordered?

It is probably not sorted at all and uses the order at which entries appear in the filesystem, i.e. the one you get when using ls -U. (At least on my machine this produces the same order as listing glob matches).

Laravel eloquent update record without loading from database

You can also use firstOrCreate OR firstOrNew

// Retrieve the Post by the attributes, or create it if it doesn't exist...
$post = Post::firstOrCreate(['id' => 3]);
// OR
// Retrieve the Post by the attributes, or instantiate a new instance...
$post = Post::firstOrNew(['id' => 3]); 

// update record
$post->title = "Updated title";
$post->save();

Hope it will help you :)

Entity Framework The underlying provider failed on Open

Please check the following things first.

While generating the Edmx you would have given a name to you connection string. that gets into the app config of the project with the Entity.

Have you copied the same connection string to your main Config file. Also the Name should be same as which you have given while generating the EDMX file.

How to fix "ImportError: No module named ..." error in Python?

If you have this problem when using an instaled version, when using setup.py, make sure your module is included inside packages

setup(name='Your program',
    version='0.7.0',
    description='Your desccription',
    packages=['foo', 'foo.bar'], # add `foo.bar` here

An existing connection was forcibly closed by the remote host - WCF

The best thing I've found for diagnosing things like this is the service trace viewer. It's pretty simple to set up (assuming you can edit the configs):

http://msdn.microsoft.com/en-us/library/ms732023.aspx

Hope this helps.

How do you create a custom AuthorizeAttribute in ASP.NET Core?

The approach recommended by the ASP.Net Core team is to use the new policy design which is fully documented here. The basic idea behind the new approach is to use the new [Authorize] attribute to designate a "policy" (e.g. [Authorize( Policy = "YouNeedToBe18ToDoThis")] where the policy is registered in the application's Startup.cs to execute some block of code (i.e. ensure the user has an age claim where the age is 18 or older).

The policy design is a great addition to the framework and the ASP.Net Security Core team should be commended for its introduction. That said, it isn't well-suited for all cases. The shortcoming of this approach is that it fails to provide a convenient solution for the most common need of simply asserting that a given controller or action requires a given claim type. In the case where an application may have hundreds of discrete permissions governing CRUD operations on individual REST resources ("CanCreateOrder", "CanReadOrder", "CanUpdateOrder", "CanDeleteOrder", etc.), the new approach either requires repetitive one-to-one mappings between a policy name and a claim name (e.g. options.AddPolicy("CanUpdateOrder", policy => policy.RequireClaim(MyClaimTypes.Permission, "CanUpdateOrder));), or writing some code to perform these registrations at run time (e.g. read all claim types from a database and perform the aforementioned call in a loop). The problem with this approach for the majority of cases is that it's unnecessary overhead.

While the ASP.Net Core Security team recommends never creating your own solution, in some cases this may be the most prudent option with which to start.

The following is an implementation which uses the IAuthorizationFilter to provide a simple way to express a claim requirement for a given controller or action:

public class ClaimRequirementAttribute : TypeFilterAttribute
{
    public ClaimRequirementAttribute(string claimType, string claimValue) : base(typeof(ClaimRequirementFilter))
    {
        Arguments = new object[] {new Claim(claimType, claimValue) };
    }
}

public class ClaimRequirementFilter : IAuthorizationFilter
{
    readonly Claim _claim;

    public ClaimRequirementFilter(Claim claim)
    {
        _claim = claim;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var hasClaim = context.HttpContext.User.Claims.Any(c => c.Type == _claim.Type && c.Value == _claim.Value);
        if (!hasClaim)
        {
            context.Result = new ForbidResult();
        }
    }
}


[Route("api/resource")]
public class MyController : Controller
{
    [ClaimRequirement(MyClaimTypes.Permission, "CanReadResource")]
    [HttpGet]
    public IActionResult GetResource()
    {
        return Ok();
    }
}

How do I increase the scrollback buffer in a running screen session?

As Already mentioned we have two ways!

 Per screen (session) interactive setting

And it's done interactively! And take effect immediately!

CTRL + A followed by : And we type scrollback 1000000 And hit ENTER

You detach from the screen and come back! It will be always the same.

You open another new screen! And the value is reset again to default! So it's not a global setting!

 And the permanent default setting

Which is done by adding defscrollback 1000000 to .screenrc (in home)

defscrollback and not scrollback (def stand for default)

What you need to know is if the file is not created ! You create it !

> cd ~ && vim .screenrc

And you add defscrollback 1000000 to it!

Or in one command

> echo "defscrollback 1000000" >> .screenrc

(if not created already)

Taking effect

When you add the default to .screenrc! The already running screen at re-attach will not take effect! The .screenrc run at the screen creation! And it make sense! Just as with a normal console and shell launch!

And all the new created screens will have the set value!

Checking the screen effective buffer size

To check type CTRL + A followed by i

And The result will be as

enter image description here

Importantly the buffer size is the number after the + sign
(in the illustration i set it to 1 000 000)

Note too that when you change it interactively! The effect is immediate and take over the default value!

Scrolling

CTRL+ A followed by ESC (to enter the copy mode).

Then navigate with Up,Down or PgUp PgDown

And ESC again to quit that mode.

(Extra info: to copy hit ENTER to start selecting! Then ENTER again to copy! Simple and cool)

Now the buffer is bigger!

And that's sum it up for the important details!

How to replace master branch in Git, entirely, from another branch?

You can rename/remove master on remote, but this will be an issue if lots of people have based their work on the remote master branch and have pulled that branch in their local repo.
That might not be the case here since everyone seems to be working on branch 'seotweaks'.

In that case you can:
git remote --show may not work. (Make a git remote show to check how your remote is declared within your local repo. I will assume 'origin')
(Regarding GitHub, house9 comments: "I had to do one additional step, click the 'Admin' button on GitHub and set the 'Default Branch' to something other than 'master', then put it back afterwards")

git branch -m master master-old  # rename master on local
git push origin :master          # delete master on remote
git push origin master-old       # create master-old on remote
git checkout -b master seotweaks # create a new local master on top of seotweaks
git push origin master           # create master on remote

But again:

  • if other users try to pull while master is deleted on remote, their pulls will fail ("no such ref on remote")
  • when master is recreated on remote, a pull will attempt to merge that new master on their local (now old) master: lots of conflicts. They actually need to reset --hard their local master to the remote/master branch they will fetch, and forget about their current master.

how to bypass Access-Control-Allow-Origin?

I have fixed this problem when calling a MVC3 Controller. I added:

Response.AddHeader("Access-Control-Allow-Origin", "*"); 

before my

return Json(model, JsonRequestBehavior.AllowGet);

And also my $.ajax was complaining that it does not accept Content-type header in my ajax call, so I commented it out as I know its JSON being passed to the Action.

Hope that helps.

Where can I get a list of Ansible pre-defined variables?

The debug module can be used to analyze variables. Be careful running the following command. In our setup it generates 444709 lines with 16MB:

ansible -m debug -a 'var=hostvars' localhost

I am not sure but it might be necessary to enable facts caching.

If you need just one host use the host name as a key for the hostvars hash:

ansible -m debug -a 'var=hostvars.localhost' localhost

This command will display also group and host variables.

Eclipse and Windows newlines

In addition to the Eclipse solutions and the tool mentioned in another answer, consider flip. It can 'flip' either way between normal and Windows linebreaks, and does nice things like preserve the file's timestamp and other stats.

You can use it like this to solve your problem:

find . -type f -not -path './.git/*' -exec flip -u {} \;

(I put in a clause to ignore your .git directory, in case you use git, but since flip ignores binary files by default, you mightn't need this.)

Clone an image in cv2 python

You can simply use Python standard library. Make a shallow copy of the original image as follows:

import copy

original_img = cv2.imread("foo.jpg")
clone_img = copy.copy(original_img)

Android Imagebutton change Image OnClick

That is because imgButton is null. Try this instead:

findViewById(R.id.imgButton).setBackgroundResource(R.drawable.ic_action_search);

or much easier to read:

imgButton = (Button) findViewById(R.id.imgButton);
imgButton.setOnClickListener(imgButtonHandler);

then in onClick: imgButton.setBackgroundResource(R.drawable.ic_action_search);

Where can I find "make" program for Mac OS X Lion?

You need to install Xcode from App Store.

Then start Xcode, go to Xcode->Preferences->Downloads and install component named "Command Line Tools". After that all the relevant tools will be placed in /usr/bin folder and you will be able to use it just as it was in 10.6.

How to run a .awk file?

The file you give is a shell script, not an awk program. So, try sh my.awk.

If you want to use awk -f my.awk life.csv > life_out.cs, then remove awk -F , ' and the last line from the file and add FS="," in BEGIN.

Eclipse error: "Editor does not contain a main type"

Try closing and reopening the file, then press Ctrl+F11.

Verify that the name of the file you are running is the same as the name of the project you are working in, and that the name of the public class in that file is the same as the name of the project you are working in as well.

Otherwise, restart Eclipse. Let me know if this solves the problem! Otherwise, comment, and I'll try and help.

Python re.sub replace with matched content

Simply use \1 instead of $1:

In [1]: import re

In [2]: method = 'images/:id/huge'

In [3]: re.sub(r'(:[a-z]+)', r'<span>\1</span>', method)
Out[3]: 'images/<span>:id</span>/huge'

Also note the use of raw strings (r'...') for regular expressions. It is not mandatory but removes the need to escape backslashes, arguably making the code slightly more readable.

How to set the thumbnail image on HTML5 video?

<?php
$thumbs_dir = 'E:/xampp/htdocs/uploads/thumbs/';
$videos = array();
if (isset($_POST["name"])) {
 if (!preg_match('/data:([^;]*);base64,(.*)/', $_POST['data'], $matches)) {
  die("error");
 }
 $data = $matches[2];
 $data = str_replace(' ', '+', $data);
 $data = base64_decode($data);
 $file = 'text.jpg';
 $dataname = file_put_contents($thumbs_dir . $file, $data);
}
?>
//jscode
<script type="text/javascript">
 var videos = <?= json_encode($videos); ?>;
 var video = document.getElementById('video');
 video.addEventListener('canplay', function () {
     this.currentTime = this.duration / 2;
 }, false);
 var seek = true;
 video.addEventListener('seeked', function () {
    if (seek) {
         getThumb();
    }
 }, false);

 function getThumb() {
     seek = false;
     var filename = video.src;
     var w = video.videoWidth;//video.videoWidth * scaleFactor;
     var h = video.videoHeight;//video.videoHeight * scaleFactor;
     var canvas = document.createElement('canvas');
     canvas.width = w;
     canvas.height = h;
     var ctx = canvas.getContext('2d');
     ctx.drawImage(video, 0, 0, w, h);
     var data = canvas.toDataURL("image/jpg");
     var xmlhttp = new XMLHttpRequest;
     xmlhttp.onreadystatechange = function () {
         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
         }
     }
     xmlhttp.open("POST", location.href, true);
     xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
     xmlhttp.send('name=' + encodeURIComponent(filename) + '&data=' + data);
 }
  function failed(e) {
     // video playback failed - show a message saying why
     switch (e.target.error.code) {
         case e.target.error.MEDIA_ERR_ABORTED:
             console.log('You aborted the video playback.');
             break;
         case e.target.error.MEDIA_ERR_NETWORK:
             console.log('A network error caused the video download to fail part-way.');
             break;
         case e.target.error.MEDIA_ERR_DECODE:
             console.log('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');
              break;
          case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
              console.log('The video could not be loaded, either because the server or network failed or because the format is not supported.');
              break;
          default:
              console.log('An unknown error occurred.');
              break;
      }


  }
</script>
//Html
<div>
    <video   id="video" src="1499752288.mp4" autoplay="true"  onerror="failed(event)" controls="controls" preload="none"></video>
</div>

Quickly create large file on a Windows system

Simple answer in Python: If you need to create a large real text file I just used a simple while loop and was able to create a 5 GB file in about 20 seconds. I know it's crude, but it is fast enough.

outfile = open("outfile.log", "a+")

def write(outfile):
    outfile.write("hello world hello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello world"+"\n")
    return

i=0
while i < 1000000:
    write(outfile)
    i += 1
outfile.close()

How to align two elements on the same line without changing HTML

_x000D_
_x000D_
div {
  display: flex;
  justify-content: space-between;
}
_x000D_
<div>
  <p>Item one</p>
  <a>Item two</a>
</div>
_x000D_
_x000D_
_x000D_

Deleting a pointer in C++

There is a rule in C++, for every new there is a delete.

  1. Why won't the first case work? Seems the most straightforward use to use and delete a pointer? The error says the memory wasn't allocated but 'cout' returned an address.

new is never called. So the address that cout prints is the address of the memory location of myVar, or the value assigned to myPointer in this case. By writing:

myPointer = &myVar;

you say:

myPointer = The address of where the data in myVar is stored

  1. On the second example the error is not being triggered but doing a cout of the value of myPointer still returns a memory address?

It returns an address that points to a memory location that has been deleted. Because first you create the pointer and assign its value to myPointer, second you delete it, third you print it. So unless you assign another value to myPointer, the deleted address will remain.

  1. Does #3 really work? Seems to work to me, the pointer is no longer storing an address, is this the proper way to delete a pointer?

NULL equals 0, you delete 0, so you delete nothing. And it's logic that it prints 0 because you did:

myPointer = NULL;

which equals:

myPointer = 0;

jQuery hyperlinks - href value?

using jquery, you may want to get only to those with a '#'

$('a[href=#]').click(function(){return false;});

if you use the newest jquery (1.3.x), there's no need to bind it again when the page changes:

$('a[href=#]').live('click', function(){return false;});

Get IPv4 addresses from Dns.GetHostEntry()

To find all local IPv4 addresses:

IPAddress[] ipv4Addresses = Array.FindAll(
    Dns.GetHostEntry(string.Empty).AddressList,
    a => a.AddressFamily == AddressFamily.InterNetwork);

or use Array.Find or Array.FindLast if you just want one.

How can I set / change DNS using the command-prompt at windows 8

Batch file for setting a new dns server

@echo off
rem usage: setdns <dnsserver> <interface>
rem default dsnserver is dhcp
rem default interface is Wi-Fi
set dnsserver="%1"
if %dnsserver%=="" set dnsserver="dhcp"
set interface="%2"
if %interface%=="" set interface="Wi-Fi"
echo Showing current DNS setting for interface a%interface%
netsh interface ipv4 show dnsserver %interface%
echo Changing dnsserver on interface %interface% to %dnsserver%
if %dnsserver% == "dhcp" netsh interface ipv4 set dnsserver %interface% %dnsserver%
if NOT %dnsserver% == "dhcp" netsh interface ipv4 add dnsserver %interface% address=%dnsserver% index=1
echo Showing new DNS setting for interface %interface%
netsh interface ipv4 show dnsserver %interface%

Can you 'exit' a loop in PHP?

You can use the break keyword.

Hide Text with CSS, Best Practice?

Actually, a new technique came out recently. This article will answer your questions: http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement

.hide-text {
  text-indent: 100%;
  white-space: nowrap;
  overflow: hidden;
}

It is accessible, an has better performance than -99999px.

Update: As @deathlock mentions in the comment area, the author of the fix above (Scott Kellum), has suggested using a transparent font: http://scottkellum.com/2013/10/25/the-new-kellum-method.html.

How do I center an anchor element in CSS?

Two options, that have different uses:

HTML:

<a class="example" href="http://www.example.com">example</a>

CSS:

.example { text-align: center; }

Or:

.example { display:block; width:100px; margin:0 auto;}

Npm install failed with "cannot run in wd"

OP here, I have learned a lot more about node since I first asked this question. Though Dmitry's answer was very helpful, what ultimately did it for me is to install node with the correct permissions.

I highly recommend not installing node using any package managers, but rather to compile it yourself so that it resides in a local directory with normal permissions.

This article provides a very clear step-by-step instruction of how to do so:

https://www.digitalocean.com/community/tutorials/how-to-install-an-upstream-version-of-node-js-on-ubuntu-12-04

How do I delete everything in Redis?

redis-cli -h <host> -p <port> flushall

It will remove all data from client connected(with host and port)

how do you insert null values into sql server

If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.

How can you find the height of text on an HTML canvas?

setting the font size might not be practical though, since setting

ctx.font = ''

will use the one defined by CSS as well as any embedded font tags. If you use the CSS font you have no idea what the height is from a programmatic way, using the measureText method, which is very short sighted. On another note though, IE8 DOES return the width and height.

Access key value from Web.config in Razor View-MVC3 ASP.NET

FOR MVC

-- WEB.CONFIG CODE IN APP SETTING -- <add key="PhaseLevel" value="1" />

-- ON VIEWS suppose you want to show or hide something based on web.config Value--

-- WRITE THIS ON TOP OF YOUR PAGE-- @{ var phase = System.Configuration.ConfigurationManager.AppSettings["PhaseLevel"].ToString(); }

-- USE ABOVE VALUE WHERE YOU WANT TO SHOW OR HIDE.

@if (phase != "1") { @Html.Partial("~/Views/Shared/_LeftSideBarPartial.cshtml") }

How do I rename a Git repository?

For Amazon AWS codecommit users,

aws codecommit update-repository-name --old-name MyDemoRepo --new-name MyRenamedDemoRepo

Reference: here

How to convert List<string> to List<int>?

What no TryParse? Safe LINQ version that filters out invalid ints (for C# 6.0 and below):

List<int>  ints = strings
    .Select(s => { int i; return int.TryParse(s, out i) ? i : (int?)null; })
    .Where(i => i.HasValue)
    .Select(i => i.Value)
    .ToList();

credit to Olivier Jacot-Descombes for the idea and the C# 7.0 version.

Get the item doubleclick event of listview

I don't yet have a large enough reputation score to add a comment where it would be most helpful, but this is in relation to those asking about a .Net 4.5 solution.

You can use the mouse X and Y co-ordinates and the ListView method GetItemAt to find the item which has been clicked on.

private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    ListViewItem item = myListView.GetItemAt(e.X, e.Y)
    // Do something here
}

PostgreSQL IF statement

Just to help if anyone stumble on this question like me, if you want to use if in PostgreSQL, you use "CASE"

select 
    case
        when stage = 1 then 'running'
        when stage = 2 then 'done'
        when stage = 3 then 'stopped'
    else 
        'not running'
    end as run_status from processes

adb uninstall failed

Maybe you're trying to uninstall an app that is a phone administrator.

To be able to uninstall it, go to Seetings > Security > Phone Administrators. If the app is listed, uncheck it and confirm the operation.

After that, you should be able to uninstall it using the App settings area or adb.

How to replace four spaces with a tab in Sublime Text 2?

If you want to recursively apply this change to all files in a directoy, you can use the Find > Find in Files... modal:

Find in Files modal

Edit I didn't highlight it in the image, but you have to click the .* button on the left to have Sublime interpret the Find field as a regex /Edit

Edit 2 I neglected to add a start of string anchor to the regex. I'm correcting that below, and will update the image when I get a chance /Edit

The regex in the Find field ^[^\S\t\n\r]{4} will match white space characters in groups of 4 (excluding tabs and newline characters). The replace field \t indicates you would like to replace them with tabs.

If you click the button to the right of the Where field, you'll see options that will help you target your search, replace. Add Folder option will let you select the folder you'd like to recursively search from. The Add Include Filter option will let you restrict the search to files of a certain extension.

Opacity of div's background without affecting contained element in IE 8?

it's simple only you have do is to give

background: rgba(0,0,0,0.3)

& for IE use this filter

background: transparent;
zoom: 1;    
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#4C000000,endColorstr=#4C000000); /* IE 6 & 7 */
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#4C000000,endColorstr=#4C000000)"; /* IE8 */

you can generate your rgba filter from here http://kimili.com/journal/rgba-hsla-css-generator-for-internet-explorer/

Get properties of a class

There is another answer here that also fits the authors request: 'compile-time' way to get all property names defined interface

If you use the plugin ts-transformer-keys and an Interface to your class you can get all the keys for the class.

But if you're using Angular or React then in some scenarios there is additional configuration necessary (webpack and typescript) to get it working: https://github.com/kimamula/ts-transformer-keys/issues/4

Is it possible to ping a server from Javascript?

The problem with standard pings is they're ICMP, which a lot of places don't let through for security and traffic reasons. That might explain the failure.

Ruby prior to 1.9 had a TCP-based ping.rb, which will run with Ruby 1.9+. All you have to do is copy it from the 1.8.7 installation to somewhere else. I just confirmed that it would run by pinging my home router.

Count all occurrences of a string in lots of files with grep

Instead of using -c, just pipe it to wc -l.

grep string * | wc -l

This will list each occurrence on a single line and then count the number of lines.

This will miss instances where the string occurs 2+ times on one line, though.

How can I use modulo operator (%) in JavaScript?

That would be the modulo operator, which produces the remainder of the division of two numbers.

How do I view the SSIS packages in SQL Server Management Studio?

  1. Open SQL server Management Studio.
  2. Go to Connect to Server and select the Server Type as Integration Services and give the Server Name then click connect.
  3. Go to Object Explorer on the left corner.
  4. You can see the Stored Package folder in Object Explorer.
  5. Expand the Stored Package folder, here you can see the SSIS interfaces.

How can I add a background thread to flask?

Your additional threads must be initiated from the same app that is called by the WSGI server.

The example below creates a background thread that executes every 5 seconds and manipulates data structures that are also available to Flask routed functions.

import threading
import atexit
from flask import Flask

POOL_TIME = 5 #Seconds

# variables that are accessible from anywhere
commonDataStruct = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
yourThread = threading.Thread()

def create_app():
    app = Flask(__name__)

    def interrupt():
        global yourThread
        yourThread.cancel()

    def doStuff():
        global commonDataStruct
        global yourThread
        with dataLock:
        # Do your stuff with commonDataStruct Here

        # Set the next thread to happen
        yourThread = threading.Timer(POOL_TIME, doStuff, ())
        yourThread.start()   

    def doStuffStart():
        # Do initialisation stuff here
        global yourThread
        # Create your thread
        yourThread = threading.Timer(POOL_TIME, doStuff, ())
        yourThread.start()

    # Initiate
    doStuffStart()
    # When you kill Flask (SIGTERM), clear the trigger for the next thread
    atexit.register(interrupt)
    return app

app = create_app()          

Call it from Gunicorn with something like this:

gunicorn -b 0.0.0.0:5000 --log-config log.conf --pid=app.pid myfile:app

Access to ES6 array element index inside for-of loop

in html/js context, on modern browsers, with other iterable objects than Arrays we could also use [Iterable].entries():

for(let [index, element] of document.querySelectorAll('div').entries()) {

    element.innerHTML = '#' + index

}

text flowing out of div

It's due to the fact that you have one long word without spaces. You can use the word-wrap property to cause the text to break:

#w74 { word-wrap: break-word; }

It has fairly good browser support, too. See documentation about it here.

Is a Python dictionary an example of a hash table?

To expand upon nosklo's explanation:

a = {}
b = ['some', 'list']
a[b] = 'some' # this won't work
a[tuple(b)] = 'some' # this will, same as a['some', 'list']

Button Center CSS

Another nice option is to use :

width: 40%;
margin-left: 30%;
margin-right: 30%

Send a ping to each IP on a subnet

In Bash shell:

#!/bin/sh

COUNTER=1

while [ $COUNTER -lt 254 ]
do
   ping 192.168.1.$COUNTER -c 1
   COUNTER=$(( $COUNTER + 1 ))
done

Failed to load ApplicationContext from Unit Test: FileNotFound

I added the spring folder to the build path and, after clean&build, it worked.

How to create many labels and textboxes dynamically depending on the value of an integer variable?

Here is a simple example that should let you keep going add somethink that would act as a placeholder to your winform can be TableLayoutPanel

and then just add controls to it

   for ( int i = 0; i < COUNT; i++ ) {


    Label lblTitle = new Label();
    lblTitle.Text = i+"Your Text";
    youlayOut.Controls.Add( lblTitle, 0, i );

    TextBox txtValue = new TextBox();
    youlayOut.Controls.Add( txtValue, 2, i );
}

Way to go from recursion to iteration

Another simple and complete example of turning the recursive function into iterative one using the stack.

#include <iostream>
#include <stack>
using namespace std;

int GCD(int a, int b) { return b == 0 ? a : GCD(b, a % b); }

struct Par
{
    int a, b;
    Par() : Par(0, 0) {}
    Par(int _a, int _b) : a(_a), b(_b) {}
};

int GCDIter(int a, int b)
{
    stack<Par> rcstack;

    if (b == 0)
        return a;
    rcstack.push(Par(b, a % b));

    Par p;
    while (!rcstack.empty()) 
    {
        p = rcstack.top();
        rcstack.pop();
        if (p.b == 0)
            continue;
        rcstack.push(Par(p.b, p.a % p.b));
    }

    return p.a;
}

int main()
{
    //cout << GCD(24, 36) << endl;
    cout << GCDIter(81, 36) << endl;

    cin.get();
    return 0;
}

How to add a title to a html select tag

<select name="city">
   <option value ="0">What is your city</option>
   <option value ="1">Sydney</option>
   <option value ="2">Melbourne</option>
   <option value ="3">Cromwell</option>
   <option value ="4">Queenstown</option>
</select>

You can use the unique id for the value instead

How to easily get network path to the file you are working on?

Just paste the below formula in any of the cells, it will render the path of the file:

=LEFT(CELL("filename"),FIND("]",CELL("filename"),1))

The above formula works in any version of Excel.

How to pass ArrayList<CustomeObject> from one activity to another?

You can pass an ArrayList<E> the same way, if the E type is Serializable.

You would call the putExtra (String name, Serializable value) of Intent to store, and getSerializableExtra (String name) for retrieval.

Example:

ArrayList<String> myList = new ArrayList<String>();
intent.putExtra("mylist", myList);

In the other Activity:

ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("mylist");

How to convert DateTime? to DateTime

Consider using the following which its far better than the accepted answer

DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate == null 
    ? DateTime.Now : (DateTime)_objHotelPackageOrder.UpdatedDate;

How to move an entire div element up x pixels?

$('#div_id').css({marginTop: '-=15px'});

This will alter the css for the element with the id "div_id"

To get the effect you want I recommend adding the code above to a callback function in your animation (that way the div will be moved up after the animation is complete):

$('#div_id').animate({...}, function () {
    $('#div_id').css({marginTop: '-=15px'});
});

And of course you could animate the change in margin like so:

$('#div_id').animate({marginTop: '-=15px'});

Here are the docs for .css() in jQuery: http://api.jquery.com/css/

And here are the docs for .animate() in jQuery: http://api.jquery.com/animate/

Jquery selector input[type=text]')

If you have multiple inputs as text in a form or a table that you need to iterate through, I did this:

var $list = $("#tableOrForm :input[type='text']");

$list.each(function(){
    // Go on with your code.
});

What I did was I checked each input to see if the type is set to "text", then it'll grab that element and store it in the jQuery list. Then, it would iterate through that list. You can set a temp variable for the current iteration like this:

var $currentItem = $(this);

This will set the current item to the current iteration of your for each loop. Then you can do whatever you want with the temp variable.

Hope this helps anyone!

Query a parameter (postgresql.conf setting) like "max_connections"

You can use SHOW:

SHOW max_connections;

This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf in your current session:

RESET max_connections;

However, not applicable to this particular setting. The manual:

This parameter can only be set at server start.

To see all settings:

SHOW ALL;

There is also pg_settings:

The view pg_settings provides access to run-time parameters of the server. It is essentially an alternative interface to the SHOW and SET commands. It also provides access to some facts about each parameter that are not directly available from SHOW, such as minimum and maximum values.

For your original request:

SELECT *
FROM   pg_settings
WHERE  name = 'max_connections';

Finally, there is current_setting(), which can be nested in DML statements:

SELECT current_setting('max_connections');

Related:

Python: Finding differences between elements of a list

In the upcoming Python 3.10 release schedule, with the new pairwise function it's possible to slide through pairs of elements and thus map on rolling pairs:

from itertools import pairwise

[y-x for (x, y) in pairwise([1, 3, 6, 7])]
# [2, 3, 1]

The intermediate result being:

pairwise([1, 3, 6, 7])
# [(1, 3), (3, 6), (6, 7)]

How to change the size of the font of a JLabel to take the maximum size

Not the most pretty code, but the following will pick an appropriate font size for a JLabel called label such that the text inside will fit the interior as much as possible without overflowing the label:

Font labelFont = label.getFont();
String labelText = label.getText();

int stringWidth = label.getFontMetrics(labelFont).stringWidth(labelText);
int componentWidth = label.getWidth();

// Find out how much the font can grow in width.
double widthRatio = (double)componentWidth / (double)stringWidth;

int newFontSize = (int)(labelFont.getSize() * widthRatio);
int componentHeight = label.getHeight();

// Pick a new font size so it will not be larger than the height of label.
int fontSizeToUse = Math.min(newFontSize, componentHeight);

// Set the label's font size to the newly determined size.
label.setFont(new Font(labelFont.getName(), Font.PLAIN, fontSizeToUse));

Basically, the code looks at how much space the text in the JLabel takes up by using the FontMetrics object, and then uses that information to determine the largest font size that can be used without overflowing the text from the JLabel.

The above code can be inserted into perhaps the paint method of the JFrame which holds the JLabel, or some method which will be invoked when the font size needs to be changed.

The following is an screenshot of the above code in action:

alt text
(source: coobird.net)

Reliable way for a Bash script to get the full path to itself

Just for the hell of it I've done a bit of hacking on a script that does things purely textually, purely in Bash. I hope I caught all the edge cases.

Note that the ${var//pat/repl} that I mentioned in the other answer doesn't work since you can't make it replace only the shortest possible match, which is a problem for replacing /foo/../ as e.g. /*/../ will take everything before it, not just a single entry. And since these patterns aren't really regexes I don't see how that can be made to work. So here's the nicely convoluted solution I came up with, enjoy. ;)

By the way, let me know if you find any unhandled edge cases.

#!/bin/bash

canonicalize_path() {
  local path="$1"
  OIFS="$IFS"
  IFS=$'/'
  read -a parts < <(echo "$path")
  IFS="$OIFS"

  local i=${#parts[@]}
  local j=0
  local back=0
  local -a rev_canon
  while (($i > 0)); do
    ((i--))
    case "${parts[$i]}" in
      ""|.) ;;
      ..) ((back++));;
      *) if (($back > 0)); then
           ((back--))
         else
           rev_canon[j]="${parts[$i]}"
           ((j++))
         fi;;
    esac
  done
  while (($j > 0)); do
    ((j--))
    echo -n "/${rev_canon[$j]}"
  done
  echo
}

canonicalize_path "/.././..////../foo/./bar//foo/bar/.././bar/../foo/bar/./../..//../foo///bar/"

Read response body in JAX-RS client from a post request

I also had the same issue, trying to run a unit test calling code that uses readEntity. Can't use getEntity in production code because that just returns a ByteInputStream and not the content of the body and there is no way I am adding production code that is hit only in unit tests.

My solution was to create a response and then use a Mockito spy to mock out the readEntity method:

Response error = Response.serverError().build();
Response mockResponse = spy(error);
doReturn("{jsonbody}").when(mockResponse).readEntity(String.class);

Note that you can't use the when(mockResponse.readEntity(String.class) option because that throws the same IllegalStateException.

Hope this helps!

Get index of array element faster than O(n)

Still I wonder if there's a more convenient way of finding index of en element without caching (or there's a good caching technique that will boost up the performance).

You can use binary search (if your array is ordered and the values you store in the array are comparable in some way). For that to work you need to be able to tell the binary search whether it should be looking "to the left" or "to the right" of the current element. But I believe there is nothing wrong with storing the index at insertion time and then using it if you are getting the element from the same array.

Could not resolve all dependencies for configuration ':classpath'

In my case deleting the .gradle folder worked for me.

Check if DataRow exists by column name in c#?

You should try

if (row.Table.Columns.Contains("US_OTHERFRIEND"))

I don't believe that row has a columns property itself.

Defined Edges With CSS3 Filter Blur

Insert the image inside a with position: relative; and overflow: hidden;

HTML

<div><img src="#"></div>

CSS

div {
    position: relative;
    overflow: hidden;
}
img {
    filter: blur(5px);
        -webkit-filter: blur(5px);
        -moz-filter: blur(5px);
        -o-filter: blur(5px);
        -ms-filter: blur(5px);
}

This also works on variable sizes elements, like dynamic div's.

Android: how to draw a border to a LinearLayout

Extend LinearLayout/RelativeLayout and use it straight on the XML

package com.pkg_name ;
...imports...
public class LinearLayoutOutlined extends LinearLayout {
    Paint paint;    

    public LinearLayoutOutlined(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        setWillNotDraw(false) ;
        paint = new Paint();
    }
    public LinearLayoutOutlined(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        setWillNotDraw(false) ;
        paint = new Paint();
    }
    @Override
    protected void onDraw(Canvas canvas) {
        /*
        Paint fillPaint = paint;
        fillPaint.setARGB(255, 0, 255, 0);
        fillPaint.setStyle(Paint.Style.FILL);
        canvas.drawPaint(fillPaint) ;
        */

        Paint strokePaint = paint;
        strokePaint.setARGB(255, 255, 0, 0);
        strokePaint.setStyle(Paint.Style.STROKE);
        strokePaint.setStrokeWidth(2);  
        Rect r = canvas.getClipBounds() ;
        Rect outline = new Rect( 1,1,r.right-1, r.bottom-1) ;
        canvas.drawRect(outline, strokePaint) ;
    }

}

<?xml version="1.0" encoding="utf-8"?>

<com.pkg_name.LinearLayoutOutlined
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
    android:layout_width=...
    android:layout_height=...
   >
   ... your widgets here ...

</com.pkg_name.LinearLayoutOutlined>

FFmpeg: How to split video efficiently?

does the later approach save computation time and memory?

There is no big difference between those two examples that you provided. The first example cuts the video sequentially, in 2 steps, while the second example does it at the same time (using threads). No particular speed-up will be noticeable. You can read more about creating multiple outputs with FFmpeg

Further more, what you can use (in recent FFmpeg) is the stream segmenter muxer which can:

output streams to a number of separate files of nearly fixed duration. Output filename pattern can be set in a fashion similar to image2.

iPhone Debugging: How to resolve 'failed to get the task for process'?

Check ur code signing section.make sure that the code signing is iPhoneDeveloper code signe

Multiplying across in a numpy array

I've compared the different options for speed and found that – much to my surprise – all options (except diag) are equally fast. I personally use

A * b[:, None]

(or (A.T * b).T) because it's short.

enter image description here


Code to reproduce the plot:

import numpy
import perfplot


def newaxis(data):
    A, b = data
    return A * b[:, numpy.newaxis]


def none(data):
    A, b = data
    return A * b[:, None]


def double_transpose(data):
    A, b = data
    return (A.T * b).T


def double_transpose_contiguous(data):
    A, b = data
    return numpy.ascontiguousarray((A.T * b).T)


def diag_dot(data):
    A, b = data
    return numpy.dot(numpy.diag(b), A)


def einsum(data):
    A, b = data
    return numpy.einsum("ij,i->ij", A, b)


perfplot.save(
    "p.png",
    setup=lambda n: (numpy.random.rand(n, n), numpy.random.rand(n)),
    kernels=[
        newaxis,
        none,
        double_transpose,
        double_transpose_contiguous,
        diag_dot,
        einsum,
    ],
    n_range=[2 ** k for k in range(13)],
    xlabel="len(A), len(b)",
)

How do I execute a bash script in Terminal?

cd to the directory that contains the script, or put it in a bin folder that is in your $PATH

then type

./scriptname.sh

if in the same directory or

scriptname.sh

if it's in the bin folder.

Auto-fit TextView for Android

Try this

TextWatcher changeText = new TextWatcher() {
     @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tv3.setText(et.getText().toString());
                tv3.post(new Runnable() {           
                    @Override
                    public void run() {
                    while(tv3.getLineCount() >= 3){                     
                            tv3.setTextSize((tv3.getTextSize())-1);                     
                        }
                    }
                });
            }

            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override public void afterTextChanged(Editable s) { }
        };

How do I generate a list with a specified increment step?

You can use scalar multiplication to modify each element in your vector.

> r <- 0:10 
> r <- r * 2
> r 
 [1]  0  2  4  6  8 10 12 14 16 18 20

or

> r <- 0:10 * 2 
> r 
 [1]  0  2  4  6  8 10 12 14 16 18 20

UIButton Image + Text IOS

In my case, I wanted to add UIImage to the right and UILabel to the left. Maybe I can achieve that by writing code (like the above mentioned), but I prefer not to write code and get it done by using the storyboard as much as possible. So this is how did it:

First, write down something in your label box and select an image that you want to show:

enter image description here

And that will create a button looking like this:

enter image description here

Next, look for Semantic and select Force Right-to-Left (If you don't specify anything, then it will show the image to the left and label to the right like the above image):

enter image description here

Finally, you'll see UIImage to the right and UILabel to the left:

enter image description here

To add space between a label and an image, go to the Size inspector and change those values depending on your requirement:

enter image description here

That's it!

How do I paste multi-line bash codes into terminal and run it all at once?

Try putting \ at the end of each line before copying it.

Example:

echo "Hello world" && \
script_b.sh

echo $?

The exit code ($?) is now the full sequence of commands, and not just the last command.

Debian 8 (Live-CD) what is the standard login and password?

I am using Debian 8 live off a USB. I was locked out of the system after 10 min of inactivity. The password that was required to log back in to the system for the user was:

login : Debian Live User
password : live

I hope this helps

How to increase font size in a plot in R?

Notice that "cex" does change things when the plot is made with text. For example, the plot of an agglomerative hierarchical clustering:

library(cluster)
data(votes.repub)
agn1 <- agnes(votes.repub, metric = "manhattan", stand = TRUE)
plot(agn1, which.plots=2)

will produce a plot with normal sized text:

enter image description here

and plot(agn1, which.plots=2, cex=0.5) will produce this one:

enter image description here

Returning binary file from controller in ASP.NET Web API

Try using a simple HttpResponseMessage with its Content property set to a StreamContent:

// using System.IO;
// using System.Net.Http;
// using System.Net.Http.Headers;

public HttpResponseMessage Post(string version, string environment,
    string filetype)
{
    var path = @"C:\Temp\test.exe";
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = 
        new MediaTypeHeaderValue("application/octet-stream");
    return result;
}

A few things to note about the stream used:

  • You must not call stream.Dispose(), since Web API still needs to be able to access it when it processes the controller method's result to send data back to the client. Therefore, do not use a using (var stream = …) block. Web API will dispose the stream for you.

  • Make sure that the stream has its current position set to 0 (i.e. the beginning of the stream's data). In the above example, this is a given since you've only just opened the file. However, in other scenarios (such as when you first write some binary data to a MemoryStream), make sure to stream.Seek(0, SeekOrigin.Begin); or set stream.Position = 0;

  • With file streams, explicitly specifying FileAccess.Read permission can help prevent access rights issues on web servers; IIS application pool accounts are often given only read / list / execute access rights to the wwwroot.

Why use double indirection? or Why use pointers to pointers?

  • Let’s say you have a pointer. Its value is an address.
  • but now you want to change that address.
  • you could. by doing pointer1 = pointer2, you give pointer1 the address of pointer2.
  • but! if you do that within a function, and you want the result to persist after the function is done, you need do some extra work. you need a new pointer3 just to point to pointer1. pass pointer3 to the function.

  • here is an example. look at the output below first, to understand.

#include <stdio.h>

int main()
{

    int c = 1;
    int d = 2;
    int e = 3;
    int * a = &c;
    int * b = &d;
    int * f = &e;
    int ** pp = &a;  // pointer to pointer 'a'

    printf("\n a's value: %x \n", a);
    printf("\n b's value: %x \n", b);
    printf("\n f's value: %x \n", f);
    printf("\n can we change a?, lets see \n");
    printf("\n a = b \n");
    a = b;
    printf("\n a's value is now: %x, same as 'b'... it seems we can, but can we do it in a function? lets see... \n", a);
    printf("\n cant_change(a, f); \n");
    cant_change(a, f);
    printf("\n a's value is now: %x, Doh! same as 'b'...  that function tricked us. \n", a);

    printf("\n NOW! lets see if a pointer to a pointer solution can help us... remember that 'pp' point to 'a' \n");
     printf("\n change(pp, f); \n");
    change(pp, f);
    printf("\n a's value is now: %x, YEAH! same as 'f'...  that function ROCKS!!!. \n", a);
    return 0;
}

void cant_change(int * x, int * z){
    x = z;
    printf("\n ----> value of 'a' is: %x inside function, same as 'f', BUT will it be the same outside of this function? lets see\n", x);
}

void change(int ** x, int * z){
    *x = z;
    printf("\n ----> value of 'a' is: %x inside function, same as 'f', BUT will it be the same outside of this function? lets see\n", *x);
}

Here is the output: (read this first)

 a's value: bf94c204

 b's value: bf94c208 

 f's value: bf94c20c 

 can we change a?, lets see 

 a = b 

 a's value is now: bf94c208, same as 'b'... it seems we can, but can we do it in a function? lets see... 

 cant_change(a, f); 

 ----> value of 'a' is: bf94c20c inside function, same as 'f', BUT will it be the same outside of this function? lets see

 a's value is now: bf94c208, Doh! same as 'b'...  that function tricked us. 

 NOW! lets see if a pointer to a pointer solution can help us... remember that 'pp' point to 'a' 

 change(pp, f); 

 ----> value of 'a' is: bf94c20c inside function, same as 'f', BUT will it be the same outside of this function? lets see

 a's value is now: bf94c20c, YEAH! same as 'f'...  that function ROCKS!!!. 

jQuery - Sticky header that shrinks when scrolling down

Based on twitter scroll trouble (http://ejohn.org/blog/learning-from-twitter/).

Here is my solution, throttling the js scroll event (usefull for mobile devices)

JS:

$(function() {
    var $document, didScroll, offset;
    offset = $('.menu').position().top;
    $document = $(document);
    didScroll = false;
    $(window).on('scroll touchmove', function() {
      return didScroll = true;
    });
    return setInterval(function() {
      if (didScroll) {
        $('.menu').toggleClass('fixed', $document.scrollTop() > offset);
        return didScroll = false;
      }
    }, 250);
  });

CSS:

.menu {
  background: pink;
  top: 5px;
}

.fixed {
  width: 100%;
  position: fixed;
  top: 0;
}

HTML:

<div class="menu">MENU FIXED ON TOP</div>

http://codepen.io/anon/pen/BgqHw

ASP.NET Identity's default Password Hasher - How does it work and is it secure?

Here is how the default implementation (ASP.NET Framework or ASP.NET Core) works. It uses a Key Derivation Function with random salt to produce the hash. The salt is included as part of the output of the KDF. Thus, each time you "hash" the same password you will get different hashes. To verify the hash the output is split back to the salt and the rest, and the KDF is run again on the password with the specified salt. If the result matches to the rest of the initial output the hash is verified.

Hashing:

public static string HashPassword(string password)
{
    byte[] salt;
    byte[] buffer2;
    if (password == null)
    {
        throw new ArgumentNullException("password");
    }
    using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, 0x10, 0x3e8))
    {
        salt = bytes.Salt;
        buffer2 = bytes.GetBytes(0x20);
    }
    byte[] dst = new byte[0x31];
    Buffer.BlockCopy(salt, 0, dst, 1, 0x10);
    Buffer.BlockCopy(buffer2, 0, dst, 0x11, 0x20);
    return Convert.ToBase64String(dst);
}

Verifying:

public static bool VerifyHashedPassword(string hashedPassword, string password)
{
    byte[] buffer4;
    if (hashedPassword == null)
    {
        return false;
    }
    if (password == null)
    {
        throw new ArgumentNullException("password");
    }
    byte[] src = Convert.FromBase64String(hashedPassword);
    if ((src.Length != 0x31) || (src[0] != 0))
    {
        return false;
    }
    byte[] dst = new byte[0x10];
    Buffer.BlockCopy(src, 1, dst, 0, 0x10);
    byte[] buffer3 = new byte[0x20];
    Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20);
    using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, dst, 0x3e8))
    {
        buffer4 = bytes.GetBytes(0x20);
    }
    return ByteArraysEqual(buffer3, buffer4);
}

Extracting numbers from vectors of strings

Or simply:

as.numeric(gsub("\\D", "", years))
# [1] 20  1

What is username and password when starting Spring Boot with Tomcat?

I think that you have Spring Security on your class path and then spring security is automatically configured with a default user and generated password

Please look into your pom.xml file for:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

If you have that in your pom than you should have a log console message like this:

Using default security password: ce6c3d39-8f20-4a41-8e01-803166bb99b6

And in the browser prompt you will import the user user and the password printed in the console.

Or if you want to configure spring security you can take a look at Spring Boot secured example

It is explained in the Spring Boot Reference documentation in the Security section, it indicates:

The default AuthenticationManager has a single user (‘user’ username and random password, printed at `INFO` level when the application starts up)

Using default security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35

How to filter by object property in angularJS

We have Collection as below:


enter image description here

Syntax:

{{(Collection/array/list | filter:{Value : (object value)})[0].KeyName}}

Example:

{{(Collectionstatus | filter:{Value:dt.Status})[0].KeyName}}

-OR-

Syntax:

ng-bind="(input | filter)"

Example:

ng-bind="(Collectionstatus | filter:{Value:dt.Status})[0].KeyName"

DIV :after - add content after DIV

Position your <div> absolutely at the bottom and don't forget to give div.A a position: relative - http://jsfiddle.net/TTaMx/

    .A {
        position: relative;
        margin: 40px 0;
        height: 40px;
        width: 200px;
        background: #eee;
    }

    .A:after {
        content: " ";
        display: block;
        background: #c00;
        height: 29px;
        width: 100%;

        position: absolute;
        bottom: -29px;
    }?

How do I embed a mp4 movie into my html?

You should look into Video For Everyone:

Video for Everybody is very simply a chunk of HTML code that embeds a video into a website using the HTML5 element which offers native playback in Firefox 3.5 and Safari 3 & 4 and an increasing number of other browsers.

The video is played by the browser itself. It loads quickly and doesn’t threaten to crash your browser.

In other browsers that do not support , it falls back to QuickTime.

If QuickTime is not installed, Adobe Flash is used. You can host locally or embed any Flash file, such as a YouTube video.

The only downside, is that you have to have 2/3 versions of the same video stored, but you can serve to every existing device/browser that supports video (i.e.: the iPhone).

<video width="640" height="360" poster="__POSTER__.jpg" controls="controls">
    <source src="__VIDEO__.mp4" type="video/mp4" />
    <source src="__VIDEO__.webm" type="video/webm" />
    <source src="__VIDEO__.ogv" type="video/ogg" /><!--[if gt IE 6]>
    <object width="640" height="375" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"><!
    [endif]--><!--[if !IE]><!-->
    <object width="640" height="375" type="video/quicktime" data="__VIDEO__.mp4"><!--<![endif]-->
    <param name="src" value="__VIDEO__.mp4" />
    <param name="autoplay" value="false" />
    <param name="showlogo" value="false" />
    <object width="640" height="380" type="application/x-shockwave-flash"
        data="__FLASH__.swf?image=__POSTER__.jpg&amp;file=__VIDEO__.mp4">
        <param name="movie" value="__FLASH__.swf?image=__POSTER__.jpg&amp;file=__VIDEO__.mp4" />
        <img src="__POSTER__.jpg" width="640" height="360" />
        <p>
            <strong>No video playback capabilities detected.</strong>
            Why not try to download the file instead?<br />
            <a href="__VIDEO__.mp4">MPEG4 / H.264 “.mp4” (Windows / Mac)</a> |
            <a href="__VIDEO__.ogv">Ogg Theora &amp; Vorbis “.ogv” (Linux)</a>
        </p>
    </object><!--[if gt IE 6]><!-->
    </object><!--<![endif]-->
</video>

There is an updated version that is a bit more readable:

<!-- "Video For Everybody" v0.4.1 by Kroc Camen of Camen Design <camendesign.com/code/video_for_everybody>
     =================================================================================================================== -->
<!-- first try HTML5 playback: if serving as XML, expand `controls` to `controls="controls"` and autoplay likewise       -->
<!-- warning: playback does not work on iPad/iPhone if you include the poster attribute! fixed in iOS4.0                 -->
<video width="640" height="360" controls preload="none">
    <!-- MP4 must be first for iPad! -->
    <source src="__VIDEO__.MP4" type="video/mp4" /><!-- WebKit video    -->
    <source src="__VIDEO__.webm" type="video/webm" /><!-- Chrome / Newest versions of Firefox and Opera -->
    <source src="__VIDEO__.OGV" type="video/ogg" /><!-- Firefox / Opera -->
    <!-- fallback to Flash: -->
    <object width="640" height="384" type="application/x-shockwave-flash" data="__FLASH__.SWF">
        <!-- Firefox uses the `data` attribute above, IE/Safari uses the param below -->
        <param name="movie" value="__FLASH__.SWF" />
        <param name="flashvars" value="image=__POSTER__.JPG&amp;file=__VIDEO__.MP4" />
        <!-- fallback image. note the title field below, put the title of the video there -->
        <img src="__VIDEO__.JPG" width="640" height="360" alt="__TITLE__"
             title="No video playback capabilities, please download the video below" />
    </object>
</video>
<!-- you *must* offer a download link as they may be able to play the file locally. customise this bit all you want -->
<p> <strong>Download Video:</strong>
    Closed Format:  <a href="__VIDEO__.MP4">"MP4"</a>
    Open Format:    <a href="__VIDEO__.OGV">"OGG"</a>
</p>

mysql after insert trigger which updates another table's column

With your requirements you don't need BEGIN END and IF with unnecessary SELECT in your trigger. So you can simplify it to this

CREATE TRIGGER occupy_trig AFTER INSERT ON occupiedroom 
FOR EACH ROW
  UPDATE BookingRequest
     SET status = 1
   WHERE idRequest = NEW.idRequest;

how to use jQuery ajax calls with node.js

Use something like the following on the server side:

http.createServer(function (request, response) {
    if (request.headers['x-requested-with'] == 'XMLHttpRequest') {
        // handle async request
        var u = url.parse(request.url, true); //not needed

        response.writeHead(200, {'content-type':'text/json'})
        response.end(JSON.stringify(some_array.slice(1, 10))) //send elements 1 to 10
    } else {
        // handle sync request (by server index.html)
        if (request.url == '/') {
            response.writeHead(200, {'content-type': 'text/html'})
            util.pump(fs.createReadStream('index.html'), response)
        } 
        else 
        {
            // 404 error
        }
    }
}).listen(31337)

SQL Server: how to create a stored procedure

T-SQL

/* 
Stored Procedure GetstudentnameInOutputVariable is modified to collect the
email address of the student with the help of the Alert Keyword
*/



CREATE  PROCEDURE GetstudentnameInOutputVariable
(

@studentid INT,                   --Input parameter ,  Studentid of the student
@studentname VARCHAR (200) OUT,    -- Output parameter to collect the student name
@StudentEmail VARCHAR (200)OUT     -- Output Parameter to collect the student email
)
AS
BEGIN
SELECT @studentname= Firstname+' '+Lastname, 
    @StudentEmail=email FROM tbl_Students WHERE studentid=@studentid
END

reading from app.config file

The reason is simple, your call to ConfigurationSettings.AppSettings is not returning the required config file. Please try any of the following ways:

  • Make sure your app config has the same name as your application's exe file - with the extension .config appended eg MyApp.exe.config
  • OR you can use ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location).AppSettings["StartingMonthColumn"]

Hope this helps

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO

ALTER TABLE `{$installer->getTable('sales/quote_payment')}`
ADD `custom_field_one` VARCHAR( 255 ) NOT NULL,
    ADD `custom_field_two` VARCHAR( 255 ) NOT NULL;

Add backtick i.e. " ` " properly. Write your getTable name and column name between backtick.

How to detect Windows 64-bit platform with .NET?

UPDATE: As Joel Coehoorn and others suggest, starting at .NET Framework 4.0, you can just check Environment.Is64BitOperatingSystem.


IntPtr.Size won't return the correct value if running in 32-bit .NET Framework 2.0 on 64-bit Windows (it would return 32-bit).

As Microsoft's Raymond Chen describes, you have to first check if running in a 64-bit process (I think in .NET you can do so by checking IntPtr.Size), and if you are running in a 32-bit process, you still have to call the Win API function IsWow64Process. If this returns true, you are running in a 32-bit process on 64-bit Windows.

Microsoft's Raymond Chen: How to detect programmatically whether you are running on 64-bit Windows

My solution:

static bool is64BitProcess = (IntPtr.Size == 8);
static bool is64BitOperatingSystem = is64BitProcess || InternalCheckIsWow64();

[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWow64Process(
    [In] IntPtr hProcess,
    [Out] out bool wow64Process
);

public static bool InternalCheckIsWow64()
{
    if ((Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1) ||
        Environment.OSVersion.Version.Major >= 6)
    {
        using (Process p = Process.GetCurrentProcess())
        {
            bool retVal;
            if (!IsWow64Process(p.Handle, out retVal))
            {
                return false;
            }
            return retVal;
        }
    }
    else
    {
        return false;
    }
}

How can I get a process handle by its name in C++?

The following code shows how you can use toolhelp and OpenProcess to get a handle to the process. Error handling removed for brevity.

HANDLE GetProcessByName(PCSTR name)
{
    DWORD pid = 0;

    // Create toolhelp snapshot.
    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    PROCESSENTRY32 process;
    ZeroMemory(&process, sizeof(process));
    process.dwSize = sizeof(process);

    // Walkthrough all processes.
    if (Process32First(snapshot, &process))
    {
        do
        {
            // Compare process.szExeFile based on format of name, i.e., trim file path
            // trim .exe if necessary, etc.
            if (string(process.szExeFile) == string(name))
            {
               pid = process.th32ProcessID;
               break;
            }
        } while (Process32Next(snapshot, &process));
    }

    CloseHandle(snapshot);

    if (pid != 0)
    {
         return OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
    }

    // Not found


       return NULL;
}

Optimistic vs. Pessimistic locking

There are basically two most popular answers. The first one basically says

Optimistic needs a three-tier architectures where you do not necessarily maintain a connection to the database for your session whereas Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking you need either a direct connection to the database.

Another answer is

optimistic (versioning) is faster because of no locking but (pessimistic) locking performs better when contention is high and it is better to prevent the work rather than discard it and start over.

or

Optimistic locking works best when you have rare collisions

As it is put on this page.

I created my answer to explain how "keep connection" is related to "low collisions".

To understand which strategy is best for you, think not about the Transactions Per Second your DB has but the duration of a single transaction. Normally, you open trasnaction, performa operation and close the transaction. This is a short, classical transaction ANSI had in mind and fine to get away with locking. But, how do you implement a ticket reservation system where many clients reserve the same rooms/seats at the same time?

You browse the offers, fill in the form with lots of available options and current prices. It takes a lot of time and options can become obsolete, all the prices invalid between you started to fill the form and press "I agree" button because there was no lock on the data you have accessed and somebody else, more agile, has intefered changing all the prices and you need to restart with new prices.

You could lock all the options as you read them, instead. This is pessimistic scenario. You see why it sucks. Your system can be brought down by a single clown who simply starts a reservation and goes smoking. Nobody can reserve anything before he finishes. Your cash flow drops to zero. That is why, optimistic reservations are used in reality. Those who dawdle too long have to restart their reservation at higher prices.

In this optimistic approach you have to record all the data that you read (as in mine Repeated Read) and come to the commit point with your version of data (I want to buy shares at the price you displayed in this quote, not current price). At this point, ANSI transaction is created, which locks the DB, checks if nothing is changed and commits/aborts your operation. IMO, this is effective emulation of MVCC, which is also associated with Optimistic CC and also assumes that your transaction restarts in case of abort, that is you will make a new reservation. A transaction here involves a human user decisions.

I am far from understanding how to implement the MVCC manually but I think that long-running transactions with option of restart is the key to understanding the subject. Correct me if I am wrong anywhere. My answer was motivated by this Alex Kuznecov chapter.

how to evenly distribute elements in a div next to each other?

In the 'old days' you'd use a table and your menu items would be evenly spaced without having to explicitly state the width for the number of items.

If it wasn't for IE 6 and 7 (if that is of concern) then you can do the same in CSS.

<div class="demo">
    <span>Span 1</span>
    <span>Span 2</span>
    <span>Span 3</span>
</div>

CSS:

div.demo {
    display: table;
    width: 100%;
    table-layout: fixed;    /* For cells of equal size */
}
div.demo span {
    display: table-cell;
    text-align: center;
}

Without having to adjust for the number of items.

Example without table-layout:fixed - the cells are evenly distributed across the full width, but they are not necessarily of equal size since their width is determined by their contents.

Example with table-layout:fixed - the cells are of equal size, regardless of their contents. (Thanks to @DavidHerse in comments for this addition.)

If you want the first and last menu elements to be left and right justified, then you can add the following CSS:

div.demo span:first-child {
    text-align: left;
}
div.demo span:last-child {
    text-align: right;
}

How to restart a single container with docker-compose

Since some of the other answers include info on rebuilding, and my use case also required a rebuild, I had a better solution (compared to those).

There's still a way to easily target just the one single worker container that both rebuilds + restarts it in a single line, albeit it's not actually a single command. The best solution for me was simply rebuild and restart:

docker-compose build worker && docker-compose restart worker

This accomplishes both major goals at once for me:

  1. Targets the single worker container
  2. Rebuilds and restarts it in a single line

Hope this helps anyone else getting here.