Programs & Examples On #Xbel

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

Jersey Exception : SEVERE: A message body reader for Java class

for Python and Swagger example:

import requests
base_url = 'https://petstore.swagger.io/v2'
def store_order(uid):
    api_url = f"{base_url}/store/order"
    api_data = {
        'id':uid,
        "petId": 0,
        "quantity": 0,
        "shipDate": "2020-04-08T07:56:05.832Z",
        "status": "placed",
        "complete": "true"
        }
    # is a kind of magic..
    r = requests.post(api_url, json=api_data)
    return r
print(store_order(0).content)    

Most important string with MIME type: r = requests.post(api_url, json=api_data)

Viewing full output of PS command

Passing it a few ws will ignore the display width.

How do I instantiate a JAXBElement<String> object?

Here is how I do it. You will need to get the namespace URL and the element name from your generated code.

new JAXBElement(new QName("http://www.novell.com/role/service","userDN"),
                new String("").getClass(),testDN);

"No such file or directory" but it exists

This error may also occur if trying to run a script and the shebang is misspelled. Make sure it reads #!/bin/sh, #!/bin/bash, or whichever interpreter you're using.

Project with path ':mypath' could not be found in root project 'myproject'

Remove all the texts in android/settings.gradle and paste the below code

rootProject.name = '****Your Project Name****'
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'

This issue will usually happen when you migrate from react-native < 0.60 to react-native >0.60. If you create a new project in react-native >0.60 you will see the same settings as above mentioned

PHP: Get the key from an array in a foreach loop

you need nested foreach loops

foreach($samplearr as $key => $item){
   echo $key;
    foreach($item as $detail){
       echo $detail['value1'] . " " . $detail['value2']
     }
 }

Capturing window.onbeforeunload

The reason why nothing happens when you use 'alert()' is probably as explained by MDN: "The HTML specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event."

But there is also another reason why you might not see the warning at all, whether it calls alert() or not, also explained on the same site:

"... browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with"

That is what I see with current versions of Chrome and FireFox. I open my page which has beforeunload handler set up with this code:

window.addEventListener
('beforeunload'
, function (evt)
  { evt.preventDefault();
    evt.returnValue = 'Hello';
    return "hello 2222"
  }
 );

If I do not click on my page, in other words "do not interact" with it, and click the close-button, the window closes without warning.

But if I click on the page before trying to close the window or tab, I DO get the warning, and can cancel the closing of the window.

So these browsers are "smart" (and user-friendly) in that if you have not done anything with the page, it can not have any user-input that would need saving, so they will close the window without any warnings.

Consider that without this feature any site might selfishly ask you: "Do you really want to leave our site?", when you have already clearly indicated your intention to leave their site.

SEE: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

How to set a Javascript object values dynamically?

myObj.name=value

or

myObj['name']=value     (Quotes are required)

Both of these are interchangeable.

Edit: I'm guessing you meant myObj[prop] = value, instead of myObj[name] = value. Second syntax works fine: http://jsfiddle.net/waitinforatrain/dNjvb/1/

Xcode 4: create IPA file instead of .xcarchive

Same issue. I solved setting the "skip install" flag to YES for each external projects, leaving the other targets of the main project unchanged.

I also had to go to "Edit scheme…", choose the "Archiving" panel and set the correct build setting for my ad-hoc purpose.

Then a simple Product -> Archive -> Share made the expected job.

How to convert a color integer to a hex String in Android?

With this method Integer.toHexString, you can have an Unknown color exception for some colors when using Color.parseColor.

And with this method String.format("#%06X", (0xFFFFFF & intColor)), you'll lose alpha value.

So I recommend this method:

public static String ColorToHex(int color) {
        int alpha = android.graphics.Color.alpha(color);
        int blue = android.graphics.Color.blue(color);
        int green = android.graphics.Color.green(color);
        int red = android.graphics.Color.red(color);

        String alphaHex = To00Hex(alpha);
        String blueHex = To00Hex(blue);
        String greenHex = To00Hex(green);
        String redHex = To00Hex(red);

        // hexBinary value: aabbggrr
        StringBuilder str = new StringBuilder("#");
        str.append(alphaHex);
        str.append(blueHex);
        str.append(greenHex);
        str.append(redHex );

        return str.toString();
    }

    private static String To00Hex(int value) {
        String hex = "00".concat(Integer.toHexString(value));
        return hex.substring(hex.length()-2, hex.length());
    }

Disable Required validation attribute under certain circumstances

You can remove all validation off a property with the following in your controller action.

ModelState.Remove<ViewModel>(x => x.SomeProperty);

@Ian's comment regarding MVC5

The following is still possible

ModelState.Remove("PropertyNameInModel");

Bit annoying that you lose the static typing with the updated API. You could achieve something similar to the old way by creating an instance of HTML helper and using NameExtensions Methods.

Could not establish secure channel for SSL/TLS with authority '*'

Problem

I was running into the same error message while calling a third party API from my ASP.NET Core MVC project.

Could not establish secure channel for SSL/TLS with authority '{base_url_of_WS}'.

Solution

It turned out that the third party API's server required TLS 1.2. To resolve this issue, I added the following line of code to my controller's constructor:

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

E11000 duplicate key error index in mongodb mongoose

Change the collection name if it already exists in the database, it will show an error. And if you given any property as unique the same error will occur.

Using prepared statements with JDBCTemplate

class Main {
    public static void main(String args[]) throws Exception {
        ApplicationContext ac = new
          ClassPathXmlApplicationContext("context.xml", Main.class);
        DataSource dataSource = (DataSource) ac.getBean("dataSource");
// DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource");

        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

        String prasobhName = 
        jdbcTemplate.query(
           "select first_name from customer where last_name like ?",
            new PreparedStatementSetter() {
              public void setValues(PreparedStatement preparedStatement) throws
                SQLException {
                  preparedStatement.setString(1, "nair%");
              }
            }, 
            new ResultSetExtractor<Long>() {
              public Long extractData(ResultSet resultSet) throws SQLException,
                DataAccessException {
                  if (resultSet.next()) {
                      return resultSet.getLong(1);
                  }
                  return null;
              }
            }
        );
        System.out.println(machaceksName);
    }
}

How to make a checkbox checked with jQuery?

$('#test').attr('checked','checked');

$('#test').removeAttr('checked');

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

function convert(str) {
    var date = new Date(str),
        mnth = ("0" + (date.getMonth()+1)).slice(-2),
        day  = ("0" + date.getDate()).slice(-2);
        hours  = ("0" + date.getHours()).slice(-2);
        minutes = ("0" + date.getMinutes()).slice(-2);
    return [ date.getFullYear(), mnth, day, hours, minutes ].join("-");
}

I used this efficiently in angular because i was losing two hours on updating a $scope.STARTevent, and $scope.ENDevent, IN console.log was fine, however saving to mYsql dropped two hours.

var whatSTART = $scope.STARTevent;
whatSTART = convert(whatever);

THIS WILL ALSO work for END

Why can't C# interfaces contain fields?

For this you can have a Car base class that implement the year field, and all other implementations can inheritance from it.

No module named setuptools

For python3 is:

sudo apt-get install -y python3-setuptools

How do you specify the Java compiler version in a pom.xml file?

Generally you don't want to value only the source version (javac -source 1.8 for example) but you want to value both the source and the target version (javac -source 1.8 -target 1.8 for example).
Note that from Java 9, you have a way to convey both information and in a more robust way for cross-compilation compatibility (javac -release 9).
Maven that wraps the javac command provides multiple ways to convey all these JVM standard options.

How to specify the JDK version?

Using maven-compiler-plugin or maven.compiler.source/maven.compiler.target properties to specify the source and the target are equivalent.

<plugins>
    <plugin>    
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>
</plugins>

and

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

are equivalent according to the Maven documentation of the compiler plugin since the <source> and the <target> elements in the compiler configuration use the properties maven.compiler.source and maven.compiler.target if they are defined.

source

The -source argument for the Java compiler.
Default value is: 1.6.
User property is: maven.compiler.source.

target

The -target argument for the Java compiler.
Default value is: 1.6.
User property is: maven.compiler.target.

About the default values for source and target, note that since the 3.8.0 of the maven compiler, the default values have changed from 1.5 to 1.6.

<release> tag — new way to specify Java version in maven-compiler-plugin 3.6

You can use the release argument :

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
        <release>9</release>
    </configuration>
</plugin>

You could also declare just the user property maven.compiler.release:

<properties>
    <maven.compiler.release>9</maven.compiler.release>
</properties>

But at this time the last one will not be enough as the maven-compiler-plugin default version you use doesn't rely on a recent enough version.

The Maven release argument conveys release to the Java compiler to access the JVM standard option newly added to Java 9, JEP 247: Compile for Older Platform Versions.

Compiles against the public, supported and documented API for a specific VM version.

This way provides a standard way to specify the same version for the source, the target and the bootstrap JVM options.
Note that specifying the bootstrap is a good practice for cross compilations and it will not hurt if you don't make cross compilations either.

Which is the best way to specify the JDK version?

Java 8 and below

Neither maven.compiler.source/maven.compiler.target properties or using the maven-compiler-plugin is better. It changes nothing in the facts since finally the two ways rely on the same properties and the same mechanism : the maven core compiler plugin.

Well, if you don't need to specify other properties or behavior than Java versions in the compiler plugin, using this way makes more sense as this is more concise:

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

Java 9 and later

The release argument (third point) is a way to strongly consider if you want to use the same version for the source and the target.

How to make a <div> appear in front of regular text/tables

It moves table down because there is no much space, try to decrease/increase width of certain elements so that it finds some space and does not push the table down. Also you may want to use absolute positioning to position the div at exactly the place you want, for example:

<style>
 #div_id
 {
   position:absolute;
   top:100px; /* set top value */
   left:100px; /* set left value */
   width:100px;  /* set width value */
 }
</style>

If you want to appear it over something, you also need to give it z-index, so it might look like this:

<style>
 #div_id
 {
   position:absolute;
   z-index:999;
   top:100px; /* set top value */
   left:100px; /* set left value */
   width:100px;  /* set width value */
 }
</style>

How do I get the max ID with Linq to Entity?

try this

int intIdt = db.Users.Max(u => u.UserId);

Update:

If no record then generate exception using above code try this

int? intIdt = db.Users.Max(u => (int?)u.UserId);

Pinging servers in Python

Make Sure pyping is installed or install it pip install pyping

#!/usr/bin/python
import pyping

response = pyping.ping('Your IP')

if response.ret_code == 0:
    print("reachable")
else:
    print("unreachable")

Ruby convert Object to Hash

To do this without Rails, a clean way is to store attributes on a constant.

class Gift
  ATTRIBUTES = [:name, :price]
  attr_accessor(*ATTRIBUTES)
end

And then, to convert an instance of Gift to a Hash, you can:

class Gift
  ...
  def to_h
    ATTRIBUTES.each_with_object({}) do |attribute_name, memo|
      memo[attribute_name] = send(attribute_name)
    end
  end
end

This is a good way to do this because it will only include what you define on attr_accessor, and not every instance variable.

class Gift
  ATTRIBUTES = [:name, :price]
  attr_accessor(*ATTRIBUTES)

  def create_random_instance_variable
    @xyz = 123
  end

  def to_h
    ATTRIBUTES.each_with_object({}) do |attribute_name, memo|
      memo[attribute_name] = send(attribute_name)
    end
  end
end

g = Gift.new
g.name = "Foo"
g.price = 5.25
g.to_h
#=> {:name=>"Foo", :price=>5.25}

g.create_random_instance_variable
g.to_h
#=> {:name=>"Foo", :price=>5.25}

How to get the selected date value while using Bootstrap Datepicker?

this works with me for inline datepicker (and the other)

$('#startdate').data('datepicker').date

How to recognize swipe in all 4 directions

From the storyboard:

  1. Add four swipe gesture recognizers to your view.
  2. Set each one with the target direction from the attribute inspector. You can select right, left, up or down
  3. One by one, select the swipe gesture recognizer, control + drag to your view controller. Insert the name (let us say leftGesture, rightGesture, upGesture and downGesture), change the connection to: Action and type to: UISwipeGestureRecognizer

From your viewController:

@IBAction func rightGesture(sender: UISwipeGestureRecognizer) {
    print("Right")
}
@IBAction func leftGesture(sender: UISwipeGestureRecognizer) {
    print("Left")
}
@IBAction func upGesture(sender: UISwipeGestureRecognizer) {
    print("Up")
}

@IBAction func downGesture(sender: UISwipeGestureRecognizer) {
    print("Down")
}  

program cant start because php5.dll is missing

I needed to change environment variable PATH and PHPRC. Also open new cmd.

