Programs & Examples On #Nsxmlparser

NSXMLParser is a class of the Foundation Framework of Mac OSX developer library. This class allows developers to parse XML documents (including DTD declarations) in an event-driven manner.

How do I append to a table in Lua

I'd personally make use of the table.insert function:

table.insert(a,"b");

This saves you from having to iterate over the whole table therefore saving valuable resources such as memory and time.

The import javax.persistence cannot be resolved

My solution was to select the maven profiles I had defined in my pom.xml in which I had declared the hibernate dependencies.

CTRL + ALT + P in eclipse.

In my project I was experiencing this problem and many others because in my pom I have different profiles for supporting Glassfish 3, Glassfish 4 and also WildFly so I have differet versions of Hibernate per container as well as different Java compilation targets and so on. Selecting the active maven profiles resolved my issue.

Setting up SSL on a local xampp/apache server

Apache part - enabling you to open https://localhost/xyz

There is the config file xampp/apache/conf/extra/httpd-ssl.conf which contains all the ssl specific configuration. It's fairly well documented, so have a read of the comments and take look at http://httpd.apache.org/docs/2.2/ssl/. The files starts with <IfModule ssl_module>, so it only has an effect if the apache has been started with its mod_ssl module.

Open the file xampp/apache/conf/httpd.conf in an editor and search for the line

#LoadModule ssl_module modules/mod_ssl.so

remove the hashmark, save the file and re-start the apache. The webserver should now start with xampp's basic/default ssl confguration; good enough for testing but you might want to read up a bit more about mod_ssl in the apache documentation.


PHP part - enabling adldap to use ldap over ssl

adldap needs php's openssl extension to use "ldap over ssl" connections. The openssl extension ships as a dll with xampp. You must "tell" php to load this dll, e.g. by having an extension=nameofmodule.dll in your php.ini
Run

echo 'ini: ', get_cfg_var('cfg_file_path');

It should show you which ini file your php installation uses (may differ between the php-apache-module and the php-cli version).
Open this file in an editor and search for

;extension=php_openssl.dll

remove the semicolon, save the file and re-start the apache.

see also: http://docs.php.net/install.windows.extensions

Best method to download image from url in Android

I recommend using the altex-image-downloader library, which makes it easy to download images:

AltexImageDownloader.writeToDisk(context, Imageurl, "IMAGES");

Add dependency in app build gradle:

implementation 'com.artjimlop:altex-image-downloader:0.0.4'

Npm install failed with "cannot run in wd"

I have experienced the same problem when trying to publish my nodejs app in a private server running CentOs using root user. The same error is fired by "postinstall": "./node_modules/bower/bin/bower install" in my package.json file so the only solution that was working for me is to use both options to avoid the error:

1: use --allow-root option for bower install command

"postinstall": "./node_modules/bower/bin/bower --allow-root install"

2: use --unsafe-perm option for npm install command

npm install --unsafe-perm

How do you get the cursor position in a textarea?

Here is code to get line number and column position

function getLineNumber(tArea) {

    return tArea.value.substr(0, tArea.selectionStart).split("\n").length;
}

function getCursorPos() {
    var me = $("textarea[name='documenttext']")[0];
    var el = $(me).get(0);
    var pos = 0;
    if ('selectionStart' in el) {
        pos = el.selectionStart;
    } else if ('selection' in document) {
        el.focus();
        var Sel = document.selection.createRange();
        var SelLength = document.selection.createRange().text.length;
        Sel.moveStart('character', -el.value.length);
        pos = Sel.text.length - SelLength;
    }
    var ret = pos - prevLine(me);
    alert(ret);

    return ret; 
}

function prevLine(me) {
    var lineArr = me.value.substr(0, me.selectionStart).split("\n");

    var numChars = 0;

    for (var i = 0; i < lineArr.length-1; i++) {
        numChars += lineArr[i].length+1;
    }

    return numChars;
}

tArea is the text area DOM element

How to use SharedPreferences in Android to store, fetch and edit values

Setting values in Preference:

// MY_PREFS_NAME - a static String variable like: 
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("name", "Elena");
 editor.putInt("idName", 12);
 editor.commit();

Retrieve data from preference:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
  String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
  int idName = prefs.getInt("idName", 0); //0 is the default value.
}

more info:

Using Shared Preferences

Shared Preferences

One time page refresh after first page load

After </body> tag:

<script type="text/javascript">
if (location.href.indexOf('reload')==-1)
{
   location.href=location.href+'?reload';
}
</script>

Rails Root directory path?

You can use:

Rails.root

But to to join the assets you can use:

Rails.root.join(*%w( app assets))

Hopefully this helps you.

How to execute the start script with Nodemon

If globally installed then

"scripts": {
    "start": "nodemon FileName.js(server.js)",
},

Make sure you have installed nodemon globally:

npm install -g nodemon

Finally, if you are a Windows user, make sure that the security restriction of the Windows PowerShell is enabled.

Center align a column in twitter bootstrap

The question is correctly answered here Center a column using Twitter Bootstrap 3

For odd rows: i.e., col-md-7 or col-large-9 use this

Add col-centered to the column you want centered.

<div class="col-lg-11 col-centered">    

And add this to your stylesheet:

.col-centered{
float: none;
margin: 0 auto;
}

For even rows: i.e., col-md-6 or col-large-10 use this

Simply use bootstrap 3's offset col class. i.e.,

<div class="col-lg-10 col-lg-offset-1">

Creating table variable in SQL server 2008 R2

@tableName Table variables are alive for duration of the script running only i.e. they are only session level objects.

To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.

There is another type of table object which can be created for temporary use. They are #tableName objects declared like similar create statement for physical tables:

Create table #test (Id int, Name varchar(50))

This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.

IF OBJECT_ID('tempdb..#test') IS NOT NULL
  DROP TABLE #test 

Hope this makes sense !

Export JAR with Netbeans

It does this by default, you just need to look into the project's /dist folder.

Static Initialization Blocks

It's also useful when you actually don't want to assign the value to anything, such as loading some class only once during runtime.

E.g.

