Programs & Examples On #Crystal reports 2010

Crystal Reports library for Visual Studio 2010 for programmatically running and exporting reports.

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304'

If you don't see log4net.dll in %systemdrive%\windows\assembly\ on the machine you are attempting to deploy it on, it is likely you haven't successfully installed the redistributable for Crystal Reports for .Net Framework 4.0

Install (or reinstall) the latest service pack from http://scn.sap.com/docs/DOC-7824 (SAP Crystal Reports, developer version for Microsoft Visual Studio Updates & Runtime Downloads)

That runtime distribution should add log4net to the GAC along with a bunch of CrystalDecisions dll's

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

I was not getting the error on 32-bit machines but was on 64-bit so I changed the target platform from x86 to Any CPU and it resolved the issue.

How to set the timeout for a TcpClient?

You would need to use the async BeginConnect method of TcpClient instead of attempting to connect synchronously, which is what the constructor does. Something like this:

var client = new TcpClient();
var result = client.BeginConnect("remotehost", this.Port, null, null);

var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));

if (!success)
{
    throw new Exception("Failed to connect.");
}

// we have connected
client.EndConnect(result);

what happens when you type in a URL in browser

Look up the specification of HTTP. Or to get started, try http://www.jmarshall.com/easy/http/

Convert spark DataFrame column to python list

I ran a benchmarking analysis and list(mvv_count_df.select('mvv').toPandas()['mvv']) is the fastest method. I'm very surprised.

I ran the different approaches on 100 thousand / 100 million row datasets using a 5 node i3.xlarge cluster (each node has 30.5 GBs of RAM and 4 cores) with Spark 2.4.5. Data was evenly distributed on 20 snappy compressed Parquet files with a single column.

Here's the benchmarking results (runtimes in seconds):

+-------------------------------------------------------------+---------+-------------+
|                          Code                               | 100,000 | 100,000,000 |
+-------------------------------------------------------------+---------+-------------+
| df.select("col_name").rdd.flatMap(lambda x: x).collect()    |     0.4 | 55.3        |
| list(df.select('col_name').toPandas()['col_name'])          |     0.4 | 17.5        |
| df.select('col_name').rdd.map(lambda row : row[0]).collect()|     0.9 | 69          |
| [row[0] for row in df.select('col_name').collect()]         |     1.0 | OOM         |
| [r[0] for r in mid_df.select('col_name').toLocalIterator()] |     1.2 | *           |
+-------------------------------------------------------------+---------+-------------+

* cancelled after 800 seconds

Golden rules to follow when collecting data on the driver node:

  • Try to solve the problem with other approaches. Collecting data to the driver node is expensive, doesn't harness the power of the Spark cluster, and should be avoided whenever possible.
  • Collect as few rows as possible. Aggregate, deduplicate, filter, and prune columns before collecting the data. Send as little data to the driver node as you can.

toPandas was significantly improved in Spark 2.3. It's probably not the best approach if you're using a Spark version earlier than 2.3.

See here for more details / benchmarking results.

How to break out of while loop in Python?

ans=(R)
while True:
    print('Your score is so far '+str(myScore)+'.')
    print("Would you like to roll or quit?")
    ans=input("Roll...")
    if ans=='R':
        R=random.randint(1, 8)
        print("You rolled a "+str(R)+".")
        myScore=R+myScore
    else:
        print("Now I'll see if I can break your score...")
        ans = False
        break

MySQL ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

I had similar problems because my password contains ";" char breaking my password when I creates it at first moment. Caution with this if can help you.

How to convert comma-separated String to List?

you can combine asList and split

Arrays.asList(CommaSeparated.split("\\s*,\\s*"))

How to terminate a thread when main program ends?

Try with enabling the sub-thread as daemon-thread.

For Instance:

Recommended:

from threading import Thread

t = Thread(target=<your-method>)
t.daemon = True  # This thread dies when main thread (only non-daemon thread) exits.
t.start()

Inline:

t = Thread(target=<your-method>, daemon=True).start()

Old API:

t.setDaemon(True)
t.start()

When your main thread terminates ("i.e. when I press Ctrl+C"), other threads will also be killed by the instructions above.

Copy text from nano editor to shell

M-^ is copy Text. "M" in my environment is "Esc" key ! not "Ctrl"; so I use Esc + 6 to copy that.

[nano help] Escape-key sequences are notated with the Meta (M-) symbol and can be entered using either the Esc, Alt, or Meta key depending on your keyboard setup.

Centering the pagination in bootstrap

solution for Bootstrap 4

You can use it Alignment use this class justify-content-center

Change the alignment of pagination components with flexbox utilities.

and learn more about it pagination

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
_x000D_
<nav aria-label="Page navigation example">_x000D_
  <ul class="pagination justify-content-center">_x000D_
    <li class="page-item disabled">_x000D_
      <a class="page-link" href="#" tabindex="-1">Previous</a>_x000D_
    </li>_x000D_
    <li class="page-item"><a class="page-link" href="#">1</a></li>_x000D_
    <li class="page-item"><a class="page-link" href="#">2</a></li>_x000D_
    <li class="page-item"><a class="page-link" href="#">3</a></li>_x000D_
    <li class="page-item">_x000D_
      <a class="page-link" href="#">Next</a>_x000D_
    </li>_x000D_
  </ul>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

MySQL Error: #1142 - SELECT command denied to user

In MySQL query browser go to Tools tab>MySQL Administrator > User Administration and then give the privileges to user.

How do I set the rounded corner radius of a color drawable using xml?

Try below code

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners
    android:bottomLeftRadius="30dp"
    android:bottomRightRadius="30dp"
    android:topLeftRadius="30dp"
    android:topRightRadius="30dp" />
<solid android:color="#1271BB" />

<stroke
    android:width="5dp"
    android:color="#1271BB" />

<padding
    android:bottom="1dp"
    android:left="1dp"
    android:right="1dp"
    android:top="1dp" /></shape>

How to read appSettings section in the web.config file?

Since you're accessing a web.config you should probably use

using System.Web.Configuration;

WebConfigurationManager.AppSettings["configFile"]

HTML Display Current date

This helped me:

<p>Date/Time: <span id="datetime"></span></p><script>var dt = new Date();
document.getElementById("datetime").innerHTML=dt.toLocaleString();</script>    

How to use PHP OPCache?

With PHP 5.6 on Amazon Linux (should be the same on RedHat or CentOS):

yum install php56-opcache

and then restart apache.

How to include quotes in a string