I already had PHP installed and added EasyPHP when the problem came up. After I changed both variables to C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\binaries\php\php_runningversion it worked fine.

Date format Mapping to JSON Jackson

Since Jackson v2.0, you can use @JsonFormat annotation directly on Object members;

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm a z")
private Date date;

MySQL 'Order By' - sorting alphanumeric correctly

This type of question has been asked previously.

The type of sorting you are talking about is called "Natural Sorting". The data on which you want to do sort is alphanumeric. It would be better to create a new column for sorting.

For further help check natural-sort-in-mysql

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

Is this what you are looking for? Otherwise, let me know and I will remove this post.

Try this jQuery plugin: http://archive.plugins.jquery.com/project/client-detect

Demo: http://www.stoimen.com/jquery.client.plugin/

This is based on quirksmode BrowserDetect a wrap for jQuery browser/os detection plugin.

For keen readers:
http://www.stoimen.com/blog/2009/07/16/jquery-browser-and-os-detection-plugin/
http://www.quirksmode.org/js/support.html

And more code around the plugin resides here: http://www.stoimen.com/jquery.client.plugin/jquery.client.js

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

This is how I have it working.

  1. Add maven { url "https://maven.google.com" } as @Gabriele_Mariotti suggests above.

    allprojects {
        repositories {
            jcenter()
            maven {
                url "https://maven.google.com"
            }
        }
    }
    
  2. Then on the build.gradle file inside the App folder add

    compileSdkVersion 26
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.xxx.yyy"
        minSdkVersion 16
        targetSdkVersion 26
    }
    
  3. Then on the dependencies use

    dependencies {
        compile 'com.android.support:appcompat-v7:26.0.1'
        compile 'com.android.support:design:26.0.1'
        compile 'com.google.android.gms:play-services-maps:11.0.4'
        compile 'com.google.android.gms:play-services-location:11.0.4'
        compile 'com.mcxiaoke.volley:library-aar:1.0.0'
        compile 'com.android.support:cardview-v7:26.0.1'
    }
    

Why isn't this code to plot a histogram on a continuous value Pandas column working?

EDIT:

After your comments this actually makes perfect sense why you don't get a histogram of each different value. There are 1.4 million rows, and ten discrete buckets. So apparently each bucket is exactly 10% (to within what you can see in the plot).


A quick rerun of your data:

In [25]: df.hist(column='Trip_distance')

enter image description here

Prints out absolutely fine.

The df.hist function comes with an optional keyword argument bins=10 which buckets the data into discrete bins. With only 10 discrete bins and a more or less homogeneous distribution of hundreds of thousands of rows, you might not be able to see the difference in the ten different bins in your low resolution plot:

In [34]: df.hist(column='Trip_distance', bins=50)

enter image description here

Are dictionaries ordered in Python 3.6+?

Are dictionaries ordered in Python 3.6+?

They are insertion ordered[1]. As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. This is considered an implementation detail in Python 3.6; you need to use OrderedDict if you want insertion ordering that's guaranteed across other implementations of Python (and other ordered behavior[1]).

As of Python 3.7, this is no longer an implementation detail and instead becomes a language feature. From a python-dev message by GvR:

Make it so. "Dict keeps insertion order" is the ruling. Thanks!

This simply means that you can depend on it. Other implementations of Python must also offer an insertion ordered dictionary if they wish to be a conforming implementation of Python 3.7.


How does the Python 3.6 dictionary implementation perform better[2] than the older one while preserving element order?

Essentially, by keeping two arrays.

  • The first array, dk_entries, holds the entries (of type PyDictKeyEntry) for the dictionary in the order that they were inserted. Preserving order is achieved by this being an append only array where new items are always inserted at the end (insertion order).

  • The second, dk_indices, holds the indices for the dk_entries array (that is, values that indicate the position of the corresponding entry in dk_entries). This array acts as the hash table. When a key is hashed it leads to one of the indices stored in dk_indices and the corresponding entry is fetched by indexing dk_entries. Since only indices are kept, the type of this array depends on the overall size of the dictionary (ranging from type int8_t(1 byte) to int32_t/int64_t (4/8 bytes) on 32/64 bit builds)

In the previous implementation, a sparse array of type PyDictKeyEntry and size dk_size had to be allocated; unfortunately, it also resulted in a lot of empty space since that array was not allowed to be more than 2/3 * dk_size full for performance reasons. (and the empty space still had PyDictKeyEntry size!).

This is not the case now since only the required entries are stored (those that have been inserted) and a sparse array of type intX_t (X depending on dict size) 2/3 * dk_sizes full is kept. The empty space changed from type PyDictKeyEntry to intX_t.

So, obviously, creating a sparse array of type PyDictKeyEntry is much more memory demanding than a sparse array for storing ints.

You can see the full conversation on Python-Dev regarding this feature if interested, it is a good read.


In the original proposal made by Raymond Hettinger, a visualization of the data structures used can be seen which captures the gist of the idea.

For example, the dictionary:

d = {'timmy': 'red', 'barry': 'green', 'guido': 'blue'}

is currently stored as [keyhash, key, value]:

entries = [['--', '--', '--'],
           [-8522787127447073495, 'barry', 'green'],
           ['--', '--', '--'],
           ['--', '--', '--'],
           ['--', '--', '--'],
           [-9092791511155847987, 'timmy', 'red'],
           ['--', '--', '--'],
           [-6480567542315338377, 'guido', 'blue']]

Instead, the data should be organized as follows:

indices =  [None, 1, None, None, None, 0, None, 2]
entries =  [[-9092791511155847987, 'timmy', 'red'],
            [-8522787127447073495, 'barry', 'green'],
            [-6480567542315338377, 'guido', 'blue']]

As you can visually now see, in the original proposal, a lot of space is essentially empty to reduce collisions and make look-ups faster. With the new approach, you reduce the memory required by moving the sparseness where it's really required, in the indices.


[1]: I say "insertion ordered" and not "ordered" since, with the existence of OrderedDict, "ordered" suggests further behavior that the dict object doesn't provide. OrderedDicts are reversible, provide order sensitive methods and, mainly, provide an order-sensive equality tests (==, !=). dicts currently don't offer any of those behaviors/methods.


[2]: The new dictionary implementations performs better memory wise by being designed more compactly; that's the main benefit here. Speed wise, the difference isn't so drastic, there's places where the new dict might introduce slight regressions (key-lookups, for example) while in others (iteration and resizing come to mind) a performance boost should be present.

Overall, the performance of the dictionary, especially in real-life situations, improves due to the compactness introduced.

Registering for Push Notifications in Xcode 8/Swift 3.0?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    if #available(iOS 10, *) {

        //Notifications get posted to the function (delegate):  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void)"


        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in

            guard error == nil else {
                //Display Error.. Handle Error.. etc..
                return
            }

            if granted {
                //Do stuff here..

                //Register for RemoteNotifications. Your Remote Notifications can display alerts now :)
                DispatchQueue.main.async {
                    application.registerForRemoteNotifications()
                }
            }
            else {
                //Handle user denying permissions..
            }
        }

        //Register for remote notifications.. If permission above is NOT granted, all notifications are delivered silently to AppDelegate.
        application.registerForRemoteNotifications()
    }
    else {
        let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()
    }

    return true
}

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

Go into Simulator-> Hardware->Keyboard and unchecking Connect Hardware Keyboard.

The same as many answers above BUT did not change for me until I quit and restart the simulator. xcode 8.2.1 and Simulator 10.0.

How can I setup & run PhantomJS on Ubuntu?

in my vagrant bootstrap:

apt-get install -y build-essential chrpath git-core libssl-dev libfontconfig1-dev
git clone git://github.com/ariya/phantomjs.git
cd phantomjs
git checkout 1.9
echo y | ./build.sh
ln -s /home/vagrant/phantomjs/bin/phantomjs /usr/local/bin/phantomjs
cd ..

Turn off auto formatting in Visual Studio

I see that many answers here solve the problem for a specific situation.

For my situation I continually found that the IDE would automatically format JavaScript code within an ASP page.

To disable, I unchecked this box: enter image description here

In addition, I found it very helpful to use the search query in the toolbar (CTRL+Q) and just search for the text format on paste. As you can see with the scroll bar, there are quite a few options to check!

enter image description here

New line in JavaScript alert box

_x000D_
_x000D_
 alert("some text\nmore text in a new line");
_x000D_
_x000D_
_x000D_

Output:

some text
more text in a new line

ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

Perform the following steps:

  1. Start the Registry Editor by typing regedit in the Run window.
  2. Select the following key in the registry: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC.
  3. In the Security menu, click Permissions.
  4. Grant Full Permission to the account which is being used for making connections.
  5. Quit the Registry Editor.

Difference between multitasking, multithreading and multiprocessing?

Multiprogramming - A computer running more than one program at a time (like running Excel and Firefox simultaneously)

Multiprocessing - A computer using more than one CPU at a time

Multiprogramming - More than one task/program/job/process can reside into the main memory at one point of time. This ability of the OS is called multiprogramming.

Multitasking: More than one task/program/job/process can reside into the same CPU at one point of time. This ability of the OS is called multitasking.

Multiusers System - a computer system in which multiple terminals connect to a host computer that handles processing tasks.

Paste a multi-line Java String in Eclipse

If your building that SQL in a tool like TOAD or other SQL oriented IDE they often have copy markup to the clipboard. For example, TOAD has a CTRL+M which takes the SQL in your editor and does exactly what you have in your code above. It also covers the reverse... when your grabbing a formatted string out of your Java and want to execute it in TOAD. Pasting the SQL back into TOAD and perform a CTRL+P to remove the multi-line quotes.

What exactly is std::atomic?

I understand that std::atomic<> makes an object atomic.

That's a matter of perspective... you can't apply it to arbitrary objects and have their operations become atomic, but the provided specialisations for (most) integral types and pointers can be used.

a = a + 12;

std::atomic<> does not (use template expressions to) simplify this to a single atomic operation, instead the operator T() const volatile noexcept member does an atomic load() of a, then twelve is added, and operator=(T t) noexcept does a store(t).

How to set a JVM TimeZone Properly

Setting environment variable TZ should also works

ex: export TZ=Asia/Shanghai

MySQL string replace

You can simply use replace() function,

with where clause-

update tabelName set columnName=REPLACE(columnName,'from','to') where condition;

without where clause-

update tabelName set columnName=REPLACE(columnName,'from','to');

Note: The above query if for update records directly in table, if you want on select query and the data should not be affected in table then can use the following query-

select REPLACE(columnName,'from','to') as updateRecord;

What is the difference between MVC and MVVM?

mvc is server-side and mvvm is client-side(browser) in web development.

most of the time javascript is used for mvvm in browser. there are many server side technologies for mvc.

Add common prefix to all cells in Excel

Select the cell you want to be like this, Go To Cell Properties (or CTRL 1) under Number tab in custom enter "X"#

PHP: How to check if a date is today, yesterday or tomorrow

function getRangeDateString($timestamp) {
    if ($timestamp) {
        $currentTime=strtotime('today');
        // Reset time to 00:00:00
        $timestamp=strtotime(date('Y-m-d 00:00:00',$timestamp));
        $days=round(($timestamp-$currentTime)/86400);
        switch($days) {
            case '0';
                return 'Today';
                break;
            case '-1';
                return 'Yesterday';
                break;
            case '-2';
                return 'Day before yesterday';
                break;
            case '1';
                return 'Tomorrow';
                break;
            case '2';
                return 'Day after tomorrow';
                break;
            default:
                if ($days > 0) {
                    return 'In '.$days.' days';
                } else {
                    return ($days*-1).' days ago';
                }
                break;
        }
    }
}

How to make the first option of <select> selected with jQuery

You can try this

$("#target").prop("selectedIndex", 0);

How to return a value from pthread threads in C?

Here is a correct solution. In this case tdata is allocated in the main thread, and there is a space for the thread to place its result.

#include <pthread.h>
#include <stdio.h>

typedef struct thread_data {
   int a;
   int b;
   int result;

} thread_data;

void *myThread(void *arg)
{
   thread_data *tdata=(thread_data *)arg;

   int a=tdata->a;
   int b=tdata->b;
   int result=a+b;

   tdata->result=result;
   pthread_exit(NULL);
}

int main()
{
   pthread_t tid;
   thread_data tdata;

   tdata.a=10;
   tdata.b=32;

   pthread_create(&tid, NULL, myThread, (void *)&tdata);
   pthread_join(tid, NULL);

   printf("%d + %d = %d\n", tdata.a, tdata.b, tdata.result);   

   return 0;
}

Scale image to fit a bounding box