static {
    try {
        Class.forName("com.example.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        throw new ExceptionInInitializerError("Cannot load JDBC driver.", e);
    }
}

Hey, there's another benefit, you can use it to handle exceptions. Imagine that getStuff() here throws an Exception which really belongs in a catch block:

private static Object stuff = getStuff(); // Won't compile: unhandled exception.

then a static initializer is useful here. You can handle the exception there.

Another example is to do stuff afterwards which can't be done during assigning:

private static Properties config = new Properties();

static {
    try { 
        config.load(Thread.currentThread().getClassLoader().getResourceAsStream("config.properties");
    } catch (IOException e) {
        throw new ExceptionInInitializerError("Cannot load properties file.", e);
    }
}

To come back to the JDBC driver example, any decent JDBC driver itself also makes use of the static initializer to register itself in the DriverManager. Also see this and this answer.

WordPress - Check if user is logged in

I think that. When guest is launching page, but Admin is not logged in we don`t show something, for example the Chat.

add_action('init', 'chat_status');

function chat_status(){

    if( get_option('admin_logged') === 1) { echo "<style>.chat{display:block;}</style>";}
        else { echo "<style>.chat{display:none;}</style>";}

}



add_action('wp_login', function(){

    if( wp_get_current_user()->roles[0] == 'administrator' ) update_option('admin_logged', 1);
});


add_action('wp_logout', function(){
    if( wp_get_current_user()->roles[0] == 'administrator' ) update_option('admin_logged', 0);
});

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

I usually use git on my linux machine, but at work I have to use Windows. I had the same problem when trying to commit the first commit in a Windows environment.

For those still facing this problem, I was able to resolve it as follows:

$ git commit --allow-empty -n -m "Initial commit".

How to change the text color of first select option

For Option 1 used as the placeholder:

select:invalid { color:grey; }

All other options:

select:valid { color:black; }

How can I hide a TD tag using inline JavaScript or CSS?

<td style = "display:none" >
<p> Content display none </p>
</td>

or

<td style="visibility:hidden"> Your content is hidden </td>

Notice that: 2 those ways are differnce. You should try it to check the result.

How do you convert epoch time in C#?

// convert datetime to unix epoch seconds
public static long ToUnixTime(DateTime date)
{
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return Convert.ToInt64((date.ToUniversalTime() - epoch).TotalSeconds);
}

Should use ToUniversalTime() for the DateTime object.

How to combine date from one field with time from another field - MS SQL Server

This is an alternative solution without any char conversions:

DATEADD(ms, DATEDIFF(ms, '00:00:00', [Time]), CONVERT(DATETIME, [Date]))

You will only get milliseconds accuracy this way, but that would normally be OK. I have tested this in SQL Server 2008.

How to Force New Google Spreadsheets to refresh and recalculate?

Quick, but manual


Updating NOW(), TODAY(), RAND(), or RANDBETWEEN() formulas

Press Backspace ? or Del on any empty cell to immediately trigger a recalculation of formulas depending on NOW(), TODAY(), RAND(), or RANDBETWEEN() (in all Sheets of the whole Spreadsheet, as usual).

(If no empty cell is at hand, you can delete a filled cell instead and then undo that with Ctrl+z.)

INDIRECT() formulas are unfortunately not updated like this by default.

Updating INDIRECT() formulas

You can update a (range of) cells of INDIRECT() formulas by pasting the range on itself:

  1. Select cell/ range
  2. Ctrl+C
  3. Ctrl+V

You can use Ctrl+A to select the whole current Sheet in step 1.. But for large Sheets then the other 2 operations can take several seconds each.
A trick to know when the process of copying a large range has finished: Copy some single cell before copying your range: The single cell losing its dotted border will be your notification of the large copy finishing.

Correct way to select from two tables in SQL Server with no common field to join on

You can (should) use CROSS JOIN. Following query will be equivalent to yours:

SELECT 
   table1.columnA
 , table2.columnA
FROM table1 
CROSS JOIN table2
WHERE table1.columnA = 'Some value'

or you can even use INNER JOIN with some always true conditon:

FROM table1 
INNER JOIN table2 ON 1=1

Regular Expression: Any character that is NOT a letter or number

This regular expression matches anything that isn't a letter, digit, or an underscore (_) character.

\W

For example in JavaScript:

"(,,@,£,() asdf 345345".replace(/\W/g, ' '); // Output: "          asdf 345345"

Call to undefined function App\Http\Controllers\ [ function name ]

If they are in the same controller class, it would be:

foreach ( $characters as $character) {
    $num += $this->getFactorial($index) * $index;
    $index ++;
}

Otherwise you need to create a new instance of the class, and call the method, ie:

$controller = new MyController();
foreach ( $characters as $character) {
    $num += $controller->getFactorial($index) * $index;
    $index ++;
}

Bootstrap: How do I identify the Bootstrap version?

you will see your current bootstrap version in this "bootstrap.min.css/bootstrap.css" files, In the top section

How do you get the magnitude of a vector in Numpy?

If you are worried at all about speed, you should instead use:

mag = np.sqrt(x.dot(x))

Here are some benchmarks:

>>> import timeit
>>> timeit.timeit('np.linalg.norm(x)', setup='import numpy as np; x = np.arange(100)', number=1000)
0.0450878
>>> timeit.timeit('np.sqrt(x.dot(x))', setup='import numpy as np; x = np.arange(100)', number=1000)
0.0181372

EDIT: The real speed improvement comes when you have to take the norm of many vectors. Using pure numpy functions doesn't require any for loops. For example:

In [1]: import numpy as np

In [2]: a = np.arange(1200.0).reshape((-1,3))

In [3]: %timeit [np.linalg.norm(x) for x in a]
100 loops, best of 3: 4.23 ms per loop

In [4]: %timeit np.sqrt((a*a).sum(axis=1))
100000 loops, best of 3: 18.9 us per loop

In [5]: np.allclose([np.linalg.norm(x) for x in a],np.sqrt((a*a).sum(axis=1)))
Out[5]: True

error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied

I've heard that using sudo with pip is unsafe.

Try adding --user to the end of your command, as mentioned here.

pip install packageName --user

I suspect that installing with this method means the packages are not available to other users.

ipython notebook clear cell output in code

And in case you come here, like I did, looking to do the same thing for plots in a Julia notebook in Jupyter, using Plots, you can use:

    IJulia.clear_output(true)

so for a kind of animated plot of multiple runs

    if nrun==1  
      display(plot(x,y))         # first plot
    else 
      IJulia.clear_output(true)  # clear the window (as above)
      display(plot!(x,y))        # plot! overlays the plot
    end

Without the clear_output call, all plots appear separately.

Rails has_many with alias name

You could do this two different ways. One is by using "as"

has_many :tasks, :as => :jobs

or

def jobs
     self.tasks
end

Obviously the first one would be the best way to handle it.

Subtract minute from DateTime in SQL Server 2005

You want to use DATEADD, using a negative duration. e.g.

DATEADD(minute, -15, '2000-01-01 08:30:00') 

Java 8 stream reverse order

Many of the solutions here sort or reverse the IntStream, but that unnecessarily requires intermediate storage. Stuart Marks's solution is the way to go:

static IntStream revRange(int from, int to) {
    return IntStream.range(from, to).map(i -> to - i + from - 1);
}

It correctly handles overflow as well, passing this test:

@Test
public void testRevRange() {
    assertArrayEquals(revRange(0, 5).toArray(), new int[]{4, 3, 2, 1, 0});
    assertArrayEquals(revRange(-5, 0).toArray(), new int[]{-1, -2, -3, -4, -5});
    assertArrayEquals(revRange(1, 4).toArray(), new int[]{3, 2, 1});
    assertArrayEquals(revRange(0, 0).toArray(), new int[0]);
    assertArrayEquals(revRange(0, -1).toArray(), new int[0]);
    assertArrayEquals(revRange(MIN_VALUE, MIN_VALUE).toArray(), new int[0]);
    assertArrayEquals(revRange(MAX_VALUE, MAX_VALUE).toArray(), new int[0]);
    assertArrayEquals(revRange(MIN_VALUE, MIN_VALUE + 1).toArray(), new int[]{MIN_VALUE});
    assertArrayEquals(revRange(MAX_VALUE - 1, MAX_VALUE).toArray(), new int[]{MAX_VALUE - 1});
}

How to group by month from Date field using sql

SELECT  to_char(Closing_Date,'MM'), 
        Category,  
        COUNT(Status) TotalCount 
FROM    MyTable
WHERE   Closing_Date >= '2012-02-01' 
AND     Closing_Date <= '2012-12-31'
AND     Defect_Status1 IS NOT NULL
GROUP BY Category;

How to gettext() of an element in Selenium Webdriver

text = driver.findElement(By.id('p_id')).getAttribute("innerHTML");

How to install wkhtmltopdf on a linux based (shared hosting) web server

Debian 8 Jessie
This works sudo apt-get install wkhtmltopdf

Read MS Exchange email in C#

Here is some old code I had laying around to do WebDAV. I think it was written against Exchange 2003, but I don't remember any more. Feel free to borrow it if its helpful...

class MailUtil
{
    private CredentialCache creds = new CredentialCache();

    public MailUtil()
    {
        // set up webdav connection to exchange
        this.creds = new CredentialCache();
        this.creds.Add(new Uri("http://mail.domain.com/Exchange/[email protected]/Inbox/"), "Basic", new NetworkCredential("myUserName", "myPassword", "WINDOWSDOMAIN"));
    }

    /// <summary>
    /// Gets all unread emails in a user's Inbox
    /// </summary>
    /// <returns>A list of unread mail messages</returns>
    public List<model.Mail> GetUnreadMail()
    {
        List<model.Mail> unreadMail = new List<model.Mail>();

        string reqStr =
            @"<?xml version=""1.0""?>
                <g:searchrequest xmlns:g=""DAV:"">
                    <g:sql>
                        SELECT
                            ""urn:schemas:mailheader:from"", ""urn:schemas:httpmail:textdescription""
                        FROM
                            ""http://mail.domain.com/Exchange/[email protected]/Inbox/"" 
                        WHERE 
                            ""urn:schemas:httpmail:read"" = FALSE 
                            AND ""urn:schemas:httpmail:subject"" = 'tbintg' 
                            AND ""DAV:contentclass"" = 'urn:content-classes:message' 
                        </g:sql>
                </g:searchrequest>";

        byte[] reqBytes = Encoding.UTF8.GetBytes(reqStr);

        // set up web request
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://mail.domain.com/Exchange/[email protected]/Inbox/");
        request.Credentials = this.creds;
        request.Method = "SEARCH";
        request.ContentLength = reqBytes.Length;
        request.ContentType = "text/xml";
        request.Timeout = 300000;

        using (Stream requestStream = request.GetRequestStream())
        {
            try
            {
                requestStream.Write(reqBytes, 0, reqBytes.Length);
            }
            catch
            {
            }
            finally
            {
                requestStream.Close();
            }
        }

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        using (Stream responseStream = response.GetResponseStream())
        {
            try
            {
                XmlDocument document = new XmlDocument();
                document.Load(responseStream);

                // set up namespaces
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable);
                nsmgr.AddNamespace("a", "DAV:");
                nsmgr.AddNamespace("b", "urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/");
                nsmgr.AddNamespace("c", "xml:");
                nsmgr.AddNamespace("d", "urn:schemas:mailheader:");
                nsmgr.AddNamespace("e", "urn:schemas:httpmail:");

                // Load each response (each mail item) into an object
                XmlNodeList responseNodes = document.GetElementsByTagName("a:response");
                foreach (XmlNode responseNode in responseNodes)
                {
                    // get the <propstat> node that contains valid HTTP responses
                    XmlNode uriNode = responseNode.SelectSingleNode("child::a:href", nsmgr);
                    XmlNode propstatNode = responseNode.SelectSingleNode("descendant::a:propstat[a:status='HTTP/1.1 200 OK']", nsmgr);
                    if (propstatNode != null)
                    {
                        // read properties of this response, and load into a data object
                        XmlNode fromNode = propstatNode.SelectSingleNode("descendant::d:from", nsmgr);
                        XmlNode descNode = propstatNode.SelectSingleNode("descendant::e:textdescription", nsmgr);

                        // make new data object
                        model.Mail mail = new model.Mail();
                        if (uriNode != null)
                            mail.Uri = uriNode.InnerText;
                        if (fromNode != null)
                            mail.From = fromNode.InnerText;
                        if (descNode != null)
                            mail.Body = descNode.InnerText;
                        unreadMail.Add(mail);
                    }
                }

            }
            catch (Exception e)
            {
                string msg = e.Message;
            }
            finally
            {
                responseStream.Close();
            }
        }

        return unreadMail;
    }
}

And model.Mail:

class Mail
{
    private string uri;
    private string from;
    private string body;

    public string Uri
    {
        get { return this.uri; }
        set { this.uri = value; }
    }

    public string From
    {
        get { return this.from; }
        set { this.from = value; }
    }

    public string Body
    {
        get { return this.body; }
        set { this.body = value; }
    }
}

Java equivalent of unsigned long long?

I don't believe so. Once you want to go bigger than a signed long, I think BigInteger is the only (out of the box) way to go.

"Active Directory Users and Computers" MMC snap-in for Windows 7?

Hey guys it exist a much more sexy tool for a developper to have a look into a Directory, whatever the Directory is (Active-Directory, OpenLDAP, eDirectory ...) its name is Apache Directory studio, it works in the same way on the top of java in Windows or in Linux. It's a kind of universal LDP.EXE for those who know this tool on Windows Servers. It allows to create LDIF files and also to browse the SCHEMA.

What does the following Oracle error mean: invalid column index

I had this problem in one legacy application that create prepared statement dynamically.

String firstName;
StringBuilder query =new StringBuilder("select id, name from employee where country_Code=1");
query.append("and  name like '");
query.append(firstName + "' ");
query.append("and ssn=?");
PreparedStatement preparedStatement =new prepareStatement(query.toString());

when it try to set value for ssn, it was giving invalid column index error, and finally found out that it is caused by firstName having ' within; that disturb the syntax.

Scale the contents of a div by a percentage?

You can simply use the zoom property:

#myContainer{
    zoom: 0.5;
    -moz-transform: scale(0.5);
}

Where myContainer contains all the elements you're editing. This is supported in all major browsers.

Contain an image within a div?

  <div id ="container">
    <img src = "http://animalia-life.com/data_images/duck/duck9.jpg"/>
#container img {
        max-width:250px;
        max-height:250px;
        width: 250px;
        height: 250px;
        border:1px solid #000;
    }

The img will lose aspect ratio

Remove empty strings from a list of strings

For a list with a combination of spaces and empty values, use simple list comprehension -

>>> s = ['I', 'am', 'a', '', 'great', ' ', '', '  ', 'person', '!!', 'Do', 'you', 'think', 'its', 'a', '', 'a', '', 'joke', '', ' ', '', '?', '', '', '', '?']

So, you can see, this list has a combination of spaces and null elements. Using the snippet -

>>> d = [x for x in s if x.strip()]
>>> d
>>> d = ['I', 'am', 'a', 'great', 'person', '!!', 'Do', 'you', 'think', 'its', 'a', 'a', 'joke', '?', '?']

How to select all records from one table that do not exist in another table?

I don't have enough rep points to vote up froadie's answer. But I have to disagree with the comments on Kris's answer. The following answer:

SELECT name
FROM table2
WHERE name NOT IN
    (SELECT name 
     FROM table1)

Is FAR more efficient in practice. I don't know why, but I'm running it against 800k+ records and the difference is tremendous with the advantage given to the 2nd answer posted above. Just my $0.02.

appending list but error 'NoneType' object has no attribute 'append'

You are not supposed to assign it to any variable, when you append something in the list, it updates automatically. use only:-

last_list.append(p.last)

if you assign this to a variable "last_list" again, it will no more be a list (will become a none type variable since you haven't declared the type for that) and append will become invalid in the next run.

yum error "Cannot retrieve metalink for repository: epel. Please verify its path and try again" updating ContextBroker

Another possible cause is that your architecture is not supported. I ran into this because I was provided with a CentOS VM, wanted to install EPEL and couldn't for the life of me get it done.

Turns out the VM was CentOS 7 i386, which is an architecture that is apparently no longer supported by EPEL. I guess the only remedy in this case is to reinstall.

display HTML page after loading complete

you can also go for this.... this will only show the HTML section once javascript has loaded.

<!-- Adds the hidden style and removes it when javascript has loaded -->
<style type="text/css">
    .hideAll  {
        visibility:hidden;
     }
</style>

<script type="text/javascript">
    $(window).load(function () {
        $("#tabs").removeClass("hideAll");
    });
</script>

<div id="tabs" class="hideAll">
   ##Content##
</div>

Twitter Bootstrap Button Text Word Wrap

FWIW, in Boostrap 4.4, you can add .text-wrap style to things like buttons:

   <a href="#" class="btn btn-primary text-wrap">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>

https://getbootstrap.com/docs/4.4/utilities/text/#text-wrapping-and-overflow

python setup.py uninstall

At {virtualenv}/lib/python2.7/site-packages/ (if not using virtualenv then {system_dir}/lib/python2.7/dist-packages/)

  • Remove the egg file (e.g. distribute-0.6.34-py2.7.egg)
  • If there is any from file easy-install.pth, remove the corresponding line (it should be a path to the source directory or of an egg file).

How to set timeout in Retrofit library?

These answers were outdated for me, so here's how it worked out.

Add OkHttp, in my case the version is 3.3.1:

compile 'com.squareup.okhttp3:okhttp:3.3.1'

Then before building your Retrofit, do this:

OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
    .connectTimeout(60, TimeUnit.SECONDS)
    .readTimeout(60, TimeUnit.SECONDS)
    .writeTimeout(60, TimeUnit.SECONDS)
    .build();
return new Retrofit.Builder()
    .baseUrl(baseUrl)
    .client(okHttpClient)
    .addConverterFactory(GsonConverterFactory.create())
    .build();

C++ convert from 1 char to string?

All of

std::string s(1, c); std::cout << s << std::endl;

and

std::cout << std::string(1, c) << std::endl;

and

std::string s; s.push_back(c); std::cout << s << std::endl;

worked for me.

How do you convert WSDLs to Java classes using Eclipse?

The Eclipse team with The Open University have prepared the following document, which includes creating proxy classes with tests. It might be what you are looking for.

http://www.eclipse.org/webtools/community/education/web/t320/Generating_a_client_from_WSDL.pdf

Everything is included in the Dynamic Web Project template.

In the project create a Web Service Client. This starts a wizard that has you point out a wsdl url and creates the client with tests for you.

The user guide (targeted at indigo though) for this task is found at http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.jst.ws.cxf.doc.user%2Ftasks%2Fcreate_client.html.

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

This is the way it worked for me:

$.post("/Controller/Action", $("#form").serialize(), function(json) {       
        // handle response
}, "json");

[HttpPost]
public ActionResult TV(MyModel id)
{
    return Json(new { success = true });
}

java.security.AccessControlException: Access denied (java.io.FilePermission

Although it is not recommended, but if you really want to let your web application access a folder outside its deployment directory. You need to add following permission in java.policy file (path is as in the reply of Petey B)

permission java.io.FilePermission "your folder path", "write"

In your case it would be

permission java.io.FilePermission "S:/PDSPopulatingProgram/-", "write"

Here /- means any files or sub-folders inside this folder.

Warning: But by doing this, you are inviting some security risk.

Print a file's last modified date in Bash

You can use:

ls -lrt filename |awk '{print "%02d",$7}'

This will display the date in 2 digits.

If between 1 to 9 it adds "0" prefix to it and converts to 01 - 09.

Hope this meets the expectation.

How can I set a custom baud rate on Linux?

I noticed the same thing about BOTHER not being defined. Like Jamey Sharp said, you can find it in <asm/termios.h>. Just a forewarning, I think I ran into problems including both it and the regular <termios.h> file at the same time.

Aside from that, I found with the glibc I have, it still didn't work because glibc's tcsetattr was doing the ioctl for the old-style version of struct termios which doesn't pay attention to the speed setting. I was able to set a custom speed by manually doing an ioctl with the new style termios2 struct, which should also be available by including <asm/termios.h>:

struct termios2 tio;

ioctl(fd, TCGETS2, &tio);
tio.c_cflag &= ~CBAUD;
tio.c_cflag |= BOTHER;
tio.c_ispeed = 12345;
tio.c_ospeed = 12345;
ioctl(fd, TCSETS2, &tio);

Error in Eclipse: "The project cannot be built until build path errors are resolved"

In my case, all libraries in the build path were OK.

To solve it, I deleted all project metadata (.project, .classpath, .settings) and re-imported the project as a Maven project.

Add User to Role ASP.NET Identity

I found good answer here Adding Role dynamically in new VS 2013 Identity UserManager

But in case to provide an example so you can check it I am gonna share some default code.

First make sure you have Roles inserted.

enter image description here

And second test it on user register method.

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser() { UserName = model.UserName  };

        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            var currentUser = UserManager.FindByName(user.UserName); 

            var roleresult = UserManager.AddToRole(currentUser.Id, "Superusers");

            await SignInAsync(user, isPersistent: false);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            AddErrors(result);
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

And finally you have to get "Superusers" from the Roles Dropdown List somehow.

How is malloc() implemented internally?

It's also important to realize that simply moving the program break pointer around with brk and sbrk doesn't actually allocate the memory, it just sets up the address space. On Linux, for example, the memory will be "backed" by actual physical pages when that address range is accessed, which will result in a page fault, and will eventually lead to the kernel calling into the page allocator to get a backing page.

Cannot ping AWS EC2 instance

If you setup the rules as "Custom ICMP" rule and "echo reply" with anywhere it will work like a champ. The "echo request" is the wrong rule for answering pings.

How to set div width using ng-style

ngStyle accepts a map:

$scope.myStyle = {
    "width" : "900px",
    "background" : "red"
};

Fiddle

Get size of all tables in database

sp_spaceused can get you information on the disk space used by a table, indexed view, or the whole database.

For example:

USE MyDatabase; GO

EXEC sp_spaceused N'User.ContactInfo'; GO

This reports the disk usage information for the ContactInfo table.

To use this for all tables at once:

USE MyDatabase; GO

sp_msforeachtable 'EXEC sp_spaceused [?]' GO

You can also get disk usage from within the right-click Standard Reports functionality of SQL Server. To get to this report, navigate from the server object in Object Explorer, move down to the Databases object, and then right-click any database. From the menu that appears, select Reports, then Standard Reports, and then "Disk Usage by Partition: [DatabaseName]".

$(document).ready shorthand

The correct shorthand is this:

$(function() {
    // this behaves as if within document.ready
});

The code you posted…

(function($){

//some code

})(jQuery);

…creates an anonymous function and executes it immediately with jQuery being passed in as the arg $. All it effectively does is take the code inside the function and execute it like normal, since $ is already an alias for jQuery. :D

How do I get the current time zone of MySQL?

The command mention in the description returns "SYSTEM" which indicated it takes the timezone of the server. Which is not useful for our query.

Following query will help to understand the timezone

SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP) as GMT_TIME_DIFF;

Above query will give you the time interval with respect to Coordinated Universal Time(UTC). So you can easily analyze the timezone. if the database time zone is IST the output will be 5:30

UTC_TIMESTAMP

In MySQL, the UTC_TIMESTAMP returns the current UTC date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS.uuuuuu format depending on the usage of the function i.e. in a string or numeric context.

NOW()

NOW() function. MySQL NOW() returns the value of current date and time in 'YYYY-MM-DD HH:MM:SS' format or YYYYMMDDHHMMSS.uuuuuu format depending on the context (numeric or string) of the function. CURRENT_TIMESTAMP, CURRENT_TIMESTAMP(), LOCALTIME, LOCALTIME(), LOCALTIMESTAMP, LOCALTIMESTAMP() are synonyms of NOW().

python ValueError: invalid literal for float()

I had a similar issue reading the serial output from a digital scale. I was reading [3:12] out of a 18 characters long output string.

In my case sometimes there is a null character "\x00" (NUL) which magically appears in the scale's reply string and is not printed.

I was getting the error:

> '     0.00'
> 3 0 fast loop, delta =  10.0 weight =  0.0 
> '     0.00'
> 1 800 fast loop, delta = 10.0 weight =  0.0 
> '     0.00'
> 6 0 fast loop, delta =  10.0 weight =  0.0
> '     0\x00.0' 
> Traceback (most recent call last):
>   File "measure_weight_speed.py", line 172, in start
>     valueScale = float(answer_string) 
>     ValueError: invalid literal for float(): 0

After some research I wrote few lines of code that work in my case.

replyScale = scale_port.read(18)
answer = replyScale[3:12]
answer_decode = answer.replace("\x00", "")
answer_strip = str(answer_decode.strip())
print(repr(answer_strip))
valueScale = float(answer_strip)

The answers in these posts helped:

  1. How to get rid of \x00 in my array of bytes?
  2. Invalid literal for float(): 0.000001, how to fix error?

Select Pandas rows based on list index

you can also use iloc:

df.iloc[[1,3],:]

This will not work if the indexes in your dataframe do not correspond to the order of the rows due to prior computations. In that case use:

df.index.isin([1,3])

... as suggested in other responses.

Reading a date using DataReader

 (DateTime)MyReader["ColumnName"];

OR

Convert.ToDateTime(MyReader["ColumnName"]);

How to call controller from the button click in asp.net MVC 4

You are mixing razor and aspx syntax,if your view engine is razor just do this:

<button class="btn btn-info" type="button" id="addressSearch"   
          onclick="location.href='@Url.Action("List", "Search")'">

What in the world are Spring beans?

Spring have the IoC container which carry the Bag of Bean ; creation maintain and deletion are the responsibilities of Spring Container. We can put the bean in to Spring by Wiring and Auto Wiring. Wiring mean we manually configure it into the XML file and "Auto Wiring" mean we put the annotations in the Java file then Spring automatically scan the root-context where java configuration file, make it and put into the bag of Spring.

Here is the detail URI where you got more information about Beans

Multiple Updates in MySQL

And now the easy way

update my_table m, -- let create a temp table with populated values
    (select 1 as id, 20 as value union -- this part will be generated
     select 2 as id, 30 as value union -- using a backend code
     -- for loop 
     select N as id, X as value
        ) t
set m.value = t.value where t.id=m.id -- now update by join - quick

How do I install PyCrypto on Windows?

In general

vcvarsall.bat is part of the Visual C++ compiler, you need that to install what you are trying to install. Don't even try to deal with MingGW if your Python was compiled with Visual Studio toolchain and vice versa. Even the version of the Microsoft tool chain is important. Python compiled with VS 2008 won't work with extensions compiled with VS 2010!

You have to compile PyCrypto with the same compiler that the version of Python was compiled with. Google for "Unable to find vcvarsall.bat" because that is the root of your problem, it is a very common problem with compiling Python extensions on Windows.

There is a lot of information and a lot to read to get this right on whatever system you are on with this link.

Beware using Visual Studio 2010 or not using Visual Studio 2008

As far as I know the following is still true. This was posted in the link above in June, 2010 referring to trying to build extensions with VS 2010 Express against the Python installers available on python.org.

Be careful if you do this. Python 2.6 and 2.7 from python.org are built with Visual Studio 2008 compilers. You will need to link with the same CRT (msvcr90.dll) as Python.

Visual Studio 2010 Express links with the wrong CRT version: msvcr100.dll.

If you do this, you must also re-build Python with Visual Studio 2010 Express. You cannot use the standard Python binary installer for Windows. Nor can you use any C/C++ extensions built with a different compiler than Visual Studio 2010 (Express).

Opinion: This is one reason I abandoned Windows for all serious development work for OSX!

Clearing an input text field in Angular2

What about something like this, without a button:

<input type="text" placeholder="Search..." [value]="searchValue" onblur="this.value=''">

How can I view an object with an alert()

alert( JSON.stringify(product) );

Webdriver Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms

This happens because of old versions. Just update the browser to latest version and update the selenium webdriver package to latest version.

Replace text in HTML page with jQuery

Like others mentioned in this thread, replacing the entire body HTML is a bad idea because it reinserts the entire DOM and can potentially break any other javascript that was acting on those elements.

Instead, replace just the text on your page and not the DOM elements themselves using jQuery filter:

  $('body :not(script)').contents().filter(function() {
    return this.nodeType === 3;
  }).replaceWith(function() {
      return this.nodeValue.replace('-9o0-9909','The new string');
  });

this.nodeType is the type of node we are looking to replace the contents of. nodeType 3 is text. See the full list here.

Editing in the Chrome debugger

As this is quite popular question that deals with live-editing of JS, I want to point out another useful option. As described by svjacob in his answer:

I realized I could attach a break-point in the debugger to some line of code before what I wanted to dynamically edit. And since break-points stay even after a reload of the page, I was able to edit the changes I wanted while paused at break-point and then continued to let the page load.

The above solution didn't work for me for quite large JS (webpack bundle - 3.21MB minified version, 130k lines of code in prettified version) - chrome crashed and asked for page reloading which reverted any saved changes. The way to go in this case was Fiddler where you can set AutoRespond option to replace any remote resource with any local file from your computer - see this SO question for details.

In my case I also had to add CORS headers to fiddler to successfully mock response.

SQLite in Android How to update a specific row

just give rowId and type of data that is going to be update in ContentValues.

public void updateStatus(String id , int status){

SQLiteDatabase db = this.getWritableDatabase();

ContentValues data = new ContentValues();

data.put("status", status);

db.update(TableName, data, "columnName" + " = "+id , null);

}

How do I select the "last child" with a specific class name in CSS?

This is a cheeky answer, but if you are constrained to CSS only and able to reverse your items in the DOM, it might be worth considering. It relies on the fact that while there is no selector for the last element of a specific class, it is actually possible to style the first. The trick is to then use flexbox to display the elements in reverse order.

_x000D_
_x000D_
ul {_x000D_
  display: flex;_x000D_
  flex-direction: column-reverse;_x000D_
}_x000D_
_x000D_
/* Apply desired style to all matching elements. */_x000D_
ul > li.list {_x000D_
  background-color: #888;_x000D_
}_x000D_
_x000D_
/* Using a more specific selector, "unstyle" elements which are not the first. */_x000D_
ul > li.list ~ li.list {_x000D_
  background-color: inherit;_x000D_
}
_x000D_
<ul>_x000D_
  <li class="list">0</li>_x000D_
  <li>1</li>_x000D_
  <li class="list">2</li>_x000D_
</ul>_x000D_
<ul>_x000D_
  <li>0</li>_x000D_
  <li class="list">1</li>_x000D_
  <li class="list">2</li>_x000D_
  <li>3</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

1114 (HY000): The table is full

This error also appears if the partition on which tmpdir resides fills up (due to an alter table or other

How to check if directory exists in %PATH%?

A comment to the "addPath" script; When supplying a path with spaces, it throws up.

Example: call addPath "c:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin"

yields: 'Files' is not recognized as an internal or external command, operable program or batch file.

JPG vs. JPEG image formats

JPG and JPEG stand both for an image format proposed and supported by the Joint Photographic Experts Group. The two terms have the same meaning and are interchangeable.

To read on, check out Difference between JPG and JPEG.

  • The reason for the different file extensions dates back to the early versions of Windows. The original file extension for the Joint Photographic Expert Group File Format was ‘.jpeg’; however in Windows all files required a three letter file extension. So, the file extension was shortened to ‘.jpg’. However, Macintosh was not limited to three letter file extensions, so Mac users used ‘.jpeg’. Eventually, with upgrades Windows also began to accept ‘.jpeg’. However, many users were already used to ‘.jpg’, so both the three letter file extension and the four letter extension began to be commonly used, and still is.

  • Today, the most commonly accepted and used form is the ‘.jpg’, as many users were Windows users. Imaging applications, such as Adobe Photoshop, save all JPEG files with a ".jpg" extension on both Mac and Windows, in an attempt to avoid confusion. The Joint Photographic Expert Group File Format can also be saved with the upper-case ‘.JPEG’ and ‘.JPG’ file extensions, which are less common, but also accepted.

source command not found in sh shell

The source builtin is a bashism. Write this simply as . instead.

e.g.

. $FILE

# OR you may need to use a relative path (such as in an `npm` script):

. ./$FILE

https://wiki.ubuntu.com/DashAsBinSh#source

Given a class, see if instance has method (Ruby)

klass.instance_methods.include :method_name or "method_name", depending on the Ruby version I think.

CSS Circle with border

You are missing the border width and the border style properties in the Border shorthand property :

_x000D_
_x000D_
.circle {
    border: 2px solid red;
    background-color: #FFFFFF;
    height: 100px;
    border-radius:50%;
    width: 100px;
}
_x000D_
<div class="circle"></div>
_x000D_
_x000D_
_x000D_


Also, You can use percentages for the border-radius property so that the value isn't dependent of the circle width/height. That is why I used 50% for border-radius (more info on border-radius in pixels and percent).

Side note : In your example, you didn't specify the border-radius property without vendor prefixes whitch you propably don't need as only browsers before chrome 4 safari 4 and Firefox 3.6 use them (see canIuse).

parse html string with jquery

One thing to note - as I had exactly this problem today, depending on your HTML jQuery may or may not parse it that well. jQuery wouldn't parse my HTML into a correct DOM - on smaller XML compliant files it worked fine, but the HTML I had (that would render in a page) wouldn't parse when passed back to an Ajax callback.

In the end I simply searched manually in the string for the tag I wanted, not ideal but did work.

How do I remove  from the beginning of a file?

Check on your index.php, find "... charset=iso-8859-1" and replace it with "... charset=utf-8".

Maybe it'll work.

test attribute in JSTL <c:if> tag

You can also use something like

<c:if test="${ testObject.testPropert == "testValue" }">...</c:if>

Multiple INNER JOIN SQL ACCESS

Access requires parentheses in the FROM clause for queries which include more than one join. Try it this way ...

FROM
    ((tbl_employee
    INNER JOIN tbl_netpay
    ON tbl_employee.emp_id = tbl_netpay.emp_id)
    INNER JOIN tbl_gross
    ON tbl_employee.emp_id = tbl_gross.emp_ID)
    INNER JOIN tbl_tax
    ON tbl_employee.emp_id = tbl_tax.emp_ID;

If possible, use the Access query designer to set up your joins. The designer will add parentheses as required to keep the db engine happy.

Git SSH error: "Connect to host: Bad file number"

On windows I tried to do quit git bash and re-run but didn't work, finally me(frustated) did a restart and it worked the next time :)

How to return a boolean method in java?

Best way would be to declare Boolean variable within the code block and return it at end of code, like this:

public boolean Test(){
    boolean booleanFlag= true; 
    if (A>B)
    {booleanFlag= true;}
    else 
    {booleanFlag = false;}
    return booleanFlag;

}

I find this the best way.

Python list iterator behavior and next(iterator)

What is happening is that next(a) returns the next value of a, which is printed to the console because it is not affected.

What you can do is affect a variable with this value:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print(i)
...    b=next(a)
...
0
2
4
6
8

Rotate a div using javascript

I recently had to build something similar. You can check it out in the snippet below.

The version I had to build uses the same button to start and stop the spinner, but you can manipulate to code if you have a button to start the spin and a different button to stop the spin

Basically, my code looks like this...

Run Code Snippet

_x000D_
_x000D_
var rocket = document.querySelector('.rocket');_x000D_
var btn = document.querySelector('.toggle');_x000D_
var rotate = false;_x000D_
var runner;_x000D_
var degrees = 0;_x000D_
_x000D_
function start(){_x000D_
    runner = setInterval(function(){_x000D_
        degrees++;_x000D_
        rocket.style.webkitTransform = 'rotate(' + degrees + 'deg)';_x000D_
    },50)_x000D_
}_x000D_
_x000D_
function stop(){_x000D_
    clearInterval(runner);_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', function(){_x000D_
    if (!rotate){_x000D_
        rotate = true;_x000D_
        start();_x000D_
    } else {_x000D_
        rotate = false;_x000D_
        stop();_x000D_
    }_x000D_
})
_x000D_
body {_x000D_
  background: #1e1e1e;_x000D_
}    _x000D_
_x000D_
.rocket {_x000D_
    width: 150px;_x000D_
    height: 150px;_x000D_
    margin: 1em;_x000D_
    border: 3px dashed teal;_x000D_
    border-radius: 50%;_x000D_
    background-color: rgba(128,128,128,0.5);_x000D_
    display: flex;_x000D_
    justify-content: center;_x000D_
    align-items: center;_x000D_
  }_x000D_
  _x000D_
  .rocket h1 {_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
    font-size: .8em;_x000D_
    color: skyblue;_x000D_
    letter-spacing: 1em;_x000D_
    text-shadow: 0 0 10px black;_x000D_
  }_x000D_
  _x000D_
  .toggle {_x000D_
    margin: 10px;_x000D_
    background: #000;_x000D_
    color: white;_x000D_
    font-size: 1em;_x000D_
    padding: .3em;_x000D_
    border: 2px solid red;_x000D_
    outline: none;_x000D_
    letter-spacing: 3px;_x000D_
  }
_x000D_
<div class="rocket"><h1>SPIN ME</h1></div>_x000D_
<button class="toggle">I/0</button>
_x000D_
_x000D_
_x000D_

Opening Chrome From Command Line

you can create batch file and insert into it the bellow line:

cmd /k start chrome "http://yourWebSite.com

after that you do just double click on this batch file.

Can I call methods in constructor in Java?

Why not to use Static Initialization Blocks ? Additional details here: Static Initialization Blocks

VBScript to send email without running Outlook

Yes. Blat or any other self contained SMTP mailer. Blat is a fairly full featured SMTP client that runs from command line

Blat is here

Connect Java to a MySQL database

Here's the very minimum you need to get data out of a MySQL database:

Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection
   ("jdbc:mysql://localhost:3306/foo", "root", "password");

Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM `FOO.BAR`");
stmt.close();
conn.close();

Add exception handling, configuration etc. to taste.

How to get Android GPS location

This code have one problem:

int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());

You can change int to double

double latitude = location.getLatitude();
double longitude = location.getLongitude();

How do you find the sum of all the numbers in an array in Java?

You have to roll your own.
You start with a total of 0. Then you consider for every integer in the array, add it to a total. Then when you're out of integers, you have the sum.

If there were no integers, then the total is 0.

How can I simulate mobile devices and debug in Firefox Browser?

You can use the already mentioned built in Responsive Design Mode (via dev tools) for setting customised screen sizes together with the Random Agent Spoofer Plugin to modify your headers to simulate you are using Mobile, Tablet etc. Many websites specify their content according to these identified headers.

As dev tools you can use the built in Developer Tools (Ctrl + Shift + I or Cmd + Shift + I for Mac) which have become quite similar to Chrome dev tools by now.

Set Date in a single line

You could use new GregorianCalendar(theYear, theMonth, theDay).getTime():

public GregorianCalendar(int year, int month, int dayOfMonth)

Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.

Python Pandas: Get index of rows which column matches certain value

Can be done using numpy where() function:

import pandas as pd
import numpy as np

In [716]: df = pd.DataFrame({"gene_name": ['SLC45A1', 'NECAP2', 'CLIC4', 'ADC', 'AGBL4'] , "BoolCol": [False, True, False, True, True] },
       index=list("abcde"))

In [717]: df
Out[717]: 
  BoolCol gene_name
a   False   SLC45A1
b    True    NECAP2
c   False     CLIC4
d    True       ADC
e    True     AGBL4

In [718]: np.where(df["BoolCol"] == True)
Out[718]: (array([1, 3, 4]),)

In [719]: select_indices = list(np.where(df["BoolCol"] == True)[0])

In [720]: df.iloc[select_indices]
Out[720]: 
  BoolCol gene_name
b    True    NECAP2
d    True       ADC
e    True     AGBL4

Though you don't always need index for a match, but incase if you need:

In [796]: df.iloc[select_indices].index
Out[796]: Index([u'b', u'd', u'e'], dtype='object')

In [797]: df.iloc[select_indices].index.tolist()
Out[797]: ['b', 'd', 'e']

How to get annotations of a member variable?

You have to use reflection to get all the member fields of User class, iterate through them and find their annotations

something like this:

public void getAnnotations(Class clazz){
    for(Field field : clazz.getDeclaredFields()){
        Class type = field.getType();
        String name = field.getName();
        field.getDeclaredAnnotations(); //do something to these
    }
}

How to open a new file in vim in a new window

I use this subtle alias:

alias vim='gnome-terminal -- vim'

-x is deprecated now. We need to use -- instead

Python: Binding Socket: "Address already in use"

Here is the complete code that I've tested and absolutely does NOT give me a "address already in use" error. You can save this in a file and run the file from within the base directory of the HTML files you want to serve. Additionally, you could programmatically change directories prior to starting the server

import socket
import SimpleHTTPServer
import SocketServer
# import os # uncomment if you want to change directories within the program

PORT = 8000

# Absolutely essential!  This ensures that socket resuse is setup BEFORE
# it is bound.  Will avoid the TIME_WAIT issue

class MyTCPServer(SocketServer.TCPServer):
    def server_bind(self):
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind(self.server_address)

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

httpd = MyTCPServer(("", PORT), Handler)

# os.chdir("/My/Webpages/Live/here.html")

httpd.serve_forever()

# httpd.shutdown() # If you want to programmatically shut off the server

Setting Android Theme background color

Open res -> values -> styles.xml and to your <style> add this line replacing with your image path <item name="android:windowBackground">@drawable/background</item>. Example:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowBackground">@drawable/background</item>
    </style>

</resources>

There is a <item name ="android:colorBackground">@color/black</item> also, that will affect not only your main window background but all the component in your app. Read about customize theme here.

If you want version specific styles:

If a new version of Android adds theme attributes that you want to use, you can add them to your theme while still being compatible with old versions. All you need is another styles.xml file saved in a values directory that includes the resource version qualifier. For example:

res/values/styles.xml        # themes for all versions
res/values-v21/styles.xml    # themes for API level 21+ only

Because the styles in the values/styles.xml file are available for all versions, your themes in values-v21/styles.xml can inherit them. As such, you can avoid duplicating styles by beginning with a "base" theme and then extending it in your version-specific styles.

Read more here(doc in theme).

JQuery get data from JSON array

You're not looping over the items. Try this instead:

$.getJSON(url, function(data){
    $.each(data.response.venue.tips.groups.items, function (index, value) {
        console.log(this.text);
    });
});

Query-string encoding of a Javascript Object

Just another way (no recursive object):

   getQueryString = function(obj)
   {
      result = "";

      for(param in obj)
         result += ( encodeURIComponent(param) + '=' + encodeURIComponent(obj[param]) + '&' );

      if(result) //it's not empty string when at least one key/value pair was added. In such case we need to remove the last '&' char
         result = result.substr(0, result.length - 1); //If length is zero or negative, substr returns an empty string [ref. http://msdn.microsoft.com/en-us/library/0esxc5wy(v=VS.85).aspx]

      return result;
   }

alert( getQueryString({foo: "hi there", bar: 123, quux: 2 }) );

How to run a method every X seconds

Here I used a thread in onCreate() an Activity repeatly, timer does not allow everything in some cases Thread is the solution

     Thread t = new Thread() {
        @Override
        public void run() {
            while (!isInterrupted()) {
                try {
                    Thread.sleep(10000);  //1000ms = 1 sec
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            SharedPreferences mPrefs = getSharedPreferences("sam", MODE_PRIVATE);
                            Gson gson = new Gson();
                            String json = mPrefs.getString("chat_list", "");
                            GelenMesajlar model = gson.fromJson(json, GelenMesajlar.class);
                            String sam = "";

                            ChatAdapter adapter = new ChatAdapter(Chat.this, model.getData());
                            listview.setAdapter(adapter);
                           // listview.setStackFromBottom(true);
                          //  Util.showMessage(Chat.this,"Merhabalar");
                        }
                    });

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    t.start();

In case it needed it can be stoped by

@Override
protected void onDestroy() {
    super.onDestroy();
    Thread.interrupted();
    //t.interrupted();
}

jquery stop child triggering parent event

Better way by using on() with chaining like,

$(document).ready(function(){
    $(".header").on('click',function(){
        $(this).children(".children").toggle();
    }).on('click','a',function(e) {
        e.stopPropagation();
   });
});

Append to the end of a file in C

Following the documentation of fopen:

``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then cur- rent end of file, irrespective of any intervening fseek(3) or similar.

So if you pFile2=fopen("myfile2.txt", "a"); the stream is positioned at the end to append automatically. just do:

FILE *pFile;
FILE *pFile2;
char buffer[256];

pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", "a");
if(pFile==NULL) {
    perror("Error opening file.");
}
else {
    while(fgets(buffer, sizeof(buffer), pFile)) {
        fprintf(pFile2, "%s", buffer);
    }
}
fclose(pFile);
fclose(pFile2);

Artisan migrate could not find driver

In your php.ini configuration file simply uncomment the extension:

;extension=pdo_mysql

(You can find your php.ini file in the php folder where your server is installed.)

make this to

extension=pdo_mysql

now you need to configure your .env file in find DB_DATABASE= write in that database name which you used than migrate like if i used my database and database name is "abc" than i need to write there DB_DATABASE=abc and save that .env file and run command again

php artisan migrate

so after run than you got some msg like as:

php artisan migrate
Migration table created successfully.

How to truncate float values?

Short and easy variant

def truncate_float(value, digits_after_point=2):
    pow_10 = 10 ** digits_after_point
    return (float(int(value * pow_10))) / pow_10

>>> truncate_float(1.14333, 2)
>>> 1.14

>>> truncate_float(1.14777, 2)
>>> 1.14


>>> truncate_float(1.14777, 4)
>>> 1.1477

Check if the file exists using VBA

Very old post, but since it helped me after I made some modifications, I thought I'd share. If you're checking to see if a directory exists, you'll want to add the vbDirectory argument to the Dir function, otherwise you'll return 0 each time. (Edit: this was in response to Roy's answer, but I accidentally made it a regular answer.)

Private Function FileExists(fullFileName As String) As Boolean
    FileExists = Len(Dir(fullFileName, vbDirectory)) > 0
End Function

Mocking Extension Methods with Moq

I found that I had to discover the inside of the extension method I was trying to mock the input for, and mock what was going on inside the extension.

I viewed using an extension as adding code directly to your method. This meant I needed to mock what happens inside the extension rather than the extension itself.

Comparing HTTP and FTP for transferring files

One advantage of FTP is that there is a standard way to list files using dir or ls. Because of this, ftp plays nice with tools such as rsync. Granted, rsync is usually done over ssh, but the option is there.

SFTP in Python? (platform independent)

With RSA Key then refer here

Snippet:

import pysftp
import paramiko
from base64 import decodebytes

keydata = b"""AAAAB3NzaC1yc2EAAAADAQABAAABAQDl""" 
key = paramiko.RSAKey(data=decodebytes(keydata)) 
cnopts = pysftp.CnOpts()
cnopts.hostkeys.add(host, 'ssh-rsa', key)


with pysftp.Connection(host=host, username=username, password=password, cnopts=cnopts) as sftp:   
  with sftp.cd(directory):
    sftp.put(file_to_sent_to_ftp)

How to show/hide JPanels in a JFrame?

If you want to hide panel on button click, write below code in JButton Action. I assume you want to hide jpanel1.

jpanel1.setVisible(false);

WPF User Control Parent

I needed to use the Window.GetWindow(this) method within Loaded event handler. In other words, I used both Ian Oakes' answer in combination with Alex's answer to get a user control's parent.

public MainView()
{
    InitializeComponent();

    this.Loaded += new RoutedEventHandler(MainView_Loaded);
}

void MainView_Loaded(object sender, RoutedEventArgs e)
{
    Window parentWindow = Window.GetWindow(this);

    ...
}

How to output loop.counter in python jinja template?

in python:

env = Environment(loader=FileSystemLoader("templates"))
env.globals["enumerate"] = enumerate

in template:

{% for k,v in enumerate(list) %}
{% endfor %}

Send file using POST from a Python script

Chris Atlee's poster library works really well for this (particularly the convenience function poster.encode.multipart_encode()). As a bonus, it supports streaming of large files without loading an entire file into memory. See also Python issue 3244.

git status shows modifications, git checkout -- <file> doesn't remove them

We faced a similar situation in our company. None of the proposed methods did not help us. As a result of the research, the problem was revealed. The thing was that in Git there were two files, the names of which differed only in the register of symbols. Unix-systems saw them as two different files, but Windows was going crazy. To solve the problem, we deleted one of the files on the server. After that, at the local repositories on Windows helped the next few commands (in different sequences):

git reset --hard
git pull origin
git merge

Fatal error: Call to undefined function mb_strlen()

To fix this install the php7.0-mbstring package:

sudo apt install php7.0-mbstring

How to make flexbox items the same size?

You could add flex-basis: 100% to achieve this.

Updated Example

.header {
  display: flex;
}

.item {
  flex-basis: 100%;
  text-align: center;
  border: 1px solid black;
}

For what it's worth, you could also use flex: 1 for the same results as well.

The shorthand of flex: 1 is the same as flex: 1 1 0, which is equivalent to:

.item {
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: 0;
  text-align: center;
  border: 1px solid black;
}

Base64 Decoding in iOS 7+

In case you want to write fallback code, decoding from base64 has been present in iOS since the very beginning by caveat of NSURL:

NSURL *URL = [NSURL URLWithString:
      [NSString stringWithFormat:@"data:application/octet-stream;base64,%@",
           base64String]];

return [NSData dataWithContentsOfURL:URL];

How do I determine scrollHeight?

scrollHeight is a regular javascript property so you don't need jQuery.

var test = document.getElementById("foo").scrollHeight;

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

SQL Server : trigger how to read value for Insert, Update, Delete

Here is the syntax to create a trigger:

CREATE TRIGGER trigger_name
ON { table | view }
[ WITH ENCRYPTION ]
{
    { { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
        [ WITH APPEND ]
        [ NOT FOR REPLICATION ]
        AS
        [ { IF UPDATE ( column )
            [ { AND | OR } UPDATE ( column ) ]
                [ ...n ]
        | IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask )
                { comparison_operator } column_bitmask [ ...n ]
        } ]
        sql_statement [ ...n ]
    }
} 

If you want to use On Update you only can do it with the IF UPDATE ( column ) section. That's not possible to do what you are asking.

awk without printing newline

one way

awk '/^\*\*/{gsub("*","");printf "\n"$0" ";next}{printf $0" "}' to-plot.xls

How do I grab an INI value within a shell script?

If using sections, this will do the job :

Example raw output :

$ ./settings
[section]
SETTING_ONE=this is setting one
SETTING_TWO=This is the second setting
ANOTHER_SETTING=This is another setting

Regexp parsing :

$ ./settings | sed -n -E "/^\[.*\]/{s/\[(.*)\]/\1/;h;n;};/^[a-zA-Z]/{s/#.*//;G;s/([^ ]*) *= *(.*)\n(.*)/\3_\1='\2'/;p;}"
section_SETTING_ONE='this is setting one'
section_SETTING_TWO='This is the second setting'
section_ANOTHER_SETTING='This is another setting'

Now all together :

$ eval "$(./settings | sed -n -E "/^\[.*\]/{s/\[(.*)\]/\1/;h;n;};/^[a-zA-Z]/{s/#.*//;G;s/([^ ]*) *= *(.*)\n(.*)/\3_\1='\2'/;p;}")"
$ echo $section_SETTING_TWO
This is the second setting

What is the default root pasword for MySQL 5.7

After you installed MySQL-community-server 5.7 from fresh on linux, you will need to find the temporary password from /var/log/mysqld.log to login as root.

  1. grep 'temporary password' /var/log/mysqld.log
  2. Run mysql_secure_installation to change new password

ref: http://dev.mysql.com/doc/refman/5.7/en/linux-installation-yum-repo.html

jQuery - What are differences between $(document).ready and $(window).load?

document.ready is a jQuery event, it runs when the DOM is ready, e.g. all elements are there to be found/used, but not necessarily all the content.
window.onload fires later (or at the same time in the worst/failing cases) when images and such are loaded. So, if you're using image dimensions for example, you often want to use this instead.

Also read a related question:
Difference between $(window).load() and $(document).ready() functions

Missing Maven dependencies in Eclipse project

I changed my project facet to java and copy pasted a working maven projects .classpath content to this project. This resolved my issue.

Frame Buster Buster ... buster code needed

I might just have just gotten a way to bust the frame buster buster javascript. Using the getElementsByName in my javascript function, i've set a loop between the frame buster and the actual frame buster buster script. check this post out. http://www.phcityonweb.com/frame-buster-buster-buster-2426

How can I tell jaxb / Maven to generate multiple schema packages?

I had to specify different generateDirectory (without this, the plugin was considering that files were up to date and wasn't generating anything during the second execution). And I recommend to follow the target/generated-sources/<tool> convention for generated sources so that they will be imported in your favorite IDE automatically. I also recommend to declare several execution instead of declaring the plugin twice (and to move the configuration inside each execution element):

<plugin>
  <groupId>org.jvnet.jaxb2.maven2</groupId>
  <artifactId>maven-jaxb2-plugin</artifactId>
  <version>0.7.1</version>
  <executions>
    <execution>
      <id>schema1-generate</id>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <schemaDirectory>src/main/resources/dir1</schemaDirectory>
        <schemaIncludes>
          <include>shiporder.xsd</include>
        </schemaIncludes>
        <generatePackage>com.stackoverflow.package1</generatePackage>
        <generateDirectory>${project.build.directory}/generated-sources/xjc1</generateDirectory>
      </configuration>
    </execution>
    <execution>
      <id>schema2-generate</id>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <schemaDirectory>src/main/resources/dir2</schemaDirectory>
        <schemaIncludes>
          <include>books.xsd</include>
        </schemaIncludes>
        <generatePackage>com.stackoverflow.package2</generatePackage>
        <generateDirectory>${project.build.directory}/generated-sources/xjc2</generateDirectory>
      </configuration>
    </execution>
  </executions>
</plugin>

With this setup, I get the following result after a mvn clean compile

$ tree target/
target/
+-- classes
¦   +-- com
¦   ¦   +-- stackoverflow
¦   ¦       +-- App.class
¦   ¦       +-- package1
¦   ¦       ¦   +-- ObjectFactory.class
¦   ¦       ¦   +-- Shiporder.class
¦   ¦       ¦   +-- Shiporder$Item.class
¦   ¦       ¦   +-- Shiporder$Shipto.class
¦   ¦       +-- package2
¦   ¦           +-- BookForm.class
¦   ¦           +-- BooksForm.class
¦   ¦           +-- ObjectFactory.class
¦   ¦           +-- package-info.class
¦   +-- dir1
¦   ¦   +-- shiporder.xsd
¦   +-- dir2
¦       +-- books.xsd
+-- generated-sources
    +-- xjc
    ¦   +-- META-INF
    ¦       +-- sun-jaxb.episode
    +-- xjc1
    ¦   +-- com
    ¦       +-- stackoverflow
    ¦           +-- package1
    ¦               +-- ObjectFactory.java
    ¦               +-- Shiporder.java
    +-- xjc2
        +-- com
            +-- stackoverflow
                +-- package2
                    +-- BookForm.java
                    +-- BooksForm.java
                    +-- ObjectFactory.java
                    +-- package-info.java

Which seems to be the expected result.

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

Documentation for crypto: http://nodejs.org/api/crypto.html

const crypto = require('crypto')

const text = 'I love cupcakes'
const key = 'abcdeg'

crypto.createHmac('sha1', key)
  .update(text)
  .digest('hex')

SVN "Already Locked Error"

If your SVN repository is locked by AnkhSVN, just use "cleanup" command from AnkhSVN to release the lock! ;)

Javamail Could not convert socket to TLS GMail

Here is the working solution bro. It's guaranteed

1) First of all open your gmail account from which you wanted to send mail, like in you case ""[email protected]"

2) open this link below https://support.google.com/accounts/answer/6010255?hl=en

3) click on "Go to the "Less secure apps" section in My Account." option

4) Then turn on it

5) that's it (:

here is my code

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class SendEmail {

   final String senderEmailID = "Sender Email id";
final String senderPassword = "Sender Pass word";
final String emailSMTPserver = "smtp.gmail.com";
final String emailServerPort = "465";
String receiverEmailID = null;
static String emailSubject = "Test Mail";
static String emailBody = ":)";
public SendEmail(String receiverEmailID, String emailSubject, String emailBody)
{
this.receiverEmailID=receiverEmailID;
this.emailSubject=emailSubject;
this.emailBody=emailBody;
Properties props = new Properties();
props.put("mail.smtp.user",senderEmailID);
props.put("mail.smtp.host", emailSMTPserver);
props.put("mail.smtp.port", emailServerPort);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", emailServerPort);
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SecurityManager security = System.getSecurityManager();
try
{
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setText(emailBody);
msg.setSubject(emailSubject);
msg.setFrom(new InternetAddress(senderEmailID));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(receiverEmailID));
Transport.send(msg);
System.out.println("Message send Successfully:)");
}
catch (Exception mex)
{
mex.printStackTrace();
}
}
public class SMTPAuthenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(senderEmailID, senderPassword);
}
}
    public static void main(String[] args) {
       SendEmail mailSender;
        mailSender = new SendEmail("Receiver Email id","Testing Code 2 example","Testing Code Body yess");
    }

}

Python - converting a string of numbers into a list of int

Split on commas, then map to integers:

map(int, example_string.split(','))

Or use a list comprehension:

[int(s) for s in example_string.split(',')]

The latter works better if you want a list result, or you can wrap the map() call in list().

This works because int() tolerates whitespace:

>>> example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'
>>> list(map(int, example_string.split(',')))  # Python 3, in Python 2 the list() call is redundant
[0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11]
>>> [int(s) for s in example_string.split(',')]
[0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11]

Splitting on just a comma also is more tolerant of variable input; it doesn't matter if 0, 1 or 10 spaces are used between values.

Increase permgen space

if you found out that the memory settings were not being used and in order to change the memory settings, I used the tomcat7w or tomcat8w in the \bin folder.Then the following should pop up:

tomcat monitor

Click the Java tab and add the arguments.restart tomcat

INSERT INTO TABLE from comma separated varchar-list

Sql Server does not (on my knowledge) have in-build Split function. Split function in general on all platforms would have comma-separated string value to be split into individual strings. In sql server, the main objective or necessary of the Split function is to convert a comma-separated string value (‘abc,cde,fgh’) into a temp table with each string as rows.

The below Split function is Table-valued function which would help us splitting comma-separated (or any other delimiter value) string to individual string.

CREATE FUNCTION dbo.Split(@String varchar(8000), @Delimiter char(1))       
returns @temptable TABLE (items varchar(8000))       
as       
begin       
    declare @idx int       
    declare @slice varchar(8000)       

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

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

        if(len(@slice)>0)  
            insert into @temptable(Items) values(@slice)       

        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break       
    end   
return       
end  

select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',')

the complete can be found at follownig link http://www.logiclabz.com/sql-server/split-function-in-sql-server-to-break-comma-separated-strings-into-table.aspx

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

The code marked @Before is executed before each test, while @BeforeClass runs once before the entire test fixture. If your test class has ten tests, @Before code will be executed ten times, but @BeforeClass will be executed only once.

In general, you use @BeforeClass when multiple tests need to share the same computationally expensive setup code. Establishing a database connection falls into this category. You can move code from @BeforeClass into @Before, but your test run may take longer. Note that the code marked @BeforeClass is run as static initializer, therefore it will run before the class instance of your test fixture is created.

In JUnit 5, the tags @BeforeEach and @BeforeAll are the equivalents of @Before and @BeforeClass in JUnit 4. Their names are a bit more indicative of when they run, loosely interpreted: 'before each tests' and 'once before all tests'.

Formatting DataBinder.Eval data

This line solved my problem:

<%#DateTime.Parse(Eval("DDDate").ToString()).ToString("dd-MM-yyyy")%>

How to initialize all the elements of an array to any specific value in java

Using Java 8, you can simply use ncopies of Collections class:

Object[] arrays = Collections.nCopies(size, object).stream().toArray();

In your case it will be:

Integer[] arrays = Collections.nCopies(10, Integer.valueOf(1)).stream().toArray(Integer[]::new);
.

Here is a detailed answer of a similar case of yours.

How can I style the border and title bar of a window in WPF?

If someone says you can't because only Windows can control the non-client area, they're wrong!

That's just a half-truth because Windows lets you specify the dimensions of the non-client area. The fact is, this is possible only throughout the Windows' kernel methods, and you're in .NET, not C/C++. Anyway, don't worry! P/Invoke was meant just for such things! Indeed, the whole of the Windows Form UI and Console application Std-I/O methods are offered using system calls. Hence, you'd have only to perform the right system calls to set the non-client area up, as documented in MSDN.

However, this is a really hard solution I came up with a lot of time ago. Luckily, as of .NET 4.5, you can use the WindowChrome class to adjust the non-client area like you want. Here you can get to start with.

In order to make things simpler and cleaner, I'll redirect you here, a guide to change the window border dimensions to whatever you want. By setting it to 0, you'll be able to implement your custom window border in place of the system's one.

I'm sorry for not posting a clear example, but later I will for sure.

How to terminate a python subprocess launched with shell=True

There is a very simple way for Python 3.5 or + (Actually tested on Python 3.8)

import subprocess, signal, time
p = subprocess.Popen(['cmd'], shell=True)
time.sleep(5) #Wait 5 secs before killing
p.send_signal(signal.CTRL_C_EVENT)

Then, your code may crash at some point if you have a keyboard input detection, or sth like this. In this case, on the line of code/function where the error is given, just use:

try:
    FailingCode #here goes the code which is raising KeyboardInterrupt
except KeyboardInterrupt:
    pass

What this code is doing is just sending a "CTRL+C" signal to the running process, what will cause the process to get killed.

error C2220: warning treated as error - no 'object' file generated

Go to project properties -> configurations properties -> C/C++ -> treats warning as error -> No (/WX-).

How do I start Mongo DB from Windows?

there are 2 ways start mongoDB Install location ( ex : C:/ )

first of all : copy mongoDB install folder into C:/ location then changed name to "mongodb" or something what u want. here is ex with "mongodb" name

1 : setup mongoDB is an windows service

    1.1 : Make directory name "data" in C:/ ( so we have C:/data ),after that make directory "C:/data/db" <br>
    1.2 : run in CMD ( Run as Admin) command ->  "echo logpath=C:/mongodb/log/mongo.log > C:/mongodb/mongodb.cfg" <br>
    1.3 : run in CMD (Run as Adin) command -> "C:/mongodb/bin/mongod.exe --config C:/mongodb/mongod.cfg --install" <br>
    1.4 : run command "net start MongoDB" <br>

2: a small .BAT file to start mongoDB without install copy and paste to notepad and save file with filetype ".bat" here is it :

C:\mongodb\bin\mongod.exe –dbpath=C:/mongodb/data/db
   PAUSE

if you getting error 1078 or 1087 lets remove all data in C:/data/db and restart mongoDB ( copy old data to new folder and back it up after restart mongoDB )

3 . GUI for mongoDB

i'm using rockmongo

have fun with it

How do I check to see if my array includes an object?

Arrays in Ruby don't have exists? method, but they have an include? method as described in the docs. Something like

unless @suggested_horses.include?(horse)
   @suggested_horses << horse
end

should work out of box.

No internet on Android emulator - why and how to fix?

If you run into this problem and are working with a non-Windows/Mac OS (Ubuntu in my case), try starting the emulator by itself in Android SDK and AVD Manager then running your application.

How do I remove objects from a JavaScript associative array?

None of the previous answers address the fact that JavaScript does not have associative arrays to begin with - there is no array type as such, see typeof.

What JavaScript has, are object instances with dynamic properties. When properties are confused with elements of an Array object instance then Bad Things™ are bound to happen:

Problem

var elements = new Array()

elements.push(document.getElementsByTagName("head")[0])
elements.push(document.getElementsByTagName("title")[0])
elements["prop"] = document.getElementsByTagName("body")[0]

console.log("number of elements: ", elements.length)   // Returns 2
delete elements[1]
console.log("number of elements: ", elements.length)   // Returns 2 (?!)

for (var i = 0; i < elements.length; i++)
{
   // Uh-oh... throws a TypeError when i == 1
   elements[i].onmouseover = function () { window.alert("Over It.")}
   console.log("success at index: ", i)
}

Solution

To have a universal removal function that does not blow up on you, use:

Object.prototype.removeItem = function (key) {
   if (!this.hasOwnProperty(key))
      return
   if (isNaN(parseInt(key)) || !(this instanceof Array))
      delete this[key]
   else
      this.splice(key, 1)
};

//
// Code sample.
//
var elements = new Array()

elements.push(document.getElementsByTagName("head")[0])
elements.push(document.getElementsByTagName("title")[0])
elements["prop"] = document.getElementsByTagName("body")[0]

console.log(elements.length)                        // Returns 2
elements.removeItem("prop")
elements.removeItem(0)
console.log(elements.hasOwnProperty("prop"))        // Returns false as it should
console.log(elements.length)                        // returns 1 as it should

Deny access to one specific folder in .htaccess

Creating index.php, index.html, index.htm is not secure. Becuse, anyone can get access on your files within specified directory by guessing files name. E.g.: http://yoursite.com/includes/file.dat So, recommended method is creating a .htaccess file to deny all visitors ;). Have fun !!

What is Hash and Range Primary Key?

As the whole thing is mixing up let's look at it function and code to simulate what it means consicely

The only way to get a row is via primary key

getRow(pk: PrimaryKey): Row

Primary key data structure can be this:

// If you decide your primary key is just the partition key.
class PrimaryKey(partitionKey: String)

// and in thids case
getRow(somePartitionKey): Row

However you can decide your primary key is partition key + sort key in this case:

// if you decide your primary key is partition key + sort key
class PrimaryKey(partitionKey: String, sortKey: String)

getRow(partitionKey, sortKey): Row
getMultipleRows(partitionKey): Row[]

So the bottom line:

  1. Decided that your primary key is partition key only? get single row by partition key.

  2. Decided that your primary key is partition key + sort key? 2.1 Get single row by (partition key, sort key) or get range of rows by (partition key)

In either way you get a single row by primary key the only question is if you defined that primary key to be partition key only or partition key + sort key

Building blocks are:

  1. Table
  2. Item
  3. KV Attribute.

Think of Item as a row and of KV Attribute as cells in that row.

  1. You can get an item (a row) by primary key.
  2. You can get multiple items (multiple rows) by specifying (HashKey, RangeKeyQuery)

You can do (2) only if you decided that your PK is composed of (HashKey, SortKey).

More visually as its complex, the way I see it:

+----------------------------------------------------------------------------------+
|Table                                                                             |
|+------------------------------------------------------------------------------+  |
||Item                                                                          |  |
||+-----------+ +-----------+ +-----------+ +-----------+                       |  |
|||primaryKey | |kv attr    | |kv attr ...| |kv attr ...|                       |  |
||+-----------+ +-----------+ +-----------+ +-----------+                       |  |
|+------------------------------------------------------------------------------+  |
|+------------------------------------------------------------------------------+  |
||Item                                                                          |  |
||+-----------+ +-----------+ +-----------+ +-----------+ +-----------+         |  |
|||primaryKey | |kv attr    | |kv attr ...| |kv attr ...| |kv attr ...|         |  |
||+-----------+ +-----------+ +-----------+ +-----------+ +-----------+         |  |
|+------------------------------------------------------------------------------+  |
|                                                                                  |
+----------------------------------------------------------------------------------+

+----------------------------------------------------------------------------------+
|1. Always get item by PrimaryKey                                                  |
|2. PK is (Hash,RangeKey), great get MULTIPLE Items by Hash, filter/sort by range     |
|3. PK is HashKey: just get a SINGLE ITEM by hashKey                               |
|                                                      +--------------------------+|
|                                 +---------------+    |getByPK => getBy(1        ||
|                 +-----------+ +>|(HashKey,Range)|--->|hashKey, > < or startWith ||
|              +->|Composite  |-+ +---------------+    |of rangeKeys)             ||
|              |  +-----------+                        +--------------------------+|
|+-----------+ |                                                                   |
||PrimaryKey |-+                                                                   |
|+-----------+ |                                       +--------------------------+|
|              |  +-----------+   +---------------+    |getByPK => get by specific||
|              +->|HashType   |-->|get one item   |--->|hashKey                   ||
|                 +-----------+   +---------------+    |                          ||
|                                                      +--------------------------+|
+----------------------------------------------------------------------------------+

So what is happening above. Notice the following observations. As we said our data belongs to (Table, Item, KVAttribute). Then Every Item has a primary key. Now the way you compose that primary key is meaningful into how you can access the data.

If you decide that your PrimaryKey is simply a hash key then great you can get a single item out of it. If you decide however that your primary key is hashKey + SortKey then you could also do a range query on your primary key because you will get your items by (HashKey + SomeRangeFunction(on range key)). So you can get multiple items with your primary key query.

Note: I did not refer to secondary indexes.

How to determine the current iPhone/device model?

Simplest way to get model name (marketing name)

Use private API -[UIDevice _deviceInfoForKey:] carefully, you won't be rejected by Apple,

// works on both simulators and real devices, iOS 8 to iOS 12
NSString *deviceModelName(void) {
    // For Simulator
    NSString *modelName = NSProcessInfo.processInfo.environment[@"SIMULATOR_DEVICE_NAME"];
    if (modelName.length > 0) {
        return modelName;
    }

    // For real devices and simulators, except simulators running on iOS 8.x
    UIDevice *device = [UIDevice currentDevice];
    NSString *selName = [NSString stringWithFormat:@"_%@ForKey:", @"deviceInfo"];
    SEL selector = NSSelectorFromString(selName);
    if ([device respondsToSelector:selector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        modelName = [device performSelector:selector withObject:@"marketing-name"];
#pragma clang diagnostic pop
    }
    return modelName;
}

How did I get the key "marketing-name"?

Running on a simulator, NSProcessInfo.processInfo.environment contains a key named "SIMULATOR_CAPABILITIES", the value of which is a plist file. Then you open the plist file, you will get the model name's key "marketing-name".

Add Text on Image using PIL

Even more minimal example (draws "Hello world!" in black and with the default font in the top-left of the image):

...
from PIL import ImageDraw
...
ImageDraw.Draw(
    image  # Image
).text(
    (0, 0),  # Coordinates
    'Hello world!',  # Text
    (0, 0, 0)  # Color
)

Query Mongodb on month, day, year... of a datetime

If you want to search for documents that belong to a specific month, make sure to query like this:

// Anything greater than this month and less than the next month
db.posts.find({created_on: {$gte: new Date(2015, 6, 1), $lt: new Date(2015, 7, 1)}});

Avoid quering like below as much as possible.

// This may not find document with date as the last date of the month
db.posts.find({created_on: {$gte: new Date(2015, 6, 1), $lt: new Date(2015, 6, 30)}});

// don't do this too
db.posts.find({created_on: {$gte: new Date(2015, 6, 1), $lte: new Date(2015, 6, 30)}});

How to access JSON decoded array in PHP

$data = json_decode($json, true);
echo $data[0]["c_name"]; // "John"


$data = json_decode($json);
echo $data[0]->c_name;      // "John"

How do I upload a file with the JS fetch API?

Jumping off from Alex Montoya's approach for multiple file input elements

const inputFiles = document.querySelectorAll('input[type="file"]');
const formData = new FormData();

for (const file of inputFiles) {
    formData.append(file.name, file.files[0]);
}

fetch(url, {
    method: 'POST',
    body: formData })

jQuery Validate Plugin - How to create a simple custom rule?

You can add a custom rule like this:

$.validator.addMethod(
    'booleanRequired',
    function (value, element, requiredValue) {
        return value === requiredValue;
    },
    'Please check your input.'
);

And add it as a rule like this:

PhoneToggle: {
    booleanRequired: 'on'
}        

How to filter files when using scp to copy dir recursively?

With ssh key based authentication enabled, the following script would work.

for x in `ssh user@remotehost 'find /usr/some -type f -name *.class'`; do y=$(echo $x|sed 's/.[^/]*$//'|sed "s/^\/usr//"); mkdir -p /usr/project/backup$y; scp $(echo 'user@remotehost:'$x) /usr/project/backup$y/; done

removeEventListener on anonymous functions in JavaScript

This is not ideal as it removes all, but might work for your needs:

z = document.querySelector('video');
z.parentNode.replaceChild(z.cloneNode(1), z);

Cloning a node copies all of its attributes and their values, including intrinsic (in–line) listeners. It does not copy event listeners added using addEventListener()

Node.cloneNode()

Importing json file in TypeScript

Often in Node.js applications a .json is needed. With TypeScript 2.9, --resolveJsonModule allows for importing, extracting types from and generating .json files.

Example #

_x000D_
_x000D_
// tsconfig.json_x000D_
_x000D_
{_x000D_
    "compilerOptions": {_x000D_
        "module": "commonjs",_x000D_
        "resolveJsonModule": true,_x000D_
        "esModuleInterop": true_x000D_
    }_x000D_
}_x000D_
_x000D_
// .ts_x000D_
_x000D_
import settings from "./settings.json";_x000D_
_x000D_
settings.debug === true;  // OK_x000D_
settings.dry === 2;  // Error: Operator '===' cannot be applied boolean and number_x000D_
_x000D_
_x000D_
// settings.json_x000D_
_x000D_
{_x000D_
    "repo": "TypeScript",_x000D_
    "dry": false,_x000D_
    "debug": false_x000D_
}
_x000D_
_x000D_
_x000D_ by: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html

m2e lifecycle-mapping not found

You can use this dummy plugin:

mvn archetype:generate -DgroupId=org.eclipse.m2e -DartifactId=lifecycle-mapping -Dversion=1.0.0 -DarchetypeArtifactId=maven-archetype-mojo

After generating the project install/deploy it.

How to get ER model of database from server with Workbench

I want to enhance Mr. Kamran Ali's answer with pictorial view.

Pictorial View is given step by step:

  1. Go to "Database" Menu option
  2. Select the "Reverse Engineer" option.

enter image description here

  1. A wizard will come. Select from "Stored Connection" and press "Next" button.

enter image description here

  1. Then "Next"..to.."Finish"

Enjoy :)

How to get a index value from foreach loop in jstl

I face Similar problem now I understand we have some more option : varStatus="loop", Here will be loop will variable which will hold the index of lop.

It can use for use to read for Zeor base index or 1 one base index.

${loop.count}` it will give 1 starting base index.

${loop.index} it will give 0 base index as normal Index of array start from 0.

For Example :

<c:forEach var="currentImage" items="${cityBannerImages}" varStatus="loop">
<picture>
   <source srcset="${currentImage}" media="(min-width: 1000px)"></source>
   <source srcset="${cityMobileImages[loop.count]}" media="(min-width:600px)"></source>
   <img srcset="${cityMobileImages[loop.count]}" alt=""></img>
</picture>
</c:forEach>

For more Info please refer this link

surface plots in matplotlib

I just came across this same problem. I have evenly spaced data that is in 3 1-D arrays instead of the 2-D arrays that matplotlib's plot_surface wants. My data happened to be in a pandas.DataFrame so here is the matplotlib.plot_surface example with the modifications to plot 3 1-D arrays.

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
    linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)
plt.title('Original Code')

That is the original example. Adding this next bit on creates the same plot from 3 1-D arrays.

# ~~~~ MODIFICATION TO EXAMPLE BEGINS HERE ~~~~ #
import pandas as pd
from scipy.interpolate import griddata
# create 1D-arrays from the 2D-arrays
x = X.reshape(1600)
y = Y.reshape(1600)
z = Z.reshape(1600)
xyz = {'x': x, 'y': y, 'z': z}

# put the data into a pandas DataFrame (this is what my data looks like)
df = pd.DataFrame(xyz, index=range(len(xyz['x']))) 

# re-create the 2D-arrays
x1 = np.linspace(df['x'].min(), df['x'].max(), len(df['x'].unique()))
y1 = np.linspace(df['y'].min(), df['y'].max(), len(df['y'].unique()))
x2, y2 = np.meshgrid(x1, y1)
z2 = griddata((df['x'], df['y']), df['z'], (x2, y2), method='cubic')

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(x2, y2, z2, rstride=1, cstride=1, cmap=cm.coolwarm,
    linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)
plt.title('Meshgrid Created from 3 1D Arrays')
# ~~~~ MODIFICATION TO EXAMPLE ENDS HERE ~~~~ #

plt.show()

Here are the resulting figures:

enter image description here enter image description here

Format date to MM/dd/yyyy in JavaScript

ISO compliant dateString

If your dateString is RFC282 and ISO8601 compliant:
pass your string into the Date Constructor:

const dateString = "2020-10-30T12:52:27+05:30"; // ISO8601 compliant dateString
const D = new Date(dateString);                 // {object Date}

from here you can extract the desired values by using Date Getters:

D.getMonth() + 1  // 10 (PS: +1 since Month is 0-based)
D.getDate()       // 30
D.getFullYear()   // 2020

Non-standard date string

If you use a non standard date string:
destructure the string into known parts, and than pass the variables to the Date Constructor:

new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])