string str = @"""Hi, "" I am programmer";

OUTPUT - "Hi, " I am programmer

How to find list intersection?

This is an example when you need Each element in the result should appear as many times as it shows in both arrays.

def intersection(nums1, nums2):
    #example:
    #nums1 = [1,2,2,1]
    #nums2 = [2,2]
    #output = [2,2]
    #find first 2 and remove from target, continue iterating

    target, iterate = [nums1, nums2] if len(nums2) >= len(nums1) else [nums2, nums1] #iterate will look into target

    if len(target) == 0:
            return []

    i = 0
    store = []
    while i < len(iterate):

         element = iterate[i]

         if element in target:
               store.append(element)
               target.remove(element)

         i += 1


    return store

Get table name by constraint name

SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";

will give you what you need

How can I populate a select dropdown list from a JSON feed with AngularJS?

In my Angular Bootstrap dropdowns I initialize the JSON Array (vm.zoneDropdown) with ng-init (you can also have ng-init inside the directive template) and I pass the Array in a custom src attribute

<custom-dropdown control-id="zone" label="Zona" model="vm.form.zone" src="vm.zoneDropdown"
                         ng-init="vm.getZoneDropdownSrc()" is-required="true" form="farmaciaForm" css-class="custom-dropdown col-md-3"></custom-dropdown>

Inside the controller:

vm.zoneDropdown = [];
vm.getZoneDropdownSrc = function () {
    vm.zoneDropdown = $customService.getZone();
}

And inside the customDropdown directive template(note that this is only one part of the bootstrap dropdown):

<ul class="uib-dropdown-menu" role="menu" aria-labelledby="btn-append-to-body">
    <li role="menuitem" ng-repeat="dropdownItem in vm.src" ng-click="vm.setValue(dropdownItem)">
        <a ng-click="vm.preventDefault($event)" href="##">{{dropdownItem.text}}</a>
    </li>
</ul>

Appending items to a list of lists in python

import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions) 
with open('data.csv', 'r') as f:
    for rec in csv.DictReader(f):
        for l, col in zip(data, cols):
            l.append(float(rec[col]))
print data

# [[3.0, 3.0], [0.01, 0.01]]

How do I decode a base64 encoded string?

The m000493 method seems to perform some kind of XOR encryption. This means that the same method can be used for both encrypting and decrypting the text. All you have to do is reverse m0001cd:

string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));

string result = m000493(p0, "_p0lizei.");
//    result == "gaia^unplugged^Ta..."

with return m0001cd(builder3.ToString()); changed to return builder3.ToString();.

Select a date from date picker using Selenium webdriver

Just do

  JavascriptExecutor js = (JavascriptExecutor)driver;
  js.executeScript("document.getElementById('id').value='1988-01-01'");

SQL (MySQL) vs NoSQL (CouchDB)

Here's a quote from a recent blog post from Dare Obasanjo.

SQL databases are like automatic transmission and NoSQL databases are like manual transmission. Once you switch to NoSQL, you become responsible for a lot of work that the system takes care of automatically in a relational database system. Similar to what happens when you pick manual over automatic transmission. Secondly, NoSQL allows you to eke more performance out of the system by eliminating a lot of integrity checks done by relational databases from the database tier. Again, this is similar to how you can get more performance out of your car by driving a manual transmission versus an automatic transmission vehicle.

However the most notable similarity is that just like most of us can’t really take advantage of the benefits of a manual transmission vehicle because the majority of our driving is sitting in traffic on the way to and from work, there is a similar harsh reality in that most sites aren’t at Google or Facebook’s scale and thus have no need for a Bigtable or Cassandra.

To which I can add only that switching from MySQL, where you have at least some experience, to CouchDB, where you have no experience, means you will have to deal with a whole new set of problems and learn different concepts and best practices. While by itself this is wonderful (I am playing at home with MongoDB and like it a lot), it will be a cost that you need to calculate when estimating the work for that project, and brings unknown risks while promising unknown benefits. It will be very hard to judge if you can do the project on time and with the quality you want/need to be successful, if it's based on a technology you don't know.

Now, if you have on the team an expert in the NoSQL field, then by all means take a good look at it. But without any expertise on the team, don't jump on NoSQL for a new commercial project.

Update: Just to throw some gasoline in the open fire you started, here are two interesting articles from people on the SQL camp. :-)

I Can't Wait for NoSQL to Die (original article is gone, here's a copy)
Fighting The NoSQL Mindset, Though This Isn't an anti-NoSQL Piece
Update: Well here is an interesting article about NoSQL
Making Sense of NoSQL

if statement in ng-click

This maybe irrelevant and of no use, but as it's javascript, you don't have to use the ternary as suggested above in the ng-click statement. You should also be able to use the lazy evaluation ("or die") syntax as well. So for your example above:

<input  ng-click="{{if(profileForm.$valid) updateMyProfile()}}" name="submit" id="submit" value="Save" class="submit" type="submit">

would become:

<input  ng-click="profileForm.$valid && updateMyProfile()" name="submit" id="submit" value="Save" class="submit" type="submit">

In this case, if the profile is not valid then nothing happens, otherwise, updateMyProfile() is called. Like in the link @falinsky provides above.

Closure in Java 7

Yes,Closure (Lambda Expressions) is the new feature with the upcoming Java SE 8 release. You can get more info about this from the below link: http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

UIView touch event in controller

Just an update to above answers :

If you want to have see changes in the click event, i.e. Color of your UIVIew shud change whenever user clicks the UIView then make changes as below...

class ClickableUIView: UIView {
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
            if let touch = touches.first {
                let currentPoint = touch.locationInView(self)
                // do something with your currentPoint
            }

            self.backgroundColor = UIColor.magentaColor()//Color when UIView is clicked.
        }

        override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
            if let touch = touches.first {
                let currentPoint = touch.locationInView(self)
                // do something with your currentPoint
            }

            self.backgroundColor = UIColor.magentaColor()//Color when UIView is clicked.
        }

        override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
            if let touch = touches.first {
                let currentPoint = touch.locationInView(self)
                // do something with your currentPoint
            }

            self.backgroundColor = UIColor.whiteColor()//Color when UIView is not clicked.

}//class closes here

Also, call this Class from Storyboard & ViewController as:

@IBOutlet weak var panVerificationUIView:ClickableUIView!

How to revert a "git rm -r ."?

If you've committed and pushed the changes, you can do this to get the file back

// Replace 2 with the # of commits back before the file was deleted.
git checkout HEAD~2 path/to/file

How to get equal width of input and select fields

create another class and increase the with size with 2px example

.enquiry_fld_normal{
width:278px !important; 
}

.enquiry_fld_normal_select{
width:280px !important; 
 }

How do I make a dotted/dashed line in Android?

I have used the below as a background for the layout:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
<stroke
   android:width="1dp"
    android:dashWidth="10px"
   android:dashGap="10px"
    android:color="android:@color/black" 
   />
</shape>

Test if string is URL encoded in PHP

I am using the following test to see if strings have been urlencoded:

if(urlencode($str) != str_replace(['%','+'], ['%25','%2B'], $str))

If a string has already been urlencoded, the only characters that will changed by double encoding are % (which starts all encoded character strings) and + (which replaces spaces.) Change them back and you should have the original string.

Let me know if this works for you.

How To Get Selected Value From UIPickerView

You can get the text of the selected item in any section of the picker using the same function that the pickerView does, from your custom ViewController class:

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component

using the selected item

[myPickerView selectedRowInComponent:0]

so to set the text of a label in a custom cell using the currently selected value from the 2nd section of myPickerView (a property of your view controller probably)

[cell.label setText:[self pickerView:myPickerView titleForRow:[myPickerView selectedRowInComponent:1] forComponent:1]];

Just change both :1s to :2s, etc for each section

Java: Check the date format of current string is according to required format or not

Disclaimer

Parsing a string back to date/time value in an unknown format is inherently impossible (let's face it, what does 3/3/3 actually mean?!), all we can do is "best effort"

Important

This solution doesn't throw an Exception, it returns a boolean, this is by design. Any Exceptions are used purely as a guard mechanism.

2018

Since it's now 2018 and Java 8+ has the date/time API (and the rest have the ThreeTen backport). The solution remains basically the same, but becomes slightly more complicated, as we need to perform checks for:

  • date and time
  • date only
  • time only

This makes it look something like...

public static boolean isValidFormat(String format, String value, Locale locale) {
    LocalDateTime ldt = null;
    DateTimeFormatter fomatter = DateTimeFormatter.ofPattern(format, locale);

    try {
        ldt = LocalDateTime.parse(value, fomatter);
        String result = ldt.format(fomatter);
        return result.equals(value);
    } catch (DateTimeParseException e) {
        try {
            LocalDate ld = LocalDate.parse(value, fomatter);
            String result = ld.format(fomatter);
            return result.equals(value);
        } catch (DateTimeParseException exp) {
            try {
                LocalTime lt = LocalTime.parse(value, fomatter);
                String result = lt.format(fomatter);
                return result.equals(value);
            } catch (DateTimeParseException e2) {
                // Debugging purposes
                //e2.printStackTrace();
            }
        }
    }

    return false;
}

This makes the following...

System.out.println("isValid - dd/MM/yyyy with 20130925 = " + isValidFormat("dd/MM/yyyy", "20130925", Locale.ENGLISH));
System.out.println("isValid - dd/MM/yyyy with 25/09/2013 = " + isValidFormat("dd/MM/yyyy", "25/09/2013", Locale.ENGLISH));
System.out.println("isValid - dd/MM/yyyy with 25/09/2013 12:13:50 = " + isValidFormat("dd/MM/yyyy", "25/09/2013  12:13:50", Locale.ENGLISH));
System.out.println("isValid - yyyy-MM-dd with 2017-18--15 = " + isValidFormat("yyyy-MM-dd", "2017-18--15", Locale.ENGLISH));

output...

isValid - dd/MM/yyyy with 20130925 = false
isValid - dd/MM/yyyy with 25/09/2013 = true
isValid - dd/MM/yyyy with 25/09/2013 12:13:50 = false
isValid - yyyy-MM-dd with 2017-18--15 = false

Original Answer

Simple try and parse the String to the required Date using something like SimpleDateFormat

Date date = null;
try {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    date = sdf.parse(value);
    if (!value.equals(sdf.format(date))) {
        date = null;
    }
} catch (ParseException ex) {
    ex.printStackTrace();
}
if (date == null) {
    // Invalid date format
} else {
    // Valid date format
}

You could then simply write a simple method that performed this action and returned true when ever Date was not null...

As a suggestion...

Updated with running example

I'm not sure what you are doing, but, the following example...

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestDateParser {

    public static void main(String[] args) {
        System.out.println("isValid - dd/MM/yyyy with 20130925 = " + isValidFormat("dd/MM/yyyy", "20130925"));
        System.out.println("isValid - dd/MM/yyyy with 25/09/2013 = " + isValidFormat("dd/MM/yyyy", "25/09/2013"));
        System.out.println("isValid - dd/MM/yyyy with 25/09/2013 12:13:50 = " + isValidFormat("dd/MM/yyyy", "25/09/2013  12:13:50"));
    }

    public static boolean isValidFormat(String format, String value) {
        Date date = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            date = sdf.parse(value);
            if (!value.equals(sdf.format(date))) {
                date = null;
            }
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
        return date != null;
    }

}

Outputs (something like)...

java.text.ParseException: Unparseable date: "20130925"
isValid - dd/MM/yyyy with 20130925 = false
isValid - dd/MM/yyyy with 25/09/2013 = true
isValid - dd/MM/yyyy with 25/09/2013 12:13:50 = false
    at java.text.DateFormat.parse(DateFormat.java:366)
    at javaapplication373.JavaApplication373.isValidFormat(JavaApplication373.java:28)
    at javaapplication373.JavaApplication373.main(JavaApplication373.java:19)

Not correct. For isValidFormat("yyyy-MM-dd", "2017-18--15"); not throw any Exception.

isValid - yyyy-MM-dd", "2017-18--15 = false

Seems to work as expected for me - the method doesn't rely on (nor does it throw) the exception alone to perform it's operation

Is it possible to have a multi-line comments in R?

No multi-line comments in R as of version 2.12 and unlikely to change. In most environments, you can comment blocks by highlighting and toggle-comment. In emacs, this is 'M-x ;'.

Ripple effect on Android Lollipop CardView

If the app minSdkVersion which you are working is level 9, you can use:

android:foreground="?selectableItemBackground"
android:clickable="true"

Instead, starting from level 11, you use:

android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"

From documentation:

clickable - Defines whether this view reacts to click events. Must be a boolean value, either "true" or "false".

foreground - Defines the drawable to draw over the content. This can be used as an overlay. The foreground drawable participates in the padding of the content if the gravity is set to fill.

PHP refresh window? equivalent to F5 page reload?

PHP cannot force the client to do anything. It cannot refresh the page, let alone refresh the parent of a frame.

EDIT: You can of course, make PHP write JavaScript, but this is not PHP doing, it's actually JavaScript, and it will fail if JavaScript is disabled.

<?php
    echo '<script>parent.window.location.reload(true);</script>';
?>

pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/

This worked for me on Ubuntu 12.04.

pip install --index-url=https://pypi.python.org/simple/ -U scikit-learn

How to add a tooltip to an svg graphic?

I always go with the generic css title with my setup. I'm just building analytics for my blog admin page. I don't need anything fancy. Here's some code...

let comps = g.selectAll('.myClass')
   .data(data)
   .enter()
   .append('rect')
   ...styling...
   ...transitions...
   ...whatever...

g.selectAll('.myClass')
   .append('svg:title')
   .text((d, i) => d.name + '-' + i);

And a screenshot of chrome...

enter image description here

How do I center content in a div using CSS?

By using transform: works like a charm!

<div class="parent">
    <span>center content using transform</span>
    </div>

    //CSS
    .parent {
        position: relative;
        height: 200px;
        border: 1px solid;
    }
    .parent span {
        position: absolute;
        top: 50%;
        left: 50%;
        -webkit-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
    }

Is it possible to set async:false to $.getJSON call

In my case, Jay D is right. I have to add this before the call.

$.ajaxSetup({
    async: false
});

In my previous code, I have this:

var jsonData= (function() {
    var result;
    $.ajax({
        type:'GET',
        url:'data.txt',
        dataType:'json',
        async:false,
        success:function(data){
            result = data;
        }
    });
    return result;
})();
alert(JSON.stringify(jsonData));

It works find. Then I change to

var jsonData= (function() {
    var result;
    $.getJSON('data.txt', {}, function(data){
      result = data;
    });
    return result;
})();
alert(JSON.stringify(jsonData));

The alert is undefined.

If I add those three lines, the alert shows the data again.

$.ajaxSetup({
    async: false
});
var jsonData= (function() {
    var result;
    $.getJSON('data.txt', {}, function(data){
      result = data;
    });
    return result;
})();
alert(JSON.stringify(jsonData));

How to use XMLReader in PHP?

It all depends on how big the unit of work, but I guess you're trying to treat each <product/> nodes in succession.

For that, the simplest way would be to use XMLReader to get to each node, then use SimpleXML to access them. This way, you keep the memory usage low because you're treating one node at a time and you still leverage SimpleXML's ease of use. For instance:

$z = new XMLReader;
$z->open('data.xml');

$doc = new DOMDocument;

// move to the first <product /> node
while ($z->read() && $z->name !== 'product');

// now that we're at the right depth, hop to the next <product/> until the end of the tree
while ($z->name === 'product')
{
    // either one should work
    //$node = new SimpleXMLElement($z->readOuterXML());
    $node = simplexml_import_dom($doc->importNode($z->expand(), true));

    // now you can use $node without going insane about parsing
    var_dump($node->element_1);

    // go to next <product />
    $z->next('product');
}

Quick overview of pros and cons of different approaches:

XMLReader only

  • Pros: fast, uses little memory

  • Cons: excessively hard to write and debug, requires lots of userland code to do anything useful. Userland code is slow and prone to error. Plus, it leaves you with more lines of code to maintain

XMLReader + SimpleXML

  • Pros: doesn't use much memory (only the memory needed to process one node) and SimpleXML is, as the name implies, really easy to use.

  • Cons: creating a SimpleXMLElement object for each node is not very fast. You really have to benchmark it to understand whether it's a problem for you. Even a modest machine would be able to process a thousand nodes per second, though.

XMLReader + DOM

  • Pros: uses about as much memory as SimpleXML, and XMLReader::expand() is faster than creating a new SimpleXMLElement. I wish it was possible to use simplexml_import_dom() but it doesn't seem to work in that case

  • Cons: DOM is annoying to work with. It's halfway between XMLReader and SimpleXML. Not as complicated and awkward as XMLReader, but light years away from working with SimpleXML.

My advice: write a prototype with SimpleXML, see if it works for you. If performance is paramount, try DOM. Stay as far away from XMLReader as possible. Remember that the more code you write, the higher the possibility of you introducing bugs or introducing performance regressions.

How to return value from function which has Observable subscription inside?

For example this is my html template:

<select class="custom-select d-block w-100" id="genre" name="genre"
                  [(ngModel)]="film.genre"
                  #genreInput="ngModel"
                  required>
            <option value="">Choose...</option>
            <option *ngFor="let genre of genres;" [value]="genre.value">{{genre.name}}</option>
          </select>

This is the field that binded with template from my Component:

  // Genres of films like action or drama that will populate dropdown list.
  genres: Genre[];

I fetch genres of films from server dynamically. In order do communicate with server I have created FilmService

This is the method which communicate server:

 fetchGenres(): Observable<Genre[]> {
    return this.client.get(WebUtils.RESOURCE_HOST_API + 'film' + '/genre') as Observable<Genre[]>;
  }

Why this method returns Observable<Genre[]> not something like Genre[]?

JavaScript is async and it does not wait for a method to return value after an expensive process. With expensive I mean a process that take a time to return value. Like fetching data from server. So you have to return reference of Observable and subscribe it.

For example in my Component :

ngOnInit() {
    this.filmService.fetchGenres().subscribe(
      val => this.genres = val
    );
  }

Show git diff on file in staging area

You can also use git diff HEAD file to show the diff for a specific file.

See the EXAMPLE section under git-diff(1)

Adb Devices can't find my phone

I have a Samsung Galaxy and I had the same issue as you. Here's how to fix it:

In device manager on your Windows PC, even though it might say the USB drivers are installed correctly, there may exist corruption.

I went into device manager and uninstalled SAMSUNG Android USB Composite Device and made sure to check the box 'delete driver software'. Now the device will have an exclamation mark etc. I right clicked and installed the driver again (refresh copy). This finally made adb acknowledge my phone as an emulator.

As others noted, for Nexus 4, you can also try this fix.

Writing a dictionary to a text file?

If you want a dictionary you can import from a file by name, and also that adds entries that are nicely sorted, and contains strings you want to preserve, you can try this:

data = {'A': 'a', 'B': 'b', }

with open('file.py','w') as file:
    file.write("dictionary_name = { \n")
    for k in sorted (data.keys()):
        file.write("'%s':'%s', \n" % (k, data[k]))
    file.write("}")

Then to import:

from file import dictionary_name

Read a zipped file as a pandas DataFrame

I think you want to open the ZipFile, which returns a file-like object, rather than read:

In [11]: crime2013 = pd.read_csv(z.open('crime_incidents_2013_CSV.csv'))

In [12]: crime2013
Out[12]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 24567 entries, 0 to 24566
Data columns (total 15 columns):
CCN                            24567  non-null values
REPORTDATETIME                 24567  non-null values
SHIFT                          24567  non-null values
OFFENSE                        24567  non-null values
METHOD                         24567  non-null values
LASTMODIFIEDDATE               24567  non-null values
BLOCKSITEADDRESS               24567  non-null values
BLOCKXCOORD                    24567  non-null values
BLOCKYCOORD                    24567  non-null values
WARD                           24563  non-null values
ANC                            24567  non-null values
DISTRICT                       24567  non-null values
PSA                            24567  non-null values
NEIGHBORHOODCLUSTER            24263  non-null values
BUSINESSIMPROVEMENTDISTRICT    3613  non-null values
dtypes: float64(4), int64(1), object(10)

Python: finding an element in a list

Here is another way using list comprehension (some people might find it debatable). It is very approachable for simple tests, e.g. comparisons on object attributes (which I need a lot):

el = [x for x in mylist if x.attr == "foo"][0]

Of course this assumes the existence (and, actually, uniqueness) of a suitable element in the list.

How to delete a folder with files using Java

private void deleteFileOrFolder(File file){
    try {
        for (File f : file.listFiles()) {
            f.delete();
            deleteFileOrFolder(f);
        }
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}

How to run Rake tasks from within Rake tasks?

for example:

Rake::Task["db:migrate"].invoke

while ($row = mysql_fetch_array($result)) - how many loops are being performed?

I'm assuming mysql_fetch_array() perfroms a loop, so I'm interested in if using a while() in conjunction with it, if it saves a nested loop.

No. mysql_fetch_array just returns the next row of the result and advances the internal pointer. It doesn't loop. (Internally it may or may not use some loop somewhere, but that's irrelevant.)

while ($row = mysql_fetch_array($result)) {
   ...
}

This does the following:

  1. mysql_fetch_array retrieves and returns the next row
  2. the row is assigned to $row
  3. the expression is evaluated and if it evaluates to true, the contents of the loop are executed
  4. the procedure begins anew
$row = mysql_fetch_array($result);
foreach($row as $r) {
    ...
}

This does the following:

  1. mysql_fetch_array retrieves and returns the next row
  2. the row is assigned to $row
  3. foreach loops over the contents of the array and executes the contents of the loop as many times as there are items in the array

In both cases mysql_fetch_array does exactly the same thing. You have only as many loops as you write. Both constructs do not do the same thing though. The second will only act on one row of the result, while the first will loop over all rows.

C# : Converting Base Class to Child Class

If you HAVE to, and you don't mind a hack, you could let serialization do the work for you.

Given these classes:

public class ParentObj
{
    public string Name { get; set; }
}

public class ChildObj : ParentObj
{
    public string Value { get; set; }
}

You can create a child instance from a parent instance like so:

var parent = new ParentObj() { Name = "something" };
var serialized = JsonConvert.SerializeObject(parent);
var child = JsonConvert.DeserializeObject<ChildObj>(serialized);

This assumes your objects play nice with serialization, obv.

Be aware that this is probably going to be slower than an explicit converter.

Where does System.Diagnostics.Debug.Write output appear?

As others have pointed out, listeners have to be registered in order to read these streams. Also note that Debug.Write will only function if the DEBUG build flag is set, while Trace.Write will only function if the TRACE build flag is set.

Setting the DEBUG and/or TRACE flags is easily done in the project properties in Visual Studio or by supplying the following arguments to csc.exe

/define:DEBUG;TRACE

how to prevent "directory already exists error" in a makefile when using mkdir

$(OBJDIR):
    mkdir $@

Which also works for multiple directories, e.g..

OBJDIRS := $(sort $(dir $(OBJECTS)))

$(OBJDIRS):
    mkdir $@

Adding $(OBJDIR) as the first target works well.

How can I use nohup to run process as a background process in linux?

  • Use screen: Start screen, start your script, press Ctrl+A, D. Reattach with screen -r.

  • Make a script that takes your "1" as a parameter, run nohup yourscript:

    #!/bin/bash
    (time bash executeScript $1 input fileOutput $> scrOutput) &> timeUse.txt
    

store return value of a Python script in a bash script

sys.exit(myString) doesn't mean "return this string". If you pass a string to sys.exit, sys.exit will consider that string to be an error message, and it will write that string to stderr. The closest concept to a return value for an entire program is its exit status, which must be an integer.

If you want to capture output written to stderr, you can do something like

python yourscript 2> return_file

You could do something like that in your bash script

output=$((your command here) 2> &1)

This is not guaranteed to capture only the value passed to sys.exit, though. Anything else written to stderr will also be captured, which might include logging output or stack traces.

example:

test.py

print "something"
exit('ohoh') 

t.sh

va=$(python test.py 2>&1)                                                                                                                    
mkdir $va

bash t.sh

edit

Not sure why but in that case, I would write a main script and two other scripts... Mixing python and bash is pointless unless you really need to.

import script1
import script2

if __name__ == '__main__':
    filename = script1.run(sys.args)
    script2.run(filename)

Convert char to int in C#

Has anyone considered using int.Parse() and int.TryParse() like this

int bar = int.Parse(foo.ToString());

Even better like this

int bar;
if (!int.TryParse(foo.ToString(), out bar))
{
    //Do something to correct the problem
}

It's a lot safer and less error prone

How to copy file from one location to another location?

Use the New Java File classes in Java >=7.

Create the below method and import the necessary libs.

public static void copyFile( File from, File to ) throws IOException {
    Files.copy( from.toPath(), to.toPath() );
} 

Use the created method as below within main:

File dirFrom = new File(fileFrom);
File dirTo = new File(fileTo);

try {
        copyFile(dirFrom, dirTo);
} catch (IOException ex) {
        Logger.getLogger(TestJava8.class.getName()).log(Level.SEVERE, null, ex);
}

NB:- fileFrom is the file that you want to copy to a new file fileTo in a different folder.

Credits - @Scott: Standard concise way to copy a file in Java?

WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

As you have to use WITH (NOLOCK) for each table it might be annoying to write it in every FROM or JOIN clause. However it has a reason why it is called a "dirty" read. So you really should know when you do one, and not set it as default for the session scope. Why?

Forgetting a WITH (NOLOCK) might not affect your program in a very dramatic way, however doing a dirty read where you do not want one can make the difference in certain circumstances.

So use WITH (NOLOCK) if the current data selected is allowed to be incorrect, as it might be rolled back later. This is mostly used when you want to increase performance, and the requirements on your application context allow it to take the risk that inconsistent data is being displayed. However you or someone in charge has to weigh up pros and cons of the decision of using WITH (NOLOCK).

How do you return a JSON object from a Java Servlet

How do you return a JSON object from a Java Servlet

response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();

  //create Json Object
  JsonObject json = new JsonObject();

    // put some value pairs into the JSON object .
    json.addProperty("Mobile", 9999988888);
    json.addProperty("Name", "ManojSarnaik");

    // finally output the json string       
    out.print(json.toString());

PHP and MySQL Select a Single Value

It is quite evident that there is only a single id corresponding to a single username because username is unique.

But the actual problem lies in the query itself-

$sql = "SELECT 'id' FROM Users WHERE username='$name'";

O/P

+----+
| id |
+----+
| id |
+----+

i.e. 'id' actually is treated as a string not as the id attribute.

Correct synatx:

$sql = "SELECT `id` FROM Users WHERE username='$name'";

i.e. use grave accent(`) instead of single quote(').

or

$sql = "SELECT id FROM Users WHERE username='$name'";

Complete code

session_start();
$name = $_GET["username"];
$sql = "SELECT `id` FROM Users WHERE username='$name'";
$result = mysql_query($sql);
$row=mysql_fetch_array($result)
$value = $row[0];
$_SESSION['myid'] = $value;

How to cast ArrayList<> from List<>

You can cast List<> to ArrayList<> if you understand what you doing. Java compiler won't block it.

But:

  1. It's bad practice to casting parent type to child type (or interface to implementation type) without checking. This way better:

if (list instanceof ArrayList<Task>) { ArrayList<Task> arraylist = (ArrayList<Task>) list; }

  1. Maybe you don't need implementation type as reference. Look SonarQube warning https://sbforge.org/sonar/rules/show/squid:S1319. You can avoid this casting in the most cases.
  2. You can use Guava method: ArrayList<Task> arraylist = Lists.newArrayList(list);

Batch file to delete files older than N days

More flexible way is to use FileTimeFilterJS.bat:

@echo off

::::::::::::::::::::::
set "_DIR=C:\Users\npocmaka\Downloads"
set "_DAYS=-5"
::::::::::::::::::::::

for /f "tokens=* delims=" %%# in ('FileTimeFilterJS.bat  "%_DIR%" -dd %_DAYS%') do (
    echo deleting  "%%~f#"
    echo del /q /f "%%~f#"
)

The script will allow you to use measurements like days, minutes ,seconds or hours. To choose weather to filter the files by time of creation, access or modification To list files before or after a certain date (or between two dates) To choose if to show files or dirs (or both) To be recursive or not

Overwriting txt file in java

Your code works fine for me. It replaced the text in the file as expected and didn't append.

If you wanted to append, you set the second parameter in

new FileWriter(fnew,false);

to true;

How to get the HTML's input element of "file" type to only accept pdf files?

Not with the HTML file control, no. A flash file uploader can do that for you though. You could use some client-side code to check for the PDF extension after they select, but you cannot directly control what they can select.

How to convert java.lang.Object to ArrayList?

I hope this will be help you

import java.util.ArrayList; 
public class Demo {

 public static void main(String[] args) {
    Object obj2 =null;
    ArrayList al1 = (ArrayList) obj2;
    al1 = (ArrayList) obj2;
    System.out.println("List2 Value: " + al1);
    }
 }

obj2 Object is default null before you cast it to ArrayList. That's why print 'al1' as null.

python convert list to dictionary

Using the usual grouper recipe, you could do:

Python 2:

d = dict(itertools.izip_longest(*[iter(l)] * 2, fillvalue=""))

Python 3:

d = dict(itertools.zip_longest(*[iter(l)] * 2, fillvalue=""))

How to get the values of a ConfigurationSection of type NameValueSectionHandler

This is an old question, but I use the following class to do the job. It's based on Scott Dorman's blog:

public class NameValueCollectionConfigurationSection : ConfigurationSection
{
    private const string COLLECTION_PROP_NAME = "";

    public IEnumerable<KeyValuePair<string, string>> GetNameValueItems()
    {
        foreach ( string key in this.ConfigurationCollection.AllKeys )
        {
            NameValueConfigurationElement confElement = this.ConfigurationCollection[key];
            yield return new KeyValuePair<string, string>
                (confElement.Name, confElement.Value);
        }
    }

    [ConfigurationProperty(COLLECTION_PROP_NAME, IsDefaultCollection = true)]
    protected NameValueConfigurationCollection ConfCollection
    {
        get
        {
            return (NameValueConfigurationCollection) base[COLLECTION_PROP_NAME];
        }
    }

The usage is straightforward:

Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
NameValueCollectionConfigurationSection config = 
    (NameValueCollectionConfigurationSection) configuration.GetSection("MyParams");

NameValueCollection myParamsCollection = new NameValueCollection();
config.GetNameValueItems().ToList().ForEach(kvp => myParamsCollection.Add(kvp));

passing JSON data to a Spring MVC controller

  1. Html

    $('#save').click(function(event) {        
        var jenis = $('#jenis').val();
        var model = $('#model').val();
        var harga = $('#harga').val();
        var json = { "jenis" : jenis, "model" : model, "harga": harga};
        $.ajax({
            url: 'phone/save',
            data: JSON.stringify(json),
            type: "POST",           
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json");
            },
            success: function(data){ 
                alert(data);
            }
        });
    
        event.preventDefault();
    });
    
    1. Controller

      @Controller
      @RequestMapping(value="/phone")
      public class phoneController {
      
          phoneDao pd=new phoneDao();
      
          @RequestMapping(value="/save",method=RequestMethod.POST)
          public @ResponseBody
          int save(@RequestBody Smartphones phone)
          {
              return pd.save(phone);
          }
      
    2. Dao

      public Integer save(Smartphones i) {
          int id = 0;
          Session session=HibernateUtil.getSessionFactory().openSession();
          Transaction trans=session.beginTransaction();
          try {
              session.save(i);   
              id=i.getId();
              trans.commit();
          }
          catch(HibernateException he){}
          return id;
      }
      

Convert XML String to Object

Simplifying Damian's great answer,

public static T ParseXml<T>(this string value) where T : class
{
    var xmlSerializer = new XmlSerializer(typeof(T));
    using (var textReader = new StringReader(value))
    {
        return (T) xmlSerializer.Deserialize(textReader);
    }
}

How to make JQuery-AJAX request synchronous

Can you try this,

var ajaxSubmit = function(formE1) {

            var password = $.trim($('#employee_password').val());

             $.ajax({
                type: "POST",
                async: "false",
                url: "checkpass.php",
                data: "password="+password,
                success: function(html) {
                    var arr=$.parseJSON(html);
                    if(arr == "Successful")
                    { 
                         **$("form[name='form']").submit();**
                        return true;
                    }
                    else
                    {    return false;
                    }
                }
            });
              **return false;**
        }

Huge performance difference when using group by vs distinct

The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct approach is executed like:

  • Copy all business_key values to a temporary table
  • Sort the temporary table
  • Scan the temporary table, returning each item that is different from the one before it

The group by could be executed like:

  • Scan the full table, storing each value of business key in a hashtable
  • Return the keys of the hashtable

The first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.

Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.

How to enable LogCat/Console in Eclipse for Android?

Go to your desired perspective. Go to 'Window->show view' menu.

If you see logcat there, click it and you are done.

Else, click on 'other' (at the bottom), chose 'Android'->logcat.

Hope that helps :-)

Convert Map<String,Object> to Map<String,String>

Great solutions here, just one more option that taking into consideration handling of null values:

Map<String,Object> map = new HashMap<>();

Map<String,String> stringifiedMap = map.entrySet().stream()
             .filter(m -> m.getKey() != null && m.getValue() !=null)
             .collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));

How to keep two folders automatically synchronized?

You need something like this: https://github.com/axkibe/lsyncd It is a tool which combines rsync and inotify - the former is a tool that mirrors, with the correct options set, a directory to the last bit. The latter tells the kernel to notify a program of changes to a directory ot file. It says:

It aggregates and combines events for a few seconds and then spawns one (or more) process(es) to synchronize the changes.

But - according to Digital Ocean at https://www.digitalocean.com/community/tutorials/how-to-mirror-local-and-remote-directories-on-a-vps-with-lsyncd - it ought to be in the Ubuntu repository!

I have similar requirements, and this tool, which I have yet to try, seems suitable for the task.

PDO get the last ID inserted

That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().

Like:

$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();

If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:

$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();

How to print a certain line of a file with PowerShell?

Just for fun, here some test:

#Added this for @Graimer's request ;) (not same computer, but one with HD little more #performant...)

measure-command { Get-Content ita\ita.txt -TotalCount 260000 | Select-Object -Last 1 }

Days              : 0
Hours             : 0

Minutes           : 0
Seconds           : 28
Milliseconds      : 893
Ticks             : 288932649
TotalDays         : 0,000334412788194444
TotalHours        : 0,00802590691666667
TotalMinutes      : 0,481554415
TotalSeconds      : 28,8932649
TotalMilliseconds : 28893,2649


> measure-command { (gc "c:\ps\ita\ita.txt")[260000] }


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 9
Milliseconds      : 257
Ticks             : 92572893
TotalDays         : 0,000107144552083333
TotalHours        : 0,00257146925
TotalMinutes      : 0,154288155
TotalSeconds      : 9,2572893
TotalMilliseconds : 9257,2893


> measure-command { ([System.IO.File]::ReadAllLines("c:\ps\ita\ita.txt"))[260000] }


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 234
Ticks             : 2348059
TotalDays         : 2,71766087962963E-06
TotalHours        : 6,52238611111111E-05
TotalMinutes      : 0,00391343166666667
TotalSeconds      : 0,2348059
TotalMilliseconds : 234,8059



> measure-command {get-content .\ita\ita.txt | select -index 260000}


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 36
Milliseconds      : 591
Ticks             : 365912596
TotalDays         : 0,000423509949074074
TotalHours        : 0,0101642387777778
TotalMinutes      : 0,609854326666667
TotalSeconds      : 36,5912596
TotalMilliseconds : 36591,2596

the winner is : ([System.IO.File]::ReadAllLines( path ))[index]

CREATE DATABASE permission denied in database 'master' (EF code-first)

I had the same problem. This what worked for me:

  1. Go to SQL Server Management Studio and run it as Administrator.
  2. Choose Security -> Then Logins
  3. Choose the usernames or whatever users that will access your database under the Logins and Double Click it.
  4. Give them a Server Roles that will give them credentials to create database. On my case, public was already checked so I checked dbcreator and sysadmin.
  5. Run update-database again on Package Manager Console. Database should now successfully created.

Here is an image so that you can get the bigger picture, I blurred my credentials of course:enter image description here

The system cannot find the file specified in java

I have copied your code and it runs fine.

I suspect you are simply having some problem in the actual file name of hello.txt, or you are running in a wrong directory. Consider verifying by the method suggested by @Eng.Fouad

Converting integer to digit list

num = list(str(100))
index = len(num)
while index > 0:
    index -= 1
    num[index] = int(num[index])
print(num)

It prints [1, 0, 0] object.

What's the actual use of 'fail' in JUnit test case?

Let's say you are writing a test case for a negative flow where the code being tested should raise an exception.

try{
   bizMethod(badData);
   fail(); // FAIL when no exception is thrown
} catch (BizException e) {
   assert(e.errorCode == THE_ERROR_CODE_U_R_LOOKING_FOR)
}

How to store a list in a column of a database table

Only one option doesn't mentioned in the answers. You can de-normalize your DB design. So you need two tables. One table contains proper list, one item per row, another table contains whole list in one column (coma-separated, for example).

Here it is 'traditional' DB design:

List(ListID, ListName) 
Item(ItemID,ItemName) 
List_Item(ListID, ItemID, SortOrder)

Here it is de-normalized table:

Lists(ListID, ListContent)

The idea here - you maintain Lists table using triggers or application code. Every time you modify List_Item content, appropriate rows in Lists get updated automatically. If you mostly read lists it could work quite fine. Pros - you can read lists in one statement. Cons - updates take more time and efforts.

iOS for VirtualBox

You could try qemu, which is what the Android emulator uses. I believe it actually emulates the ARM hardware.

ProgressDialog in AsyncTask

A couple of days ago I found a very nice solution of this problem. Read about it here. In two words Mike created a AsyncTaskManager that mediates ProgressDialog and AsyncTask. It's very easy to use this solution. You just need to include in your project several interfaces and several classes and in your activity write some simple code and nest your new AsyncTask from BaseTask. I also advice you to read comments because there are some useful tips.

Form Submit jQuery does not work

Since every control element gets referenced with its name on the form element (see forms specs), controls with name "submit" will override the build-in submit function.

Which leads to the error mentioned in comments above:

Uncaught TypeError: Property 'submit' of object #<HTMLFormElement> is not a function

As in the accepted answer above the simplest solution would be to change the name of that control element.

However another solution could be to use dispatchEvent method on form element:

$("#form_id")[0].dispatchEvent(new Event('submit')); 

Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error?

Took me a while to find this out but if you a number stored in a variable, say x and you want to select it, use

document.querySelector('a[data-a= + CSS.escape(x) + ']'). 

This is due to some attribute naming specifications that I'm not yet very familiar with. Hope this will help someone.

Export data from Chrome developer tool

if you right click on any of the rows you can export the item or the entire data set as HAR which appears to be a JSON format.

It shouldn't be terribly difficult to script up something to transform that to a csv if you really need it in excel, but if you're already scripting you might as well just use the script to ask your questions of the data.

If anyone knows how to drive the "load page, export data" part of the process from the command line I'd be quite interested in hearing how

Configure Apache .conf for Alias

Sorry not sure what was going on this worked in the end:

<VirtualHost *> 
    ServerName example.com
    DocumentRoot /var/www/html/mjp

    Alias /ncn "/var/www/html/ncn"

    <Directory "/var/www/html/ncn">
        Options None
        AllowOverride None
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

Loaded nib but the 'view' outlet was not set

You guys are right, but as I'm a newcomer it took me a little while to figure out all the steps to do that. Here's what worked for me:

  • Open the XIB file causing problems
  • Click on file's owner icon on the left bar (top one, looks like a yellow outlined box)
  • If you don't see the right-hand sidebar, click on the third icon above "view" in your toolbar. This will show the right-hand sidebar
  • In the right-hand sidebar, click on the fourth tab--the one that looks a bit like a newspaper
  • Under "Custom Class" at the top, make sure Class is the name of the ViewController that should correspond to this view. If not, enter it
  • In the right-hand sidebar, click on the last tab--the one that looks like a circle with an arrow in it
  • You should see "outlets" with "view" under it. Drag the circle next to it over to the "view" icon on the left bar (bottom one, looks like a white square with a thick gray outline
  • Save the xib and re-run

Open File Dialog, One Filter for Multiple Excel Extensions?

If you want to merge the filters (eg. CSV and Excel files), use this formula:

OpenFileDialog of = new OpenFileDialog();
of.Filter = "CSV files (*.csv)|*.csv|Excel Files|*.xls;*.xlsx";

Or if you want to see XML or PDF files in one time use this:

of.Filter = @" XML or PDF |*.xml;*.pdf";

bash: shortest way to get n-th column of output

You can use cut to access the second field:

cut -f2

Edit: Sorry, didn't realise that SVN doesn't use tabs in its output, so that's a bit useless. You can tailor cut to the output but it's a bit fragile - something like cut -c 10- would work, but the exact value will depend on your setup.

Another option is something like: sed 's/.\s\+//'

package javax.mail and javax.mail.internet do not exist

Had the same issue. Obviously these .jars were included with Java <= v8.x out of the box, but are not anymore. Thus one has to separately download them and place them in the appropriate classpath as highlighted by several folks above. I understand that the new Java is modularized and thus potentially more light-weight (which is certainly a good thing, since the old setup was a monster). On the other hand this - as we can see - breaks lots of old build setups. Since the time to fix these isn't chargeable to Oracle I guess this made their decision easy...

What is Inversion of Control?

IoC / DI to me is pushing out dependencies to the calling objects. Super simple.

The non-techy answer is being able to swap out an engine in a car right before you turn it on. If everything hooks up right (the interface), you are good.

What's the difference between JPA and Hibernate?

JPA is just a specification.In market there are many vendors which implements JPA. Different types of vendors implement JPA in different way. so different types of vendors provide different functionality so choose proper vendor based on your requirements.

If you are using Hibernate or any other vendors instead of JPA than you can not easily move to hibernate to EclipseLink or OpenJPA to Hibernate.But If you using JPA than you just have to change provide in persistence XML file.So migration is easily possible in JPA.

How to read xml file contents in jQuery and display in html elements?

I think you want like this, DEMO

var xmlDoc = $.parseXML( xml ); 

var $xml = $(xmlDoc);

var $person = $xml.find("person");

$person.each(function(){

    var name = $(this).find('name').text(),
        age = $(this).find('age').text();

    $("#ProfileList" ).append('<li>' +name+ ' - ' +age+ '</li>');

});

python: how to check if a line is an empty line

I use the following code to test the empty line with or without white spaces.

if len(line.strip()) == 0 :
    # do something with empty line

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

Get user info via Google API

Add this to the scope - https://www.googleapis.com/auth/userinfo.profile

And after authorization is done, get the information from - https://www.googleapis.com/oauth2/v1/userinfo?alt=json

It has loads of stuff - including name, public profile url, gender, photo etc.

How to convert time milliseconds to hours, min, sec format in JavaScript?

Based on @Chand answer. This is the implementation in Typescript. A bit safer than coercing types in JS. If you remove the type annotation should be valid JS. Also using new string functions to normalise the time.

function displayTime(millisec: number) {
 const normalizeTime = (time: string): string => (time.length === 1) ? time.padStart(2, '0') : time;

 let seconds: string = (millisec / 1000).toFixed(0);
 let minutes: string = Math.floor(parseInt(seconds) / 60).toString();
 let hours: string = '';

 if (parseInt(minutes) > 59) {
   hours = normalizeTime(Math.floor(parseInt(minutes) / 60).toString());
   minutes = normalizeTime((parseInt(minutes) - (parseInt(hours) * 60)).toString());
 }
 seconds = normalizeTime(Math.floor(parseInt(seconds) % 60).toString());

 if (hours !== '') {
    return `${hours}:${minutes}:${seconds}`;
 }
   return `${minutes}:${seconds}`;
}

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

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

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

So to calculate the sum of series of numbers:

n(n+1)/2

But you need to calculate this

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

So in order to get this you can use

n(n+1)/2 - n

that is equal to

n(n-1)/2

TypeError: can't use a string pattern on a bytes-like object in re.findall()

You want to convert html (a byte-like object) into a string using .decode, e.g. html = response.read().decode('utf-8').

See Convert bytes to a Python String

What precisely does 'Run as administrator' do?

UPDATE

"Run as Aministrator" is just a command, enabling the program to continue some operations that require the Administrator privileges, without displaying the UAC alerts.

Even if your user is a member of administrators group, some applications like yours need the Administrator privileges to continue running, because the application is considered not safe, if it is doing some special operation, like editing a system file or something else. This is the reason why Windows needs the Administrator privilege to execute the application and it notifies you with a UAC alert. Not all applications need an Amnistrator account to run, and some applications, like yours, need the Administrator privileges.

If you execute the application with 'run as administrator' command, you are notifying the system that your application is safe and doing something that requires the administrator privileges, with your confirm.

If you want to avoid this, just disable the UAC on Control Panel.

If you want to go further, read the question Difference between "Run as Administrator" and Windows 7 Administrators Group on Microsoft forum or this SuperUser question.

Node.js heap out of memory

This command works perfectly. I have 8GB ram in my laptop, So I set size=8192. It is all about ram and also you need set file name. I run npm run build command that's why I used build.js.

node --expose-gc --max-old-space-size=8192 node_modules/react-scripts/scripts/build.js

Multiple INNER JOIN SQL ACCESS

Thanks HansUp for your answer, it is very helpful and it works!

I found three patterns working in Access, yours is the best, because it works in all cases.

  • INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM
         ((class
           INNER JOIN person AS cr 
           ON class.C_P_ClassRep=cr.P_Nr
         )
         INNER JOIN person AS cr2
         ON class.C_P_ClassRep2nd=cr2.P_Nr
      )
    

    ;

  • INNER JOIN "chained-set pattern"

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM person AS cr
    INNER JOIN ( class 
       INNER JOIN ( person AS cr2
       ) ON class.C_P_ClassRep2nd=cr2.P_Nr
    ) ON class.C_P_ClassRep=cr.P_Nr
    ;
    
  • CROSS JOIN with WHERE

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM class, person AS cr, person AS cr2
    WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
    ;
    

How to detect if a stored procedure already exists

The cleanest way is to test for it's existence, drop it if it exists, and then recreate it. You can't embed a "create proc" statement inside an IF statement. This should do nicely:

IF OBJECT_ID('MySproc', 'P') IS NOT NULL
DROP PROC MySproc
GO

CREATE PROC MySproc
AS
BEGIN
    ...
END

What's the equivalent of Java's Thread.sleep() in JavaScript?

setTimeout would not hold and resume on your own thread however Thread.sleep does. There is no actual equal in Javascript

sqlplus statement from command line

I'm able to execute your exact query by just making sure there is a semicolon at the end of my select statement. (Output is actual, connection params removed.)

echo "select 1 from dual;" | sqlplus -s username/password@host:1521/service 

Output:

         1
----------
         1

Note that is should matter but this is running on Mac OS X Snow Leopard and Oracle 11g.

node.js string.replace doesn't work?

Strings are always modelled as immutable (atleast in heigher level languages python/java/javascript/Scala/Objective-C).

So any string operations like concatenation, replacements always returns a new string which contains intended value, whereas the original string will still be same.

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

At each point in these instructions, check to see if the problem is fixed. If so, great! Otherwise, continue.

  1. Get to Services. (I was able to right click the Apache launch icon to get there.)
  2. Scroll down to MySQL. Click to start. This will get rid of the #2002 error. Now you'll have a new error:

#1045 - Access denied for user 'root'@'localhost' (using password: NO)

  1. Edit the C:\wamp\apps\phpmyadmin3.5.1\config.inc.php file, changing $cfg['Servers'][$i]['extension'] = 'mysqli'; to instead be= 'mysql'
  2. Open Services again and Stop MySQL
  3. While in Services, Start wampmysqld

This is convoluted, I know, but that's what worked for me. Some posts may say you need a password in the config file, but you don't. Mine is still ""

Hope this helps.

Sharing a variable between multiple different threads

In addition to the other suggestions - you can also wrap the flag in a control class and make a final instance of it in your parent class:

public class Test {
  class Control {
    public volatile boolean flag = false;
  }
  final Control control = new Control();

  class T1 implements Runnable {
    @Override
    public void run() {
      while ( !control.flag ) {

      }
    }
  }

  class T2 implements Runnable {
    @Override
    public void run() {
      while ( !control.flag ) {

      }
    }
  }

  private void test() {
    T1 main = new T1();
    T2 help = new T2();

    new Thread(main).start();
    new Thread(help).start();
  }

  public static void main(String[] args) throws InterruptedException {
    try {
      Test test = new Test();
      test.test();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Where can I find Android's default icons?

You can find the default Android menu icons here - link is broken now.

Update: You can find Material Design icons here.

Loading .sql files from within PHP

Try This:

// SQL File
$SQLFile = 'YourSQLFile.sql';

// Server Name
$hostname = 'localhost';

// User Name
$db_user = 'root';

// User Password
$db_password = '';

// DBName
$database_name = 'YourDBName';

// Connect MySQL
$link = mysql_connect($hostname, $db_user, $db_password);

if (!$link) {
die("MySQL Connection error");
}

// Select MySQL DB
mysql_select_db($database_name, $link) or die("Wrong MySQL Database");

// Function For Run Multiple Query From .SQL File
function MultiQuery($sqlfile, $sqldelimiter = ';') {
set_time_limit(0);

if (is_file($sqlfile) === true) {
$sqlfile = fopen($sqlfile, 'r');

if (is_resource($sqlfile) === true) {
$query = array();
echo "<table cellspacing='3' cellpadding='3' border='0'>";

while (feof($sqlfile) === false) {
$query[] = fgets($sqlfile);

if (preg_match('~' . preg_quote($sqldelimiter, '~') . '\s*$~iS', end($query)) === 1) {
$query = trim(implode('', $query));

if (mysql_query($query) === false) {
echo '<tr><td>ERROR:</td><td> ' . $query . '</td></tr>';
} else {
echo '<tr><td>SUCCESS:</td><td>' . $query . '</td></tr>';
}

while (ob_get_level() &gt; 0) {
ob_end_flush();
}

flush();
}

if (is_string($query) === true) {
$query = array();
}
}
echo "</table>";

return fclose($sqlfile);
}
}

return false;
}

/* * * Use Function Like This: ** */

MultiQuery($SQLFile);

Adding multiple columns AFTER a specific column in MySQL

Try this

ALTER TABLE users
ADD COLUMN `count` SMALLINT(6) NOT NULL AFTER `lastname`,
ADD COLUMN `log` VARCHAR(12) NOT NULL AFTER `count`,
ADD COLUMN `status` INT(10) UNSIGNED NOT NULL AFTER `log`;

check the syntax

Pass mouse events through absolutely-positioned element

pointer-events: none;

Is a CSS property that makes events "pass through" the element to which it is applied and makes the event occur on the element "below".

See for details: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

It is not supported up to IE 11; all other vendors support it since quite some time (global support was ~92% in 12/'16): http://caniuse.com/#feat=pointer-events (thanks to @s4y for providing the link in the comments).

Compare two dates in Java

It's not clear to me what you want, but I'll mention that the Date class also has a compareTo method, which can be used to determine with one call if two Date objects are equal or (if they aren't equal) which occurs sooner. This allows you to do something like:

switch (today.compareTo(questionDate)) {
    case -1:  System.out.println("today is sooner than questionDate");  break;
    case 0:   System.out.println("today and questionDate are equal");  break;
    case 1:   System.out.println("today is later than questionDate");  break;
    default:  System.out.println("Invalid results from date comparison"); break;
}

It should be noted that the API docs don't guarantee the results to be -1, 0, and 1, so you may want to use if-elses rather than a switch in any production code. Also, if the second date is null, you'll get a NullPointerException, so wrapping your code in a try-catch may be useful.

How can I reorder a list?

>>> a = [1, 2, 3]
>>> a[0], a[2] = a[2], a[0]
>>> a
[3, 2, 1]

extract part of a string using bash/cut/split

Define a function like this:

getUserName() {
    echo $1 | cut -d : -f 1 | xargs basename
}

And pass the string as a parameter:

userName=$(getUserName "/var/cpanel/users/joebloggs:DNS9=domain.com")
echo $userName

SQLite DateTime comparison

The following is working fine for me using SQLite:

SELECT * 
    FROM ingresosgastos 
    WHERE fecharegistro BETWEEN "2010-01-01" AND "2013-01-01"

Error 500: Premature end of script headers

I experienced this problem today, but unfortunately none of the suggestions here helped. The only problem was that I didn't see ANY errors.. I literally had to do an strace -p <process_id> on the Apache thread to spot the headers being written and Apache crashing on the next line; Somewhere in my PHP code I was setting a header with over 12KB of data.

The lesson here is that in some cases, Apache crashing with a HTTP error 500 - Premature end of script-failure can be the result of having too long or overflowing HTTP headers.

Debug your headers for length if you have this same problems because most (if not all) web servers have HTTP header limits.

PS: This reply has some info on header sizes.

Which Ruby version am I really running?

If you have access to a console in the context you are investigating, you can determine which version you are running by printing the value of the global constant RUBY_VERSION.

Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP

Although a bit late, I've come across this question while searching the solution for the same problem, so I hope it can be of any help...

Found myself in the same darkness than you. Just found this article, which explains some new hints introduced in NetBeans 7.4, including this one:

https://blogs.oracle.com/netbeansphp/entry/improve_your_code_with_new

The reason why it has been added is because superglobals usually are filled with user input, which shouldn't ever be blindly trusted. Instead, some kind of filtering should be done, and that's what the hint suggests. Filter the superglobal value in case it has some poisoned content.

For instance, where I had:

$_SERVER['SERVER_NAME']

I've put instead:

filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_SANITIZE_STRING)

You have the filter_input and filters doc here:

http://www.php.net/manual/en/function.filter-input.php

http://www.php.net/manual/en/filter.filters.php

Injection of autowired dependencies failed;

The error shows that com.bd.service.ArticleService is not a registered bean. Add the packages in which you have beans that will be autowired in your application context:

<context:component-scan base-package="com.bd.service"/>
<context:component-scan base-package="com.bd.controleur"/>

Alternatively, if you want to include all subpackages in com.bd:

<context:component-scan base-package="com.bd">
     <context:include-filter type="aspectj" expression="com.bd.*" />
</context:component-scan>

As a side note, if you're using Spring 3.1 or later, you can take advantage of the @ComponentScan annotation, so that you don't have to use any xml configuration regarding component-scan. Use it in conjunction with @Configuration.

@Controller
@RequestMapping("/Article/GererArticle")
@Configuration
@ComponentScan("com.bd.service") // No need to include component-scan in xml
public class ArticleControleur {

    @Autowired
    ArticleService articleService;
    ...
}

You might find this Spring in depth section on Autowiring useful.

Java Currency Number format

NumberFormat currency = NumberFormat.getCurrencyInstance();
String myCurrency = currency.format(123.5);
System.out.println(myCurrency);

output:

$123.50

If you want to change the currency,

NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.CHINA);
String myCurrency = currency.format(123.5);
System.out.println(myCurrency);

output:

?123.50

What is the definition of "interface" in object oriented programming

Consider the following situation:

You are in the middle of a large, empty room, when a zombie suddenly attacks you.

You have no weapon.

Luckily, a fellow living human is standing in the doorway of the room.

"Quick!" you shout at him. "Throw me something I can hit the zombie with!"

Now consider:
You didn't specify (nor do you care) exactly what your friend will choose to toss;
...But it doesn't matter, as long as:

  • It's something that can be tossed (He can't toss you the sofa)

  • It's something that you can grab hold of (Let's hope he didn't toss a shuriken)

  • It's something you can use to bash the zombie's brains out (That rules out pillows and such)

It doesn't matter whether you get a baseball bat or a hammer -
as long as it implements your three conditions, you're good.

To sum it up:

When you write an interface, you're basically saying: "I need something that..."

Use Conditional formatting to turn a cell Red, yellow or green depending on 3 values in another sheet

  1. Highlight the range in question.
  2. On the Home tab, in the Styles Group, Click "Conditional Formatting".
  3. Click "Highlight cell rules"

For the first rule,

Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.

For the second,

Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.

For the third,

Same as the second, except your formula is =".8*" rather than .9.

how to sort an ArrayList in ascending order using Collections and Comparator

Sort By Value

  public Map sortByValue(Map map, final boolean ascending) {
            Map result = new LinkedHashMap();
            try {
                List list = new LinkedList(map.entrySet());

                Collections.sort(list, new Comparator() {
                    @Override
                    public int compare(Object object1, Object object2) {
                        if (ascending)
                            return ((Comparable) ((Map.Entry) (object1)).getValue())
                                    .compareTo(((Map.Entry) (object2)).getValue());
                        else
                            return ((Comparable) ((Map.Entry) (object2)).getValue())
                                    .compareTo(((Map.Entry) (object1)).getValue());

                    }
                });

                for (Iterator it = list.iterator(); it.hasNext();) {
                    Map.Entry entry = (Map.Entry) it.next();
                    result.put(entry.getKey(), entry.getValue());
                }

            } catch (Exception e) {
                Log.e("Error", e.getMessage());
            }

            return result;
        }

Javascript Image Resize

Instead of modifying the height and width attributes of the image, try modifying the CSS height and width.

myimg = document.getElementById('myimg');
myimg.style.height = "50px";
myimg.style.width = "50px";

One common "gotcha" is that the height and width styles are strings that include a unit, like "px" in the example above.

Edit - I think that setting the height and width directly instead of using style.height and style.width should work. It would also have the advantage of already having the original dimensions. Can you post a bit of your code? Are you sure you're in standards mode instead of quirks mode?

This should work:

myimg = document.getElementById('myimg');
myimg.height = myimg.height * 2;
myimg.width = myimg.width * 2;

How do I perform HTML decoding/encoding using Python/Django?

Below is a python function that uses module htmlentitydefs. It is not perfect. The version of htmlentitydefs that I have is incomplete and it assumes that all entities decode to one codepoint which is wrong for entities like &NotEqualTilde;:

http://www.w3.org/TR/html5/named-character-references.html

NotEqualTilde;     U+02242 U+00338    ??

With those caveats though, here's the code.

def decodeHtmlText(html):
    """
    Given a string of HTML that would parse to a single text node,
    return the text value of that node.
    """
    # Fast path for common case.
    if html.find("&") < 0: return html
    return re.sub(
        '&(?:#(?:x([0-9A-Fa-f]+)|([0-9]+))|([a-zA-Z0-9]+));',
        _decode_html_entity,
        html)

def _decode_html_entity(match):
    """
    Regex replacer that expects hex digits in group 1, or
    decimal digits in group 2, or a named entity in group 3.
    """
    hex_digits = match.group(1)  # '&#10;' -> unichr(10)
    if hex_digits: return unichr(int(hex_digits, 16))
    decimal_digits = match.group(2)  # '&#x10;' -> unichr(0x10)
    if decimal_digits: return unichr(int(decimal_digits, 10))
    name = match.group(3)  # name is 'lt' when '&lt;' was matched.
    if name:
        decoding = (htmlentitydefs.name2codepoint.get(name)
            # Treat &GT; like &gt;.
            # This is wrong for &Gt; and &Lt; which HTML5 adopted from MathML.
            # If htmlentitydefs included mappings for those entities,
            # then this code will magically work.
            or htmlentitydefs.name2codepoint.get(name.lower()))
        if decoding is not None: return unichr(decoding)
    return match.group(0)  # Treat "&noSuchEntity;" as "&noSuchEntity;"

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

I had the same problem and I solved it with the following steps

  1. Help > Install New Software...
  2. Select "Eclipse Web Tools Platform Repository (http://download.eclipse.org/webtools/updates)" from the "Work with" drop-down.
  3. Select "Web Tools Platform (WTP)" and "Project Provided Components".

Complete all the installation steps and restart Eclipse. You'll see a bunch of servers when you try to add a server runtime environment.

Removing empty lines in Notepad++

There is a plugin that adds a menu entitled TextFX. This menu, which houses a dizzying array of quick text editing options, gives a person the ability to make quick coding changes. In this menu, you can find selections such as Drop Quotes, Delete Blank Lines as well as Unwrap and Rewrap Text

Do the following:

TextFX > TextFX Edit > Delete Blank Lines
TextFX > TextFX Edit > Delete Surplus Blank Lines

Could not load file or assembly 'Microsoft.ReportViewer.WebForms'

You need to reference both Microsoft.ReportViewer.WebForms and Microsoft.ReportViewer.Common and set the CopyLocal property to true. This will result in the dll's being copied to our bin directory (both are necessary).

PHP date add 5 year to current date

To add one year to todays date use the following:

$oneYearOn = date('Y-m-d',strtotime(date("Y-m-d", mktime()) . " + 365 day"));

Byte Array to Image object

Since it sounds like you already know what format the byte[] array is in (e.g. RGB, ARGB, BGR etc.) you might be able to use BufferedImage.setRGB(...), or a combination of BufferedImage.getRaster() and WritableRaster.setPixels(...) or WritableRaster.setSamples(...). Unforunately both of these methods require you transform your byte[] into one of int[], float[] or double[] depending on the image format.

How to provide animation when calling another activity in Android?

Jelly Bean adds support for this with the ActivityOptions.makeCustomAnimation() method. Of course, since it's only on Jelly Bean, it's pretty much worthless for practical purposes.

"401 Unauthorized" on a directory

You need to check the folder permissions on your server and check that the account that you are using to run your application has access to that folder.

Different class for the last element in ng-repeat

You could use limitTo filter with -1 for find the last element

Example :

<div ng-repeat="friend in friends | limitTo: -1">
    {{friend.name}}
</div>

Convert char* to string C++

char *charPtr = "test string";
cout << charPtr << endl;

string str = charPtr;
cout << str << endl;

How do you remove Subversion control for a folder?

From a Windows command line:

rmdir .svn /s /q

Numpy matrix to array

This will convert the matrix into array

A = np.ravel(M).T

Windows Forms ProgressBar: Easiest way to start/stop marquee?

This code is a part of a login form where the users wait for the authentication server to respond.

using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace LoginWithProgressBar
{
    public partial class TheForm : Form
    {
        // BackgroundWorker object deals with the long running task
        private readonly BackgroundWorker _bw = new BackgroundWorker();

        public TheForm()
        {
            InitializeComponent();

            // set MarqueeAnimationSpeed
            progressBar.MarqueeAnimationSpeed = 30;

            // set Visible false before you start long running task
            progressBar.Visible = false;

            _bw.DoWork += Login;
            _bw.RunWorkerCompleted += BwRunWorkerCompleted;
        }

        private void BwRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            // hide the progress bar when the long running process finishes
            progressBar.Hide();
        }

        private static void Login(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            // emulate long (3 seconds) running task
            Thread.Sleep(3000);
        }

        private void ButtonLoginClick(object sender, EventArgs e)
        {
            // show the progress bar when the associated event fires (here, a button click)
            progressBar.Show();

            // start the long running task async
            _bw.RunWorkerAsync();
        }
    }
}    

Laravel 5 – Remove Public from URL

Just create .htaccess file at root and add these lines to it

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

That's it!

The above code works on the root public_html folder. Having said that your core laravel file should be inside the public_html folder, if your directory looks like public_html/laravelapp/public and if you put the above code inside laravelapp it won't work. Therefore you must copy all your core files into public_html and put the .htaccess file there .

If you want to keep the code in a subdirectory then you can create a subdomain then this code will work for that also.

Python dictionary get multiple values

You can use At from pydash:

from pydash import at
dict = {'a': 1, 'b': 2, 'c': 3}
list = at(dict, 'a', 'b')
list == [1, 2]

How to remove elements/nodes from angular.js array

My solution to this (which hasn't caused any performance issues):

  1. Extend the array object with a method remove (i'm sure you will need it more than just one time):
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

I'm using it in all of my projects and credits go to John Resig John Resig's Site

  1. Using forEach and a basic check:
$scope.items.forEach(function(element, index, array){
          if(element.name === 'ted'){
              $scope.items.remove(index);
          }
        });

At the end the $digest will be fired in angularjs and my UI is updated immediately without any recognizable lag.

How to check if a column is empty or null using SQL query select statement?

If you want blanks and NULLS to be displayed as other text, such as "Uncategorized" you can simply say...

SELECT ISNULL(NULLIF([PropertyValue], ''), 'Uncategorized') FROM UserProfile

The above answers the main question very well. This answer is an extension of that and is of value to readers.

How do I remove all non-ASCII characters with regex and Notepad++?

In addition to the answer by ProGM, in case you see characters in boxes like NUL or ACK and want to get rid of them, those are ASCII control characters (0 to 31), you can find them with the following expression and remove them:

[\x00-\x1F]+

In order to remove all non-ASCII AND ASCII control characters, you should remove all characters matching this regex:

[^\x1F-\x7F]+

How to test my servlet using JUnit

Another approach would be to create an embedded server to "host" your servlet, allowing you to write calls against it with libraries meant to make calls to actual servers (the usefulness of this approach somewhat depends on how easily you can make "legitimate" programatic calls to the server - I was testing a JMS (Java Messaging Service) access point, for which clients abound).

There are a couple of different routes you can go - the usual two are tomcat and jetty.

Warning: something to be mindful of when choosing the server to embed is the version of servlet-api you are using (the library which provides classes like HttpServletRequest). If you are using 2.5, I found Jetty 6.x to work well (which is the example I'll give below). If you're using servlet-api 3.0, the tomcat-7 embedded stuff seems to be a good option, however I had to abandon my attempt to use it, as the application I was testing used servlet-api 2.5. Trying to mix the two will result in NoSuchMethod and other such exceptions when attempting to configure or start the server.

You can set up such a server like this (Jetty 6.1.26, servlet-api 2.5):

public void startServer(int port, Servlet yourServletInstance){
    Server server = new Server(port);
    Context root = new Context(server, "/", Context.SESSIONS);

    root.addServlet(new ServletHolder(yourServletInstance), "/servlet/context/path");

    //If you need the servlet context for anything, such as spring wiring, you coudl get it like this
    //ServletContext servletContext = root.getServletContext();

    server.start();
}

Calling multiple JavaScript functions on a button click

And of course you can never call the two functions at the same time. Not any one in the world except you are working on two processors simultaneously.

The best way is to call a JavaScript parent function and in that, specify all the sequence of function you want to call. For example,

function ShowDiv1() {
    document.getElementById("ReportDiv").style.display = 'block';
    return false;
}

function validateView()
{
    if (document.getElementById("ctl00_ContentPlaceHolder1_DLCategory").selectedIndex == 0) {
        document.getElementById("ctl00_ContentPlaceHolder1_ErrorMsg").innerHTML = "Please Select Your Category";
        document.getElementById("ctl00_ContentPlaceHolder1_DLCategory").focus();
        return false;
    }
    if (document.getElementById("ctl00_ContentPlaceHolder1_DLEmpName").selectedIndex == 0) {
        document.getElementById("ctl00_ContentPlaceHolder1_ErrorMsg").innerHTML = "Please Select Your Employee Name";
        document.getElementById("ctl00_ContentPlaceHolder1_DLEmpName").focus();
        return false;
    }
    ShowDiv1();
    return true;
}

What's the difference between a 302 and a 307 redirect?

302 is temporary redirect, which is generated by the server whereas 307 is internal redirect response generated by the browser. Internal redirect means that redirect is done automatically by browser internally, basically the browser alters the entered url from http to https in get request by itself before making the request so request for unsecured connection is never made to the internet. Whether browser will alter the url to https or not depends upon the hsts preload list that comes preinstalled with the browser. You can also add any site which support https to the list by entering the domain in the hsts preload list of your own browser which is at chrome://net-internals/#hsts.One more thing website domains can be added by their owners to preload list by filling up the form at https://hstspreload.org/ so that it comes preinstalled in browsers for every user even though I mention you can do particularly for yourself also.


Let me explain with an example:
I made a get request to http://www.pentesteracademy.com which supports only https and I don't have that domain in my hsts preload list on my browser as site owner has not registered for it to come with preinstalled hsts preload list. request and response headers
GET request for unsecure version of the site is redirected to secure version(see http header named location for that in response in above image).
Now I add the site to my own browser preload list by adding its domain in Add hsts domain form at chrome://net-internals/#hsts, which modifies my personal preload list on my chrome browser.Be sure to select include subdomains for STS option there.
Let's see the request and response for the same website now after adding it to hsts preload list.
request and response headers
you can see the internal redirect 307 there in response headers, actually this response is generated by your browser not by server.
Also HSTS preload list can help prevent users reach the unsecure version of site as 302 redirect are prone to mitm attacks.
Hope I somewhat helped you understand more about redirects.

ERROR! MySQL manager or server PID file could not be found! QNAP

screenshot

If you're using MySQL Workbench, the mysql.server stop/restart/start will not work.

You will need to login into the workbench and then click "shutdown server". See image attached.

How to rebuild docker container in docker-compose.yml?

Maybe these steps are not quite correct, but I do like this:

stop docker compose: $ docker-compose down

remove the container: $ docker system prune -a

start docker compose: $ docker-compose up -d

How to upload multiple files using PHP, jQuery and AJAX

My solution

  • Assuming that form id = "my_form_id"
  • It detects the form method and form action from HTML

jQuery code

$('#my_form_id').on('submit', function(e) {
    e.preventDefault();
    var formData = new FormData($(this)[0]);
    var msg_error = 'An error has occured. Please try again later.';
    var msg_timeout = 'The server is not responding';
    var message = '';
    var form = $('#my_form_id');
    $.ajax({
        data: formData,
        async: false,
        cache: false,
        processData: false,
        contentType: false,
        url: form.attr('action'),
        type: form.attr('method'),
        error: function(xhr, status, error) {
            if (status==="timeout") {
                alert(msg_timeout);
            } else {
                alert(msg_error);
            }
        },
        success: function(response) {
            alert(response);
        },
        timeout: 7000
    });
});

How do I increase the contrast of an image in Python OpenCV

Best explanation for X = aY + b (in fact it f(x) = ax + b)) is provided at https://math.stackexchange.com/a/906280/357701

A Simpler one by just adjusting lightness/luma/brightness for contrast as is below:

import cv2

img = cv2.imread('test.jpg')
cv2.imshow('test', img)
cv2.waitKey(1000)
imghsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)


imghsv[:,:,2] = [[max(pixel - 25, 0) if pixel < 190 else min(pixel + 25, 255) for pixel in row] for row in imghsv[:,:,2]]
cv2.imshow('contrast', cv2.cvtColor(imghsv, cv2.COLOR_HSV2BGR))
cv2.waitKey(1000)
raw_input()

Python: importing a sub-package or sub-module

The reason #2 fails is because sys.modules['module'] does not exist (the import routine has its own scope, and cannot see the module local name), and there's no module module or package on-disk. Note that you can separate multiple imported names by commas.

from package.subpackage.module import attribute1, attribute2, attribute3

Also:

from package.subpackage import module
print module.attribute1

C99 stdint.h header and MS Visual Studio

Boost contains cstdint.hpp header file with the types you are looking for: http://www.boost.org/doc/libs/1_36_0/boost/cstdint.hpp

Correct way to set Bearer token with CURL

If you are working with a private token instead (like Gitlab API), you should replace:

$authorization = "Authorization: Bearer 080042cad6356ad5dc0a720c18b53b8e53d4c274"

with:

$authorization = "PRIVATE-TOKEN 080042cad6356ad5dc0a720c18b53b8e53d4c274";

Python: Importing urllib.quote

Use six:

from six.moves.urllib.parse import quote

six will simplify compatibility problems between Python 2 and Python 3, such as different import paths.

how to re-format datetime string in php?

why not use date() just like below,try this

$t = strtotime('20130409163705');
echo date('d/m/y H:i:s',$t);

and will be output

09/04/13 16:37:05

Visual Studio SignTool.exe Not Found

Windows Software Development Kit (SDK) for Windows 8.1

http://go.microsoft.com/fwlink/p/?LinkId=323507

Right click on Project, select properties and Un-Check the sign on option in teh project save and re-built.

This has fixed issue for me.

Elegant way to check for missing packages and install them?

The coming version of RStudio (1.2), already available as a preview, will include a feature to detect missing packages in library() and require() calls, and prompt the user to install them:

Detect missing R packages

Many R scripts open with calls to library() and require() to load the packages they need in order to execute. If you open an R script that references packages that you don’t have installed, RStudio will now offer to install all the needed packages in a single click. No more typing install.packages() repeatedly until the errors go away!
https://blog.rstudio.com/2018/11/19/rstudio-1-2-preview-the-little-things/

This seems to address the original concern of OP particularly well:

Many of them are novice/intermediate R users and don't realize that they have to install packages they don't already have.

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

This error seems to occur mostly if there is a space before or after your secret key

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

In my case, after a long search I found that PyCharm in your Django settings (Settings > Languages & Frameworks > Django) had the configuration file field undefined. You should make this field point to your project's settings file. Then, you must open the Run / Debug settings and remove the environment variable DJANGO_SETTINGS_MODULE = existing path.

This happens because the Django plugin in PyCharm forces the configuration of the framework. So there is no point in configuring any os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings')

How do I run a command on an already existing Docker container?

Your container will exit as the command you gave it will end. Use the following options to keep it live:

  • -i Keep STDIN open even if not attached.
  • -t Allocate a pseudo-TTY.

So your new run command is:

docker run -it -d shykes/pybuilder bin/bash

If you would like to attach to an already running container:

docker exec -it CONTAINER_ID /bin/bash

In these examples /bin/bash is used as the command.

Fastest way to convert Image to Byte array

I'm not sure if you're going to get any huge gains for reasons Jon Skeet pointed out. However, you could try and benchmark the TypeConvert.ConvertTo method and see how it compares to using your current method.

ImageConverter converter = new ImageConverter();
byte[] imgArray = (byte[])converter.ConvertTo(imageIn, typeof(byte[]));

Git with SSH on Windows

If Git for windows is installed, run Git Bash shell:

  bash

You can run ssh from within Bash shell (Bash is aware of the path of ssh)

To know the exact path of ssh, run "where" command in Bash shell:

  $ where ssh

you get:

  c:\Program Files\Git\usr\bin\ssh.exe

Which loop is faster, while or for?

Some optimizing compilers will be able to do better loop unrolling with a for loop, but odds are that if you're doing something that can be unrolled, a compiler smart enough to unroll it is probably also smart enough to interpret the loop condition of your while loop as something it can unroll as well.

jQuery find and replace string

var string ='my string'
var new_string = string.replace('string','new string');
alert(string);
alert(new_string);

Extension methods must be defined in a non-generic static class

Try changing

public class LinqHelper

to

 public static class LinqHelper

Jenkins returned status code 128 with github

I changed the permission of my .ssh/id_rsa (private key) to 604. chmod 700 id_rsa

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

I am not sure this will help but I resolved the issue by importing mongoose like below and implementing it as below

const mongoose = require('mongoose')

_id: new mongoose.Types.ObjectId(),

How to getText on an input in protractor

You can try something like this

var access_token = driver.findElement(webdriver.By.name("AccToken"))

        var access_token_getTextFunction = function() {
            access_token.getText().then(function(value) {
                console.log(value);
                return value;
            });
        }

Than you can call this function where you want to get the value..

Using Keras & Tensorflow with AMD GPU

Tensorflow 1.3 has been supported on AMD ROCm stack:

A pre-built docker image has also been posted publicly:

Take a list of numbers and return the average

You want to iterate through the list, sum all the numbers, and then divide the sum by the number of elements in the list. You can use a for loop to accomplish this.

average = 0
sum = 0    
for n in numbers:
    sum = sum + n
average = sum / len(numbers)

The for loop looks at each element in the list, and then adds it to the current sum. You then divide by the length of the list (or the number of elements in the list) to find the average.

I would recommend googling a python reference to find out how to use common programming concepts like loops and conditionals so that you feel comfortable when starting out. There are lots of great resources online that you could look up.

Good luck!

Create patch or diff file from git repository and apply it to another different git repository

you can apply two commands

  1. git diff --patch > mypatch.patch // to generate the patch
  2. git apply mypatch.patch // to apply the patch

How to remove trailing whitespaces with sed?

You can use the in place option -i of sed for Linux and Unix:

sed -i 's/[ \t]*$//' "$1"

Be aware the expression will delete trailing t's on OSX (you can use gsed to avoid this problem). It may delete them on BSD too.

If you don't have gsed, here is the correct (but hard-to-read) sed syntax on OSX:

sed -i '' -E 's/[ '$'\t'']+$//' "$1"

Three single-quoted strings ultimately become concatenated into a single argument/expression. There is no concatenation operator in bash, you just place strings one after the other with no space in between.

The $'\t' resolves as a literal tab-character in bash (using ANSI-C quoting), so the tab is correctly concatenated into the expression.

Check file size before upload

Client side Upload Canceling

On modern browsers (FF >= 3.6, Chrome >= 19.0, Opera >= 12.0, and buggy on Safari), you can use the HTML5 File API. When the value of a file input changes, this API will allow you to check whether the file size is within your requirements. Of course, this, as well as MAX_FILE_SIZE, can be tampered with so always use server side validation.

<form method="post" enctype="multipart/form-data" action="upload.php">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" value="Submit" />
</form>

<script>
document.forms[0].addEventListener('submit', function( evt ) {
    var file = document.getElementById('file').files[0];

    if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
        //Submit form        
    } else {
        //Prevent default and display error
        evt.preventDefault();
    }
}, false);
</script>

Server Side Upload Canceling

On the server side, it is impossible to stop an upload from happening from PHP because once PHP has been invoked the upload has already completed. If you are trying to save bandwidth, you can deny uploads from the server side with the ini setting upload_max_filesize. The trouble with this is this applies to all uploads so you'll have to pick something liberal that works for all of your uploads. The use of MAX_FILE_SIZE has been discussed in other answers. I suggest reading the manual on it. Do know that it, along with anything else client side (including the javascript check), can be tampered with so you should always have server side (PHP) validation.

PHP Validation

On the server side you should validate that the file is within the size restrictions (because everything up to this point except for the INI setting could be tampered with). You can use the $_FILES array to find out the upload size. (Docs on the contents of $_FILES can be found below the MAX_FILE_SIZE docs)

upload.php

<?php
if(isset($_FILES['file'])) {
    if($_FILES['file']['size'] > 10485760) { //10 MB (size is also in bytes)
        // File too big
    } else {
        // File within size restrictions
    }
}

Relative paths based on file location instead of current working directory

Just one line will be OK.

cat "`dirname $0`"/../some.txt

How to write a unit test for a Spring Boot Controller endpoint

Let assume i am having a RestController with GET/POST/PUT/DELETE operations and i have to write unit test using spring boot.I will just share code of RestController class and respective unit test.Wont be sharing any other related code to the controller ,can have assumption on that.

@RestController
@RequestMapping(value = “/myapi/myApp” , produces = {"application/json"})
public class AppController {


    @Autowired
    private AppService service;

    @GetMapping
    public MyAppResponse<AppEntity> get() throws Exception {

        MyAppResponse<AppEntity> response = new MyAppResponse<AppEntity>();
        service.getApp().stream().forEach(x -> response.addData(x));    
        return response;
    }


    @PostMapping
    public ResponseEntity<HttpStatus> create(@RequestBody AppRequest request) throws Exception {
        //Validation code       
        service.createApp(request);

        return ResponseEntity.ok(HttpStatus.OK);
    }

    @PutMapping
    public ResponseEntity<HttpStatus> update(@RequestBody IDMSRequest request) throws Exception {

        //Validation code
        service.updateApp(request);

        return ResponseEntity.ok(HttpStatus.OK);
    }

    @DeleteMapping
    public ResponseEntity<HttpStatus> delete(@RequestBody AppRequest request) throws Exception {

        //Validation        
        service.deleteApp(request.id);

        return ResponseEntity.ok(HttpStatus.OK);
    }

}

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Main.class)
@WebAppConfiguration
public abstract class BaseTest {
   protected MockMvc mvc;
   @Autowired
   WebApplicationContext webApplicationContext;

   protected void setUp() {
      mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
   }
   protected String mapToJson(Object obj) throws JsonProcessingException {
      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.writeValueAsString(obj);
   }
   protected <T> T mapFromJson(String json, Class<T> clazz)
      throws JsonParseException, JsonMappingException, IOException {

      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.readValue(json, clazz);
   }
}

public class AppControllerTest extends BaseTest {

    @MockBean
    private IIdmsService service;

    private static final String URI = "/myapi/myApp";


   @Override
   @Before
   public void setUp() {
      super.setUp();
   }

   @Test
   public void testGet() throws Exception {
       AppEntity entity = new AppEntity();
      List<AppEntity> dataList = new ArrayList<AppEntity>();
      AppResponse<AppEntity> dataResponse = new AppResponse<AppEntity>();
      entity.setId(1);
      entity.setCreated_at("2020-02-21 17:01:38.717863");
      entity.setCreated_by(“Abhinav Kr”);
      entity.setModified_at("2020-02-24 17:01:38.717863");
      entity.setModified_by(“Jyoti”);
            dataList.add(entity);

      dataResponse.setData(dataList);

      Mockito.when(service.getApp()).thenReturn(dataList);

      RequestBuilder requestBuilder =  MockMvcRequestBuilders.get(URI)
                 .accept(MediaType.APPLICATION_JSON);

        MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
        MockHttpServletResponse response = mvcResult.getResponse();

        String expectedJson = this.mapToJson(dataResponse);
        String outputInJson = mvcResult.getResponse().getContentAsString();

        assertEquals(HttpStatus.OK.value(), response.getStatus());
        assertEquals(expectedJson, outputInJson);
   }

   @Test
   public void testCreate() throws Exception {

       AppRequest request = new AppRequest();
       request.createdBy = 1;
       request.AppFullName = “My App”;
       request.appTimezone = “India”;

       String inputInJson = this.mapToJson(request);
       Mockito.doNothing().when(service).createApp(Mockito.any(AppRequest.class));
       service.createApp(request);
       Mockito.verify(service, Mockito.times(1)).createApp(request);

       RequestBuilder requestBuilder =  MockMvcRequestBuilders.post(URI)
                                                             .accept(MediaType.APPLICATION_JSON).content(inputInJson)
                                                             .contentType(MediaType.APPLICATION_JSON);

       MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
       MockHttpServletResponse response = mvcResult.getResponse();
       assertEquals(HttpStatus.OK.value(), response.getStatus());

   }

   @Test
   public void testUpdate() throws Exception {

       AppRequest request = new AppRequest();
       request.id = 1;
       request.modifiedBy = 1;
        request.AppFullName = “My App”;
       request.appTimezone = “Bharat”;

       String inputInJson = this.mapToJson(request);
       Mockito.doNothing().when(service).updateApp(Mockito.any(AppRequest.class));
       service.updateApp(request);
       Mockito.verify(service, Mockito.times(1)).updateApp(request);

       RequestBuilder requestBuilder =  MockMvcRequestBuilders.put(URI)
                                                             .accept(MediaType.APPLICATION_JSON).content(inputInJson)
                                                             .contentType(MediaType.APPLICATION_JSON);

       MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
       MockHttpServletResponse response = mvcResult.getResponse();
       assertEquals(HttpStatus.OK.value(), response.getStatus());

   }

   @Test
   public void testDelete() throws Exception {

       AppRequest request = new AppRequest();
       request.id = 1;

       String inputInJson = this.mapToJson(request);
       Mockito.doNothing().when(service).deleteApp(Mockito.any(Integer.class));
       service.deleteApp(request.id);
       Mockito.verify(service, Mockito.times(1)).deleteApp(request.id);

       RequestBuilder requestBuilder =  MockMvcRequestBuilders.delete(URI)
                                                             .accept(MediaType.APPLICATION_JSON).content(inputInJson)
                                                             .contentType(MediaType.APPLICATION_JSON);

       MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
       MockHttpServletResponse response = mvcResult.getResponse();
       assertEquals(HttpStatus.OK.value(), response.getStatus());

   }

}

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

Using GNU sed:

sed "/cdef/aline1\nline2\nline3\nline4" input.txt

If you started with:

abcd
accd
cdef
line
web

this would produce:

abcd
accd
cdef
line1
line2
line3
line4
line
web

If you want to save the changes to the file in-place, say:

sed -i "/cdef/aline1\nline2\nline3\nline4" input.txt

Dynamically display a CSV file as an HTML table on a web page

Just improved phihag's code because it runs into a infinite loop if file not exists.

<?php

$filename = "so-csv.csv";

echo "<html><body><table>\n\n";

if (file_exists($filename)) {
$f = fopen($filename, "r");
while (($line = fgetcsv($f)) !== false) {
        echo "<tr>";
        foreach ($line as $cell) {
                echo "<td>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>\n";
}
fclose($f);
}

else{ echo "<tr><td>No file exists ! </td></tr>" ;}
echo "\n</table></body></html>";
?>

CSS Classes & SubClasses

Your problem seems to be a missing space between your two classes in the CSS:

.area1.item
{
    color:red;
}

Should be

.area1 .item
{
    color:red;
}

How should I edit an Entity Framework connection string?

Follow the next steps:

  1. Open the app.config and comment on the connection string (save file)
  2. Open the edmx (go to properties, the connection string should be blank), close the edmx file again
  3. Open the app.config and uncomment the connection string (save file)
  4. Open the edmx, go to properties, you should see the connection string uptated!!

Excel VBA Run-time error '13' Type mismatch

I had the same problem as you mentioned here above and my code was doing great all day yesterday.

I kept on programming this morning and when I opened my application (my file with an Auto_Open sub), I got the Run-time error '13' Type mismatch, I went on the web to find answers, I tried a lot of things, modifications and at one point I remembered that I read somewhere about "Ghost" data that stays in a cell even if we don't see it.

My code do only data transfer from one file I opened previously to another and Sum it. My code stopped at the third SheetTab (So it went right for the 2 previous SheetTab where the same code went without stopping) with the Type mismatch message. And it does that every time at the same SheetTab when I restart my code.

So I selected the cell where it stopped, manually entered 0,00 (Because the Type mismatch comes from a Summation variables declared in a DIM as Double) and copied that cell in all the subsequent cells where the same problem occurred. It solved the problem. Never had the message again. Nothing to do with my code but the "Ghost" or data from the past. It is like when you want to use the Control+End and Excel takes you where you had data once and deleted it. Had to "Save" and close the file when you wanted to use the Control+End to make sure Excel pointed you to the right cell.

MD5 hashing in Android

In our MVC application we generate for long param

using System.Security.Cryptography;
using System.Text;
    ...
    public static string getMD5(long id)
    {
        // convert
        string result = (id ^ long.MaxValue).ToString("X") + "-ANY-TEXT";
        using (MD5 md5Hash = MD5.Create())
        {
            // Convert the input string to a byte array and compute the hash. 
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(result));

            // Create a new Stringbuilder to collect the bytes and create a string.
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
                sBuilder.Append(data[i].ToString("x2"));

            // Return the hexadecimal string. 
            result = sBuilder.ToString().ToUpper();
        }

        return result;
    }

and same in Android application (thenk helps Andranik)

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
...
public String getIdHash(long id){
    String hash = null;
    long intId = id ^ Long.MAX_VALUE;
    String md5 = String.format("%X-ANY-TEXT", intId);
    try {
        MessageDigest md = java.security.MessageDigest.getInstance("MD5");
        byte[] arr = md.digest(md5.getBytes());
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < arr.length; ++i)
            sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1,3));

        hash = sb.toString();
    } catch (NoSuchAlgorithmException e) {
        Log.e("MD5", e.getMessage());
    }

    return hash.toUpperCase();
}

Python "extend" for a dictionary

a.update(b)

Will add keys and values from b to a, overwriting if there's already a value for a key.

Setting java locale settings

I believe java gleans this from the environment variables in which it was launched, so you'll need to make sure your LANG and LC_* environment variables are set appropriately.

The locale manpage has full info on said environment variables.

Converting year and month ("yyyy-mm" format) to a date?

I think @ben-rollert's solution is a good solution.

You just have to be careful if you want to use this solution in a function inside a new package.

When developping packages, it's recommended to use the syntaxe packagename::function_name() (see http://kbroman.org/pkg_primer/pages/depends.html).

In this case, you have to use the version of as.Date() defined by the zoo library.

Here is an example :

> devtools::session_info()
Session info ----------------------------------------------------------------------------------------------------------------------------------------------------
 setting  value                       
 version  R version 3.3.1 (2016-06-21)
 system   x86_64, linux-gnu           
 ui       RStudio (1.0.35)            
 language (EN)                        
 collate  C                           
 tz       <NA>                        
 date     2016-11-09                  

Packages --------------------------------------------------------------------------------------------------------------------------------------------------------

 package  * version date       source        
 devtools   1.12.0  2016-06-24 CRAN (R 3.3.1)
 digest     0.6.10  2016-08-02 CRAN (R 3.2.3)
 memoise    1.0.0   2016-01-29 CRAN (R 3.2.3)
 withr      1.0.2   2016-06-20 CRAN (R 3.2.3)

> as.Date(zoo::as.yearmon("1989-10", "%Y-%m")) 
Error in as.Date.default(zoo::as.yearmon("1989-10", "%Y-%m")) : 
  do not know how to convert 'zoo::as.yearmon("1989-10", "%Y-%m")' to class “Date”

> zoo::as.Date(zoo::as.yearmon("1989-10", "%Y-%m"))
[1] "1989-10-01"

So if you're developping a package, the good practice is to use :

zoo::as.Date(zoo::as.yearmon("1989-10", "%Y-%m"))

Apple Mach-O Linker Error when compiling for device

Check to make sure that you don't have a specific framework search path specified. if you go to the info on the target and just remove the framework search path entries it should use the defaults for your specified deployment version.

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

Move the -h and specify that mydir is a directory

attrib /S /D /L -H mydir\*.*

In Excel, how do I extract last four letters of a ten letter string?

No need to use a macro. Supposing your first string is in A1.

=RIGHT(A1, 4)

Drag this down and you will get your four last characters.

Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()

=RIGHT(TRIMSPACES(A1), 4)

Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:

=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))

How do I write a Windows batch script to copy the newest file from a directory?

@echo off
set source="C:\test case"
set target="C:\Users\Alexander\Desktop\random folder"

FOR /F "delims=" %%I IN ('DIR %source%\*.* /A:-D /O:-D /B') DO COPY %source%\"%%I" %target% & echo %%I & GOTO :END
:END
TIMEOUT 4

My attempt to copy the newest file from a folder

just set your source and target folders and it should work

This one ignores folders, concern itself only with files

Recommed that you choose filetype in the DIR path changing *.* to *.zip for example

TIMEOUT wont work on winXP I think

How to print a debug log?

If you are on Linux:

file_put_contents('your_log_file', 'your_content');

or

error_log ('your_content', 3, 'your_log_file');

and then in console

tail -f your_log_file

This will show continuously the last line put in the file.

More elegant way of declaring multiple variables at the same time

Sounds like you're approaching your problem the wrong way to me.

Rewrite your code to use a tuple or write a class to store all of the data.

Get a list of dates between two dates

I needed a list with all months between 2 dates for statistics. The 2 dates are the start and enddate from a subscription. So the list shows all months and the amount of subscriptions per month.

MYSQL

CREATE PROCEDURE `get_amount_subscription_per_month`()
BEGIN
   -- Select the ultimate start and enddate from subscribers
   select @startdate := min(DATE_FORMAT(a.startdate, "%Y-%m-01")), 
          @enddate := max(DATE_FORMAT(a.enddate, "%Y-%m-01")) + interval 1 MONTH
   from subscription a;

   -- Tmp table with all months (dates), you can always format them with DATE_FORMAT) 
   DROP TABLE IF EXISTS tmp_months;
   create temporary table tmp_months (
      year_month date,
      PRIMARY KEY (year_month)
   );


   set @tempDate=@startdate;  #- interval 1 MONTH;

   -- Insert every month in tmp table
   WHILE @tempDate <= @enddate DO
     insert into tmp_months (year_month) values (@tempDate);
     set @tempDate = (date(@tempDate) + interval 1 MONTH);
   END WHILE;

   -- All months
   select year_month from tmp_months;

   -- If you want the amount of subscription per month else leave it out
   select mnd.year_month, sum(subscription.amount) as subscription_amount
   from tmp_months mnd
   LEFT JOIN subscription ON mnd.year_month >= DATE_FORMAT(subscription.startdate, "%Y-%m-01") and mnd.year_month <= DATE_FORMAT(subscription.enddate, "%Y-%m-01")
   GROUP BY mnd.year_month;

 END

What is thread Safe in java?

As Seth stated thread safe means that a method or class instance can be used by multiple threads at the same time without any problems occuring.

Consider the following method:

private int myInt = 0;
public int AddOne()
{
    int tmp = myInt;
    tmp = tmp + 1;
    myInt = tmp;
    return tmp;
}

Now thread A and thread B both would like to execute AddOne(). but A starts first and reads the value of myInt (0) into tmp. Now for some reason the scheduler decides to halt thread A and defer execution to thread B. Thread B now also reads the value of myInt (still 0) into it's own variable tmp. Thread B finishes the entire method, so in the end myInt = 1. And 1 is returned. Now it's Thread A's turn again. Thread A continues. And adds 1 to tmp (tmp was 0 for thread A). And then saves this value in myInt. myInt is again 1.

So in this case the method AddOne() was called two times, but because the method was not implemented in a thread safe way the value of myInt is not 2, as expected, but 1 because the second thread read the variable myInt before the first thread finished updating it.

Creating thread safe methods is very hard in non trivial cases. And there are quite a few techniques. In Java you can mark a method as synchronized, this means that only one thread can execute that method at a given time. The other threads wait in line. This makes a method thread safe, but if there is a lot of work to be done in a method, then this wastes a lot of time. Another technique is to 'mark only a small part of a method as synchronized' by creating a lock or semaphore, and locking this small part (usually called the critical section). There are even some methods that are implemented as lockless thread safe, which means that they are built in such a way that multiple threads can race through them at the same time without ever causing problems, this can be the case when a method only executes one atomic call. Atomic calls are calls that can't be interrupted and can only be done by one thread at a time.

Get Country of IP Address with PHP

I run the service at IPLocate.io, which you can hook into for free with one easy call:

<?php
$res = file_get_contents('https://www.iplocate.io/api/lookup/8.8.8.8');
$res = json_decode($res);

echo $res->country; // United States
echo $res->continent; // North America
echo $res->latitude; // 37.751
echo $res->longitude; // -97.822

var_dump($res);

The $res object will contain your geolocation fields like country, city, etc.

Check out the docs for more information.

__init__() got an unexpected keyword argument 'user'

You can't do

LivingRoom.objects.create(user=instance)

because you have an __init__ method that does NOT take user as argument.

You need something like

#signal function: if a user is created, add control livingroom to the user    
def create_control_livingroom(sender, instance, created, **kwargs):
    if created:
        my_room = LivingRoom()
        my_room.user = instance

Update

But, as bruno has already said it, Django's models.Model subclass's initializer is best left alone, or should accept *args and **kwargs matching the model's meta fields.

So, following better principles, you should probably have something like

class LivingRoom(models.Model):
    '''Living Room object'''
    user = models.OneToOneField(User)

    def __init__(self, *args, temp=65, **kwargs):
        self.temp = temp
        return super().__init__(*args, **kwargs)

Note - If you weren't using temp as a keyword argument, e.g. LivingRoom(65), then you'll have to start doing that. LivingRoom(user=instance, temp=66) or if you want the default (65), simply LivingRoom(user=instance) would do.

How can I convert a comma-separated string to an array?

Return function

var array = (new Function("return [" + str+ "];")());

Its accept string and objectstrings:

var string = "0,1";

var objectstring = '{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"}, {Name:"Dress", CatGroupName:"Clothes", Gender:"female"}, {Name:"Belt", CatGroupName:"Leather", Gender:"child"}';

var stringArray = (new Function("return [" + string+ "];")());

var objectStringArray = (new Function("return [" + objectstring+ "];")());

JSFiddle https://jsfiddle.net/7ne9L4Lj/1/

Convert a dta file to csv without Stata software

I have not tried, but if you know Perl you can use the Parse-Stata-DtaReader module to convert the file for you.

The module has a command-line tool dta2csv, which can "convert Stata 8 and Stata 10 .dta files to csv"

How to Alter a table for Identity Specification is identity SQL Server

You don't set value to default in a table. You should clear the option "Default value or Binding" first.

imagecreatefromjpeg and similar functions are not working in PHP

After installing php5-gd apache restart is needed.