I have used table to center image inside the box. It keeps aspect ratio and scales image in a way that is totally inside the box. If the image is smaller than the box then it is shown as it is in the center. Below code uses 40px width and 40px height box. (Not quite sure how well it works because I removed it from another more complex code and simplified it little bit)

_x000D_
_x000D_
.SmallThumbnailContainer {
  display: inline-block;
  position: relative;
  float: left;
  width: 40px;
  height: 40px;
  border: 1px solid #ccc;
  margin: 0px;
  padding: 0px;
}

.SmallThumbnailContainer {
  width: 40px;
  margin: 0px 10px 0px 0px;
}

.SmallThumbnailContainer tr {
  height: 40px;
  text-align: center;
}

.SmallThumbnailContainer tr td {
  vertical-align: middle;
  position: relative;
  width: 40px;
}

.SmallThumbnailContainer tr td img {
  overflow: hidden;
  max-height: 40px;
  max-width: 40px;
  vertical-align: middle;
  margin: -1px -1px 1px -1px;
}
_x000D_
<table class="SmallThumbnailContainer" cellpadding="0" cellspacing="0">
  <tr>
    <td>
      <img src="https://www.gravatar.com/avatar/bf7d39f4ed9c289feca7de38a0093250?s=32&d=identicon&r=PG" width="32" height="32" alt="OP's SO avatar image used as a sample jpg because it is hosted on SO, thus always available" />
    </td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

Note: the native thumbnail size in this snippet is 32px x 32px, which is smaller than its 40px x 40px container. If the container is instead sized smaller than the thumbnail in any dimension, say 40px x 20px, the image flows outside the container in the dimensions that are smaller than the corresponding image dimension. The container is marked by a gray 1px border.

Show and hide a View with a slide up/down animation

you can slide up and down any view or layout by using bellow code in android app

boolean isClicked=false;
LinearLayout mLayoutTab = (LinearLayout)findViewById(R.id.linearlayout);

        if(isClicked){
                    isClicked = false;
                    mLayoutTab.animate()
                    .translationYBy(120)
                    .translationY(0)     
                    .setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime));

        }else{
                isClicked = true;
                mLayoutTab.animate()
                .translationYBy(0)
                .translationY(120)
                .setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime));
                }

Substring a string from the end of the string

string s = "Hello Marco !";
s = s.Remove(s.length - 2, 2);

MySQL: how to get the difference between two timestamps in seconds

How about "TIMESTAMPDIFF":

SELECT TIMESTAMPDIFF(SECOND,'2009-05-18','2009-07-29') from `post_statistics`

https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_timestampdiff

Why does Git tell me "No such remote 'origin'" when I try to push to origin?

I'm guessing you didn't run this command after the commit failed so just actually run this to create the remote :

 git remote add origin https://github.com/VijayNew/NewExample.git

And the commit failed because you need to git add some files you want to track.

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

select to_char(to_date('1/21/2000','mm/dd/yyyy'),'dd-mm-yyyy') from dual

Are members of a C++ struct initialized to 0 by default?

With POD you can also write

Snapshot s = {};

You shouldn't use memset in C++, memset has the drawback that if there is a non-POD in the struct it will destroy it.

or like this:

struct init
{
  template <typename T>
  operator T * ()
  {
    return new T();
  }
};

Snapshot* s = init();

How do you detect the clearing of a "search" HTML5 input?

The search or onclick works... but the issue I found was with the older browsers - the search fails. Lots of plugins (jquery ui autocomplete or fancytree filter) have blur and focus handlers. Adding this to an autocomplete input box worked for me(used this.value == "" because it was faster to evaluate). The blur then focus kept the cursor in the box when you hit the little 'x'.

The PropertyChange and input worked for both IE 10 and IE 8 as well as other browsers:

$("#INPUTID").on("propertychange input", function(e) { 
    if (this.value == "") $(this).blur().focus(); 
});

For FancyTree filter extension, you can use a reset button and force it's click event as follows:

var TheFancyTree = $("#FancyTreeID").fancytree("getTree");

$("input[name=FT_FilterINPUT]").on("propertychange input", function (e) {
    var n,
    leavesOnly = false,
    match = $(this).val();
    // check for the escape key or empty filter
    if (e && e.which === $.ui.keyCode.ESCAPE || $.trim(match) === "") {
        $("button#btnResetSearch").click();
        return;
    }

    n = SiteNavTree.filterNodes(function (node) {
        return MatchContainsAll(CleanDiacriticsString(node.title.toLowerCase()), match);
        }, leavesOnly);

    $("button#btnResetSearch").attr("disabled", false);
    $("span#SiteNavMatches").text("(" + n + " matches)");
}).focus();

// handle the reset and check for empty filter field... 
// set the value to trigger the change
$("button#btnResetSearch").click(function (e) {
    if ($("input[name=FT_FilterINPUT]").val() != "")
        $("input[name=FT_FilterINPUT]").val("");
    $("span#SiteNavMatches").text("");
    SiteNavTree.clearFilter();
}).attr("disabled", true);

Should be able to adapt this for most uses.

How can I add numbers in a Bash script?

You should declare metab as integer and then use arithmetic evaluation

declare -i metab num
...
num+=metab
...

For more information see https://www.gnu.org/software/bash/manual/html_node/Shell-Arithmetic.html#Shell-Arithmetic

How to pass multiple parameter to @Directives (@Components) in Angular with TypeScript?

Another neat option is to use the Directive as an element and not as an attribute.

@Directive({
   selector: 'app-directive'
})
export class InformativeDirective implements AfterViewInit {

    @Input()
    public first: string;

    @Input()
    public second: string;

    ngAfterViewInit(): void {
       console.log(`Values: ${this.first}, ${this.second}`);
    }
}

And this directive can be used like that:

<app-someKindOfComponent>
    <app-directive [first]="'first 1'" [second]="'second 1'">A</app-directive>
    <app-directive [first]="'First 2'" [second]="'second 2'">B</app-directive>
    <app-directive [first]="'First 3'" [second]="'second 3'">C</app-directive>