const dateString = "30/10/2020 12:52:27";
const [d, M, y, h, m, s] = dateString.match(/\d+/g);

// PS: M-1 since Month is 0-based
const D = new Date(y, M-1, d, h, m, s);  // {object Date}


D.getMonth() + 1  // 10 (PS: +1 since Month is 0-based)
D.getDate()       // 30
D.getFullYear()   // 2020

python date of the previous month

Simple, one liner:

import datetime as dt
previous_month = (dt.date.today().replace(day=1) - dt.timedelta(days=1)).month

SELECT list is not in GROUP BY clause and contains nonaggregated column

As @Brian Riley already said you should either remove 1 column in your select

select countrylanguage.language ,sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language
order by sum(country.population*countrylanguage.percentage) desc ;

or add it to your grouping

select countrylanguage.language, country.code, sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language, country.code
order by sum(country.population*countrylanguage.percentage) desc ;

Insert multiple lines into a file after specified pattern using shell script

This answer is easy to understand

  • Copy before the pattern
  • Add your lines
  • Copy after the pattern
  • Replace original file

    FILENAME='app/Providers/AuthServiceProvider.php'

STEP 1 copy until the pattern

sed '/THEPATTERNYOUARELOOKINGFOR/Q' $FILENAME >>${FILENAME}_temp

STEP 2 add your lines

cat << 'EOL' >> ${FILENAME}_temp

HERE YOU COPY AND
PASTE MULTIPLE
LINES, ALSO YOU CAN
//WRITE COMMENTS

AND NEW LINES
AND SPECIAL CHARS LIKE $THISONE

EOL

STEP 3 add the rest of the file

grep -A 9999 'THEPATTERNYOUARELOOKINGFOR' $FILENAME >>${FILENAME}_temp

REPLACE original file

mv ${FILENAME}_temp $FILENAME

if you need variables, in step 2 replace 'EOL' with EOL

cat << EOL >> ${FILENAME}_temp

this variable will expand: $variable1

EOL

Check if value is zero or not null in python

If number could be None or a number, and you wanted to include 0, filter on None instead:

if number is not None:

If number can be any number of types, test for the type; you can test for just int or a combination of types with a tuple:

if isinstance(number, int):  # it is an integer
if isinstance(number, (int, float)):  # it is an integer or a float

or perhaps:

from numbers import Number

if isinstance(number, Number):

to allow for integers, floats, complex numbers, Decimal and Fraction objects.

Using underscores in Java variables and method names

I don't think using _ or m_ to indicate member variables is bad in Java or any other language. It my opinion it improves readability of your code because it allows you to look at a snippet and quickly identify out all of the member variables from locals.