</app-someKindOfComponent>`

Simple, neat and powerful.

ADB - Android - Getting the name of the current activity

Below command can be used for finding both package and current Activity name. Found this very useful command to quickly fetch these two information about an app especially when developing tests with Appium.

adb shell dumpsys window windows | grep -E 'mCurrentFocus'

Response of this command contains both package name and current Activity. For example: in following "com.android.contacts" is the package and "com.android.contacts.activities.TwelveKeyDialer" is current Activity launched on the phone which is connected via adb.

mCurrentFocus=Window{2089af8 u0 com.android.contacts/com.android.contacts.activities.TwelveKeyDialer}

Reference: http://www.automationtestinghub.com/apppackage-and-appactivity-name/

Styling multi-line conditions in 'if' statements?

Pardon my noobness, but it happens that I'm not as knowledgeable of #Python as anyone of you here, but it happens that I have found something similar when scripting my own objects in a 3D BIM modeling, so I will adapt my algorithm to that of python.

The problem that I find here, is double sided:

  1. Values my seem foreign for someone who may try to decipher the script.
  2. Code maintenance will come at a high cost, if those values are changed (most probable), or if new conditions must be added (broken schema)

Do to bypass all these problems, your script must go like this

param_Val01 = Value 01   #give a meaningful name for param_Val(i) preferable an integer
param_Val02 = Value 02
param_Val03 = Value 03
param_Val04 = Value 04   # and ... etc

conditions = 0           # this is a value placeholder

########
Add script that if true will make:

conditions = conditions + param_Val01   #value of placeholder is updated
########

### repeat as needed


if conditions = param_Val01 + param_Val02 + param_Val03 + param_Val04:
    do something

Pros of this method:

  1. Script is readable.

  2. Script can be easy maintained.

  3. conditions is a 1 comparison operation to a sum of values that represents the desired conditions.
  4. No need for multilevel conditions

Hope it help you all

How can I make a "color map" plot in matlab?

I also suggest using contourf(Z). For my problem, I wanted to visualize a 3D histogram in 2D, but the contours were too smooth to represent a top view of histogram bars.

So in my case, I prefer to use jucestain's answer. The default shading faceted of pcolor() is more suitable. However, pcolor() does not use the last row and column of the plotted matrix. For this, I used the padarray() function:

pcolor(padarray(Z,[1 1],0,'post'))

Sorry if that is not really related to the original post

How should I throw a divide by zero exception in Java without actually dividing by zero?

You should not throw an ArithmeticException. Since the error is in the supplied arguments, throw an IllegalArgumentException. As the documentation says:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

Which is exactly what is going on here.

if (divisor == 0) {
    throw new IllegalArgumentException("Argument 'divisor' is 0");
}

Change value of input onchange?

You can't access your fieldname as a global variable. Use document.getElementById:

function updateInput(ish){
    document.getElementById("fieldname").value = ish;
}

and

onchange="updateInput(this.value)"

Create a jTDS connection string

A shot in the dark, but From the looks of your error message, it seems that either the sqlserver instance is not running on port 1433 or something is blocking the requests to that port

Bootstrap 3: Scroll bars

You need to use the overflow option, but with the following parameters:

.nav {
    max-height:300px;
    overflow-y:auto;  
}

Use overflow-y:auto; so the scrollbar only appears when the content exceeds the maximum height.

If you use overflow-y:scroll, the scrollbar will always be visible - on all .nav - regardless if the content exceeds the maximum heigh or not.

Presumably you want something that adapts itself to the content rather then the the opposite.

Hope it may helpful

gradlew command not found?

If you are using VS Code with flutter, you should find it in your app folder, under the android folder:

C:\myappFolder\android

You can run this in the terminal:

./gradlew signingReport

How to make a simple popup box in Visual C#?

In Visual Studio 2015 (community edition), System.Windows.Forms is not available and hence we can't use MessageBox.Show("text").

Use this Instead:

var Msg = new MessageDialog("Some String here", "Title of Message Box");    
await Msg.ShowAsync();

Note: Your function must be defined async to use above await Msg.ShowAsync().

How to add a linked source folder in Android Studio?

in your build.gradle add the following to the end of the android node

android {
    ....
    ....

    sourceSets {
        main.java.srcDirs += 'src/main/<YOUR DIRECTORY>'
    }

}

How can I make one python file run another?

Get one python file to run another, using python 2.7.3 and Ubuntu 12.10:

  1. Put this in main.py:

    #!/usr/bin/python
    import yoursubfile
    
  2. Put this in yoursubfile.py

    #!/usr/bin/python
    print("hello")
    
  3. Run it:

    python main.py 
    
  4. It prints:

    hello
    

Thus main.py runs yoursubfile.py

There are 8 ways to answer this question, A more canonical answer is here: How to import other Python files?

Use CSS3 transitions with gradient backgrounds

Partial workaround for gradient transition is to use inset box shadow - you can transition either the box shadow itself, or the background color - e.g. if you create inset box shadow of the same color as background and than use transition on background color, it creates illusion that plain background is changing to radial gradient

.button SPAN {
    padding: 10px 30px; 
    border: 1px solid ##009CC5;

    -moz-box-shadow: inset 0 0 20px 1px #00a7d1;
    -webkit-box-shadow: inset 0 0 20px 1px#00a7d1;
    box-shadow: inset 0 0 20px 1px #00a7d1; 

    background-color: #00a7d1;
    -webkit-transition: background-color 0.5s linear;
    -moz-transition: background-color 0.5s linear;
    -o-transition: background-color 0.5s linear;
    transition: background-color 0.5s linear;
}

.button SPAN:hover {
    background-color: #00c5f7; 
}

duplicate 'row.names' are not allowed error

In my case was a comma at the end of every line. By removing that worked

grep output to show only matching file

grep -l 

(That's a lowercase L)

How to get the position of a character in Python?

What happens when the string contains a duplicate character? from my experience with index() I saw that for duplicate you get back the same index.

For example:

s = 'abccde'
for c in s:
    print('%s, %d' % (c, s.index(c)))

would return:

a, 0
b, 1
c, 2
c, 2
d, 4

In that case you can do something like that:

for i, character in enumerate(my_string):
   # i is the position of the character in the string

Is it possible to insert multiple rows at a time in an SQLite database?

On sqlite 3.7.2:

INSERT INTO table_name (column1, column2) 
                SELECT 'value1', 'value1' 
          UNION SELECT 'value2', 'value2' 
          UNION SELECT 'value3', 'value3' 

and so on

Unable to convert MySQL date/time value to System.DateTime

You must add Convert Zero Datetime=True to your connection string, for example:

server=localhost;User Id=root;password=mautauaja;Persist Security Info=True;database=test;Convert Zero Datetime=True

Rename specific column(s) in pandas

data.rename(columns={'gdp':'log(gdp)'}, inplace=True)

The rename show that it accepts a dict as a param for columns so you just pass a dict with a single entry.

Also see related

How do I finish the merge after resolving my merge conflicts?

The next steps after resolving the conflicts manually are:-

  1. git add .
  2. git status (this will show you which commands are necessary to continue automatic merge procedure)
  3. [command git suggests, e.g. git merge --continue, git cherry-pick --continue, git rebase --continue]

Escaping HTML strings with jQuery

Since you're using jQuery, you can just set the element's text property:

// before:
// <div class="someClass">text</div>
var someHtmlString = "<script>alert('hi!');</script>";

// set a DIV's text:
$("div.someClass").text(someHtmlString);
// after: 
// <div class="someClass">&lt;script&gt;alert('hi!');&lt;/script&gt;</div>

// get the text in a string:
var escaped = $("<div>").text(someHtmlString).html();
// value: 
// &lt;script&gt;alert('hi!');&lt;/script&gt;

Can Android Studio be used to run standard Java projects?

Spent a day on finding the easiest way to do this. The purpose was to find the fastest way to achieve this goal. I couldn't make it as fast as running javac command from terminal or compiling from netbeans or sublime text 3. But still got a good speed with android studio.

This looks ruff and tuff way but since we don't initiate projects on daily bases that is why I am okay to do this.

I downloaded IntelliJ IDEA community version and created a simply java project. I added a main class and tested a run. Then simply closed IntelliJ IDEA and opened Android Studio and opened the same project there. Then I had to simply attach JDK where IDE helped me by showing a list of available JDKs and I selected 1.8 and then it compiled well. I can now open any main file and press Control+Shift+R to run that main file.

Then I copied all my Java files into src folder by Mac OS Finder. And I am able to compile anything I want to.

There is nothing related to Gradle or Android and compile speed is pretty good.

Thanks buddies

Query to get all rows from previous month

select fields FROM table WHERE date_created LIKE concat(LEFT(DATE_SUB(NOW(), interval 1 month),7),'%');

this one will be able to take advantage of an index if your date_created is indexed, because it doesn't apply any transformation function to the field value.

Creation timestamp and last update timestamp with Hibernate and MySQL

I think it is neater not doing this in Java code, you can simply set column default value in MySql table definition. enter image description here

Automatic HTTPS connection/redirect with node.js/express

I use the solution proposed by Basarat but I also need to overwrite the port because I used to have 2 different ports for HTTP and HTTPS protocols.

res.writeHead(301, { "Location": "https://" + req.headers['host'].replace(http_port,https_port) + req.url });

I prefer also to use not standard port so to start nodejs without root privileges. I like 8080 and 8443 because I came from lots of years of programming on tomcat.

My complete file become

var fs = require('fs');
var http = require('http');
var http_port    =   process.env.PORT || 8080; 
var app = require('express')();

// HTTPS definitions
var https = require('https');
var https_port    =   process.env.PORT_HTTPS || 8443; 
var options = {
   key  : fs.readFileSync('server.key'),
   cert : fs.readFileSync('server.crt')
};

app.get('/', function (req, res) {
   res.send('Hello World!');
});

https.createServer(options, app).listen(https_port, function () {
   console.log('Magic happens on port ' + https_port); 
});

// Redirect from http port to https
http.createServer(function (req, res) {
    res.writeHead(301, { "Location": "https://" + req.headers['host'].replace(http_port,https_port) + req.url });
    console.log("http request, will go to >> ");
    console.log("https://" + req.headers['host'].replace(http_port,https_port) + req.url );
    res.end();
}).listen(http_port);

Then I use iptable for forwording 80 and 443 traffic on my HTTP and HTTPS ports.

sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 8443

How to search in array of object in mongodb

as explained in above answers Also, to return only one field from the entire array you can use projection into find. and use $

db.getCollection("sizer").find(
  { awards: { $elemMatch: { award: "National Medal", year: 1975 } } },
  { "awards.$": 1, name: 1 }
);

will be reutrn

{
    _id: 1,
    name: {
        first: 'John',
        last: 'Backus'
    },
    awards: [
        {
            award: 'National Medal',
            year: 1975,
            by: 'NSF'
        }
    ]
}

What is tail recursion?

Tail Recursion is pretty fast as compared to normal recursion. It is fast because the output of the ancestors call will not be written in stack to keep the track. But in normal recursion all the ancestor calls output written in stack to keep the track.

CSS Always On Top

Ensure position is on your element and set the z-index to a value higher than the elements you want to cover.

element {
    position: fixed;
    z-index: 999;
}

div {
    position: relative;
    z-index: 99;
}

It will probably require some more work than that but it's a start since you didn't post any code.

How to deny access to a file in .htaccess

Place the below line in your .htaccess file and replace the file name as you wish

RewriteRule ^(test\.php) - [F,L,NC]

In C#, should I use string.Empty or String.Empty or "" to intitialize a string?

I personally prefer "" unless there is a good reason to something more complex.

How to swap String characters in Java?

'In' a string, you cant. Strings are immutable. You can easily create a second string with:

 String second = first.replaceFirst("(.)(.)", "$2$1");

JavaScript: function returning an object

In JavaScript, most functions are both callable and instantiable: they have both a [[Call]] and [[Construct]] internal methods.

As callable objects, you can use parentheses to call them, optionally passing some arguments. As a result of the call, the function can return a value.

var player = makeGamePlayer("John Smith", 15, 3);

The code above calls function makeGamePlayer and stores the returned value in the variable player. In this case, you may want to define the function like this:

function makeGamePlayer(name, totalScore, gamesPlayed) {
  // Define desired object
  var obj = {
    name:  name,
    totalScore: totalScore,
    gamesPlayed: gamesPlayed
  };
  // Return it
  return obj;
}

Additionally, when you call a function you are also passing an additional argument under the hood, which determines the value of this inside the function. In the case above, since makeGamePlayer is not called as a method, the this value will be the global object in sloppy mode, or undefined in strict mode.

As constructors, you can use the new operator to instantiate them. This operator uses the [[Construct]] internal method (only available in constructors), which does something like this:

  1. Creates a new object which inherits from the .prototype of the constructor
  2. Calls the constructor passing this object as the this value
  3. It returns the value returned by the constructor if it's an object, or the object created at step 1 otherwise.
var player = new GamePlayer("John Smith", 15, 3);

The code above creates an instance of GamePlayer and stores the returned value in the variable player. In this case, you may want to define the function like this:

function GamePlayer(name,totalScore,gamesPlayed) {
  // `this` is the instance which is currently being created
  this.name =  name;
  this.totalScore = totalScore;
  this.gamesPlayed = gamesPlayed;
  // No need to return, but you can use `return this;` if you want
}

By convention, constructor names begin with an uppercase letter.

The advantage of using constructors is that the instances inherit from GamePlayer.prototype. Then, you can define properties there and make them available in all instances

React.js: Wrapping one component into another

In addition to Sophie's answer, I also have found a use in sending in child component types, doing something like this:

var ListView = React.createClass({
    render: function() {
        var items = this.props.data.map(function(item) {
            return this.props.delegate({data:item});
        }.bind(this));
        return <ul>{items}</ul>;
    }
});

var ItemDelegate = React.createClass({
    render: function() {
        return <li>{this.props.data}</li>
    }
});

var Wrapper = React.createClass({    
    render: function() {
        return <ListView delegate={ItemDelegate} data={someListOfData} />
    }
});

Line Break in XML?

just use &lt;br&gt; at the end of your lines.

Eliminate space before \begin{itemize}

\renewcommand{\@listI}{%
\leftmargin=25pt
\rightmargin=0pt
\labelsep=5pt
\labelwidth=20pt
\itemindent=0pt
\listparindent=0pt
\topsep=0pt plus 2pt minus 4pt
\partopsep=0pt plus 1pt minus 1pt
\parsep=0pt plus 1pt
\itemsep=\parsep}

Causes of getting a java.lang.VerifyError

This can happen on Android when you're trying to load a library that was compiled against Oracle's JDK.

Here is the problem for Ning Async HTTP client.

Using GregorianCalendar with SimpleDateFormat

tl;dr

LocalDate.parse(
    "23-Mar-2017" ,
    DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US ) 
)

Avoid legacy date-time classes

The Question and other Answers are now outdated, using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

Using java.time

You seem to be dealing with date-only values. So do not use a date-time class. Instead use LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.

Specify a Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.

Parse a string.

String input = "23-Mar-2017" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US ) ;
LocalDate ld = LocalDate.parse( input , f );

Generate a string.

String output = ld.format( f );

If you were given numbers rather than text for the year, month, and day-of-month, use LocalDate.of.

LocalDate ld = LocalDate.of( 2017 , 3 , 23 );  // ( year , month 1-12 , day-of-month )

See this code run live at IdeOne.com.

input: 23-Mar-2017

ld.toString(): 2017-03-23

output: 23-Mar-2017


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to read a text file into a string variable and strip newlines?

I'm surprised nobody mentioned splitlines() yet.

with open ("data.txt", "r") as myfile:
    data = myfile.read().splitlines()

Variable data is now a list that looks like this when printed:

['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']

Note there are no newlines (\n).

At that point, it sounds like you want to print back the lines to console, which you can achieve with a for loop:

for line in data:
    print(line)

Append file contents to the bottom of existing file in Bash

This should work:

 cat "$API" >> "$CONFIG"

You need to use the >> operator to append to a file. Redirecting with > causes the file to be overwritten. (truncated).

alert() not working in Chrome

Take a look at this thread: http://code.google.com/p/chromium/issues/detail?id=4158

The problem is caused by javascript method "window.open(URL, windowName[, windowFeatures])". If the 3rd parameter windowFeatures is specified, then alert box doesn't work in the popup constrained window in Chrome, here is a simplified reduction:

http://go/reductions/4158/test-home-constrained.html

If the 3rd parameter windowFeatures is ignored, then alert box works in the popup in Chrome(the popup is actually opened as a new tab in Chrome), like this:

http://go/reductions/4158/test-home-newtab.html

it doesn't happen in IE7, Firefox3 or Safari3, it's a chrome specific issue.

See also attachments for simplified reductions

Run text file as commands in Bash

you can make a shell script with those commands, and then chmod +x <scriptname.sh>, and then just run it by

./scriptname.sh

Its very simple to write a bash script

Mockup sh file:

#!/bin/sh
sudo command1
sudo command2 
.
.
.
sudo commandn

How does bitshifting work in Java?

These examples cover the three types of shifts applied to both a positive and a negative number:

// Signed left shift on 626348975
00100101010101010101001110101111 is   626348975
01001010101010101010011101011110 is  1252697950 after << 1
10010101010101010100111010111100 is -1789571396 after << 2
00101010101010101001110101111000 is   715824504 after << 3

// Signed left shift on -552270512
11011111000101010000010101010000 is  -552270512
10111110001010100000101010100000 is -1104541024 after << 1
01111100010101000001010101000000 is  2085885248 after << 2
11111000101010000010101010000000 is  -123196800 after << 3


// Signed right shift on 626348975
00100101010101010101001110101111 is   626348975
00010010101010101010100111010111 is   313174487 after >> 1
00001001010101010101010011101011 is   156587243 after >> 2
00000100101010101010101001110101 is    78293621 after >> 3

// Signed right shift on -552270512
11011111000101010000010101010000 is  -552270512
11101111100010101000001010101000 is  -276135256 after >> 1
11110111110001010100000101010100 is  -138067628 after >> 2
11111011111000101010000010101010 is   -69033814 after >> 3


// Unsigned right shift on 626348975
00100101010101010101001110101111 is   626348975
00010010101010101010100111010111 is   313174487 after >>> 1
00001001010101010101010011101011 is   156587243 after >>> 2
00000100101010101010101001110101 is    78293621 after >>> 3

// Unsigned right shift on -552270512
11011111000101010000010101010000 is  -552270512
01101111100010101000001010101000 is  1871348392 after >>> 1
00110111110001010100000101010100 is   935674196 after >>> 2
00011011111000101010000010101010 is   467837098 after >>> 3

Binding an Image in WPF MVVM

@Sheridan thx.. if I try your example with "DisplayedImagePath" on both sides, it works with absolute path as you show.

As for the relative paths, this is how I always connect relative paths, I first include the subdirectory (!) and the image file in my project.. then I use ~ character to denote the bin-path..

    public string DisplayedImagePath
    {
        get { return @"~\..\images\osc.png"; }
    }

This was tested, see below my Solution Explorer in VS2015..

example of image binding in VS2015)

Note: if you want a Click event, use the Button tag around the image,

_x000D_
_x000D_
<Button Click="image_Click" Width="128" Height="128"  Grid.Row="2" VerticalAlignment="Top" HorizontalAlignment="Left">_x000D_
  <Image x:Name="image" Source="{Binding DisplayedImagePath}" Margin="0,0,0,0" />_x000D_
</Button>
_x000D_
_x000D_
_x000D_

How to format Joda-Time DateTime to only mm/dd/yyyy?

I have a very dumb but working option. if you have the String fullDate = "11/15/2013 08:00:00";

   String finalDate = fullDate.split(" ")[0];

That should work easy and fast. :)

Can vue-router open a link in a new tab?

If you are interested ONLY on relative paths like: /dashboard, /about etc, See other answers.

If you want to open an absolute path like: https://www.google.com to a new tab, you have to know that Vue Router is NOT meant to handle those.

However, they seems to consider that as a feature-request. #1280. But until they do that,



Here is a little trick you can do to handle external links with vue-router.

  • Go to the router configuration (probably router.js) and add this code:
/* Vue Router is not meant to handle absolute urls. */
/* So whenever we want to deal with those, we can use this.$router.absUrl(url) */
Router.prototype.absUrl = function(url, newTab = true) {
  const link = document.createElement('a')
  link.href = url
  link.target = newTab ? '_blank' : ''
  if (newTab) link.rel = 'noopener noreferrer' // IMPORTANT to add this
  link.click()
}

Now, whenever we deal with absolute URLs we have a solution. For example to open google to a new tab

this.$router.absUrl('https://www.google.com)

Remember that whenever we open another page to a new tab we MUST use noopener noreferrer.

Read more here

or Here

What is the significance of #pragma marks? Why do we need #pragma marks?

#pragma mark - NSSecureCoding

The main purpose of "pragma" is for developer reference.enter image description here

You can easily find a method/Function in a vast thousands of coding lines.

Xcode 11+:

Marker Line in Top

// MARK: - Properties

Marker Line in Top and Bottom

// MARK: - Properties - 

Marker Line only in bottom

// MARK: Properties -

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

.catch(error => { throw error}) is a no-op. It results in unhandled rejection in route handler.

As explained in this answer, Express doesn't support promises, all rejections should be handled manually:

router.get("/emailfetch", authCheck, async (req, res, next) => {
  try {
  //listing messages in users mailbox 
    let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
    emailFetch = emailFetch.data
    res.send(emailFetch)
  } catch (err) {
    next(err);
  }
})

IOError: [Errno 32] Broken pipe: Python

I feel obliged to point out that the method using

signal(SIGPIPE, SIG_DFL) 

is indeed dangerous (as already suggested by David Bennet in the comments) and in my case led to platform-dependent funny business when combined with multiprocessing.Manager (because the standard library relies on BrokenPipeError being raised in several places). To make a long and painful story short, this is how I fixed it:

First, you need to catch the IOError (Python 2) or BrokenPipeError (Python 3). Depending on your program you can try to exit early at that point or just ignore the exception:

from errno import EPIPE

try:
    broken_pipe_exception = BrokenPipeError
except NameError:  # Python 2
    broken_pipe_exception = IOError

try:
    YOUR CODE GOES HERE
except broken_pipe_exception as exc:
    if broken_pipe_exception == IOError:
        if exc.errno != EPIPE:
            raise

However, this isn't enough. Python 3 may still print a message like this:

Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
BrokenPipeError: [Errno 32] Broken pipe

Unfortunately getting rid of that message is not straightforward, but I finally found http://bugs.python.org/issue11380 where Robert Collins suggests this workaround that I turned into a decorator you can wrap your main function with (yes, that's some crazy indentation):

from functools import wraps
from sys import exit, stderr, stdout
from traceback import print_exc


def suppress_broken_pipe_msg(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except SystemExit:
            raise
        except:
            print_exc()
            exit(1)
        finally:
            try:
                stdout.flush()
            finally:
                try:
                    stdout.close()
                finally:
                    try:
                        stderr.flush()
                    finally:
                        stderr.close()
    return wrapper


@suppress_broken_pipe_msg
def main():
    YOUR CODE GOES HERE

Get the name of a pandas DataFrame

From here what I understand DataFrames are:

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects.

And Series are:

Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.).

Series have a name attribute which can be accessed like so:

 In [27]: s = pd.Series(np.random.randn(5), name='something')

 In [28]: s
 Out[28]: 
 0    0.541
 1   -1.175
 2    0.129
 3    0.043
 4   -0.429
 Name: something, dtype: float64

 In [29]: s.name
 Out[29]: 'something'

EDIT: Based on OP's comments, I think OP was looking for something like:

 >>> df = pd.DataFrame(...)
 >>> df.name = 'df' # making a custom attribute that DataFrame doesn't intrinsically have
 >>> print(df.name)
 'df'

Run jar file in command prompt

java [any other JVM options you need to give it] -jar foo.jar

Response Content type as CSV

MIME type of the CSV is text/csv according to RFC 4180.

Convert InputStream to byte array in Java

This works for me,

if(inputStream != null){
                ByteArrayOutputStream contentStream = readSourceContent(inputStream);
                String stringContent = contentStream.toString();
                byte[] byteArr = encodeString(stringContent);
            }

readSourceContent()

public static ByteArrayOutputStream readSourceContent(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int nextChar;
        try {
            while ((nextChar = inputStream.read()) != -1) {
                outputStream.write(nextChar);
            }
            outputStream.flush();
        } catch (IOException e) {
            throw new IOException("Exception occurred while reading content", e);
        }

        return outputStream;
    }

encodeString()

public static byte[] encodeString(String content) throws UnsupportedEncodingException {
        byte[] bytes;
        try {
            bytes = content.getBytes();

        } catch (UnsupportedEncodingException e) {
            String msg = ENCODING + " is unsupported encoding type";
            log.error(msg,e);
            throw new UnsupportedEncodingException(msg, e);
        }
        return bytes;
    }

Java: splitting the filename into a base and extension

You can also user java Regular Expression. String.split() also uses the expression internally. Refer http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html

Reading a file line by line in Go

In the new version of Go 1.16 we can use package embed to read the file contents as shown below.

package main

import _"embed"


func main() {
    //go:embed "hello.txt"
    var s string
    print(s)

    //go:embed "hello.txt"
    var b []byte
    print(string(b))

    //go:embed hello.txt
    var f embed.FS
    data, _ := f.ReadFile("hello.txt")
    print(string(data))
}

For more details go through https://tip.golang.org/pkg/embed/ And https://golangtutorial.dev/tips/embed-files-in-go/

Displaying unicode symbols in HTML

I know an answer has already been accepted, but wanted to point a few things out.

Setting the content-type and charset is obviously a good practice, doing it on the server is much better, because it ensures consistency across your application.

However, I would use UTF-8 only when the language of my application uses a lot of characters that are available only in the UTF-8 charset. If you want to show a unicode character or symbol in one of cases, you can do so without changing the charset of your page.

HTML renderers have always been able to display symbols which are not part of the encoding character set of the page, as long as you mention the symbol in its numeric character reference (NCR). Sounds weird but its true.

So, even if your html has a header that states it has an encoding of ansi or any of the iso charsets, you can display a check mark by using its html character reference, in decimal - &#10003; or in hex - &#x2713;

So its a little difficult to understand why you are facing this issue on your pages. Can you check if the NCR value is correct, this is a good reference http://www.fileformat.info/info/unicode/char/2713/index.htm

What does <a href="#" class="view"> mean?

It probably works with Javascript. When you click the link, nothing happens because it points to the current site. The javascript will then load a window or an url. It's used a lot in AJAX web apps.

Android Studio: Plugin with id 'android-library' not found

Just for the record (took me quite a while) before Grzegorzs answer worked for me I had to install "android support repository" through the SDK Manager!

Install it and add the following code above apply plugin: 'android-library' in the build.gradle of actionbarsherlock folder!

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.+'
    }
}

window.onload vs document.onload

When do they fire?

window.onload

  • By default, it is fired when the entire page loads, including its content (images, CSS, scripts, etc.).

In some browsers it now takes over the role of document.onload and fires when the DOM is ready as well.

document.onload

  • It is called when the DOM is ready which can be prior to images and other external content is loaded.

How well are they supported?

window.onload appears to be the most widely supported. In fact, some of the most modern browsers have in a sense replaced document.onload with window.onload.

Browser support issues are most likely the reason why many people are starting to use libraries such as jQuery to handle the checking for the document being ready, like so:

$(document).ready(function() { /* code here */ });
$(function() { /* code here */ });

For the purpose of history. window.onload vs body.onload:

A similar question was asked on codingforums a while back regarding the usage of window.onload over body.onload. The result seemed to be that you should use window.onload because it is good to separate your structure from the action.

How to Turn Off Showing Whitespace Characters in Visual Studio IDE

for VS code and later versions Ctrl + P to open and then writing Whitespace, you can select the View: Toggle Render Whitespace

Enum to String C++

You could throw the enum value and string into an STL map. Then you could use it like so.

   return myStringMap[Enum::Apple];

How do I configure Maven for offline development?

You have two options for this:

1.) make changes in the settings.xml add this in first tag

<localRepository>C:/Users/admin/.m2/repository</localRepository>

2.) use the -o tag for offline command.

mvn -o clean install -DskipTests=true
mvn -o jetty:run

Python constructor and default value

class Node:
    def __init__(self, wordList=None adjacencyList=None):
        self.wordList = wordList or []
        self.adjacencyList = adjacencyList or []

Oracle copy data to another table

Creating a table and copying the data in a single command:

create table T_NEW as
  select * from T;

* This will not copy PKs, FKs, Triggers, etc.

How to check currently internet connection is available or not in android

try using ConnectivityManager

ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
    }
 return false

Also Add permission to AndroidManifest.xml

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

How to insert an object in an ArrayList at a specific position

This method Appends the specified element to the end of this list.

add(E e) //append element to the end of the arraylist.

This method Inserts the specified element at the specified position in this list.

void add(int index, E element) //inserts element at the given position in the array list.

This method Replaces the element at the specified position in this list with the specified element.

set(int index, E element) //Replaces the element at the specified position in this list with the specified element.
      

      

Why is Android Studio reporting "URI is not registered"?

Started getting this again, What actually works now is to add some rubbish inside build.gradle. Then try and sync. When it fails remove the rubbish and re-sync. After indexing, it works.

How to Get the HTTP Post data in C#?

Try this

string[] keys = Request.Form.AllKeys;
var value = "";
for (int i= 0; i < keys.Length; i++) 
{
   // here you get the name eg test[0].quantity
   // keys[i];
   // to get the value you use
   value = Request.Form[keys[i]];
}

Control the dashed border stroke length and distance between strokes

I just recently had the same problem.

I managed to solve it with two absolutely positioned divs carrying the border (one for horizontal and one for vertical), and then transforming them. The outer box just needs to be relatively positioned.

<div class="relative">
    <div class="absolute absolute--fill overflow-hidden">
        <div class="absolute absolute--fill b--dashed b--red"
            style="
                border-width: 4px 0px 4px 0px;
                transform: scaleX(2);
        "></div>
        <div class="absolute absolute--fill b--dashed b--red"
            style="
                border-width: 0px 4px 0px 4px;
                transform: scaleY(2);
        "></div>
    </div>

    <div> {{Box content goes here}} </div>
</div>

Note: i used tachyons in this example, but i guess the classes are kind of self-explanatory.

Visual Studio Code how to resolve merge conflicts with git?

  1. Click "Source Control" button on left.
  2. See MERGE CHANGES in sidebar.
  3. Those files have merge conflicts.

VS Code > Source Control > Merge Changes (Example)

ProgressDialog spinning circle

Try this.........

ProgressDialog pd1;
pd1=new ProgressDialog(<current context reference here>);
pd1.setMessage("Loading....");
pd1.setCancelable(false);
pd1.show();

To dismiss....

if(pd1!=null)
 pd1.dismiss(); 

Refresh (reload) a page once using jQuery?

$('#div-id').click(function(){

   location.reload();
        });

This is the correct syntax.

$('#div-id').html(newContent); //This doesnt work

Making an asynchronous task in Flask

Threading is another possible solution. Although the Celery based solution is better for applications at scale, if you are not expecting too much traffic on the endpoint in question, threading is a viable alternative.

This solution is based on Miguel Grinberg's PyCon 2016 Flask at Scale presentation, specifically slide 41 in his slide deck. His code is also available on github for those interested in the original source.

From a user perspective the code works as follows:

  1. You make a call to the endpoint that performs the long running task.
  2. This endpoint returns 202 Accepted with a link to check on the task status.
  3. Calls to the status link returns 202 while the taks is still running, and returns 200 (and the result) when the task is complete.

To convert an api call to a background task, simply add the @async_api decorator.

Here is a fully contained example:

from flask import Flask, g, abort, current_app, request, url_for
from werkzeug.exceptions import HTTPException, InternalServerError
from flask_restful import Resource, Api
from datetime import datetime
from functools import wraps
import threading
import time
import uuid

tasks = {}

app = Flask(__name__)
api = Api(app)


@app.before_first_request
def before_first_request():
    """Start a background thread that cleans up old tasks."""
    def clean_old_tasks():
        """
        This function cleans up old tasks from our in-memory data structure.
        """
        global tasks
        while True:
            # Only keep tasks that are running or that finished less than 5
            # minutes ago.
            five_min_ago = datetime.timestamp(datetime.utcnow()) - 5 * 60
            tasks = {task_id: task for task_id, task in tasks.items()
                     if 'completion_timestamp' not in task or task['completion_timestamp'] > five_min_ago}
            time.sleep(60)

    if not current_app.config['TESTING']:
        thread = threading.Thread(target=clean_old_tasks)
        thread.start()


def async_api(wrapped_function):
    @wraps(wrapped_function)
    def new_function(*args, **kwargs):
        def task_call(flask_app, environ):
            # Create a request context similar to that of the original request
            # so that the task can have access to flask.g, flask.request, etc.
            with flask_app.request_context(environ):
                try:
                    tasks[task_id]['return_value'] = wrapped_function(*args, **kwargs)
                except HTTPException as e:
                    tasks[task_id]['return_value'] = current_app.handle_http_exception(e)
                except Exception as e:
                    # The function raised an exception, so we set a 500 error
                    tasks[task_id]['return_value'] = InternalServerError()
                    if current_app.debug:
                        # We want to find out if something happened so reraise
                        raise
                finally:
                    # We record the time of the response, to help in garbage
                    # collecting old tasks
                    tasks[task_id]['completion_timestamp'] = datetime.timestamp(datetime.utcnow())

                    # close the database session (if any)

        # Assign an id to the asynchronous task
        task_id = uuid.uuid4().hex

        # Record the task, and then launch it
        tasks[task_id] = {'task_thread': threading.Thread(
            target=task_call, args=(current_app._get_current_object(),
                               request.environ))}
        tasks[task_id]['task_thread'].start()

        # Return a 202 response, with a link that the client can use to
        # obtain task status
        print(url_for('gettaskstatus', task_id=task_id))
        return 'accepted', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
    return new_function


class GetTaskStatus(Resource):
    def get(self, task_id):
        """
        Return status about an asynchronous task. If this request returns a 202
        status code, it means that task hasn't finished yet. Else, the response
        from the task is returned.
        """
        task = tasks.get(task_id)
        if task is None:
            abort(404)
        if 'return_value' not in task:
            return '', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
        return task['return_value']


class CatchAll(Resource):
    @async_api
    def get(self, path=''):
        # perform some intensive processing
        print("starting processing task, path: '%s'" % path)
        time.sleep(10)
        print("completed processing task, path: '%s'" % path)
        return f'The answer is: {path}'


api.add_resource(CatchAll, '/<path:path>', '/')
api.add_resource(GetTaskStatus, '/status/<task_id>')


if __name__ == '__main__':
    app.run(debug=True)

Calling an executable program using awk

A much more robust way would be to use the getline() function of GNU awk to use a variable from a pipe. In form cmd | getline result, cmd is run, then its output is piped to getline. It returns 1 if got output, 0 if EOF, -1 on failure.

First construct the command to run in a variable in the BEGIN clause if the command is not dependant on the contents of the file, e.g. a simple date or an ls.

A simple example of the above would be

awk 'BEGIN {
    cmd = "ls -lrth"
    while ( ( cmd | getline result ) > 0 ) {
        print result
    }
    close(cmd);
}'

When the command to run is part of the columnar content of a file, you generate the cmd string in the main {..} as below. E.g. consider a file whose $2 contains the name of the file and you want it to be replaced with the md5sum hash content of the file. You can do

awk '{ cmd = "md5sum "$2
       while ( ( cmd | getline md5result ) > 0 ) { 
           $2 = md5result
       }
       close(cmd);
 }1'

Another frequent usage involving external commands in awk is during date processing when your awk does not support time functions out of the box with mktime(), strftime() functions.

Consider a case when you have Unix EPOCH timestamp stored in a column and you want to convert that to a human readable date format. Assuming GNU date is available

awk '{ cmd = "date -d @" $1 " +\"%d-%m-%Y %H:%M:%S\"" 
       while ( ( cmd | getline fmtDate) > 0 ) { 
           $1 = fmtDate
       }
       close(cmd);
}1' 

for an input string as

1572608319 foo bar zoo

the above command produces an output as

01-11-2019 07:38:39 foo bar zoo

The command can be tailored to modify the date fields on any of the columns in a given line. Note that -d is a GNU specific extension, the *BSD variants support -f ( though not exactly similar to -d).

More information about getline can be referred to from this AllAboutGetline article at awk.freeshell.org page.

BigDecimal setScale and round

There is indeed a big difference, which you should keep in mind. setScale really set the scale of your number whereas round does round your number to the specified digits BUT it "starts from the leftmost digit of exact result" as mentioned within the jdk. So regarding your sample the results are the same, but try 0.0034 instead. Here's my note about that on my blog:

http://araklefeistel.blogspot.com/2011/06/javamathbigdecimal-difference-between.html

Run javascript function when user finishes typing instead of on key up?

Declare the following delay function:

var delay = (function () {
    var timer = 0;
    return function (callback, ms) {
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    };
})()

and then use it:

let $filter = $('#item-filter');
$filter.on('keydown', function () {
    delay(function () {            
        console.log('this will hit, once user has not typed for 1 second');            
    }, 1000);
});    

Error while sending QUERY packet

I encountered a rare edge case in cygwin, where I would get this error when doing exec('rsync'); somewhere before the query. Might be a general PHP problem, but I could only reproduce this in cygwin with rsync.

$pdo = new PDO('mysql:host=127.0.0.1;dbname=mysql', 'root');
var_dump($pdo->query('SELECT * FROM db'));
exec('rsync');
var_dump($pdo->query('SELECT * FROM db'));

produces

object(PDOStatement)#2 (1) {
   ["queryString"]=>
   string(16) "SELECT * FROM db"
}
PHP Warning:  Error while sending QUERY packet. PID=15036 in test.php on line 5
bool(false)

Bug reported in https://cygwin.com/ml/cygwin/2017-05/msg00272.html

Remove duplicates from a list of objects based on property in Java 8

Try this code:

Collection<Employee> nonDuplicatedEmployees = employees.stream()
   .<Map<Integer, Employee>> collect(HashMap::new,(m,e)->m.put(e.getId(), e), Map::putAll)
   .values();

ImportError: No module named mysql.connector using Python2

In my case i already installed the package

pip install mysql-connector
pip install mysql-connector-python

It giving me the same error so, i uninstall the both package by using

pip uninstall mysql-connector
pip uninstall mysql-connector-python

and then again install the second package only

pip install mysql-connector-python

This solution worked for me.

I can't install intel HAXM

I think that you would install Android SDK files not in (your PC)\Appdata\Local\Android\sdk (default Path). Also there was nothing when you double click 'intelhaxm-android.exe' file.

If it was, Browse (your PC)\Appdata\Local\Temp\intel\HAXM\6.0.3(yyyy-mm-dd_hh_mm_ss) (or silent), then you must see 'hax64' (or hax) file, and simply invoke this file.

How to 'foreach' a column in a DataTable using C#?

Something like this:

 DataTable dt = new DataTable();

 // For each row, print the values of each column.
    foreach(DataRow row in dt .Rows)
    {
        foreach(DataColumn column in dt .Columns)
        {
            Console.WriteLine(row[column]);
        }
    }

http://msdn.microsoft.com/en-us/library/system.data.datatable.rows.aspx

Verify a certificate chain using openssl verify

From verify documentation:

If a certificate is found which is its own issuer it is assumed to be the root CA.

In other words, root CA needs to self signed for verify to work. This is why your second command didn't work. Try this instead:

openssl verify -CAfile RootCert.pem -untrusted Intermediate.pem UserCert.pem

It will verify your entire chain in a single command.

Seeing the underlying SQL in the Spring JdbcTemplate?

This works for me with org.springframework.jdbc-3.0.6.RELEASE.jar. I could not find this anywhere in the Spring docs (maybe I'm just lazy) but I found (trial and error) that the TRACE level did the magic.

I'm using log4j-1.2.15 along with slf4j (1.6.4) and properties file to configure the log4j:

log4j.logger.org.springframework.jdbc.core = TRACE

This displays both the SQL statement and bound parameters like this:

Executing prepared SQL statement [select HEADLINE_TEXT, NEWS_DATE_TIME from MY_TABLE where PRODUCT_KEY = ? and NEWS_DATE_TIME between ? and ? order by NEWS_DATE_TIME]
Setting SQL statement parameter value: column index 1, parameter value [aaa], value class [java.lang.String], SQL type unknown
Setting SQL statement parameter value: column index 2, parameter value [Thu Oct 11 08:00:00 CEST 2012], value class [java.util.Date], SQL type unknown
Setting SQL statement parameter value: column index 3, parameter value [Thu Oct 11 08:00:10 CEST 2012], value class [java.util.Date], SQL type unknown

Not sure about the SQL type unknown but I guess we can ignore it here

For just an SQL (i.e. if you're not interested in bound parameter values) DEBUG should be enough.

Origin null is not allowed by Access-Control-Allow-Origin

Just wanted to add that the "run a webserver" answer seems quite daunting, but if you have python on your system (installed by default at least on MacOS and any Linux distribution) it's as easy as:

python -m http.server  # with python3

or

python -m SimpleHTTPServer  # with python2

So if you have your html file myfile.html in a folder, say mydir, all you have to do is:

cd /path/to/mydir
python -m http.server  # or the python2 alternative above

Then point your browser to:

http://localhost:8000/myfile.html

And you are done! Works on all browsers, without disabling web security, allowing local files, or even restarting the browser with command line options.

C function that counts lines in file

You declare

int countlines(char *filename)

to take a char * argument.

You call it like this

countlines(fp)

passing in a FILE *.

That is why you get that compile error.

You probably should change that second line to

countlines("Test.txt")

since you open the file in countlines

Your current code is attempting to open the file in two different places.

How do I declare class-level properties in Objective-C?

Starting from Xcode 8, you can use the class property attribute as answered by Berbie.

However, in the implementation, you need to define both class getter and setter for the class property using a static variable in lieu of an iVar.

Sample.h

@interface Sample: NSObject
@property (class, retain) Sample *sharedSample;
@end

Sample.m

@implementation Sample
static Sample *_sharedSample;
+ ( Sample *)sharedSample {
   if (_sharedSample==nil) {
      [Sample setSharedSample:_sharedSample];
   }
   return _sharedSample;
}

+ (void)setSharedSample:(Sample *)sample {
   _sharedSample = [[Sample alloc]init];
}
@end

How to list only files and not directories of a directory Bash?

You can also use ls with grep or egrep and put it in your profile as an alias:

ls -l | egrep -v '^d'
ls -l | grep -v '^d'

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

How to change symbol for decimal point in double.ToString()?

Convert.ToString(value, CultureInfo.InvariantCulture);

Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

You can define a function type in interface in various ways,

  1. general way:
export interface IParam {
  title: string;
  callback(arg1: number, arg2: number): number;
}
  1. If you would like to use property syntax then,
export interface IParam {
  title: string;
  callback: (arg1: number, arg2: number) => number;
}
  1. If you declare the function type first then,
type MyFnType = (arg1: number, arg2: number) => number;

export interface IParam {
  title: string;
  callback: MyFnType;
}

Using is very straight forward,

function callingFn(paramInfo: IParam):number {
    let needToCall = true;
    let result = 0;
   if(needToCall){
     result = paramInfo.callback(1,2);
    }

    return result;
}
  1. You can declare a function type literal also , which mean a function can accept another function as it's parameter. parameterize function can be called as callback also.
export interface IParam{
  title: string;
  callback(lateCallFn?:
             (arg1:number,arg2:number)=>number):number;

}

How to assign Php variable value to Javascript variable?

The most secure way (in terms of special character and data type handling) is using json_encode():

var spge = <?php echo json_encode($cname); ?>;

Error : ORA-01704: string literal too long

The split work until 4000 chars depending on the characters that you are inserting. If you are inserting special characters it can fail. The only secure way is to declare a variable.

PHP class: Global variable as property in class

Try to avoid globals, instead you can use something like this

class myClass() {
 private $myNumber;

 public function setNumber($number) {
  $this->myNumber = $number;
 }
}

Now you can call

$class = new myClass();
$class->setNumber('1234');

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

If you use jCanvas library you can use opacity property when drawing. If you need fade effect on top of that, simply redraw with different values.

C++ pass an array by reference

Yes, but when argument matching for a reference, the implicit array to pointer isn't automatic, so you need something like:

void foo( double (&array)[42] );

or

void foo( double (&array)[] );

Be aware, however, that when matching, double [42] and double [] are distinct types. If you have an array of an unknown dimension, it will match the second, but not the first, and if you have an array with 42 elements, it will match the first but not the second. (The latter is, IMHO, very counter-intuitive.)

In the second case, you'll also have to pass the dimension, since there's no way to recover it once you're inside the function.

XSL xsl:template match="/"

The match attribute indicates on which parts the template transformation is going to be applied. In that particular case the "/" means the root of the xml document. The value you have to provide into the match attribute should be XPath expression. XPath is the language you have to use to refer specific parts of the target xml file.

To gain a meaningful understanding of what else you can put into match attribute you need to understand what xpath is and how to use it. I suggest yo look at links I've provided for youat the bottom of the answer.

Could I write "table" or any other html tag instead of "/" ?

Yes you can. But this depends what exactly you are trying to do. if your target xml file contains HMTL elements and you are triyng to apply this xsl:template on them it makes sense to use table, div or anithing else.

Here a few links:

Parsing JSON using C

Do you need to parse arbitrary JSON structures, or just data that's specific to your application. If the latter, you can make it a lot lighter and more efficient by not having to generate any hash table/map structure mapping JSON keys to values; you can instead just store the data directly into struct fields or whatever.

How to generate the JPA entity Metamodel?

For eclipselink, only the following dependency is sufficient to generate metamodel. Nothing else is needed.

    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
        <version>2.5.1</version>
        <scope>provided</scope>
    </dependency>

What is default color for text in textview?

It may not be possible in all situations, but why not simply use the value of a different random TextView that exists in the same Activity and that carries the colour you are looking for?

txtOk.setTextColor(txtSomeOtherText.getCurrentTextColor());

Fatal error: [] operator not supported for strings

Such behavior is described in Migrating from PHP 7.0.x to PHP 7.1.x/

The empty index operator is not supported for strings anymore Applying the empty index operator to a string (e.g. $str[] = $x) throws a fatal error instead of converting silently to array.

In my case it was a mere initialization. I fixed it by replacing $foo='' with $foo=[].

$foo='';
$foo[]='test';
print_r($foo);

How to iterate through LinkedHashMap with lists as values

I'm assuming you have a typo in your get statement and that it should be test1.get(key). If so, I'm not sure why it is not returning an ArrayList unless you are not putting in the correct type in the map in the first place.

This should work:

// populate the map
Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.put("key1", new ArrayList<String>());
test1.put("key2", new ArrayList<String>());

// loop over the set using an entry set
for( Map.Entry<String,List<String>> entry : test1.entrySet()){
  String key = entry.getKey();
  List<String>value = entry.getValue();
  // ...
}

or you can use

// second alternative - loop over the keys and get the value per key
for( String key : test1.keySet() ){
  List<String>value = test1.get(key);
  // ...
}

You should use the interface names when declaring your vars (and in your generic params) unless you have a very specific reason why you are defining using the implementation.

Java - What does "\n" mean?

\n is an escape character for strings that is replaced with the new line object. Writing \n in a string that prints out will print out a new line instead of the \n

Java Escape Characters

How to remove unwanted space between rows and columns in table?

For images in td, use this for images:

display: block;

That removes unwanted space for me

Access nested dictionary items via a list of keys?

Pure Python style, without any import:

def nested_set(element, value, *keys):
    if type(element) is not dict:
        raise AttributeError('nested_set() expects dict as first argument.')
    if len(keys) < 2:
        raise AttributeError('nested_set() expects at least three arguments, not enough given.')

    _keys = keys[:-1]
    _element = element
    for key in _keys:
        _element = _element[key]
    _element[keys[-1]] = value

example = {"foo": { "bar": { "baz": "ok" } } }
keys = ['foo', 'bar']
nested_set(example, "yay", *keys)
print(example)

Output

{'foo': {'bar': 'yay'}}

"Default Activity Not Found" on Android Studio upgrade

@TouchBoarder almost had it. Although selecting "Do not launch Activity" results in nothing launching.

In Android Studio under Run/Debug Configuration -> Android Application -> General -> Activity -> select the option "Launch:"

Choose your Activity. This doesn't exactly fix the intended behaviour but rather overrides it correctly.

Edit run/debug configurations and specify launch activity

Html attributes for EditorFor() in ASP.NET MVC

EditorFor works with metadata, so if you want to add html attributes you could always do it. Another option is to simply write a custom template and use TextBoxFor:

<%= Html.TextBoxFor(model => model.Control.PeriodType, 
    new { disabled = "disabled", @readonly = "readonly" }) %>    

C# List<string> to string with delimiter

You can use String.Join. If you have a List<string> then you can call ToArray first:

List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join(", ", names.ToArray());

In .NET 4 you don't need the ToArray anymore, since there is an overload of String.Join that takes an IEnumerable<string>.

Results:


John, Anna, Monica

How to find specified name and its value in JSON-string from Java?

Gson allows for one of the simplest possible solutions. Compared to similar APIs like Jackson or svenson, Gson by default doesn't even need the unused JSON elements to have bindings available in the Java structure. Specific to the question asked, here's a working solution.

import com.google.gson.Gson;

public class Foo
{
  static String jsonInput = 
    "{" + 
      "\"name\":\"John\"," + 
      "\"age\":\"20\"," + 
      "\"address\":\"some address\"," + 
      "\"someobject\":" +
      "{" + 
        "\"field\":\"value\"" + 
      "}" + 
    "}";

  String age;

  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    Foo thing = gson.fromJson(jsonInput, Foo.class);
    if (thing.age != null)
    {
      System.out.println("age is " + thing.age);
    }
    else
    {
      System.out.println("age element not present or value is null");
    }
  }
}

Append String in Swift

You can simply append string like:

var worldArg = "world is good"

worldArg += " to live";

How to display two digits after decimal point in SQL Server

You can also do something much shorter:

SELECT FORMAT(2.3332232,'N2')

How to fix "unable to write 'random state' " in openssl

I did not find where the .rnd file is so I ran the cmd as administrator and it worked like a charm.

onclick open window and specific size

<a href="/index2.php?option=com_jumi&amp;fileid=3&amp;Itemid=11"
   onclick="window.open(this.href,'targetWindow',
                                   `toolbar=no,
                                    location=no,
                                    status=no,
                                    menubar=no,
                                    scrollbars=yes,
                                    resizable=yes,
                                    width=SomeSize,
                                    height=SomeSize`);
 return false;">Popup link</a>

Where width and height are pixels without units (width=400 not width=400px).

In most browsers it will not work if it is not written without line breaks, once the variables are setup have everything in one line:

<a href="/index2.php?option=com_jumi&amp;fileid=3&amp;Itemid=11" onclick="window.open(this.href,'targetWindow','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=SomeSize,height=SomeSize'); return false;">Popup link</a> 

How to append contents of multiple files into one file

If all your files are named similarly you could simply do:

cat *.log >> output.log

Why aren't python nested functions called closures?

I had a situation where I needed a separate but persistent name space. I used classes. I don't otherwise. Segregated but persistent names are closures.

>>> class f2:
...     def __init__(self):
...         self.a = 0
...     def __call__(self, arg):
...         self.a += arg
...         return(self.a)
...
>>> f=f2()
>>> f(2)
2
>>> f(2)
4
>>> f(4)
8
>>> f(8)
16

# **OR**
>>> f=f2() # **re-initialize**
>>> f(f(f(f(2)))) # **nested**
16

# handy in list comprehensions to accumulate values
>>> [f(i) for f in [f2()] for i in [2,2,4,8]][-1] 
16

Valid values for android:fontFamily and what they map to?

As far as I'm aware, you can't declare custom fonts in xml or themes. I usually just make custom classes extending textview that set their own font on instantiation and use those in my layout xml files.

ie:

public class Museo500TextView extends TextView {
    public Museo500TextView(Context context, AttributeSet attrs) {
        super(context, attrs);      
        this.setTypeface(Typeface.createFromAsset(context.getAssets(), "path/to/font.ttf"));
    }
}

and

<my.package.views.Museo900TextView
        android:id="@+id/dialog_error_text_header"
        android:layout_width="190dp"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textSize="12sp" />

How to round up the result of integer division?

The following should do rounding better than the above solutions, but at the expense of performance (due to floating point calculation of 0.5*rctDenominator):

uint64_t integerDivide( const uint64_t& rctNumerator, const uint64_t& rctDenominator )
{
  // Ensure .5 upwards is rounded up (otherwise integer division just truncates - ie gives no remainder)
  return (rctDenominator == 0) ? 0 : (rctNumerator + (int)(0.5*rctDenominator)) / rctDenominator;
}

SQL DELETE with JOIN another table for WHERE condition

I think, from your description, the following would suffice:

DELETE FROM guide_category 
WHERE id_guide NOT IN (SELECT id_guide FROM guide)

I assume, that there are no referential integrity constraints on the tables involved, are there?

What is HTML5 ARIA?

What is ARIA?

ARIA emerged as a way to address the accessibility problem of using a markup language intended for documents, HTML, to build user interfaces (UI). HTML includes a great many features to deal with documents (P, h3,UL,TABLE) but only basic UI elements such as A, INPUT and BUTTON. Windows and other operating systems support APIs that allow (Assistive Technology) AT to access the functionality of UI controls. Internet Explorer and other browsers map the native HTML elements to the accessibility API, but the html controls are not as rich as the controls common on desktop operating systems, and are not enough for modern web applications Custom controls can extend html elements to provide the rich UI needed for modern web applications. Before ARIA, the browser had no way to expose this extra richness to the accessibility API or AT. The classic example of this issue is adding a click handler to an image. It creates what appears to be a clickable button to a mouse user, but is still just an image to a keyboard or AT user.

The solution was to create a set of attributes that allow developers to extend HTML with UI semantics. The ARIA term for a group of HTML elements that have custom functionality and use ARIA attributes to map these functions to accessibility APIs is a “Widget. ARIA also provides a means for authors to document the role of content itself, which in turn, allows AT to construct alternate navigation mechanisms for the content that are much easier to use than reading the full text or only iterating over a list of the links.

It is important to remember that in simple cases, it is much preferred to use native HTML controls and style them rather than using ARIA. That is don’t reinvent wheels, or checkboxes, if you don’t have to.

Fortunately, ARIA markup can be added to existing sites without changing the behavior for mainstream users. This greatly reduces the cost of modifying and testing the website or application.

Best way to display data via JSON using jQuery

You can create a jQuery object from a JSON object:

$.getJSON(url, data, function(json) {
    $(json).each(function() {
        /* YOUR CODE HERE */
    });
});

Postgres password authentication fails

Assuming, that you have root access on the box you can do:

sudo -u postgres psql

If that fails with a database "postgres" does not exists this block.

sudo -u postgres psql template1

Then sudo nano /etc/postgresql/11/main/pg_hba.conf file

local   all         postgres                          ident

For newer versions of PostgreSQL ident actually might be peer.

Inside the psql shell you can give the DB user postgres a password:

ALTER USER postgres PASSWORD 'newPassword';

How do I make WRAP_CONTENT work on a RecyclerView

From Android Support Library 23.2.1 update, all WRAP_CONTENT should work correctly.

Please update version of a library in gradle file OR to further :

compile 'com.android.support:recyclerview-v7:23.2.1'

solved some issue like Fixed bugs related to various measure-spec methods

Check http://developer.android.com/tools/support-library/features.html#v7-recyclerview

you can check Support Library revision history

Why can't I inherit static classes?

Hmmm... would it be much different if you just had non-static classes filled with static methods..?

What is the main difference between PATCH and PUT request?

Put and Patch method are similar . But in rails it has different metod If we want to update/replace whole record then we have to use Put method. If we want to update particular record use Patch method.

how to align text vertically center in android

In relative layout you need specify textview height:

android:layout_height="100dp"

Or specify lines attribute:

android:lines="3"

Batch file script to zip files

No external dependency on 7zip or ZIP - create a vbs script and execute:

    @ECHO Zipping
    mkdir %TEMPDIR%
    xcopy /y /s %FILETOZIP% %TEMPDIR%
    echo Set objArgs = WScript.Arguments > _zipIt.vbs
    echo InputFolder = objArgs(0) >> _zipIt.vbs
    echo ZipFile = objArgs(1) >> _zipIt.vbs
    echo CreateObject("Scripting.FileSystemObject").CreateTextFile(ZipFile, True).Write "PK" ^& Chr(5) ^& Chr(6) ^& String(18, vbNullChar) >> _zipIt.vbs
    echo Set objShell = CreateObject("Shell.Application") >> _zipIt.vbs
    echo Set source = objShell.NameSpace(InputFolder).Items >> _zipIt.vbs
    echo objShell.NameSpace(ZipFile).CopyHere(source) >> _zipIt.vbs
    @ECHO *******************************************
    @ECHO Zipping, please wait..
    echo wScript.Sleep 12000 >> _zipIt.vbs
    CScript  _zipIt.vbs  %TEMPDIR%  %OUTPUTZIP%
    del _zipIt.vbs
    rmdir /s /q  %TEMPDIR%

    @ECHO *******************************************
    @ECHO      ZIP Completed

What's the key difference between HTML 4 and HTML 5?

HTML5 has several goals which differentiate it from HTML4.

Consistency in Handling Malformed Documents

The primary one is consistent, defined error handling. As you know, HTML purposely supports 'tag soup', or the ability to write malformed code and have it corrected into a valid document. The problem is that the rules for doing this aren't written down anywhere. When a new browser vendor wants to enter the market, they just have to test malformed documents in various browsers (especially IE) and reverse-engineer their error handling. If they don't, then many pages won't display correctly (estimates place roughly 90% of pages on the net as being at least somewhat malformed).

So, HTML5 is attempting to discover and codify this error handling, so that browser developers can all standardize and greatly reduce the time and money required to display things consistently. As well, long in the future after HTML has died as a document format, historians may still want to read our documents, and having a completely defined parsing algorithm will greatly aid this.

Better Web Application Features

The secondary goal of HTML5 is to develop the ability of the browser to be an application platform, via HTML, CSS, and Javascript. Many elements have been added directly to the language that are currently (in HTML4) Flash or JS-based hacks, such as <canvas>, <video>, and <audio>. Useful things such as Local Storage (a js-accessible browser-built-in key-value database, for storing information beyond what cookies can hold), new input types such as date for which the browser can expose easy user interface (so that we don't have to use our js-based calendar date-pickers), and browser-supported form validation will make developing web applications much simpler for the developers, and make them much faster for the users (since many things will be supported natively, rather than hacked in via javascript).

Improved Element Semantics

There are many other smaller efforts taking place in HTML5, such as better-defined semantic roles for existing elements (<strong> and <em> now actually mean something different, and even <b> and <i> have vague semantics that should work well when parsing legacy documents) and adding new elements with useful semantics - <article>, <section>, <header>, <aside>, and <nav> should replace the majority of <div>s used on a web page, making your pages a bit more semantic, but more importantly, easier to read. No more painful scanning to see just what that random </div> is closing - instead you'll have an obvious </header>, or </article>, making the structure of your document much more intuitive.

How to change the font color of a disabled TextBox?

You can try this. Override the OnPaint event of the TextBox.

    protected override void OnPaint(PaintEventArgs e)
{
     SolidBrush drawBrush = new SolidBrush(ForeColor); //Use the ForeColor property
     // Draw string to screen.
     e.Graphics.DrawString(Text, Font, drawBrush, 0f,0f); //Use the Font property
}

set the ControlStyles to "UserPaint"

public MyTextBox()//constructor
{
     // This call is required by the Windows.Forms Form Designer.
     this.SetStyle(ControlStyles.UserPaint,true);

     InitializeComponent();

     // TODO: Add any initialization after the InitForm call
}

Refrence

Or you can try this hack

In Enter event set the focus

int index=this.Controls.IndexOf(this.textBox1);

this.Controls[index-1].Focus();

So your control will not focussed and behave like disabled.

Sending data through POST request from a node.js server to a node.js server

Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?) as the request body.

This requires Content-Type and Content-Length headers, so the receiving server knows how to interpret the incoming data. (*)

var querystring = require('querystring');
var http = require('http');

var data = querystring.stringify({
      username: yourUsernameValue,
      password: yourPasswordValue
    });

var options = {
    host: 'my.url',
    port: 80,
    path: '/login',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(data)
    }
};

var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log("body: " + chunk);
    });
});

req.write(data);
req.end();

(*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded for the traditional format that a standard HTML form would use.

It's easy to send JSON (application/json) in exactly the same manner; just JSON.stringify() the data beforehand.

URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.

The bottom line is: The server must be able to interpret the content type in question. It could be text/plain or anything else; there is no need to convert data if the receiving server understands it as it is.

Add a charset parameter (e.g. application/json; charset=Windows-1252) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.

lambda expression join multiple tables with select and where clause

I was looking for something and I found this post. I post this code that managed many-to-many relationships in case someone needs it.

    var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
    .Select (m => new 
    {
        UserName = u.UserProfile.UserName,
        RoleName = u.Roles.RoleName
    });

How do I put a variable inside a string?

Not sure exactly what all the code you posted does, but to answer the question posed in the title, you can use + as the normal string concat function as well as str().

"hello " + str(10) + " world" = "hello 10 world"

Hope that helps!

Select value from list of tuples where condition

If you have named tuples you can do this:

results = [t.age for t in mylist if t.person_id == 10]

Otherwise use indexes:

results = [t[1] for t in mylist if t[0] == 10]

Or use tuple unpacking as per Nate's answer. Note that you don't have to give a meaningful name to every item you unpack. You can do (person_id, age, _, _, _, _) to unpack a six item tuple.

Why do I get permission denied when I try use "make" to install something?

The problem is frequently with 'secure' setup of mountpoints, such as /tmp

If they are mounted noexec (check with cat /etc/mtab and or sudo mount) then there is no permission to execute any binaries or build scripts from within the (temporary) folder.

E.g. to remount temporarily:

 sudo mount -o remount,exec /tmp

Or to change permanently, remove noexec in /etc/fstab

How can I parse a time string containing milliseconds in it with python?

I know this is an older question but I'm still using Python 2.4.3 and I needed to find a better way of converting the string of data to a datetime.

The solution if datetime doesn't support %f and without needing a try/except is:

    (dt, mSecs) = row[5].strip().split(".") 
    dt = datetime.datetime(*time.strptime(dt, "%Y-%m-%d %H:%M:%S")[0:6])
    mSeconds = datetime.timedelta(microseconds = int(mSecs))
    fullDateTime = dt + mSeconds 

This works for the input string "2010-10-06 09:42:52.266000"

Javascript change Div style

you may check the color before you click to change it.

function abc(){
     var color = document.getElementById("test").style.color;
     if(color==''){
         //change
     }else{
         //change back
     }
}

What does -z mean in Bash?

-z string True if the string is null (an empty string)

Plain Old CLR Object vs Data Transfer Object

POCO is simply an object that does not take a dependency on an external framework. It is PLAIN.

Whether a POCO has behaviour or not it's immaterial.

A DTO may be POCO as may a domain object (which would typically be rich in behaviour).

Typically DTOs are more likely to take dependencies on external frameworks (eg. attributes) for serialisation purposes as typically they exit at the boundary of a system.

In typical Onion style architectures (often used within a broadly DDD approach) the domain layer is placed at the centre and so its objects should not, at this point, have dependencies outside of that layer.

Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

In XML, xmlns declares a Namespace. In fact, when you do:

<LinearLayout android:id>
</LinearLayout>

Instead of calling android:id, the xml will use http://schemas.android.com/apk/res/android:id to be unique. Generally this page doesn't exist (it's a URI, not a URL), but sometimes it is a URL that explains the used namespace.

The namespace has pretty much the same uses as the package name in a Java application.

Here is an explanation.

Uniform Resource Identifier (URI)

A Uniform Resource Identifier (URI) is a string of characters which identifies an Internet Resource.

The most common URI is the Uniform Resource Locator (URL) which identifies an Internet domain address. Another, not so common type of URI is the Universal Resource Name (URN).

In our examples we will only use URLs.

When should I write the keyword 'inline' for a function/method?

You want to put it in the very beginning, before return type. But most Compilers ignore it. If it's defined, and it has a smaller block of code, most compilers consider it inline anyway.

Want to upgrade project from Angular v5 to Angular v6

This is how I make it work.

My Environment:

Angular CLI Global : 6.0.0, Local: 1.7.4, Angular: 5.2, Typescript 2.5.3

Note: To enable ng Update you need to install Angular CLI 6.0 first npm install -g @angular/cli or npm install @angular/cli

  1. ng update //update Angular Package core/common/complier... to 6.0.0

  2. ng update @angular/cli //change angular-cli.json to angular.json

optional if you have angular-material 5.4.2, ngx-translate 9.1.1, ng-bootstrap/ng-bootstrap 1.1.1:

  1. ng update @angular/material //upgrade to 6.0.1

  2. npm install @ngx-translate/[email protected] --save //upgrade ngX translate to 10.0.1 for Angular 6

5 npm install --save @ng-bootstrap/[email protected] //for ng-bootstrap

If you use Observable and get the error:

ERROR in node_modules/rxjs/Observable.d.ts(1,15): error TS2307: Cannot find module 'rxjs-compat/Observable'. node_modules/rxjs/observable/of.d.ts(1,15): error TS2307: Cannot find module 'rxjs-compat/observable/of'.

Change: import { Observable } from "rxjs/Observable"; import { of } from 'rxjs/observable/of';

To

import { Observable, of } from "rxjs";

Angular CLI issue: https://github.com/angular/angular-cli/issues/10621

How do I do top 1 in Oracle?

With Oracle 12c (June 2013), you are able to use it like the following.

SELECT * FROM   MYTABLE
--ORDER BY COLUMNNAME -OPTIONAL          
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY

How to get the current time in milliseconds in C Programming

quick answer

#include<stdio.h>   
#include<time.h>   

int main()   
{   
    clock_t t1, t2;  
    t1 = clock();   
    int i;
    for(i = 0; i < 1000000; i++)   
    {   
        int x = 90;  
    }   

    t2 = clock();   

    float diff = ((float)(t2 - t1) / 1000000.0F ) * 1000;   
    printf("%f",diff);   

    return 0;   
}

Add User to Role ASP.NET Identity

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

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

First make sure you have Roles inserted.

enter image description here

And second test it on user register method.

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

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

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

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

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

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

Creating the checkbox dynamically using JavaScript?

   /* worked for me  */
     <div id="divid"> </div>
     <script type="text/javascript">
         var hold = document.getElementById("divid");
         var checkbox = document.createElement('input');
         checkbox.type = "checkbox";
         checkbox.name = "chkbox1";
         checkbox.id = "cbid";
         var label = document.createElement('label');
         var tn = document.createTextNode("Not A RoBot");
         label.htmlFor="cbid";
         label.appendChild(tn); 
         hold.appendChild(label);
         hold.appendChild(checkbox);
      </script>  

How do I print uint32_t and uint16_t variables value?

The macros defined in <inttypes.h> are the most correct way to print values of types uint32_t, uint16_t, and so forth -- but they're not the only way.

Personally, I find those macros difficult to remember and awkward to use. (Given the syntax of a printf format string, that's probably unavoidable; I'm not claiming I could have come up with a better system.)

An alternative is to cast the values to a predefined type and use the format for that type.

Types int and unsigned int are guaranteed by the language to be at least 16 bits wide, and therefore to be able to hold any converted value of type int16_t or uint16_t, respectively. Similarly, long and unsigned long are at least 32 bits wide, and long long and unsigned long long are at least 64 bits wide.

For example, I might write your program like this (with a few additional tweaks):

#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>  

int main(void)
{
    uint32_t a=12, a1;
    uint16_t b=1, b1;
    a1 = htonl(a);
    printf("%lu---------%lu\n", (unsigned long)a, (unsigned long)a1);
    b1 = htons(b);
    printf("%u-----%u\n", (unsigned)b, (unsigned)b1);
    return 0;
}

One advantage of this approach is that it can work even with pre-C99 implementations that don't support <inttypes.h>. Such an implementation most likely wouldn't have <stdint.h> either, but the technique is useful for other integer types.

OnClick in Excel VBA

Clearly, there is no perfect answer. However, if you want to allow the user to

  1. select certain cells
  2. allow them to change those cells, and
  3. trap each click,even repeated clicks on the same cell,

then the easiest way seems to be to move the focus off the selected cell, so that clicking it will trigger a Select event.

One option is to move the focus as I suggested above, but this prevents cell editing. Another option is to extend the selection by one cell (left/right/up/down),because this permits editing of the original cell, but will trigger a Select event if that cell is clicked again on its own.

If you only wanted to trap selection of a single column of cells, you could insert a hidden column to the right, extend the selection to include the hidden cell to the right when the user clicked,and this gives you an editable cell which can be trapped every time it is clicked. The code is as follows

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  'prevent Select event triggering again when we extend the selection below
  Application.EnableEvents = False
  Target.Resize(1, 2).Select
  Application.EnableEvents = True
End Sub