You can also achieve this by forcing users to prepend instance variables with "this" but I find this slighly draconian. In many ways it violates DRY because it's an instance variable, why qualify it twice.

My own personal style is to use m_ instead of _. The reason being that there are also global and static variables. The advantage to m_/_ is it distinguishes a variables scope. So you can't reuse _ for global or static and instead I choose g_ and s_ respectively.

How do I import modules or install extensions in PostgreSQL 9.1+?

How to download and install if you have SUSE. As an example I am downloading the tablefunc module so I can use crosstab. I have PostgreSQL 9.6.1.

right-click desktop, terminal, type:

sudo zypper in postgreql-contrib

Enter credentials, continue by typing:

y

Run query (I ran mine from pgAdminIII):

CREATE EXTENSION tablefunc;

You should now have the crosstab function.

I did not have to restart.

Cordova app not displaying correctly on iPhone X (Simulator)

I'm developing cordova apps for 2 years and I spent weeks to solve related problems (eg: webview scrolls when keyboard open). Here's a tested and proven solution for both ios and android

P.S.: I'm using iScroll for scrolling content

  1. Never use viewport-fit=cover at index.html's meta tag, leave the app stay out of statusbar. iOS will handle proper area for all iPhone variants.
  2. In XCode uncheck hide status bar and requires full screen and don't forget to select Launch Screen File as CDVLaunchScreen
  3. In config.xml set fullscreen as false
  4. Finally, (thanks to Eddy Verbruggen for great plugins) add his plugin cordova-plugin-webviewcolor to set statusbar and bottom area background color. This plugin will allow you to set any color you want.
  5. Add below to config.xml (first ff after x is opacity)

    <preference name="BackgroundColor" value="0xff088c90" />
    
  6. Handle your scroll position yourself by adding focus events to input elements

    iscrollObj.scrollToElement(elm, transitionduration ... etc)
    

For android, do the same but instead of cordova-plugin-webviewcolor, install cordova-plugin-statusbar and cordova-plugin-navigationbar-color

Here's a javascript code using those plugins to work on both ios and android:

function setStatusColor(colorCode) {
    //colorCode is smtg like '#427309';
    if (cordova.platformId == 'android') {
        StatusBar.backgroundColorByHexString(colorCode);
        NavigationBar.backgroundColorByHexString(colorCode);
    } else if (cordova.platformId == 'ios') {
        window.plugins.webviewcolor.change(colorCode);
    }
}

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

c# .net change label text

  Label label1 = new System.Windows.Forms.Label
//label1.Text = "test";
    if (Request.QueryString["ID"] != null)
    {

        string test = Request.QueryString["ID"];
        label1.Text = "Du har nu lånat filmen:" + test;
    }

   else
    {

        string test = Request.QueryString["ID"];
        label1.Text = "test";
    }

This should make it

A non-blocking read on a subprocess.PIPE in Python

Here is a simple solution based on threads which:

  • works on both Linux and Windows (not relying on select).
  • reads both stdout and stderr asynchronouly.
  • doesn't rely on active polling with arbitrary waiting time (CPU friendly).
  • doesn't use asyncio (which may conflict with other libraries).
  • runs until the child process terminates.

printer.py

import time
import sys

sys.stdout.write("Hello\n")
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("World!\n")
sys.stdout.flush()
time.sleep(1)
sys.stderr.write("That's an error\n")
sys.stderr.flush()
time.sleep(2)
sys.stdout.write("Actually, I'm fine\n")
sys.stdout.flush()
time.sleep(1)

reader.py

import queue
import subprocess
import sys
import threading


def enqueue_stream(stream, queue, type):
    for line in iter(stream.readline, b''):
        queue.put(str(type) + line.decode('utf-8'))
    stream.close()


def enqueue_process(process, queue):
    process.wait()
    queue.put('x')


p = subprocess.Popen('python printer.py', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
q = queue.Queue()
to = threading.Thread(target=enqueue_stream, args=(p.stdout, q, 1))
te = threading.Thread(target=enqueue_stream, args=(p.stderr, q, 2))
tp = threading.Thread(target=enqueue_process, args=(p, q))
te.start()
to.start()
tp.start()

while True:
    line = q.get()
    if line[0] == 'x':
        break
    if line[0] == '2':  # stderr
        sys.stdout.write("\033[0;31m")  # ANSI red color
    sys.stdout.write(line[1:])
    if line[0] == '2':
        sys.stdout.write("\033[0m")  # reset ANSI code
    sys.stdout.flush()

tp.join()
to.join()
te.join()

Pandas - Compute z-score for all columns

The almost one-liner solution:

df2 = (df.ix[:,1:] - df.ix[:,1:].mean()) / df.ix[:,1:].std()
df2['ID'] = df['ID']

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

From Twitter Bootstrap documentation:

  • small grid (= 768px) = .col-sm-*,
  • medium grid (= 992px) = .col-md-*,
  • large grid (= 1200px) = .col-lg-*.

SELECT * FROM multiple tables. MySQL

You will have the duplicate values for name and price here. And ids are duplicate in the drinks_photos table.There is no way you can avoid them.Also what exactly you want the output ?

How can I develop for iPhone using a Windows development machine?

If you have a jailbroken iPhone, you can install the iphone-gcc toolchain onto the iPhone through Cydia and that way you can just compilie the apps on the iPhone. Apps that are developed this way can still be submitted to the App Store.

And although Mr Valdez said it is a grey area (which it is), jailbreaking is incredibly easy and pretty much risk free. Yes, it voids your warrenty but you can just do a restore and they will never know.

Make Error 127 when running trying to compile code

Error 127 means one of two things:

  1. file not found: the path you're using is incorrect. double check that the program is actually in your $PATH, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.
  2. ldso is not found: you're using a pre-compiled binary and it wants an interpreter that isn't on your system. maybe you're using an x86_64 (64-bit) distro, but the prebuilt is for x86 (32-bit). you can determine whether this is the answer by opening a terminal and attempting to execute it directly. or by running file -L on /bin/sh (to get your default/native format) and on the compiler itself (to see what format it is).

if the problem is (2), then you can solve it in a few diff ways:

  1. get a better binary. talk to the vendor that gave you the toolchain and ask them for one that doesn't suck.
  2. see if your distro can install the multilib set of files. most x86_64 64-bit distros allow you to install x86 32-bit libraries in parallel.
  3. build your own cross-compiler using something like crosstool-ng.
  4. you could switch between an x86_64 & x86 install, but that seems a bit drastic ;).

How to import/include a CSS file using PHP code and not HTML code?

I solved a similar problem by enveloping all css instructions in a php echo and then saving it as a php file (ofcourse starting and ending the file with the php tags), and then included the php file. This was a necessity as a redirect followed (header ("somefilename.php")) and no html code is allowed before a redirect.

gcc makefile error: "No rule to make target ..."

In my case it was due to a multi-line rule error in the Makefile. I had something like:

OBJS-$(CONFIG_OBJ1)            += file1.o file2.o \
                                  file3.o file4.o \
OBJS-$(CONFIG_OBJ2)            += file5.o 
OBJS-$(CONFIG_OBJ3)            += file6.o
...

The backslash at the end of file list in CONFIG_OBJ1's rule caused this error. It should be like:

OBJS-$(CONFIG_OBJ1)            += file1.o file2.o \
                                  file3.o file4.o
OBJS-$(CONFIG_OBJ2)            += file5.o
...

PostgreSQL next value of the sequences?

I tried this and it works perfectly

@Entity
public class Shipwreck {
  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
  @Basic(optional = false)
  @SequenceGenerator(name = "seq", sequenceName = "shipwreck_seq", allocationSize = 1)
  Long id;

....

CREATE SEQUENCE public.shipwreck_seq
    INCREMENT 1
    START 110
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;

Is there "\n" equivalent in VBscript?

This page has a table of string constants including vbCrLf

vbCrLf | Chr(13) & Chr(10) | Carriage return–linefeed combination

How to store arrays in MySQL?

you can store your array using group_Concat like that

 INSERT into Table1 (fruits)  (SELECT GROUP_CONCAT(fruit_name) from table2)
 WHERE ..... //your clause here

HERE an example in fiddle

Is there an alternative to string.Replace that is case-insensitive?

Seems like string.Replace should have an overload that takes a StringComparison argument. Since it doesn't, you could try something like this:

public static string ReplaceString(string str, string oldValue, string newValue, StringComparison comparison)
{
    StringBuilder sb = new StringBuilder();

    int previousIndex = 0;
    int index = str.IndexOf(oldValue, comparison);
    while (index != -1)
    {
        sb.Append(str.Substring(previousIndex, index - previousIndex));
        sb.Append(newValue);
        index += oldValue.Length;

        previousIndex = index;
        index = str.IndexOf(oldValue, index, comparison);
    }
    sb.Append(str.Substring(previousIndex));

    return sb.ToString();
}

DateTime.TryParseExact() rejecting valid formats

Try C# 7.0

var Dob= DateTime.TryParseExact(s: YourDateString,format: "yyyyMMdd",provider: null,style: 0,out var dt)
 ? dt : DateTime.Parse("1800-01-01");

How do I generate a random integer between min and max in Java?

You can use Random.nextInt(n). This returns a random int in [0,n). Just using max-min+1 in place of n and adding min to the answer will give a value in the desired range.

remove legend title in ggplot

This works too and also demonstrates how to change the legend title:

ggplot(df, aes(x, y, colour=g)) +
  geom_line(stat="identity") + 
  theme(legend.position="bottom") +
  scale_color_discrete(name="")

How to set a CheckBox by default Checked in ASP.Net MVC

I use viewbag with the same variable name in the Controller. E.g if the variable is called "IsActive" and I want this to default to true on the "Create" form, on the Create Action I set the value ViewBag.IsActive = true;

public ActionResult Create()
{
    ViewBag.IsActive = true;
    return View();
}

Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function

I ran across this question while troubleshooting my own code.

So this does NOT work...

$myLogText = ""
function AddLog ($Message)
{
    $myLogText += ($Message)
}
AddLog ("Hello")
Write-Host $myLogText

This APPEARS to work, but only in the PowerShell ISE:

$myLogText = ""
function AddLog ($Message)
{
    $global:myLogText += ($Message)
}
AddLog ("Hello")
Write-Host $myLogText

This is actually what works in both ISE and command line:

$global:myLogText = ""
function AddLog ($Message)
{
    $global:myLogText += ($Message)
}
AddLog ("Hello")
Write-Host $global:myLogText

How to get scrollbar position with Javascript?

Answer for 2018:

The best way to do things like that is to use the Intersection Observer API.

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.

Historically, detecting visibility of an element, or the relative visibility of two elements in relation to each other, has been a difficult task for which solutions have been unreliable and prone to causing the browser and the sites the user is accessing to become sluggish. Unfortunately, as the web has matured, the need for this kind of information has grown. Intersection information is needed for many reasons, such as:

  • Lazy-loading of images or other content as a page is scrolled.
  • Implementing "infinite scrolling" web sites, where more and more content is loaded and rendered as you scroll, so that the user doesn't have to flip through pages.
  • Reporting of visibility of advertisements in order to calculate ad revenues.
  • Deciding whether or not to perform tasks or animation processes based on whether or not the user will see the result.

Implementing intersection detection in the past involved event handlers and loops calling methods like Element.getBoundingClientRect() to build up the needed information for every element affected. Since all this code runs on the main thread, even one of these can cause performance problems. When a site is loaded with these tests, things can get downright ugly.

See the following code example:

var options = {
  root: document.querySelector('#scrollArea'),
  rootMargin: '0px',
  threshold: 1.0
}

var observer = new IntersectionObserver(callback, options);

var target = document.querySelector('#listItem');
observer.observe(target);

Most modern browsers support the IntersectionObserver, but you should use the polyfill for backward-compatibility.

How do I create a WPF Rounded Corner container?

I just had to do this myself, so I thought I would post another answer here.

Here is another way to create a rounded corner border and clip its inner content. This is the straightforward way by using the Clip property. It's nice if you want to avoid a VisualBrush.

The xaml:

<Border
    Width="200"
    Height="25"
    CornerRadius="11"
    Background="#FF919194"
>
    <Border.Clip>
        <RectangleGeometry
            RadiusX="{Binding CornerRadius.TopLeft, RelativeSource={RelativeSource AncestorType={x:Type Border}}}"
            RadiusY="{Binding RadiusX, RelativeSource={RelativeSource Self}}"
        >
            <RectangleGeometry.Rect>
                <MultiBinding
                    Converter="{StaticResource widthAndHeightToRectConverter}"
                >
                    <Binding
                        Path="ActualWidth"
                        RelativeSource="{RelativeSource AncestorType={x:Type Border}}"
                    />
                    <Binding
                        Path="ActualHeight"
                        RelativeSource="{RelativeSource AncestorType={x:Type Border}}"
                    />
                </MultiBinding>
            </RectangleGeometry.Rect>
        </RectangleGeometry>
    </Border.Clip>

    <Rectangle
        Width="100"
        Height="100"
        Fill="Blue"
        HorizontalAlignment="Left"
        VerticalAlignment="Center"
    />
</Border>

The code for the converter:

public class WidthAndHeightToRectConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        double width = (double)values[0];
        double height = (double)values[1];
        return new Rect(0, 0, width, height);
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

How do I make a fully statically linked .exe with Visual Studio Express 2005?

In regards Jared's response, having Windows 2000 or better will not necessarily fix the issue at hand. Rob's response does work, however it is possible that this fix introduces security issues, as Windows updates will not be able to patch applications built as such.

In another post, Nick Guerrera suggests packaging the Visual C++ Runtime Redistributable with your applications, which installs quickly, and is independent of Visual Studio.

How do I hide the status bar in a Swift iOS app?

Go to your Info.plist and add two Keys:

Go to your Info.plist and add two Keys:

Implement Validation for WPF TextBoxes

When it comes to DiSaSteR's answer, I noticed a different behavior. textBox.Text shows the text in the TextBox as it was before the user entered a new character, while e.Text shows the single character the user just entered. One challenge is that this character might not get appended to the end, but it will be inserted at the carret position:

private void salary_texbox_PreviewTextInput(object sender, TextCompositionEventArgs e){
  Regex regex = new Regex ( "[^0-9]+" );

  string text;
  if (textBox.CaretIndex==textBox.Text.Length) {
    text = textBox.Text + e.Text;
  } else {
    text = textBox.Text.Substring(0, textBox.CaretIndex)  + e.Text + textBox.Text.Substring(textBox.CaretIndex);
  }

  if(regex.IsMatch(text)){
      MessageBox.Show("Error");
  }
}