Programs & Examples On #Nsmutabledata

NSMutableData (and its superclass NSData) provide data objects, object-oriented wrappers for byte buffers. It is available in OS X v10.0 and later and available in iOS 2.0 and later .Use this tag [tag:NSMutableData] for questions referring to NSMutableData in OS X or iOS platform .

How to make an HTTP request + basic auth in Swift

I am calling the json on login button click

@IBAction func loginClicked(sender : AnyObject){

var request = NSMutableURLRequest(URL: NSURL(string: kLoginURL)) // Here, kLogin contains the Login API.


var session = NSURLSession.sharedSession()

request.HTTPMethod = "POST"

var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(self.criteriaDic(), options: nil, error: &err) // This Line fills the web service with required parameters.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
 //   println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")       
var err1: NSError?
var json2 = NSJSONSerialization.JSONObjectWithData(strData.dataUsingEncoding(NSUTF8StringEncoding), options: .MutableLeaves, error:&err1 ) as NSDictionary

println("json2 :\(json2)")

if(err) {
    println(err!.localizedDescription)
}
else {
    var success = json2["success"] as? Int
    println("Succes: \(success)")
}
})

task.resume()

}

Here, I have made a seperate dictionary for the parameters.

var params = ["format":"json", "MobileType":"IOS","MIN":"f8d16d98ad12acdbbe1de647414495ec","UserName":emailTxtField.text,"PWD":passwordTxtField.text,"SigninVia":"SH"]as NSDictionary
     return params
}

NSURLConnection Using iOS Swift

Swift 3.0

AsynchonousRequest

let urlString = "http://heyhttp.org/me.json"
var request = URLRequest(url: URL(string: urlString)!)
let session = URLSession.shared

session.dataTask(with: request) {data, response, error in
  if error != nil {
    print(error!.localizedDescription)
    return
  }

  do {
    let jsonResult: NSDictionary? = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
    print("Synchronous\(jsonResult)")
  } catch {
    print(error.localizedDescription)
  }
}.resume()

self.tableView.reloadData() not working in Swift

Beside the obvious reloadData from UI/Main Thread (whatever Apple calls it), in my case, I had forgotten to also update the SECTIONS info. Therefor it did not detect any new sections!

Send POST request using NSURLSession

    use like this.....

    Create file

    #import <Foundation/Foundation.h>`    
    #import "SharedManager.h"
    #import "Constant.h"
    #import "UserDetails.h"

    @interface APISession : NSURLSession<NSURLSessionDelegate>
    @property (nonatomic, retain) NSMutableData *responseData;
    +(void)postRequetsWithParam:(NSMutableDictionary* )objDic withAPIName:(NSString* 
    )strAPIURL completionHandler:(void (^)(id result, BOOL status))completionHandler;
    @end

****************.m*************************
    #import "APISession.h"
    #import <UIKit/UIKit.h>
    @implementation APISession

    +(void)postRequetsWithParam:(NSMutableDictionary *)objDic withAPIName:(NSString 
    *)strAPIURL completionHandler:(void (^)(id, BOOL))completionHandler
    {
    NSURL *url=[NSURL URLWithString:strAPIURL];
    NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSError *err = nil;

    NSData *data=[NSJSONSerialization dataWithJSONObject:objDic options:NSJSONWritingPrettyPrinted error:&err];
    [request setHTTPBody:data];

    NSString *strJsonFormat = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"API URL: %@ \t  Api Request Parameter ::::::::::::::%@",url,strJsonFormat);
    //    NSLog(@"Request data===%@",objDic);
    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

    //  NSURLSession *session=[NSURLSession sharedSession];

    NSURLSessionTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
                            {
                                if (error==nil) {
                                    NSDictionary *dicData=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];\
                                    NSLog(@"Response Data=============%@",dicData);
                                    if([[dicData valueForKey:@"tokenExpired"]integerValue] == 1)
                                    {

                                        NSLog(@"hello");
                                        NSDictionary *dict = [NSDictionary dictionaryWithObject:@"Access Token Expire." forKey:@"message"];
                                        [[NSNotificationCenter defaultCenter] postNotificationName:@"UserLogOut" object:self userInfo:dict];
                                    }
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        completionHandler(dicData,(error == nil));
                                    });
                                    NSLog(@"%@",dicData);
                                }
                                else{
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        completionHandler(error.localizedDescription,NO);
                                    });
                                }
                            }];
    //    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [task resume];
    //    });
    }
    @end

    *****************************in .your view controller***********
    #import "file"
    txtEmail.text = [txtEmail.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

    {
            [SVProgressHUD showWithStatus:@"Loading..."];
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];

            NSMutableDictionary *objLoginDic=[[NSMutableDictionary alloc] init];
            [objLoginDic setValue:txtEmail.text forKey:@"email"];
            [objLoginDic setValue:@0            forKey:kDeviceType];
            [objLoginDic setValue:txtPassword.text forKey:kPassword];
            [objLoginDic setValue:@"376545432"  forKey:kDeviceTokan];
            [objLoginDic setValue:@""           forKey:kcountryId];
            [objLoginDic setValue:@""           forKey:kfbAccessToken];
            [objLoginDic setValue:@0            forKey:kloginType];

            [APISession postRequetsWithParam:objLoginDic withAPIName:KLOGIN_URL completionHandler:^(id result, BOOL status) {

                [SVProgressHUD dismiss];

                NSInteger statusResponse=[[result valueForKey:kStatus] integerValue];
                NSString *strMessage=[result valueForKey:KMessage];
                if (status) {
                    if (statusResponse == 1)
                {
                        UserDetails *objLoginUserDetail=[[UserDetails alloc] 
                        initWithObject:[result valueForKey:@"userDetails"]];
                          [[NSUserDefaults standardUserDefaults] 
                        setObject:@(objLoginUserDetail.userId) forKey:@"user_id"];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                        [self clearTextfeilds];
                        HomeScreen *obj=[Kiran_Storyboard instantiateViewControllerWithIdentifier:@"HomeScreen"];
                        [self.navigationController pushViewController:obj animated:YES];
                    }
                    else{
                        [strMessage showAsAlert:self];
                    }
                }
            }];
        }
**********use model class for represnt data*************

    #import <Foundation/Foundation.h>
    #import "Constant.h"
    #import <objc/runtime.h>


    @interface UserDetails : NSObject
    @property(strong,nonatomic) NSString *emailId,
    *deviceToken,
    *countryId,
    *fbAccessToken,
    *accessToken,
    *countryName,
    *isProfileSetup,
    *profilePic,
    *firstName,
    *lastName,
    *password;

    @property (assign) NSInteger userId,deviceType,loginType;

    -(id)initWithObject :(NSDictionary *)dicUserData;
    -(void)saveLoginUserDetail;
    +(UserDetails *)getLoginUserDetail;
    -(UserDetails *)getEmptyModel;
    - (NSArray *)allPropertyNames;
    -(void)printDescription;
       -(NSMutableDictionary *)getDictionary;

    @end

    ******************model.m*************

    #import "UserDetails.h"
    #import "SharedManager.h"

    @implementation UserDetails



      -(id)initWithObject :(NSDictionary *)dicUserData
       {
       self = [[UserDetails alloc] init];
       if (self)
       {
           @try {
               [self setFirstName:([dicUserData valueForKey:@"firstName"] != [NSNull null])? 
               [dicUserData valueForKey:@"firstName"]:@""];


               [self setUserId:([dicUserData valueForKey:kUserId] != [NSNull null])? 
               [[dicUserData valueForKey:kUserId] integerValue]:0];


               }
        @catch (NSException *exception) {
            NSLog(@"Exception: %@",exception.description);
        }
        @finally {
        }
    }
    return self;
}

    -(UserDetails *)getEmptyModel{
    [self setFirstName:@""];
    [self setLastName:@""];



    [self setDeviceType:0];


    return self;
       }

     -  (void)encodeWithCoder:(NSCoder *)encoder {
    //    Encode properties, other class variables, etc
    [encoder encodeObject:_firstName forKey:kFirstName];


    [encoder encodeObject:[NSNumber numberWithInteger:_deviceType] forKey:kDeviceType];

    }

    - (id)initWithCoder:(NSCoder *)decoder {
    if((self = [super init])) {
        _firstName = [decoder decodeObjectForKey:kEmailId];

        _deviceType= [[decoder decodeObjectForKey:kDeviceType] integerValue];

    }
    return self;
    }
    - (NSArray *)allPropertyNames
    {
    unsigned count;
    objc_property_t *properties = class_copyPropertyList([self class], &count);

    NSMutableArray *rv = [NSMutableArray array];

    unsigned i;
    for (i = 0; i < count; i++)
    {
        objc_property_t property = properties[i];
        NSString *name = [NSString stringWithUTF8String:property_getName(property)];
        [rv addObject:name];
    }

    free(properties);

    return rv; 
    } 

    -(void)printDescription{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];

    for(NSString *key in [self allPropertyNames])
    {
        [dic setValue:[self valueForKey:key] forKey:key];
    }
    NSLog(@"\n========================= User Detail ==============================\n");
    NSLog(@"%@",[dic description]);
    NSLog(@"\n=============================================================\n");
    }
    -(NSMutableDictionary *)getDictionary{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    for(NSString *key in [self allPropertyNames])
    {
        [dic setValue:[self valueForKey:key] forKey:key];
    }
    return dic;
    }
    #pragma mark
    #pragma mark - Save and get User details
    -(void)saveLoginUserDetail{
    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:self];
    [Shared_UserDefault setObject:encodedObject forKey:kUserDefault_SavedUserDetail];
    [Shared_UserDefault synchronize];
    }
      +(UserDetails *)getLoginUserDetail{
      NSData *encodedObject = [Shared_UserDefault objectForKey:kUserDefault_SavedUserDetail];
    UserDetails *object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
    return object;
   }
    @end


     ************************usefull code while add data into model and get data********

                   NSLog(@"Response %@",result);
                  NSString *strMessg = [result objectForKey:kMessage];
                 NSString *status = [NSString stringWithFormat:@"%@",[result 
                objectForKey:kStatus]];

            if([status isEqualToString:@"1"])
            {
                arryBankList =[[NSMutableArray alloc]init];

                NSMutableArray *arrEvents=[result valueForKey:kbankList];
                ShareOBJ.isDefaultBank = [result valueForKey:kisDefaultBank];
                if ([arrEvents count]>0)
                {

                for (NSMutableArray *dic in arrEvents)
                    {
                        BankList *objBankListDetail =[[BankList alloc]initWithObject:[dic 
                         mutableCopy]];
                        [arryBankList addObject:objBankListDetail];
                    }
           //display data using model...
           BankList *objBankListing  =[arryBankList objectAtIndex:indexPath.row];

Sending an HTTP POST request on iOS

Objective C

Post API with parameters and validate with url to navigate if json
response key with status:"success"

NSString *string= [NSString stringWithFormat:@"url?uname=%@&pass=%@&uname_submit=Login",self.txtUsername.text,self.txtPassword.text];
    NSLog(@"%@",string);
    NSURL *url = [NSURL URLWithString:string];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSURLResponse *response;
    NSError *err;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
    NSLog(@"responseData: %@", responseData);
    NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"responseData: %@", str);
        NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                         options:kNilOptions
                                                           error:nil];
    NSDictionary* latestLoans = [json objectForKey:@"status"];
    NSString *str2=[NSString stringWithFormat:@"%@", latestLoans];
    NSString *str3=@"success";
    if ([str3 isEqualToString:str2 ])
    {
        [self performSegueWithIdentifier:@"move" sender:nil];
        NSLog(@"successfully.");
    }
    else
    {
        UIAlertController *alert= [UIAlertController
                                 alertControllerWithTitle:@"Try Again"
                                 message:@"Username or Password is Incorrect."
                                 preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction * action){
                                                       [self.view endEditing:YES];
                                                   }
                             ];
        [alert addAction:ok];
        [[UIView appearanceWhenContainedIn:[UIAlertController class], nil] setTintColor:[UIColor redColor]];
        [self presentViewController:alert animated:YES completion:nil];
        [self.view endEditing:YES];
      }

JSON Response : {"status":"success","user_id":"58","user_name":"dilip","result":"You have been logged in successfully"} Working code

**

Xcode error - Thread 1: signal SIGABRT

You are trying to load a XIB named DetailViewController, but no such XIB exists or it's not member of your current target.

How to send json data in the Http request using NSURLRequest

You can try this code for send json string

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ARRAY_CONTAIN_JSON_STRING options:NSJSONWritin*emphasized text*gPrettyPrinted error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *WS_test = [NSString stringWithFormat:@"www.test.com?xyz.php&param=%@",jsonString];

Displaying a 3D model in JavaScript/HTML5

do you work with a 3d tool such as maya? for maya you can look at http://www.inka3d.com

Why do people write #!/usr/bin/env python on the first line of a Python script?

If you have several versions of Python installed, /usr/bin/env will ensure the interpreter used is the first one on your environment's $PATH. The alternative would be to hardcode something like #!/usr/bin/python; that's ok, but less flexible.

In Unix, an executable file that's meant to be interpreted can indicate what interpreter to use by having a #! at the start of the first line, followed by the interpreter (and any flags it may need).

If you're talking about other platforms, of course, this rule does not apply (but that "shebang line" does no harm, and will help if you ever copy that script to a platform with a Unix base, such as Linux, Mac, etc).

Converting BitmapImage to Bitmap and vice versa

using System.Windows.Interop; ...

 private BitmapImage Bitmap2BitmapImage(Bitmap bitmap)
        {                
            BitmapSource i = Imaging.CreateBitmapSourceFromHBitmap(
                           bitmap.GetHbitmap(),
                           IntPtr.Zero,
                           Int32Rect.Empty,
                           BitmapSizeOptions.FromEmptyOptions());
            return (BitmapImage)i;
        }

Java: Enum parameter in method

Even cooler with enums you can use switch:

switch (align) {
   case LEFT: { 
      // do stuff
      break;
   }
   case RIGHT: {
      // do stuff
      break;
   }
   default: { //added TOP_RIGHT but forgot about it?
      throw new IllegalArgumentException("Can't yet handle " + align);

   }
}

Enums are cool because the output of the exception will be the name of the enum value, rather than some arbitrary int value.

Angular ng-class if else

Both John Conde's and ryeballar's answers are correct and will work.

If you want to get too geeky:

  • John's has the downside that it has to make two decisions per $digest loop (it has to decide whether to add/remove center and it has to decide whether to add/remove left), when clearly only one is needed.

  • Ryeballar's relies on the ternary operator which is probably going to be removed at some point (because the view should not contain any logic). (We can't be sure it will indeed be removed and it probably won't be any time soon, but if there is a more "safe" solution, why not ?)


So, you can do the following as an alternative:

ng-class="{true:'center',false:'left'}[page.isSelected(1)]"

Permission denied at hdfs

For Hadoop 3.x, if you try to create a file on HDFS when unauthenticated (e.g. user=dr.who) you will get this error.

It is not recommended for systems that need to be secure, however if you'd like to disable file permissions entirely in Hadoop 3 the hdfs-site.xml setting has changed to:

<property>
  <name>dfs.permissions.enabled</name>
  <value>false</value>
</property>

https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/hdfs-default.xml

How do I get the type of a variable?

I believe I have a valid use case for using typeid(), the same way it is valid to use sizeof(). For a template function, I need to special case the code based on the template variable, so that I offer maximum functionality and flexibility.

It is much more compact and maintainable than using polymorphism, to create one instance of the function for each type supported. Even in that case I might use this trick to write the body of the function only once:

Note that because the code uses templates, the switch statement below should resolve statically into only one code block, optimizing away all the false cases, AFAIK.

Consider this example, where we may need to handle a conversion if T is one type vs another. I use it for class specialization to access hardware where the hardware will use either myClassA or myClassB type. On a mismatch, I need to spend time converting the data.

switch ((typeid(T)) {
  case typeid(myClassA):
    // handle that case
    break;
  case typeid(myClassB):
    // handle that case
    break;
  case typeid(uint32_t):
    // handle that case
    break;
  default:
    // handle that case
}

binning data in python with scipy/numpy

I would add, and also to answer the question find mean bin values using histogram2d python that the scipy also have a function specially designed to compute a bidimensional binned statistic for one or more sets of data

import numpy as np
from scipy.stats import binned_statistic_2d

x = np.random.rand(100)
y = np.random.rand(100)
values = np.random.rand(100)
bin_means = binned_statistic_2d(x, y, values, bins=10).statistic

the function scipy.stats.binned_statistic_dd is a generalization of this funcion for higher dimensions datasets

What is the meaning of CTOR?

Type "ctor" and press the TAB key twice this will add the default constructor automatically

Create an Oracle function that returns a table

To return the whole table at once you could change the SELECT to:

SELECT  ...
BULK COLLECT INTO T
FROM    ...

This is only advisable for results that aren't excessively large, since they all have to be accumulated in memory before being returned; otherwise consider the pipelined function as suggested by Charles, or returning a REF CURSOR.

How to convert LINQ query result to List?

List<course> = (from c in obj.tbCourses
                 select 
                new course(c)).toList();

You can convert the entity object to a list directly on the call. There are methods to converting it to different data struct (list, array, dictionary, lookup, or string)

Can you install and run apps built on the .NET framework on a Mac?

  • .NET Core will install and run on macOS - and just about any other desktop OS.
    IDEs are available for the mac, including:

  • Mono is a good option that I've used in the past. But with Core 3.0 out now, I would go that route.

SQL Stored Procedure set variables using SELECT

select @currentTerm = CurrentTerm, @termID = TermID, @endDate = EndDate
    from table1
    where IsCurrent = 1

Make HTML5 video poster be same size as video itself

I was playing around with this and tried all solutions, eventually the solution I went with was a suggestion from Google Chrome's Inspector. If you add this to your CSS it worked for me:

video{
   object-fit: inherit;
}

Where is my m2 folder on Mac OS X Mavericks

If you have used brew to install maven, create .m2 directory and then copy settings.xml in .m2 directory.

mkdir ~/.m2
cp /usr/local/Cellar/maven32/3.2.5/libexec/conf/settings.xml ~/.m2

You may need to change the maven version in the path, mine is 3.2.5

How do I drag and drop files into an application?

In Windows Forms, set the control's AllowDrop property, then listen for DragEnter event and DragDrop event.

When the DragEnter event fires, set the argument's AllowedEffect to something other than none (e.g. e.Effect = DragDropEffects.Move).

When the DragDrop event fires, you'll get a list of strings. Each string is the full path to the file being dropped.

Add day(s) to a Date object

date.setTime( date.getTime() + days * 86400000 );

Where is android_sdk_root? and how do I set it.?

For macOS with zshrc:

ANDROID_HOME is depreciated, use ANDROID_SDK_ROOT instead

  1. Ensure that Android Build Tools is installed. Check if it exists in your File Directory
  2. Get the path to your SDK. Usually it is /Users/<USER>/Library/Android/sdk
  3. Add ANDROID_SDK_ROOT as a path to your Environment variables: echo 'export ANDROID_SDK_ROOT=/Users/<USER>/Library/Android/sdk' >> ~/.zshenv
  4. Apply the changes with source ~/.zshrc
  5. Check if it was saved by ...
    • ... checking the specific environment variable echo $ANDROID_SDK_ROOT
    • ... checking the complete list of environment variables on your system env

You can apply this process to every environment variable beeing installed on your macOS system. It took me a while to comprehend it for myself

Convert Mercurial project to Git

This would be better as a comment, sorry I do not have commenting permissions.

@mar10 comment was the missing piece I needed to do this.

Note that '/path/to/old/mercurial_repo' must be a path on the file system (not a URL), so you have to clone the original repository before. – mar10 Dec 27 '13 at 16:30

This comment was in regards to the answer that solved this for me, https://stackoverflow.com/a/10710294/2148757 which is the same answer as the one marked correct here, https://stackoverflow.com/a/16037861/2148757

This moved our hg project to git with the commit history intact.

ng is not recognized as an internal or external command

I was also following this problem so I tried this command and it worked perfectly. Use this command: npm run ng

Path of assets in CSS files in Symfony 2

The cssrewrite filter is not compatible with the @bundle notation for now. So you have two choices:

  • Reference the CSS files in the web folder (after: console assets:install --symlink web)

    {% stylesheets '/bundles/myCompany/css/*." filter="cssrewrite" %}
    
  • Use the cssembed filter to embed images in the CSS like this.

    {% stylesheets '@MyCompanyMyBundle/Resources/assets/css/*.css' filter="cssembed" %}
    

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

In my case, i got this error trying to get an object on an S3 bucket folder. But in that folder my object was not here (i put the wrong folder), so S3 send this message. Hope it could help you too.

Difference between Grunt, NPM and Bower ( package.json vs bower.json )

Npm and Bower are both dependency management tools. But the main difference between both is npm is used for installing Node js modules but bower js is used for managing front end components like html, css, js etc.

A fact that makes this more confusing is that npm provides some packages which can be used in front-end development as well, like grunt and jshint.

These lines add more meaning

Bower, unlike npm, can have multiple files (e.g. .js, .css, .html, .png, .ttf) which are considered the main file(s). Bower semantically considers these main files, when packaged together, a component.

Edit: Grunt is quite different from Npm and Bower. Grunt is a javascript task runner tool. You can do a lot of things using grunt which you had to do manually otherwise. Highlighting some of the uses of Grunt:

  1. Zipping some files (e.g. zipup plugin)
  2. Linting on js files (jshint)
  3. Compiling less files (grunt-contrib-less)

There are grunt plugins for sass compilation, uglifying your javascript, copy files/folders, minifying javascript etc.

Please Note that grunt plugin is also an npm package.

Question-1

When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json

It really depends where does this package belong to. If it is a node module(like grunt,request) then it will go in package.json otherwise into bower json.

Question-2

When should I ever install packages explicitly like that without adding them to the file that manages dependencies

It does not matter whether you are installing packages explicitly or mentioning the dependency in .json file. Suppose you are in the middle of working on a node project and you need another project, say request, then you have two options:

  • Edit the package.json file and add a dependency on 'request'
  • npm install

OR

  • Use commandline: npm install --save request

--save options adds the dependency to package.json file as well. If you don't specify --save option, it will only download the package but the json file will be unaffected.

You can do this either way, there will not be a substantial difference.

Navigation drawer: How do I set the selected item at startup?

When using BottomNavigationView the other answers such as navigationView.getMenu().getItem(0).setChecked(true); and navigationView.setCheckedItem(id); won't work calling setSelectedItemId works:

    BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation_view);

    bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
            // TODO: 10-Aug-19 your code here 
        }
    });

    bottomNavigationView.setSelectedItemId(R.id.myitem);

Multi-dimensional associative arrays in JavaScript

Don't use an array, use an object.

var foo = new Object();

String contains - ignore case

An optimized Imran Tariq's version

Pattern.compile(strptrn, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher(str1).find();

Pattern.quote(strptrn) always returns "\Q" + s + "\E" even if there is nothing to quote, concatination spoils performance.

Hide horizontal scrollbar on an iframe?

This answer is only applicable for websites which use Bootstrap. The responsive embed feature of the Bootstrap takes care of the scrollbars.

<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="http://www.youtube.com/embed/WsFWhL4Y84Y"></iframe>
</div> 

jsfiddle: http://jsfiddle.net/00qggsjj/2/

http://getbootstrap.com/components/#responsive-embed

Gradients in Internet Explorer 9

As of version 11, Opera supports linear gradients with the -o- vendor prefix. Chris Mills wrote a Dev.Opera article about it: http://dev.opera.com/articles/view/css3-linear-gradients/

Radial gradients are still in the works (both in the spec, and within Opera).

How to export a Hive table into a CSV file?

This is a much easier way to do it within Hive's SQL:

set hive.execution.engine=tez;
set hive.merge.tezfiles=true;
set hive.exec.compress.output=false;

INSERT OVERWRITE DIRECTORY '/tmp/job/'
ROW FORMAT DELIMITED
FIELDS TERMINATED by ','
NULL DEFINED AS ''
STORED AS TEXTFILE
SELECT * from table;

Changing java platform on which netbeans runs

You can change the JDK for Netbeans by modifying the config file:

  1. Open netbeans.conf file available under etc folder inside the NetBeans installation.
  2. Modify the netbeans_jdkhome variable to point to new JDK path, and then
  3. Restart your Netbeans.

JS - window.history - Delete a state

There is no way to delete or read the past history.

You could try going around it by emulating history in your own memory and calling history.pushState everytime window popstate event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:

  • popstate event can happen when user goes back ~2-3 states to the past
  • popstate event can happen when user goes forward

So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.

Function ereg_replace() is deprecated - How to clear this bug?

Switch to preg_replaceDocs and update the expression to use preg syntax (PCRE) instead of ereg syntax (POSIX) where there are differencesDocs (just as it says to do in the manual for ereg_replaceDocs).

How to redirect to a different domain using NGINX?

Temporary redirect

rewrite ^ http://www.RedirectToThisDomain.com$request_uri? redirect;

Permanent redirect

rewrite ^ http://www.RedirectToThisDomain.com$request_uri? permanent;

In nginx configuration file for specific site:

server {    
    server_name www.example.com;
    rewrite ^ http://www.RedictToThisDomain.com$request_uri? redirect;

}

Changing default encoding of Python?

You could change the encoding of your entire operating system. On Ubuntu you can do this with

sudo apt install locales 
sudo locale-gen en_US en_US.UTF-8    
sudo dpkg-reconfigure locales

Node JS Error: ENOENT

To expand a bit on why the error happened: A forward slash at the beginning of a path means "start from the root of the filesystem, and look for the given path". No forward slash means "start from the current working directory, and look for the given path".

The path

/tmp/test.jpg

thus translates to looking for the file test.jpg in the tmp folder at the root of the filesystem (e.g. c:\ on windows, / on *nix), instead of the webapp folder. Adding a period (.) in front of the path explicitly changes this to read "start from the current working directory", but is basically the same as leaving the forward slash out completely.

./tmp/test.jpg = tmp/test.jpg

Splitting String and put it on int array

List<String> stringList = new ArrayList<String>(Arrays.asList(arr.split(",")));
List<Integer> intList = new ArrayList<Integer>();
for (String s : stringList) 
   intList.add(Integer.valueOf(s));

500 internal server error, how to debug

Try writing all the errors to a file.

error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");

Something like that.

How does the @property decorator work in Python?

The property() function returns a special descriptor object:

>>> property()
<property object at 0x10ff07940>

It is this object that has extra methods:

>>> property().getter
<built-in method getter of property object at 0x10ff07998>
>>> property().setter
<built-in method setter of property object at 0x10ff07940>
>>> property().deleter
<built-in method deleter of property object at 0x10ff07998>

These act as decorators too. They return a new property object:

>>> property().getter(None)
<property object at 0x10ff079f0>

that is a copy of the old object, but with one of the functions replaced.

Remember, that the @decorator syntax is just syntactic sugar; the syntax:

@property
def foo(self): return self._foo

really means the same thing as

def foo(self): return self._foo
foo = property(foo)

so foo the function is replaced by property(foo), which we saw above is a special object. Then when you use @foo.setter(), what you are doing is call that property().setter method I showed you above, which returns a new copy of the property, but this time with the setter function replaced with the decorated method.

The following sequence also creates a full-on property, by using those decorator methods.

First we create some functions and a property object with just a getter:

>>> def getter(self): print('Get!')
... 
>>> def setter(self, value): print('Set to {!r}!'.format(value))
... 
>>> def deleter(self): print('Delete!')
... 
>>> prop = property(getter)
>>> prop.fget is getter
True
>>> prop.fset is None
True
>>> prop.fdel is None
True

Next we use the .setter() method to add a setter:

>>> prop = prop.setter(setter)
>>> prop.fget is getter
True
>>> prop.fset is setter
True
>>> prop.fdel is None
True

Last we add a deleter with the .deleter() method:

>>> prop = prop.deleter(deleter)
>>> prop.fget is getter
True
>>> prop.fset is setter
True
>>> prop.fdel is deleter
True

Last but not least, the property object acts as a descriptor object, so it has .__get__(), .__set__() and .__delete__() methods to hook into instance attribute getting, setting and deleting:

>>> class Foo: pass
... 
>>> prop.__get__(Foo(), Foo)
Get!
>>> prop.__set__(Foo(), 'bar')
Set to 'bar'!
>>> prop.__delete__(Foo())
Delete!

The Descriptor Howto includes a pure Python sample implementation of the property() type:

class Property:
    "Emulate PyProperty_Type() in Objects/descrobject.c"

    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        if doc is None and fget is not None:
            doc = fget.__doc__
        self.__doc__ = doc

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        if self.fget is None:
            raise AttributeError("unreadable attribute")
        return self.fget(obj)

    def __set__(self, obj, value):
        if self.fset is None:
            raise AttributeError("can't set attribute")
        self.fset(obj, value)

    def __delete__(self, obj):
        if self.fdel is None:
            raise AttributeError("can't delete attribute")
        self.fdel(obj)

    def getter(self, fget):
        return type(self)(fget, self.fset, self.fdel, self.__doc__)

    def setter(self, fset):
        return type(self)(self.fget, fset, self.fdel, self.__doc__)

    def deleter(self, fdel):
        return type(self)(self.fget, self.fset, fdel, self.__doc__)

Check if a string is html or not

Using jQuery in this case, the simplest form would be:

if ($(testString).length > 0)

If $(testString).length = 1, this means that there is one HTML tag inside textStging.

Find objects between two dates MongoDB

use $gte and $lte to find between date data's in mongodb

var tomorrowDate = moment(new Date()).add(1, 'days').format("YYYY-MM-DD");
db.collection.find({"plannedDeliveryDate":{ $gte: new Date(tomorrowDate +"T00:00:00.000Z"),$lte: new Date(tomorrowDate + "T23:59:59.999Z")}})

Does MySQL foreign_key_checks affect the entire database?

As explained by Ron, there are two variables, local and global. The local variable is always used, and is the same as global upon connection.

SET FOREIGN_KEY_CHECKS=0;
SET GLOBAL FOREIGN_KEY_CHECKS=0;

SHOW Variables WHERE Variable_name='foreign_key_checks'; # always shows local variable

When setting the GLOBAL variable, the local one isn't changed for any existing connections. You need to reconnect or set the local variable too.

Perhaps unintuitive, MYSQL does not enforce foreign keys when FOREIGN_KEY_CHECKS are re-enabled. This makes it possible to create an inconsistent database even though foreign keys and checks are on.

If you want your foreign keys to be completely consistent, you need to add the keys while checking is on.

Lock, mutex, semaphore... what's the difference?

Using C programming on a Linux variant as a base case for examples.

Lock:

• Usually a very simple construct binary in operation either locked or unlocked

• No concept of thread ownership, priority, sequencing etc.

• Usually a spin lock where the thread continuously checks for the locks availability.

• Usually relies on atomic operations e.g. Test-and-set, compare-and-swap, fetch-and-add etc.

• Usually requires hardware support for atomic operation.

File Locks:

• Usually used to coordinate access to a file via multiple processes.

• Multiple processes can hold the read lock however when any single process holds the write lock no other process is allowed to acquire a read or write lock.

• Example : flock, fcntl etc..

Mutex:

• Mutex function calls usually work in kernel space and result in system calls.

• It uses the concept of ownership. Only the thread that currently holds the mutex can unlock it.

• Mutex is not recursive (Exception: PTHREAD_MUTEX_RECURSIVE).

• Usually used in Association with Condition Variables and passed as arguments to e.g. pthread_cond_signal, pthread_cond_wait etc.

• Some UNIX systems allow mutex to be used by multiple processes although this may not be enforced on all systems.

Semaphore:

• This is a kernel maintained integer whose values is not allowed to fall below zero.

• It can be used to synchronize processes.

• The value of the semaphore may be set to a value greater than 1 in which case the value usually indicates the number of resources available.

• A semaphore whose value is restricted to 1 and 0 is referred to as a binary semaphore.

Adding a column after another column within SQL

In a Firebird database the AFTER myOtherColumn does not work but you can try re-positioning the column using:

ALTER TABLE name ALTER column POSITION new_position

I guess it may work in other cases as well.

Android runOnUiThread explanation

If you already have the data "for (Parcelable currentHeadline : allHeadlines)," then why are you doing that in a separate thread?

You should poll the data in a separate thread, and when it's finished gathering it, then call your populateTables method on the UI thread:

private void populateTable() {
    runOnUiThread(new Runnable(){
        public void run() {
            //If there are stories, add them to the table
            for (Parcelable currentHeadline : allHeadlines) {
                addHeadlineToTable(currentHeadline);
            }
            try {
                dialog.dismiss();
            } catch (final Exception ex) {
                Log.i("---","Exception in thread");
            }
        }
    });
}

Truncate a SQLite table if it exists?

I got it to work with:

SQLiteDatabase db= this.getWritableDatabase();
        db.delete(TABLE_NAME, null, null);

Is there a cross-domain iframe height auto-resizer that works?

I got the solution for setting the height of the iframe dynamically based on it's content. This works for the cross domain content. There are some steps to follow to achieve this.

  1. Suppose you have added iframe in "abc.com/page" web page

    <div> <iframe id="IframeId" src="http://xyz.pqr/contactpage" style="width:100%;" onload="setIframeHeight(this)"></iframe> </div>

  2. Next you have to bind windows "message" event under web page "abc.com/page"

window.addEventListener('message', function (event) {
//Here We have to check content of the message event  for safety purpose
//event data contains message sent from page added in iframe as shown in step 3
if (event.data.hasOwnProperty("FrameHeight")) {
        //Set height of the Iframe
        $("#IframeId").css("height", event.data.FrameHeight);        
    }
});

On iframe load you have to send message to iframe window content with "FrameHeight" message:

function setIframeHeight(ifrm) {
   var height = ifrm.contentWindow.postMessage("FrameHeight", "*");   
}
  1. On main page that added under iframe here "xyz.pqr/contactpage" you have to bind windows "message" event where all messages are going to receive from parent window of "abc.com/page"
window.addEventListener('message', function (event) {

    // Need to check for safety as we are going to process only our messages
    // So Check whether event with data(which contains any object) contains our message here its "FrameHeight"
   if (event.data == "FrameHeight") {

        //event.source contains parent page window object 
        //which we are going to use to send message back to main page here "abc.com/page"

        //parentSourceWindow = event.source;

        //Calculate the maximum height of the page
        var body = document.body, html = document.documentElement;
        var height = Math.max(body.scrollHeight, body.offsetHeight,
            html.clientHeight, html.scrollHeight, html.offsetHeight);

       // Send height back to parent page "abc.com/page"
        event.source.postMessage({ "FrameHeight": height }, "*");       
    }
});

How do I perform query filtering in django templates

This can be solved with an assignment tag:

from django import template

register = template.Library()

@register.assignment_tag
def query(qs, **kwargs):
    """ template tag which allows queryset filtering. Usage:
          {% query books author=author as mybooks %}
          {% for book in mybooks %}
            ...
          {% endfor %}
    """
    return qs.filter(**kwargs)

How to check for null in Twig?

I don't think you can. This is because if a variable is undefined (not set) in the twig template, it looks like NULL or none (in twig terms). I'm pretty sure this is to suppress bad access errors from occurring in the template.

Due to the lack of a "identity" in Twig (===) this is the best you can do

{% if var == null %}
    stuff in here
{% endif %}

Which translates to:

if ((isset($context['somethingnull']) ? $context['somethingnull'] : null) == null)
{
  echo "stuff in here";
}

Which if your good at your type juggling, means that things such as 0, '', FALSE, NULL, and an undefined var will also make that statement true.

My suggest is to ask for the identity to be implemented into Twig.

How to delete a remote tag?

As @CubanX suggested, I've split this answer from my original:

Here is a method which is several times faster than xargs and may scale much more with tweaking. It uses the Github API, a personal access token, and leverages the utility parallel.

git tag | sorting_processing_etc | parallel --jobs 2 curl -i -X DELETE \ 
https://api.github.com/repos/My_Account/my_repo/git/refs/tags/{} -H 
\"authorization: token GIT_OAUTH_OR_PERSONAL_KEY_HERE\"  \
-H \"cache-control: no-cache\"`

parallel has many operating modes, but generally parallelizes any command you give it while allowing you to set limits on the number of processes. You can alter the --jobs 2 parameter to allow faster operation, but I had problems with Github's rate limits, which are currently 5000/hr, but also seems to have an undocumented short-term limit as well.


After this, you'll probably want to delete your local tags too. This is much faster so we can go back to using xargs and git tag -d, which is sufficient.

git tag | sorting_processing_etc | xargs -L 1 git tag -d

Iterate over object attributes in python

in general put a __iter__ method in your class and iterate through the object attributes or put this mixin class in your class.

class IterMixin(object):
    def __iter__(self):
        for attr, value in self.__dict__.iteritems():
            yield attr, value

Your class:

>>> class YourClass(IterMixin): pass
...
>>> yc = YourClass()
>>> yc.one = range(15)
>>> yc.two = 'test'
>>> dict(yc)
{'one': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 'two': 'test'}

Apache won't follow symlinks (403 Forbidden)

The 403 error may also be caused by an encrypted file system, e.g. a symlink to an encrypted home folder.

If your symlink points into the encrypted folder, the apache user (e.g. www-data) cannot access the contents, even if apache and file/folder permissions are set correctly. Access of the www-data user can be tested with such a call:

sudo -u www-data ls -l /var/www/html/<your symlink>/

There are workarounds/solutions to this, e.g. adding the www-data user to your private group (exposes the encrypted data to the web user) or by setting up an unencrypted rsynced folder (probably rather secure). I for myself will probably go for an rsync solution during development.

https://askubuntu.com/questions/633625/public-folder-in-an-encrypted-home-directory

A convenient tool for my purposes is lsyncd. This allows me to work directly in my encrypted home folder and being able to see changes almost instantly in the apache web page. The synchronization is triggered by changes in the file system, calling an rsync. As I'm only working on rather small web pages and scripts, the syncing is very fast. I decided to use a short delay of 1 second before the rsync is started, even though it is possible to set a delay of 0 seconds.

Installing lsyncd (in Ubuntu):

sudo apt-get install lsyncd

Starting the background service:

lsyncd -delay 1 -rsync /home/<me>/<work folder>/ /var/www/html/<web folder>/

JQuery, setTimeout not working

You've got a couple of issues here.

Firstly, you're defining your code within an anonymous function. This construct:

(function() {
  ...
)();

does two things. It defines an anonymous function and calls it. There are scope reasons to do this but I'm not sure it's what you actually want.

You're passing in a code block to setTimeout(). The problem is that update() is not within scope when executed like that. It however if you pass in a function pointer instead so this works:

(function() {
  $(document).ready(function() {update();});

  function update() { 
    $("#board").append(".");
    setTimeout(update, 1000);     }
  }
)();

because the function pointer update is within scope of that block.

But like I said, there is no need for the anonymous function so you can rewrite it like this:

$(document).ready(function() {update();});

function update() { 
  $("#board").append(".");
  setTimeout(update, 1000);     }
}

or

$(document).ready(function() {update();});

function update() { 
  $("#board").append(".");
  setTimeout('update()', 1000);     }
}

and both of these work. The second works because the update() within the code block is within scope now.

I also prefer the $(function() { ... } shortened block form and rather than calling setTimeout() within update() you can just use setInterval() instead:

$(function() {
  setInterval(update, 1000);
});

function update() {
  $("#board").append(".");
}

Hope that clears that up.

CSS3 transition doesn't work with display property

I found a solution while tinkering around.

People who directly wanna see the results:

With click: https://jsfiddle.net/dt52jazg/

With Hover: https://jsfiddle.net/7gkufLsh/1/

Below is the code:

HTML

<ul class="list">
  <li>Hey</li>
  <li>This</li>
  <li>is</li>
  <li>just</li>
  <li>a</li>
  <li>test</li>
</ul>

<button class="click-me">
  Click me
</button>

CSS

.list li {
  min-height: 0;
  max-height: 0;
  opacity: 0;
  -webkit-transition: all .3s ease-in-out;
  transition: all .3s ease-in-out;
}

.active li {
  min-height: 20px;
  opacity: 1;
}

JS

(function() {
  $('.click-me').on('click', function() {
    $('.list').toggleClass('active');
  });
})();

Please let me know whether there is any problem with this solution 'coz I feel there would be no restriction of max-height with this solution.

how to convert JSONArray to List of Object using camel-jackson

/*
 It has been answered in http://stackoverflow.com/questions/15609306/convert-string-to-json-array/33292260#33292260
 * put string into file jsonFileArr.json
 * [{"username":"Hello","email":"[email protected]","credits"
 * :"100","twitter_username":""},
 * {"username":"Goodbye","email":"[email protected]"
 * ,"credits":"0","twitter_username":""},
 * {"username":"mlsilva","email":"[email protected]"
 * ,"credits":"524","twitter_username":""},
 * {"username":"fsouza","email":"[email protected]"
 * ,"credits":"1052","twitter_username":""}]
 */

public class TestaGsonLista {

public static void main(String[] args) {
Gson gson = new Gson();
 try {
    BufferedReader br = new BufferedReader(new FileReader(
            "C:\\Temp\\jsonFileArr.json"));
    JsonArray jsonArray = new JsonParser().parse(br).getAsJsonArray();
    for (int i = 0; i < jsonArray.size(); i++) {
        JsonElement str = jsonArray.get(i);
        Usuario obj = gson.fromJson(str, Usuario.class);
        //use the add method from the list and returns it.
        System.out.println(obj);
        System.out.println(str);
        System.out.println("-------");
    }
 } catch (IOException e) {
    e.printStackTrace();
 }
}

WebSockets and Apache proxy : how to configure mod_proxy_wstunnel?

I finally managed to do it, thanks to this topic.

TODO:

1) Have Apache 2.4 installed (doesn't work with 2.2), and do:

a2enmod proxy
a2enmod proxy_http
a2enmod proxy_wstunnel

2) Have nodejs running on port 3001

3) Do this in the Apache config

<VirtualHost *:80>
  ServerName www.domain2.com

  RewriteEngine On
  RewriteCond %{REQUEST_URI}  ^/socket.io            [NC]
  RewriteCond %{QUERY_STRING} transport=websocket    [NC]
  RewriteRule /(.*)           ws://localhost:3001/$1 [P,L]

  ProxyPass / http://localhost:3001/
  ProxyPassReverse / http://localhost:3001/
</VirtualHost>

Note: if you have more than one service on the same server that uses websockets, you might want to do this to separate them.

Import regular CSS file in SCSS file?

This was implemented and merged starting from version 3.2 (pull #754 merged on 2 Jan 2015 for libsass, issues originaly were defined here: sass#193 #556, libsass#318).

To cut the long story short, the syntax in next:

  1. to import (include) the raw CSS-file

    the syntax is without .css extension at the end (results in actual read of partial s[ac]ss|css and include of it inline to SCSS/SASS):

    @import "path/to/file";

  2. to import the CSS-file in a traditional way

    syntax goes in traditional way, with .css extension at the end (results to @import url("path/to/file.css"); in your compiled CSS):

    @import "path/to/file.css";

And it is damn good: this syntax is elegant and laconic, plus backward compatible! It works excellently with libsass and node-sass.

__

To avoid further speculations in comments, writing this explicitly: Ruby based Sass still has this feature unimplemented after 7 years of discussions. By the time of writing this answer, it's promised that in 4.0 there will be a simple way to accomplish this, probably with the help of @use. It seems there will be an implementation very soon, the new "planned" "Proposal Accepted" tag was assigned for the issue #556 and the new @use feature.

answer might be updated, as soon as something changes.

How do I deal with certificates using cURL while trying to access an HTTPS url?

For what it's worth, checking which curl is being run is significant too.

A user on a shared machine I maintain had been getting this error. But the cause turned out to be because they'd installed Anaconda (http://continuum.io). Doing so put Anaconda's binary path before the standard $PATH, and it comes with its own curl binary, which had trouble finding the default certs that were installed on this Ubuntu machine.

Initialize a Map containing arrays

Per Mozilla's Map documentation, you can initialize as follows:

private _gridOptions:Map<string, Array<string>> = 
    new Map([
        ["1", ["test"]],
        ["2", ["test2"]]
    ]);

Laravel Password & Password_Confirmation Validation

Try this:

'password' => 'required|min:6|confirmed',
'password_confirmation' => 'required|min:6'

proper name for python * operator?

I call *args "star args" or "varargs" and **kwargs "keyword args".

With Spring can I make an optional path variable?

You can't have optional path variables, but you can have two controller methods which call the same service code:

@RequestMapping(value = "/json/{type}", method = RequestMethod.GET)
public @ResponseBody TestBean typedTestBean(
        HttpServletRequest req,
        @PathVariable String type,
        @RequestParam("track") String track) {
    return getTestBean(type);
}

@RequestMapping(value = "/json", method = RequestMethod.GET)
public @ResponseBody TestBean testBean(
        HttpServletRequest req,
        @RequestParam("track") String track) {
    return getTestBean();
}

How do I analyze a .hprof file?

You can also use HeapWalker from the Netbeans Profiler or the Visual VM stand-alone tool. Visual VM is a good alternative to JHAT as it is stand alone, but is much easier to use than JHAT.

You need Java 6+ to fully use Visual VM.

How to execute an SSIS package from .NET?

To add to @Craig Schwarze answer,

Here are some related MSDN links:

Loading and Running a Local Package Programmatically:

Loading and Running a Remote Package Programmatically

Capturing Events from a Running Package:

using System;
using Microsoft.SqlServer.Dts.Runtime;

namespace RunFromClientAppWithEventsCS
{
  class MyEventListener : DefaultEvents
  {
    public override bool OnError(DtsObject source, int errorCode, string subComponent, 
      string description, string helpFile, int helpContext, string idofInterfaceWithError)
    {
      // Add application-specific diagnostics here.
      Console.WriteLine("Error in {0}/{1} : {2}", source, subComponent, description);
      return false;
    }
  }
  class Program
  {
    static void Main(string[] args)
    {
      string pkgLocation;
      Package pkg;
      Application app;
      DTSExecResult pkgResults;

      MyEventListener eventListener = new MyEventListener();

      pkgLocation =
        @"C:\Program Files\Microsoft SQL Server\100\Samples\Integration Services" +
        @"\Package Samples\CalculatedColumns Sample\CalculatedColumns\CalculatedColumns.dtsx";
      app = new Application();
      pkg = app.LoadPackage(pkgLocation, eventListener);
      pkgResults = pkg.Execute(null, null, eventListener, null, null);

      Console.WriteLine(pkgResults.ToString());
      Console.ReadKey();
    }
  }
}

Oracle: SQL query to find all the triggers belonging to the tables?

Another table that is useful is:

SELECT * FROM user_objects WHERE object_type='TRIGGER';

You can also use this to query views, indexes etc etc

Detecting a mobile browser

According to MDN's article on Browser detection using the user agent, it is encouraged to avoid this approach if possible and suggest other avenues such as feature detection.

However, if one must use the user agent as a means to detect if the device is mobile, they suggest:

In summary, we recommend looking for the string “Mobi” anywhere in the User Agent to detect a mobile device.

Therefore, this one-liner will suffice:

const isMobileDevice = window.navigator.userAgent.toLowerCase().includes("mobi");

[UPDATE]:

As @zenw0lf suggests in the comments, using a Regular Expression would be better:

const isMobileDevice = /Mobi/i.test(window.navigator.userAgent)

gdb: "No symbol table is loaded"

Whenever gcc on the compilation machine and gdb on the testing machine have differing versions, you may be facing debuginfo format incompatibility.

To fix that, try downgrading the debuginfo format:

gcc -gdwarf-3 ...
gcc -gdwarf-2 ...
gcc -gstabs ...
gcc -gstabs+ ...
gcc -gcoff ...
gcc -gxcoff ...
gcc -gxcoff+ ...

Or match gdb to the gcc you're using.

JOptionPane Input to int

// sample code for addition using JOptionPane

import javax.swing.JOptionPane;

public class Addition {

    public static void main(String[] args) {

        String firstNumber = JOptionPane.showInputDialog("Input <First Integer>");

        String secondNumber = JOptionPane.showInputDialog("Input <Second Integer>");

        int num1 = Integer.parseInt(firstNumber);
        int num2 = Integer.parseInt(secondNumber);
        int sum = num1 + num2;
        JOptionPane.showMessageDialog(null, "Sum is" + sum, "Sum of two Integers", JOptionPane.PLAIN_MESSAGE);
    }
}

How do I run a Python script from C#?

Actually its pretty easy to make integration between Csharp (VS) and Python with IronPython. It's not that much complex... As Chris Dunaway already said in answer section I started to build this inegration for my own project. N its pretty simple. Just follow these steps N you will get your results.

step 1 : Open VS and create new empty ConsoleApp project.

step 2 : Go to tools --> NuGet Package Manager --> Package Manager Console.

step 3 : After this open this link in your browser and copy the NuGet Command. Link: https://www.nuget.org/packages/IronPython/2.7.9

step 4 : After opening the above link copy the PM>Install-Package IronPython -Version 2.7.9 command and paste it in NuGet Console in VS. It will install the supportive packages.

step 5 : This is my code that I have used to run a .py file stored in my Python.exe directory.

using IronPython.Hosting;//for DLHE
using Microsoft.Scripting.Hosting;//provides scripting abilities comparable to batch files
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
class Hi
{
private static void Main(string []args)
{
Process process = new Process(); //to make a process call
ScriptEngine engine = Python.CreateEngine(); //For Engine to initiate the script
engine.ExecuteFile(@"C:\Users\daulmalik\AppData\Local\Programs\Python\Python37\p1.py");//Path of my .py file that I would like to see running in console after running my .cs file from VS.//process.StandardInput.Flush();
process.StandardInput.Close();//to close
process.WaitForExit();//to hold the process i.e. cmd screen as output
}
} 

step 6 : save and execute the code

Convert Java String to sql.Timestamp

If you get time as string in format such as 1441963946053 you simply could do something as following:

//String timestamp;
Long miliseconds = Long.valueOf(timestamp);
Timestamp ti = new Timestamp(miliseconds);

What is the best way to tell if a character is a letter or number in Java without using regexes?

// check if ch is a letter
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
    // ...

// check if ch is a digit
if (ch >= '0' && ch <= '9')
    // ...

// check if ch is a whitespace
if ((ch == ' ') || (ch =='\n') || (ch == '\t'))
    // ...

Source: https://docs.oracle.com/javase/tutorial/i18n/text/charintro.html

How to concatenate variables into SQL strings

You can accomplish this (if I understand what you are trying to do) using dynamic SQL.

The trick is that you need to create a string containing the SQL statement. That's because the tablename has to specified in the actual SQL text, when you execute the statement. The table references and column references can't be supplied as parameters, those have to appear in the SQL text.

So you can use something like this approach:

SET @stmt = 'INSERT INTO @tmpTbl1 SELECT ' + @KeyValue 
    + ' AS fld1 FROM tbl' + @KeyValue

EXEC (@stmt)

First, we create a SQL statement as a string. Given a @KeyValue of 'Foo', that would create a string containing:

'INSERT INTO @tmpTbl1 SELECT Foo AS fld1 FROM tblFoo'

At this point, it's just a string. But we can execute the contents of the string, as a dynamic SQL statement, using EXECUTE (or EXEC for short).

The old-school sp_executesql procedure is an alternative to EXEC, another way to execute dymamic SQL, which also allows you to pass parameters, rather than specifying all values as literals in the text of the statement.


FOLLOWUP

EBarr points out (correctly and importantly) that this approach is susceptible to SQL Injection.

Consider what would happen if @KeyValue contained the string:

'1 AS foo; DROP TABLE students; -- '

The string we would produce as a SQL statement would be:

'INSERT INTO @tmpTbl1 SELECT 1 AS foo; DROP TABLE students; -- AS fld1 ...'

When we EXECUTE that string as a SQL statement:

INSERT INTO @tmpTbl1 SELECT 1 AS foo;
DROP TABLE students;
-- AS fld1 FROM tbl1 AS foo; DROP ...

And it's not just a DROP TABLE that could be injected. Any SQL could be injected, and it might be much more subtle and even more nefarious. (The first attacks can be attempts to retreive information about tables and columns, followed by attempts to retrieve data (email addresses, account numbers, etc.)

One way to address this vulnerability is to validate the contents of @KeyValue, say it should contain only alphabetic and numeric characters (e.g. check for any characters not in those ranges using LIKE '%[^A-Za-z0-9]%'. If an illegal character is found, then reject the value, and exit without executing any SQL.

Function vs. Stored Procedure in SQL Server

SQL Server functions, like cursors, are meant to be used as your last weapon! They do have performance issues and therefore using a table-valued function should be avoided as much as possible. Talking about performance is talking about a table with more than 1,000,000 records hosted on a server on a middle-class hardware; otherwise you don't need to worry about the performance hit caused by the functions.

  1. Never use a function to return a result-set to an external code (like ADO.Net)
  2. Use views/stored procs combination as much as possible. you can recover from future grow-performance issues using the suggestions DTA (Database Tuning Adviser) would give you (like indexed views and statistics) --sometimes!

for further reference see: http://databases.aspfaq.com/database/should-i-use-a-view-a-stored-procedure-or-a-user-defined-function.html

C# Regex for Guid

I use an easier regex pattern

^[0-9A-Fa-f\-]{36}$

maven command line how to point to a specific settings.xml for a single command?

You can simply use:

mvn --settings YourOwnSettings.xml clean install

or

mvn -s YourOwnSettings.xml clean install

How to locate the php.ini file (xampp)

For Windows, you can find the file in the C:\xampp\php\php.ini-Folder (Windows) or in the etc-Folder (within the xampp-Folder).

Under Linux, most distributions put lampp under /opt/lampp, so the file can be found under /opt/lampp/etc/php.ini.

It can be edited using a normal Text-Editor.

Clarification:

  • Xampp (X (for "some OS"), Apache, MySQL, Perl, PHP)
  • Lampp (Linux, Apache, MySQL, Perl, PHP)

in this context, they can be substituted for one another.

Visual Studio displaying errors even if projects build

There are a lot of answers to delete the SUO / hidden solution files.

In my case it was because I needed to run Visual Studio as an Admin in order publish. Which overrode those files with admin permissions. Now when running as a standard user I can not get rid of any errors.

If I re-run in admin mode I am able to resolve all the errors.

Is there a reason for C#'s reuse of the variable in a foreach?

What you are asking is thoroughly covered by Eric Lippert in his blog post Closing over the loop variable considered harmful and its sequel.

For me, the most convincing argument is that having new variable in each iteration would be inconsistent with for(;;) style loop. Would you expect to have a new int i in each iteration of for (int i = 0; i < 10; i++)?

The most common problem with this behavior is making a closure over iteration variable and it has an easy workaround:

foreach (var s in strings)
{
    var s_for_closure = s;
    query = query.Where(i => i.Prop == s_for_closure); // access to modified closure

My blog post about this issue: Closure over foreach variable in C#.

Setting a property by reflection with a string value

I tried the answer from LBushkin and it worked great, but it won't work for null values and nullable fields. So I've changed it to this:

propertyName= "Latitude";
PropertyInfo propertyInfo = ship.GetType().GetProperty(propertyName);
if (propertyInfo != null)
{
     Type t = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
     object safeValue = (value == null) ? null : Convert.ChangeType(value, t);
     propertyInfo.SetValue(ship, safeValue, null);
}

Sending event when AngularJS finished loading

If you don't use ngRoute module, i.e. you don't have $viewContentLoaded event.

You can use another directive method:

    angular.module('someModule')
        .directive('someDirective', someDirective);

    someDirective.$inject = ['$rootScope', '$timeout']; //Inject services

    function someDirective($rootScope, $timeout){
        return {
            restrict: "A",
            priority: Number.MIN_SAFE_INTEGER, //Lowest priority
            link    : function(scope, element, attr){
                $timeout(
                    function(){
                        $rootScope.$emit("Some:event");
                    }
                );
            }
        };
    }

Accordingly to trusktr's answer it has lowest priority. Plus $timeout will cause Angular to run through an entire event loop before callback execution.

$rootScope used, because it allow to place directive in any scope of the application and notify only necessary listeners.

$rootScope.$emit will fire an event for all $rootScope.$on listeners only. The interesting part is that $rootScope.$broadcast will notify all $rootScope.$on as well as $scope.$on listeners Source

How to inject window into a service?

Actually its very simple to access window object here is my basic component and i tested it its working

import { Component, OnInit,Inject } from '@angular/core';
import {DOCUMENT} from '@angular/platform-browser';

@Component({
  selector: 'app-verticalbanners',
  templateUrl: './verticalbanners.component.html',
  styleUrls: ['./verticalbanners.component.css']
})
export class VerticalbannersComponent implements OnInit {

  constructor(){ }

  ngOnInit() {
    console.log(window.innerHeight );
  }

}

How to change the background color of a UIButton while it's highlighted?

if you won't override just set two action touchDown touchUpInside

Month name as a string

A sample way to get the date and time in this format "2018 Nov 01 16:18:22" use this

DateFormat dateFormat = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
        Date date = new Date();
         dateFormat.format(date);

Making view resize to its parent when added with addSubview

Swift 4 extension using explicit constraints:

import UIKit.UIView

extension UIView {
    public func addSubview(_ subview: UIView, stretchToFit: Bool = false) {
        addSubview(subview)
        if stretchToFit {
            subview.translatesAutoresizingMaskIntoConstraints = false
            leftAnchor.constraint(equalTo: subview.leftAnchor).isActive = true
            rightAnchor.constraint(equalTo: subview.rightAnchor).isActive = true
            topAnchor.constraint(equalTo: subview.topAnchor).isActive = true
            bottomAnchor.constraint(equalTo: subview.bottomAnchor).isActive = true
        }
    }
}

Usage:

parentView.addSubview(childView) // won't resize (default behavior unchanged)
parentView.addSubview(childView, stretchToFit: false) // won't resize
parentView.addSubview(childView, stretchToFit: true) // will resize

Already defined in .obj - no double inclusions

I do recomend doing it in 2 filles (.h .cpp) But if u lazy just add inline before the function So it will look something like this

inline void functionX() 
{ }

more about inline functions:

The inline functions are a C++ enhancement feature to increase the execution time of a program. Functions can be instructed to compiler to make them inline so that compiler can replace those function definition wherever those are being called. Compiler replaces the definition of inline functions at compile time instead of referring function definition at runtime. NOTE- This is just a suggestion to compiler to make the function inline, if function is big (in term of executable instruction etc) then, compiler can ignore the “inline” request and treat the function as normal function.

more info here

trace a particular IP and port

tcptraceroute   xx.xx.xx.xx 9100

if you didn't find it you can install it

yum -y install tcptraceroute 

or

aptitude -y install tcptraceroute 

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist


Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit


There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

C# generic list <T> how to get the type of T?

Marc's answer is the approach I use for this, but for simplicity (and a friendlier API?) you can define a property in the collection base class if you have one such as:

public abstract class CollectionBase<T> : IList<T>
{
   ...

   public Type ElementType
   {
      get
      {
         return typeof(T);
      }
   }
}

I have found this approach useful, and is easy to understand for any newcomers to generics.

Changing the resolution of a VNC session in linux

I'm not sure about linux, but under windows, tightvnc will detect and adapt to resolution changes on the server.

So you should be able to VNC into the workstation, do the equivalent of right-click on desktop, properties, set resolution to whatever, and have your client vnc window resize itself accordingly.

a = open("file", "r"); a.readline() output without \n

That would be:

b.rstrip('\n')

If you want to strip space from each and every line, you might consider instead:

a.read().splitlines()

This will give you a list of lines, without the line end characters.

Executing a command stored in a variable from PowerShell

Here is yet another way without Invoke-Expression but with two variables (command:string and parameters:array). It works fine for me. Assume 7z.exe is in the system path.

$cmd = '7z.exe'
$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'

& $cmd $prm

If the command is known (7z.exe) and only parameters are variable then this will do

$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'

& 7z.exe $prm

BTW, Invoke-Expression with one parameter works for me, too, e.g. this works

$cmd = '& 7z.exe a -tzip "c:\temp\with space\test2.zip" "C:\TEMP\with space\changelog"'

Invoke-Expression $cmd

P.S. I usually prefer the way with a parameter array because it is easier to compose programmatically than to build an expression for Invoke-Expression.

How to execute two mysql queries as one in PHP/MYSQL?

As others have answered, the mysqli API can execute multi-queries with the msyqli_multi_query() function.

For what it's worth, PDO supports multi-query by default, and you can iterate over the multiple result sets of your multiple queries:

$stmt = $dbh->prepare("
    select sql_calc_found_rows * from foo limit 1 ; 
    select found_rows()");
$stmt->execute();
do {
  while ($row = $stmt->fetch()) {
    print_r($row);
  }
} while ($stmt->nextRowset());

However, multi-query is pretty widely considered a bad idea for security reasons. If you aren't careful about how you construct your query strings, you can actually get the exact type of SQL injection vulnerability shown in the classic "Little Bobby Tables" XKCD cartoon. When using an API that restrict you to single-query, that can't happen.

Can't import database through phpmyadmin file size too large

You no need to edit php.ini or any thing. I suggest best thing as Just use MySQL WorkBench.

JUST FOLLOW THE STEPS.

Install MySQL WorkBench 6.0

And In "Navigation panel"(Left side) there is option call 'Data import' under "MANAGEMENT". Click that and [follow steps below]

  1. click Import Self-Contained File and choose your SQL file
  2. Go to My Document and create folder call "dump"[simple].
  3. now you ready to upload file. Click IMPORT Button on down.

Git : fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists

This usually happens when you use two ssh keys to access two different GitHub account.

Follow these steps to fix this it look too long but trust me it won't take more than 5 minutes:

Step-1: Create two ssh key pairs:

ssh-keygen -t rsa -C "[email protected]"

Step-2: It will create two ssh keys here:

~/.ssh/id_rsa_account1
~/.ssh/id_rsa_account2

Step-3: Now we need to add these keys:

ssh-add ~/.ssh/id_rsa_account2
ssh-add ~/.ssh/id_rsa_account1
  • You can see the added keys list by using this command: ssh-add -l
  • You can remove old cached keys by this command: ssh-add -D

Step-4: Modify the ssh config

cd ~/.ssh/
touch config

subl -a config or code config or nano config

Step-5: Add this to config file:

#Github account1
Host github.com-account1
    HostName github.com
    User account1
    IdentityFile ~/.ssh/id_rsa_account1

#Github account2
Host github.com-account2
    HostName github.com
    User account2
    IdentityFile ~/.ssh/id_rsa_account2

Step-6: Update your .git/config file:

Step-6.1: Navigate to account1's project and update host:

[remote "origin"]
        url = [email protected]:account1/gfs.git

If you are invited by some other user in their git Repository. Then you need to update the host like this:

[remote "origin"]
            url = [email protected]:invitedByUserName/gfs.git

Step-6.2: Navigate to account2's project and update host:

[remote "origin"]
        url = [email protected]:account2/gfs.git

Step-7: Update user name and email for each repository separately if required this is not an amendatory step:

Navigate to account1 project and run these:

git config user.name "account1"
git config user.email "[email protected]" 

Navigate to account2 project and run these:

git config user.name "account2"
git config user.email "[email protected]" 

Button Listener for button in fragment in android

While you are declaring onclick in XML then you must declair method and pass View v as parameter and make the method public...

Ex:
//in xml
android:onClick="onButtonClicked"


// in java file
public void onButtonClicked(View v)
{
//your code here
}

Regular expression for matching HH:MM time format

You can use this one 24H, seconds are optional

^([0-1]?[0-9]|[2][0-3]):([0-5][0-9])(:[0-5][0-9])?$

How can I count the rows with data in an Excel sheet?

This is what I finally came up with, which works great!

{=SUM(IF((ISTEXT('Worksheet Name!A:A))+(ISTEXT('CCSA Associates'!E:E)),1,0))-1}

Don't forget since it is an array to type the formula above without the "{}", and to CTRL + SHIFT + ENTER instead of just ENTER for the "{}" to appear and for it to be entered properly.

How to import a bak file into SQL Server Express

I had the same error. What worked for me is when you go for the SMSS GUI option, look at General, Files in Options settings. After I did that (replace DB, set location) all went well.

Disable cross domain web security in Firefox

For anyone finding this question while using Nightwatch.js (1.3.4), there's an acceptInsecureCerts: true setting in the config file:

_x000D_
_x000D_
firefox: {_x000D_
      desiredCapabilities: {_x000D_
        browserName: 'firefox',_x000D_
        alwaysMatch: {_x000D_
          // Enable this if you encounter unexpected SSL certificate errors in Firefox_x000D_
          acceptInsecureCerts: true,_x000D_
          'moz:firefoxOptions': {_x000D_
            args: [_x000D_
              // '-headless',_x000D_
              // '-verbose'_x000D_
            ],_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
    },
_x000D_
_x000D_
_x000D_

Sending multipart/formdata with jQuery.ajax

Nowadays you don't even need jQuery:) fetch API support table

let result = fetch('url', {method: 'POST', body: new FormData(document.querySelector("#form"))})

Key hash for Android-Facebook app

To generate a hash of your release key, run the following command on Mac or Windows substituting your release key alias and the path to your keystore.

On Windows, use:

keytool -exportcert -alias <RELEASE_KEY_ALIAS> -keystore <RELEASE_KEY_PATH> | openssl sha1 -binary | openssl base64

This command should generate a 28 characher string. Remember that COPY and PASTE this Release Key Hash into your Facebook App ID's Android settings.

image: fbcdn-dragon-a.akamaihd.net/hphotos-ak-xpa1/t39.2178-6/851568_627654437290708_1803108402_n.png

Refer from : https://developers.facebook.com/docs/android/getting-started#release-key-hash and http://note.taable.com

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

Random numbers with Math.random() in Java

if min=10 and max=100:

(int)(Math.random() * max) + min        

gives a result between 10 and 110, while

(int)(Math.random() * (max - min) + min)

gives a result between 10 and 100, so they are very different formulas. What's important here is clarity, so whatever you do, make sure the code makes it clear what is being generated.

(PS. the first makes more sense if you change the variable 'max' to be called 'range')

How to Get a Layout Inflater Given a Context?

You can use the static from() method from the LayoutInflater class:

 LayoutInflater li = LayoutInflater.from(context);

Java Multithreading concept and join() method

I'm not able to understand the flow of execution of the program, And when ob1 is created then the constructor is called where t.start() is written but still run() method is not executed rather main() method continues execution. So why is this happening?

This depends on Thread Scheduler as main shares the same priority order. Calling start() doesn't mean run() will be called immediately, it depends on thread scheduler when it chooses to run your thread.

join() method is used to wait until the thread on which it is called does not terminates, but here in output we see alternate outputs of the thread why??

This is because of the Thread.sleep(1000) in your code. Remove that line and you will see ob1 finishes before ob2 which in turn finishes before ob3 (as expected with join()). Having said that it all depends on when ob1 ob2 and ob3 started. Calling sleep will pause thread execution for >= 1 second (in your code), giving scheduler a chance to call other threads waiting (same priority).

postgreSQL - psql \i : how to execute script in a given path

Try this, I work myself to do so

\i 'somedir\\script2.sql'

How to compile C programming in Windows 7?

Microsoft Visual Studio Express

It's a full IDE, with powerful debugging tools, syntax highlighting, etc.

What is the Linux equivalent to DOS pause?

read does this:

user@host:~$ read -n1 -r -p "Press any key to continue..." key
[...]
user@host:~$ 

The -n1 specifies that it only waits for a single character. The -r puts it into raw mode, which is necessary because otherwise, if you press something like backslash, it doesn't register until you hit the next key. The -p specifies the prompt, which must be quoted if it contains spaces. The key argument is only necessary if you want to know which key they pressed, in which case you can access it through $key.

If you are using Bash, you can also specify a timeout with -t, which causes read to return a failure when a key isn't pressed. So for example:

read -t5 -n1 -r -p 'Press any key in the next five seconds...' key
if [ "$?" -eq "0" ]; then
    echo 'A key was pressed.'
else
    echo 'No key was pressed.'
fi

How to _really_ programmatically change primary and accent color in Android Lollipop?

from an activity you can do:

getWindow().setStatusBarColor(i color);

Make div scrollable

use overflow:auto property, If overflow is clipped, a scroll-bar should be added to see the rest of the content,and mention the height

DEMO

 .itemconfiguration
    {
        height: 440px;
        width: 215px;
        overflow: auto;
        float: left;
        position: relative;
        margin-left: -5px;
    }

How to detect shake event with android?

Dont forget to add this code in your MainActivity.java:

MainActivity.java

mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
    public void onShake() {
        Toast.makeText(MainActivity.this, "Shake " , Toast.LENGTH_LONG).show();        
    }
});

@Override
protected void onResume() {
    super.onResume();
    mShaker.resume();
}

@Override
protected void onPause() {
    super.onPause();
    mShaker.pause();
}

Or I give you a link about this stuff.

Verilog generate/genvar in an always block

for verilog just do

parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
  temp <= {ROWBITS{1'b0}}; // fill with 0
end

Xcode error - Thread 1: signal SIGABRT

You are trying to load a XIB named DetailViewController, but no such XIB exists or it's not member of your current target.

App can't be opened because it is from an unidentified developer

you can modify the gatekeeper settings by running the following command

To disable to allow apps from anywhere to be installed use the following command in terminal ::

sudo spctl --master-disable

To re-enable use the following command

sudo spctl --master-enable

How can I do a BEFORE UPDATED trigger with sql server?

T-SQL supports only AFTER and INSTEAD OF triggers, it does not feature a BEFORE trigger, as found in some other RDBMSs.

I believe you will want to use an INSTEAD OF trigger.

How to add hours to current time in python

from datetime import datetime, timedelta

nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)

And then use string formatting to get the relevant pieces:

>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'

If you're only formatting the datetime then you can use:

>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'

Or, as @eumiro has pointed out in comments - strftime

Rename master branch for both local and remote Git repositories

git checkout -b new-branch-name
git push remote-name new-branch-name :old-branch-name

You may have to manually switch to new-branch-name before deleting old-branch-name

excel formula to subtract number of days from a date

Assuming the original date is in cell A1:

=A1-180

Works in at least Excel 2003 and 2010.

How to give Jenkins more heap space when it´s started as a service under Windows?

In your Jenkins installation directory there is a jenkins.xml, where you can set various options. Add the parameter -Xmx with the size you want to the arguments-tag (or increase the size if its already there).

Parsing XML in Python using ElementTree example

So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:

import elementtree.ElementTree as ET

tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')

print thingy.attrib

and got the following back:

{'name': 'NWIS Time Series Instantaneous Values'}

It appears to have found the timeSeries element without needing to use numerical indices.

What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.

Switch statement: must default be the last case?

The C99 standard is not explicit about this, but taking all facts together, it is perfectly valid.

A case and default label are equivalent to a goto label. See 6.8.1 Labeled statements. Especially interesting is 6.8.1.4, which enables the already mentioned Duff's Device:

Any statement may be preceded by a prefix that declares an identifier as a label name. Labels in themselves do not alter the flow of control, which continues unimpeded across them.

Edit: The code within a switch is nothing special; it is a normal block of code as in an if-statement, with additional jump labels. This explains the fall-through behaviour and why break is necessary.

6.8.4.2.7 even gives an example:

switch (expr) 
{ 
    int i = 4; 
    f(i); 
case 0: 
    i=17; 
    /*falls through into default code */ 
default: 
    printf("%d\n", i); 
} 

In the artificial program fragment the object whose identifier is i exists with automatic storage duration (within the block) but is never initialized, and thus if the controlling expression has a nonzero value, the call to the printf function will access an indeterminate value. Similarly, the call to the function f cannot be reached.

The case constants must be unique within a switch statement:

6.8.4.2.3 The expression of each case label shall be an integer constant expression and no two of the case constant expressions in the same switch statement shall have the same value after conversion. There may be at most one default label in a switch statement.

All cases are evaluated, then it jumps to the default label, if given:

6.8.4.2.5 The integer promotions are performed on the controlling expression. The constant expression in each case label is converted to the promoted type of the controlling expression. If a converted value matches that of the promoted controlling expression, control jumps to the statement following the matched case label. Otherwise, if there is a default label, control jumps to the labeled statement. If no converted case constant expression matches and there is no default label, no part of the switch body is executed.

How to Identify Microsoft Edge browser via CSS?

/* Microsoft Edge Browser 12-18 (All versions before Chromium) */

This one should work:

@supports (-ms-ime-align:auto) {
    .selector {
        property: value;
    }
}

For more see: Browser Strangeness

Get month and year from date cells Excel

Please try something like:

=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))  

You seem to have three main possible scenarios:

  1. Space-separated date with time as text (eg as A1 below)
  2. Hyphen-separated date as text (eg as A2 below)
  3. Formatted date index (as A4 and A5 below)

ColumnA below is formatted General and ColumnB as Date (my default setting). ColumnC also as date but with custom formatting to suit the appearances mentioned in your question.
A clue as to whether or not text format is the left or right alignment of the cells’ contents.

I am suggesting separate treatment for each of the above three main cases, so use =IF to differentiate them.

Case #1

This is longer than any of the others, so can be distinguished as having a length greater than say 10 characters, with =LEN.
In this case we want all but the last six characters but for added flexibility (for instance, in case the time element included seconds) I have chosen to count from the left rather than from the right. The problem then is that the month names may vary in length, so I have chosen to look for the space that immediately follows the year to indicate the limit for the relevant number of characters.

This with =FIND which looks for a space (" ") in C1, starting with the eighth character within C1 counting from the left, on the assumption that for this case days will be expressed as two characters and months as three or more.

Since =LEFT is a string function it returns a string, but this can be converted to a value with=VALUE.

So

=VALUE(LEFT(C1,FIND(" ",C1,8))) 

returns 40671 in this example – in Excel’s 1900 date system the date serial number for May 5, 2011.

Case #2

If the length of C1 is not greater than 10 characters, we still need to distinguish between a text entry or a value entry which I have chosen to do with =ISTEXT and, where the if condition is TRUE (as for C2) apply =DATE which takes three parameters, here provided by:

=RIGHT(C2,4)  

Takes the last four characters of C2, hence 2011 in this example.

=MID(C2,4,2) 

Starting at the fourth character, takes the next two characters of C2, hence 05 in this example (representing May).

=LEFT(C2,2))  

Takes the first two characters of C2, hence 08 in this example (representing the 8th day of the month). Date is not a text function so does not need to be wrapped in =VALUE.

Taken together

=DATE(RIGHT(C2,4),MID(C2,4,2),LEFT(C2,2)) 

also returns 40671 in this example, but from different input from Case #1.

Case #3

Is simple because already a date serial number, so just

=C2  

is sufficient.


Put the above together to cover all three cases in a single formula:

=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))  

as applied in ColumnF (formatted to suit OP) or in General format (to show values are integers) in ColumnH:

SO23928568 example

How to get a web page's source code from Java

I am sure that you have found a solution somewhere over the past 2 years but the following is a solution that works for your requested site

package javasandbox;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
*
* @author Ryan.Oglesby
*/
public class JavaSandbox {

private static String sURL;

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws MalformedURLException, IOException {
    sURL = "http://www.cumhuriyet.com.tr/?hn=298710";
    System.out.println(sURL);
    URL url = new URL(sURL);
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    //set http request headers
            httpCon.addRequestProperty("Host", "www.cumhuriyet.com.tr");
            httpCon.addRequestProperty("Connection", "keep-alive");
            httpCon.addRequestProperty("Cache-Control", "max-age=0");
            httpCon.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            httpCon.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
            httpCon.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
            httpCon.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
            //httpCon.addRequestProperty("Cookie", "JSESSIONID=EC0F373FCC023CD3B8B9C1E2E2F7606C; lang=tr; __utma=169322547.1217782332.1386173665.1386173665.1386173665.1; __utmb=169322547.1.10.1386173665; __utmc=169322547; __utmz=169322547.1386173665.1.1.utmcsr=stackoverflow.com|utmccn=(referral)|utmcmd=referral|utmcct=/questions/8616781/how-to-get-a-web-pages-source-code-from-java; __gads=ID=3ab4e50d8713e391:T=1386173664:S=ALNI_Mb8N_wW0xS_wRa68vhR0gTRl8MwFA; scrElm=body");
            HttpURLConnection.setFollowRedirects(false);
            httpCon.setInstanceFollowRedirects(false);
            httpCon.setDoOutput(true);
            httpCon.setUseCaches(true);

            httpCon.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream(), "UTF-8"));
            String inputLine;
            StringBuilder a = new StringBuilder();
            while ((inputLine = in.readLine()) != null)
                a.append(inputLine);
            in.close();

            System.out.println(a.toString());

            httpCon.disconnect();
}
}

What's the difference between identifying and non-identifying relationships?

Like well explained in the link below, an identifying relation is somewhat like a weak entity type relation to its parent in the ER conceptual model. UML style CADs for data modeling do not use ER symbols or concepts, and the kind of relations are: identifying, non-identifying and non-specific.

Identifying ones are relations parent/child where the child is kind of a weak entity (even at the traditional ER model its called identifying relationship), which does not have a real primary key by its own attributes and therefore cannot be identified uniquely by its own. Every access to the child table, on the physical model, will be dependent (inclusive semantically) on the parent's primary key, which turns into part or total of the child's primary key (also being a foreign key), generally resulting in a composite key on the child side. The eventual existing keys of the child itself are only pseudo or partial-keys, not sufficient to identify any instance of that type of Entity or Entity Set, without the parent's PK.

Non-identifying relationship are the ordinary relations (partial or total), of completely independent entity sets, whose instances do not depend on each others' primary keys to be uniquely identified, although they might need foreign keys for partial or total relationships, but not as the primary key of the child. The child has its own primary key. The parent idem. Both independently. Depending on the cardinality of the relationship, the PK of one goes as a FK to the other (N side), and if partial, can be null, if total, must be not null. But, at a relationship like this, the FK will never be also the PK of the child, as when an identifying relationship is the case.

http://docwiki.embarcadero.com/ERStudioDA/XE7/en/Creating_and_Editing_Relationships

How do I get elapsed time in milliseconds in Ruby?

Time.now.to_f can help you but it returns seconds.

In general, when working with benchmarks I:

  • put in variable the current time;
  • insert the block to test;
  • put in a variable the current time, subtracting the preceding current-time value;

It's a very simple process, so I'm not sure you were really asking this...

java.net.ConnectException :connection timed out: connect?

Exception : java.net.ConnectException

This means your request didn't getting response from server in stipulated time. And their are some reasons for this exception:

  • Too many requests overloading the server
  • Request packet loss because of wrong network configuration or line overload
  • Sometimes firewall consume request packet before sever getting
  • Also depends on thread connection pool configuration and current status of connection pool
  • Response packet lost during transition

How to do a SQL NOT NULL with a DateTime?

Just to rule out a possibility - it doesn't appear to have anything to do with the ANSI_NULLS option, because that controls comparing to NULL with the = and <> operators. IS [NOT] NULL works whether ANSI_NULLS is ON or OFF.

I've also tried this against SQL Server 2005 with isql, because ANSI_NULLS defaults to OFF when using DB-Library.

HTML: Select multiple as dropdown

Because you're using multiple. Despite it still technically being a dropdown, it doesn't look or act like a standard dropdown. Rather, it populates a list box and lets them select multiple options.

Size determines how many options appear before they have to click down or up to see the other options.

I have a feeling what you want to achieve is only going to be possible with a JavaScript plugin.

Some examples:

jQuery multiselect drop down menu

http://labs.abeautifulsite.net/archived/jquery-multiSelect/demo/

How to show empty data message in Datatables

I was finding same but lastly i found an answer. I hope this answer help you so much.

when your array is empty then you can send empty array just like

if(!empty($result))
        {
            echo json_encode($result);
        }
        else
        {
            echo json_encode(array('data'=>''));
        }

Thank you

How do I query for all dates greater than a certain date in SQL Server?

To sum it all up, the correct answer is :

select * from db where Date >= '20100401'  (Format of date yyyymmdd)

This will avoid any problem with other language systems and will use the index.

ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

You can use [FromBody] but you need to set the Content-Type header of your request to application/json, i.e.

Content-Type: application/json

How to represent the double quotes character (") in regex?

you need to use backslash before ". like \"

From the doc here you can see that

A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.

and " (double quote) is a escacpe sequence

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence

She said "Hello!" to me.

you would write

System.out.println("She said \"Hello!\" to me.");

How to include (source) R script in other scripts

You could write a function that takes a filename and an environment name, checks to see if the file has been loaded into the environment and uses sys.source to source the file if not.

Here's a quick and untested function (improvements welcome!):

include <- function(file, env) {
  # ensure file and env are provided
  if(missing(file) || missing(env))
    stop("'file' and 'env' must be provided")
  # ensure env is character
  if(!is.character(file) || !is.character(env))
    stop("'file' and 'env' must be a character")

  # see if env is attached to the search path
  if(env %in% search()) {
    ENV <- get(env)
    files <- get(".files",ENV)
    # if the file hasn't been loaded
    if(!(file %in% files)) {
      sys.source(file, ENV)                        # load the file
      assign(".files", c(file, files), envir=ENV)  # set the flag
    }
  } else {
    ENV <- attach(NULL, name=env)      # create/attach new environment
    sys.source(file, ENV)              # load the file
    assign(".files", file, envir=ENV)  # set the flag
  }
}

How can I run code on a background thread on Android?

Today I was looking for this and Mr Brandon Rude gave an excellent answer. Unfortunately, AsyncTask is now depricated, you can still use it, but it gives you a warning which is very annoying. So an alternative is to use Executors like this way (in kotlin):


    val someRunnable = object : Runnable{
      override fun run() {
        // todo: do your background tasks
        requireActivity().runOnUiThread{
          // update views / ui if you are in a fragment
        };
        /*
        runOnUiThread {
          // update ui if you are in an activity
        }
        * */
      }
    };
    Executors.newSingleThreadExecutor().execute(someRunnable);

And in java it looks like this:


        Runnable someRunnable = new Runnable() {
            @Override
            public void run() {
                // todo: background tasks
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // todo: update your ui / view in activity
                    }
                });

                /*
                requireActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // todo: update your ui / view in Fragment
                    }
                });*/
            }
        };

        Executors.newSingleThreadExecutor().execute(someRunnable);

ImportError: No module named tensorflow

You may need this since first one may not work.

python3 -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.12.0-py3-none-any.whl

exceeds the list view threshold 5000 items in Sharepoint 2010

The setting for the list throttle

  • Open the SharePoint Central Administration,
  • go to Application Management --> Manage Web Applications
  • Click to select the web application that hosts your list (eg. SharePoint - 80)
  • At the Ribbon, select the General Settings and select Resource Throttling
  • Then, you can see the 5000 List View Threshold limit and you can edit the value you want.
  • Click OK to save it.

For addtional reading: http://blogs.msdn.com/b/dinaayoub/archive/2010/04/22/sharepoint-2010-how-to-change-the-list-view-threshold.aspx

How to suppress Update Links warning?

I've found a temporary solution that will at least let me process this job. I wrote a short AutoIt script that waits for the "Update Links" window to appear, then clicks the "Don't Update" button. Code is as follows:

while 1
if winexists("Microsoft Excel","This workbook contains links to other data sources.") Then
   controlclick("Microsoft Excel","This workbook contains links to other data sources.",2)
EndIf
WEnd

So far this seems to be working. I'd really like to find a solution that's entirely VBA, however, so that I can make this a standalone application.

ADB No Devices Found

Use another cable.

Just found out that one of my regular charging cables had Vcc, Gnd pairs, but no Data+, Data-.

https://en.wikipedia.org/wiki/USB#Pinouts

jQuery get the name of a select option

 $(this).attr("name") 

means the name of the select tag not option name.

To get option name

 $("#band_type_choices option:selected").attr('name');

A formula to copy the values from a formula to another column

Use =concatenate(). Concatenate is generally used to combine the words of several cells into one, but if you only input one cell it will return that value. There are other methods, but I find this is the best because it is the only method that works when a formula, whose value you wish to return, is in a merged cell.

What does "subject" mean in certificate?

The Subject, in security, is the thing being secured. In this case it could be a persons email or a website or a machine.

If we take the example of an email, say my email, then the subject key container would be the protected location containing my private key.

The certificate store usually refers to Microsoft certificate store which contains certificates form trusted roots, machines on the network, people etc. In my case the subjects certificate store would be the place, within this store, holding my certificates.

If you are working within a microsoft domain then the subject name will invariably hold the Distinguished Name, of the subject, which is how the domain references the subject and holds it in its directory. e.g. CN=Mark Sutton, OU=Developers, O=Mycompany C=UK

To look at your certificates on a microsoft machine:-

Log in as you run>mmc Select File>add/remove snap-in and select certificates then select my user account click Finish then close then ok. Look in the personal area of the store.

In the other areas of the store you will see the other trusted certificates used to validate signatures etc.

How can I find the number of elements in an array?

void numel(int array1[100][100])
{
    int count=0;
    for(int i=0;i<100;i++)
    {
        for(int j=0;j<100;j++)
        {
            if(array1[i][j]!='\0') 
            {
                count++;
                //printf("\n%d-%d",array1[i][j],count);
            }
            else 
                break;
        }
    }
    printf("Number of elements=%d",count);
}
int main()
{   
    int r,arr[100][100]={0},c;
    printf("Enter the no. of rows: ");
    scanf("%d",&r);
    printf("\nEnter the no. of columns: ");
    scanf("%d",&c);
    printf("\nEnter the elements: ");
    for(int i=0;i<r;i++)
    {
        for(int j=0;j<c;j++)
        {
            scanf("%d",&arr[i][j]);
        }
    }
    numel(arr);
}

This shows the exact number of elements in matrix irrespective of the array size you mentioned while initilasing(IF that's what you meant)

SQL Server: How to check if CLR is enabled?

The correct result for me with SQL Server 2017:

USE <DATABASE>;
EXEC sp_configure 'clr enabled' ,1
GO

RECONFIGURE
GO
EXEC sp_configure 'clr enabled'   -- make sure it took
GO

USE <DATABASE>
GO

EXEC sp_changedbowner 'sa'
USE <DATABASE>
GO

ALTER DATABASE <DATABASE> SET TRUSTWORTHY ON;  

From An error occurred in the Microsoft .NET Framework while trying to load assembly id 65675

Is there a way to make AngularJS load partials in the beginning and not at when needed?

I just use eco to do the job for me. eco is supported by Sprockets by default. It's a shorthand for Embedded Coffeescript which takes a eco file and compile into a Javascript template file, and the file will be treated like any other js files you have in your assets folder.

All you need to do is to create a template with extension .jst.eco and write some html code in there, and rails will automatically compile and serve the file with the assets pipeline, and the way to access the template is really easy: JST['path/to/file']({var: value}); where path/to/file is based on the logical path, so if you have file in /assets/javascript/path/file.jst.eco, you can access the template at JST['path/file']()

To make it work with angularjs, you can pass it into the template attribute instead of templateDir, and it will start working magically!

Using bind variables with dynamic SELECT INTO clause in PL/SQL

Bind variable can be used in Oracle SQL query with "in" clause.

Works in 10g; I don't know about other versions.

Bind variable is varchar up to 4000 characters.

Example: Bind variable containing comma-separated list of values, e.g.

:bindvar = 1,2,3,4,5

select * from mytable
  where myfield in
    (
      SELECT regexp_substr(:bindvar,'[^,]+', 1, level) items
      FROM dual
      CONNECT BY regexp_substr(:bindvar, '[^,]+', 1, level) is not null
    );

(Same info as I posted here: How do you specify IN clause in a dynamic query using a variable? )

"Parser Error Message: Could not load type" in Global.asax

I also got the same error...check the name of the Application you developed properly ie. the namespace and the assembly name alloted and also try physically changing the name of the folder created for the application, all of this should be same as the name in the above namespace present in the file global.asax

How do you convert a C++ string to an int?

Let me add my vote for boost::lexical_cast

#include <boost/lexical_cast.hpp>

int val = boost::lexical_cast<int>(strval) ;

It throws bad_lexical_cast on error.

How to access at request attributes in JSP?

Using JSTL:

<c:set var="message" value='${requestScope["Error_Message"]}' />

Here var sets the variable name and request.getAttribute is equal to requestScope. But it's not essential. ${Error_Message} will give you the same outcome. It'll search every scope. If you want to do some operation with content you take from Error_Message you have to do it using message. like below one.

<c:out value="${message}"/>

HTML entity for the middle dot

Try the HTML code: &#0149;

Which will appear as: •

Get distance between two points in canvas

The distance between two coordinates x and y! x1 and y1 is the first point/position, x2 and y2 is the second point/position!

_x000D_
_x000D_
function diff (num1, num2) {_x000D_
  if (num1 > num2) {_x000D_
    return (num1 - num2);_x000D_
  } else {_x000D_
    return (num2 - num1);_x000D_
  }_x000D_
};_x000D_
_x000D_
function dist (x1, y1, x2, y2) {_x000D_
  var deltaX = diff(x1, x2);_x000D_
  var deltaY = diff(y1, y2);_x000D_
  var dist = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));_x000D_
  return (dist);_x000D_
};
_x000D_
_x000D_
_x000D_

How to convert a string of numbers to an array of numbers?

One liner

Array.from(a.split(','), Number)

Submitting form and pass data to controller method of type FileStreamResult

here the problem is model binding if you specify a class then the model binding can understand it during the post if it an integer or string then you have to specify the [FromBody] to bind it properly.

make the following changes in FormMethod

using (@Html.BeginForm("myMethod", "Home", FormMethod.Post, new { id = @item.JobId })){

}

and inside your home controller for binding the string you should specify [FromBody]

using System.Web.Http;
[HttpPost]
public FileStreamResult myMethod([FromBody]string id)
{
     // Set a local variable with the incoming data
     string str = id;

}

FromBody is available in System.Web.Http. make sure you have the reference to that class and added it in the cs file.

How to create a static library with g++?

You can create a .a file using the ar utility, like so:

ar crf lib/libHeader.a header.o

lib is a directory that contains all your libraries. it is good practice to organise your code this way and separate the code and the object files. Having everything in one directory generally looks ugly. The above line creates libHeader.a in the directory lib. So, in your current directory, do:

mkdir lib

Then run the above ar command.

When linking all libraries, you can do it like so:

g++ test.o -L./lib -lHeader -o test  

The -L flag will get g++ to add the lib/ directory to the path. This way, g++ knows what directory to search when looking for libHeader. -llibHeader flags the specific library to link.

where test.o is created like so:

g++ -c test.cpp -o test.o 

jQuery - multiple $(document).ready ...?

It is important to note that each jQuery() call must actually return. If an exception is thrown in one, subsequent (unrelated) calls will never be executed.

This applies regardless of syntax. You can use jQuery(), jQuery(function() {}), $(document).ready(), whatever you like, the behavior is the same. If an early one fails, subsequent blocks will never be run.

This was a problem for me when using 3rd-party libraries. One library was throwing an exception, and subsequent libraries never initialized anything.

How to output JavaScript with PHP

You need to escape your quotes.

You can do this:

echo "<script type=\"text/javascript\">";

or this:

echo "<script type='text/javascript'>";

or this:

echo '<script type="text/javascript">';

Or just stay out of php

<script type="text/javascript">

How to create a Restful web service with input parameters?

Be careful. For this you need @GET (not @PUT).

How to detect a loop in a linked list?

Better than Floyd's algorithm

Richard Brent described an alternative cycle detection algorithm, which is pretty much like the hare and the tortoise [Floyd's cycle] except that, the slow node here doesn't move, but is later "teleported" to the position of the fast node at fixed intervals.

The description is available here : http://www.siafoo.net/algorithm/11 Brent claims that his algorithm is 24 to 36 % faster than the Floyd's cycle algorithm. O(n) time complexity, O(1) space complexity.

public static boolean hasLoop(Node root){
    if(root == null) return false;

    Node slow = root, fast = root;
    int taken = 0, limit = 2;

    while (fast.next != null) {
        fast = fast.next;
        taken++;
        if(slow == fast) return true;

        if(taken == limit){
            taken = 0;
            limit <<= 1;    // equivalent to limit *= 2;
            slow = fast;    // teleporting the turtle (to the hare's position) 
        }
    }
    return false;
}

Java path..Error of jvm.cfg

For anyone still having an issue I made mine work by doing this probably not the best fix but it worked for me..

I uninstalled all Java's that i current had installed, reinstalled the latest one and changed the install directory to C:/Windows/jre (Basically where it kept saying there was no config file)

Dark Theme for Visual Studio 2010 With Productivity Power Tools

Not sure if any of these help, but this might get you started: http://studiostyles.info

I know that the site owner has been gradually adding functionality to allow support for new color assignments, so perhaps there's something there.

How to get all count of mongoose model?

The reason your code doesn't work is because the count function is asynchronous, it doesn't synchronously return a value.

Here's an example of usage:

userModel.count({}, function( err, count){
    console.log( "Number of users:", count );
})

What does operator "dot" (.) mean?

The dot itself is not an operator, .^ is.

The .^ is a pointwise¹ (i.e. element-wise) power, as .* is the pointwise product.

.^ Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. The sizes of A and B must be the same or be compatible.

C.f.

¹) Hence the dot.

display HTML page after loading complete

The easiest thing to do is putting a div with the following CSS in the body:

#hideAll
 {
   position: fixed;
   left: 0px; 
   right: 0px; 
   top: 0px; 
   bottom: 0px; 
   background-color: white;
   z-index: 99; /* Higher than anything else in the document */

 }

(Note that position: fixed won't work in IE6 - I know of no sure-fire way of doing this in that browser)

Add the DIV like so (directly after the opening body tag):

<div style="display: none" id="hideAll">&nbsp;</div>

show the DIV directly after :

 <script type="text/javascript">
   document.getElementById("hideAll").style.display = "block";
 </script> 

and hide it onload:

 window.onload = function() 
  { document.getElementById("hideAll").style.display = "none"; }

or using jQuery

 $(window).load(function() {  document.getElementById("hideAll").style.display = "none"; });

this approach has the advantage that it will also work for clients who have JavaScript turned off. It shouldn't cause any flickering or other side-effects, but not having tested it, I can't entirely guarantee it for every browser out there.

What should I use to open a url instead of urlopen in urllib3

You should use urllib.reuqest, not urllib3.

import urllib.request   # not urllib - important!
urllib.request.urlopen('https://...')

How to make canvas responsive

To change width is not that hard. Just remove the width attribute from the tag and add width: 100%; in the css for #canvas

#canvas{
  border: solid 1px blue;  
  width: 100%;
}

Changing height is a bit harder: you need javascript. I have used jQuery because i'm more comfortable with.

you need to remove the height attribute from the canvas tag and add this script:

  <script>
  function resize(){    
    $("#canvas").outerHeight($(window).height()-$("#canvas").offset().top- Math.abs($("#canvas").outerHeight(true) - $("#canvas").outerHeight()));
  }
  $(document).ready(function(){
    resize();
    $(window).on("resize", function(){                      
        resize();
    });
  });
  </script>

You can see this fiddle: https://jsfiddle.net/1a11p3ng/3/

EDIT:

To answer your second question. You need javascript

0) First of all i changed your #border id into a class since ids must be unique for an element inside an html page (you can't have 2 tags with the same id)

.border{
  border: solid 1px black;
}

#canvas{
  border: solid 1px blue;  
  width: 100%;
}

1) Changed your HTML to add ids where needed, two inputs and a button to set the values

<div class="row">
  <div class="col-xs-2 col-sm-2 border">content left</div>
  <div class="col-xs-6 col-sm-6 border" id="main-content">
    <div class="row">
      <div class="col-xs-6">
        Width <input id="w-input" type="number" class="form-control">
      </div>
      <div class="col-xs-6">
        Height <input id="h-input" type="number" class="form-control">
      </div>
      <div class="col-xs-12 text-right" style="padding: 3px;">
        <button id="set-size" class="btn btn-primary">Set</button>
      </div> 
    </div>
    canvas
    <canvas id="canvas"></canvas>

  </div>
  <div class="col-xs-2 col-sm-2 border">content right</div>
</div>

2) Set the canvas height and width so that it fits inside the container

$("#canvas").outerHeight($(window).height()-$("#canvas").offset().top-Math.abs( $("#canvas").outerHeight(true) - $("#canvas").outerHeight()));

3) Set the values of the width and height forms

$("#h-input").val($("#canvas").outerHeight());
$("#w-input").val($("#canvas").outerWidth());

4) Finally, whenever you click on the button you set the canvas width and height to the values set. If the width value is bigger than the container's width then it will resize the canvas to the container's width instead (otherwise it will break your layout)

    $("#set-size").click(function(){
        $("#canvas").outerHeight($("#h-input").val());
        $("#canvas").outerWidth(Math.min($("#w-input").val(), $("#main-content").width()));
    });

See a full example here https://jsfiddle.net/1a11p3ng/7/

UPDATE 2:

To have full control over the width you can use this:

<div class="container-fluid">
<div class="row">
  <div class="col-xs-2 border">content left</div>
  <div class="col-xs-8 border" id="main-content">
    <div class="row">
      <div class="col-xs-6">
        Width <input id="w-input" type="number" class="form-control">
      </div>
      <div class="col-xs-6">
        Height <input id="h-input" type="number" class="form-control">
      </div>
      <div class="col-xs-12 text-right" style="padding: 3px;">
        <button id="set-size" class="btn btn-primary">Set</button>
      </div> 
    </div>
      canvas
    <canvas id="canvas">

    </canvas>

  </div>
  <div class="col-xs-2 border">content right</div>
</div>
</div>
  <script>
   $(document).ready(function(){
    $("#canvas").outerHeight($(window).height()-$("#canvas").offset().top-Math.abs( $("#canvas").outerHeight(true) - $("#canvas").outerHeight()));
    $("#h-input").val($("#canvas").outerHeight());
    $("#w-input").val($("#canvas").outerWidth());
    $("#set-size").click(function(){
        $("#canvas").outerHeight($("#h-input").val());
      $("#main-content").width($("#w-input").val());
      $("#canvas").outerWidth($("#main-content").width());
    });
   });
  </script>

https://jsfiddle.net/1a11p3ng/8/

the content left and content right columns will move above and belove the central div if the width is too high, but this can't be helped if you are using bootstrap. This is not, however, what responsive means. a truly responsive site will adapt its size to the user screen to keep the layout as you have intended without any external input, letting the user set any size which may break your layout does not mean making a responsive site.

Fixed point vs Floating point number

From my understanding, fixed-point arithmetic is done using integers. where the decimal part is stored in a fixed amount of bits, or the number is multiplied by how many digits of decimal precision is needed.

For example, If the number 12.34 needs to be stored and we only need two digits of precision after the decimal point, the number is multiplied by 100 to get 1234. When performing math on this number, we'd use this rule set. Adding 5620 or 56.20 to this number would yield 6854 in data or 68.54.

If we want to calculate the decimal part of a fixed-point number, we use the modulo (%) operand.

12.34 (pseudocode):

v1 = 1234 / 100 // get the whole number
v2 = 1234 % 100 // get the decimal number (100ths of a whole).
print v1 + "." + v2 // "12.34"

Floating point numbers are a completely different story in programming. The current standard for floating point numbers use something like 23 bits for the data of the number, 8 bits for the exponent, and 1 but for sign. See this Wikipedia link for more information on this.

Append a single character to a string or char array in java?

just add them like this :

        String character = "a";
        String otherString = "helen";
        otherString=otherString+character;
        System.out.println(otherString);

Get MAC address using shell script

On a modern GNU/Linux system you can see the available network interfaces listing the content of /sys/class/net/, for example:

$ ls /sys/class/net/
enp0s25  lo  virbr0  virbr0-nic  wlp2s0

You can check if an interface is up looking at operstate in the device directory. For example, here's how you can see if enp0s25 is up:

$ cat /sys/class/net/enp0s25/operstate
up

You can then get the MAC address of that interface with:

$ cat /sys/class/net/enp0s25/address 
ff:00:ff:e9:84:a5

For example, here's a simple bash script that prints MAC addresses for active interfaces:

#!/bin/bash
# getmacifup.sh: Print active NICs MAC addresses
D='/sys/class/net'
for nic in $( ls $D )
do
    echo $nic
    if  grep -q up $D/$nic/operstate
    then
        echo -n '   '
        cat $D/$nic/address
    fi
done

And here's its output on a system with an ethernet and a wifi interface:

$ ./getmacifup.sh
enp0s25
   ff:00:ff:e9:84:a5
lo
wlp2s0

For details see the Kernel documentation


Remember also that from 2015 most GNU/Linux distributions switched to systemd, and don't use ethX interface naming scheme any more - now they use a more robust naming convention based on the hardware topology, see:

Safest way to convert float to integer in python?

Another code sample to convert a real/float to an integer using variables. "vel" is a real/float number and converted to the next highest INTEGER, "newvel".

import arcpy.math, os, sys, arcpy.da
.
.
with arcpy.da.SearchCursor(densifybkp,[floseg,vel,Length]) as cursor:
 for row in cursor:
    curvel = float(row[1])
    newvel = int(math.ceil(curvel))

Difference between using Makefile and CMake to compile the code

The statement about CMake being a "build generator" is a common misconception.

It's not technically wrong; it just describes HOW it works, but not WHAT it does.

In the context of the question, they do the same thing: take a bunch of C/C++ files and turn them into a binary.

So, what is the real difference?

  • CMake is much more high-level. It's tailored to compile C++, for which you write much less build code, but can be also used for general purpose build. make has some built-in C/C++ rules as well, but they are useless at best.

  • CMake does a two-step build: it generates a low-level build script in ninja or make or many other generators, and then you run it. All the shell script pieces that are normally piled into Makefile are only executed at the generation stage. Thus, CMake build can be orders of magnitude faster.

  • The grammar of CMake is much easier to support for external tools than make's.

  • Once make builds an artifact, it forgets how it was built. What sources it was built from, what compiler flags? CMake tracks it, make leaves it up to you. If one of library sources was removed since the previous version of Makefile, make won't rebuild it.

  • Modern CMake (starting with version 3.something) works in terms of dependencies between "targets". A target is still a single output file, but it can have transitive ("public"/"interface" in CMake terms) dependencies. These transitive dependencies can be exposed to or hidden from the dependent packages. CMake will manage directories for you. With make, you're stuck on a file-by-file and manage-directories-by-hand level.

You could code up something in make using intermediate files to cover the last two gaps, but you're on your own. make does contain a Turing complete language (even two, sometimes three counting Guile); the first two are horrible and the Guile is practically never used.

To be honest, this is what CMake and make have in common -- their languages are pretty horrible. Here's what comes to mind:

  • They have no user-defined types;
  • CMake has three data types: string, list, and a target with properties. make has one: string;
  • you normally pass arguments to functions by setting global variables.
    • This is partially dealt with in modern CMake - you can set a target's properties: set_property(TARGET helloworld APPEND PROPERTY INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}");
  • referring to an undefined variable is silently ignored by default;

Generate sql insert script from excel worksheet

Here is another tool that works very well...

http://www.convertcsv.com/csv-to-sql.htm

It can take tab separated values and generate an INSERT script. Just copy and paste and in the options under step 2 check the box "First row is column names"

Then scroll down and under step 3, enter your table name in the box "Schema.Table or View Name:"

Pay attention to the delete and create table check boxes as well, and make sure you examine the generated script before running it.

This is the quickest and most reliable way I've found.

URL to load resources from the classpath in Java

I dont know if there is one already, but you can make it yourself easilly.

That different protocols example looks to me like a facade pattern. You have a common interface when there are different implementations for each case.

You could use the same principle, make a ResourceLoader class which takes the string from your properties file, and checks for a custom protocol of ours

myprotocol:a.xml
myprotocol:file:///tmp.txt
myprotocol:http://127.0.0.1:8080/a.properties
myprotocol:jar:http://www.foo.com/bar/baz.jar!/COM/foo/Quux.class

strips the myprotocol: from the start of the string and then makes a decision of which way to load the resource, and just gives you the resource.

What is an optional value in Swift?

Well...

? (Optional) indicates your variable may contain a nil value while ! (unwrapper) indicates your variable must have a memory (or value) when it is used (tried to get a value from it) at runtime.

The main difference is that optional chaining fails gracefully when the optional is nil, whereas forced unwrapping triggers a runtime error when the optional is nil.

To reflect the fact that optional chaining can be called on a nil value, the result of an optional chaining call is always an optional value, even if the property, method, or subscript you are querying returns a nonoptional value. You can use this optional return value to check whether the optional chaining call was successful (the returned optional contains a value), or did not succeed due to a nil value in the chain (the returned optional value is nil).

Specifically, the result of an optional chaining call is of the same type as the expected return value, but wrapped in an optional. A property that normally returns an Int will return an Int? when accessed through optional chaining.

var defaultNil : Int?  // declared variable with default nil value
println(defaultNil) >> nil  

var canBeNil : Int? = 4
println(canBeNil) >> optional(4)

canBeNil = nil
println(canBeNil) >> nil

println(canBeNil!) >> // Here nil optional variable is being unwrapped using ! mark (symbol), that will show runtime error. Because a nil optional is being tried to get value using unwrapper

var canNotBeNil : Int! = 4
print(canNotBeNil) >> 4

var cantBeNil : Int = 4
cantBeNil = nil // can't do this as it's not optional and show a compile time error

Here is basic tutorial in detail, by Apple Developer Committee: Optional Chaining

Delete specified file from document directory

    NSError *error;
    [[NSFileManager defaultManager] removeItemAtPath:new_file_path_str error:&error];
    if (error){
        NSLog(@"%@", error);
    }

RegEx: How can I match all numbers greater than 49?

I know this is old, but none of these expressions worked for me (maybe it's because I'm on PHP). The following expression worked fine to validate that a number is higher than 49:

/([5-9][0-9])|([1-9]\d{3}\d*)/

How to open a link in new tab (chrome) using Selenium WebDriver?

I have tried other techniques, but none of them worked, also no error produced, but when I have used the code below, it worked for me.

((JavascriptExecutor)driver).executeScript("window.open()");
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
driver.get("http://google.com");

How to set IntelliJ IDEA Project SDK

For IntelliJ IDEA 2017.2 I did the following to fix this issue: Go to your project structure enter image description here Now go to SDKs under platform settings and click the green add button. Add your JDK path. In my case it was this path C:\Program Files\Java\jdk1.8.0_144 enter image description here Now Just go Project under Project settings and select the project SDK. enter image description here

How to debug .htaccess RewriteRule not working

Perhaps a more logical method would be to create a file (e.g. test.html), add some content and then try to set it as the index page:

DirectoryIndex test.html

For the most part, the .htaccess rule will override the Apache configuration where working at the directory/file level

Why does intellisense and code suggestion stop working when Visual Studio is open?

Intellisense did not recognized an imported namespace in my case, although I could compile the project successfully. The solution was to uncheck imported namespace on project references tab, save the project, check it again and save the project again.

Ruby value of a hash key?

It seems that your question is maybe a bit ambiguous.

If “values” in the first sentence means any generic value (i.e. object, since everything in Ruby can be viewed as an object), then one of the other answers probably tells you what you need to know (i.e. use Hash#[] (e.g. hash[some_key]) to find the value associated with a key).

If, however, “values” in first sentence is taken to mean the value part of the “key, value pairs” (as are stored in hashes), then your question seems like it might be about working in the other direction (key for a given value).

You can find a key that leads to a certain value with Hash#key.

ruby-1.9.2-head :001 > hash = { :a => '1', :b => :two, :c => 3, 'bee' => :two }
 => {:a=>"1", :b=>:two, :c=>3, "bee"=>:two} 
ruby-1.9.2-head :002 > a_value = :two
 => :two 
ruby-1.9.2-head :003 > hash.key(a_value)
 => :b 

If you are using a Ruby earlier than 1.9, you can use Hash#index.

When there are multiple keys with the desired value, the method will only return one of them. If you want all the keys with a given value, you may have to iterate a bit:

ruby-1.9.2-head :004 > hash[:b] == hash['bee']
 => true 
ruby-1.9.2-head :005 > keys = hash.inject([]) do # all keys with value a_value
ruby-1.9.2-head :006 >       |l,kv| kv[1] == a_value ? l << kv[0] : l
ruby-1.9.2-head :007?>   end
 => [:b, "bee"] 

Once you have a key (the keys) that lead to the value, you can compare them and act on them with if/unless/case expressions, custom methods that take blocks, et cetera. Just how you compare them depends on the kind of objects you are using for keys (people often use strings and symbols, but Ruby hashes can use any kind of object as keys (as long as they are not modified while they serve as keys)).

PHP: Call to undefined function: simplexml_load_string()

I also faced this issue. My Operating system is Ubuntu 18.04 and my PHP version is PHP 7.2.

Here's how I solved it:

Install Simplexml on your Ubuntu Server:

sudo apt-get install php7.2-simplexml

Restart Apache Server

sudo systemctl restart apache2

That's all.

I hope this helps

How to install Java SDK on CentOS?

If you want the Oracle JDK and are willing not to use yum/rpm, see this answer here:

Downloading Java JDK on Linux via wget is shown license page instead

As per that post, you can automate the download of the tarball using curl and specifying a cookie header.

Then you can put the tarball contents in the right place and add java to your PATH, for example:

curl -v -j -k -L -H "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u45-b14/jdk-8u45-linux-x64.tar.gz > jdk.tar.gz

tar xzvf jdk.tar.gz
sudo mkdir /usr/local/java
sudo mv jdk1.8.0_45 /usr/local/java/
sudo ln -s /usr/local/java/jdk1.8.0_45 /usr/local/java/jdk

sudo vi /etc/profile.d/java.sh
export PATH="$PATH:/usr/local/java/jdk/bin"
export JAVA_HOME=/usr/local/java/jdk

source /etc/profile.d/java.sh

Short description of the scoping rules?

The Python name resolution only knows the following kinds of scope:

  1. builtins scope which provides the Builtin Functions, such as print, int, or zip,
  2. module global scope which is always the top-level of the current module,
  3. three user-defined scopes that can be nested into each other, namely
    1. function closure scope, from any enclosing def block, lambda expression or comprehension.
    2. function local scope, inside a def block, lambda expression or comprehension,
    3. class scope, inside a class block.

Notably, other constructs such as if, for, or with statements do not have their own scope.

The scoping TLDR: The lookup of a name begins at the scope in which the name is used, then any enclosing scopes (excluding class scopes), to the module globals, and finally the builtins – the first match in this search order is used. The assignment to a scope is by default to the current scope – the special forms nonlocal and global must be used to assign to a name from an outer scope.

Finally, comprehensions and generator expressions as well as := asignment expressions have one special rule when combined.


Nested Scopes and Name Resolution

These different scopes build a hierarchy, with builtins then global always forming the base, and closures, locals and class scope being nested as lexically defined. That is, only the nesting in the source code matters, not for example the call stack.

print("builtins are available without definition")

some_global = "1"  # global variables are at module scope

def outer_function():
    some_closure = "3.1"  # locals and closure are defined the same, at function scope
    some_local = "3.2"    # a variable becomes a closure if a nested scope uses it

    class InnerClass:
         some_classvar = "3.3"   # class variables exist *only* at class scope

         def nested_function(self):
             some_local = "3.2"   # locals can replace outer names
             print(some_closure)  # closures are always readable
    return InnerClass

Even though class creates a scope and may have nested classes, functions and comprehensions, the names of the class scope are not visible to enclosed scopes. This creates the following hierarchy:

? builtins           [print, ...]
??? globals            [some_global]
  ??? outer_function     [some_local, some_closure]
    ??? InnerClass         [some_classvar]
    ??? inner_function     [some_local]

Name resolution always starts at the current scope in which a name is accessed, then goes up the hierarchy until a match is found. For example, looking up some_local inside outer_function and inner_function starts at the respective function - and immediately finds the some_local defined in outer_function and inner_function, respectively. When a name is not local, it is fetched from the nearest enclosing scope that defines it – looking up some_closure and print inside inner_function searches until outer_function and builtins, respectively.


Scope Declarations and Name Binding

By default, a name belongs to any scope in which it is bound to a value. Binding the same name again in an inner scope creates a new variable with the same name - for example, some_local exists separately in both outer_function and inner_function. As far as scoping is concerned, binding includes any statement that sets the value of a name – assignment statements, but also the iteration variable of a for loop, or the name of a with context manager. Notably, del also counts as name binding.

When a name must refer to an outer variable and be bound in an inner scope, the name must be declared as not local. Separate declarations exists for the different kinds of enclosing scopes: nonlocal always refers to the nearest closure, and global always refers to a global name. Notably, nonlocal never refers to a global name and global ignores all closures of the same name. There is no declaration to refer to the builtin scope.


some_global = "1"

def outer_function():
    some_closure = "3.2"
    some_global = "this is ignored by a nested global declaration"
    
    def inner_function():
        global some_global     # declare variable from global scope
        nonlocal some_closure  # declare variable from enclosing scope
        message = " bound by an inner scope"
        some_global = some_global + message
        some_closure = some_closure + message
    return inner_function

Of note is that function local and nonlocal are resolved at compile time. A nonlocal name must exist in some outer scope. In contrast, a global name can be defined dynamically and may be added or removed from the global scope at any time.


Comprehensions and Assignment Expressions

The scoping rules of list, set and dict comprehensions and generator expressions are almost the same as for functions. Likewise, the scoping rules for assignment expressions are almost the same as for regular name binding.

The scope of comprehensions and generator expressions is of the same kind as function scope. All names bound in the scope, namely the iteration variables, are locals or closures to the comprehensions/generator and nested scopes. All names, including iterables, are resolved using name resolution as applicable inside functions.

some_global = "global"

def outer_function():
    some_closure = "closure"
    return [            # new function-like scope started by comprehension
        comp_local      # names resolved using regular name resolution
        for comp_local  # iteration targets are local
        in "iterable"
        if comp_local in some_global and comp_local in some_global
    ]

An := assignment expression works on the nearest function, class or global scope. Notably, if the target of an assignment expression has been declared nonlocal or global in the nearest scope, the assignment expression honors this like a regular assignment.

print(some_global := "global")

def outer_function():
    print(some_closure := "closure")

However, an assignment expression inside a comprehension/generator works on the nearest enclosing scope of the comprehension/generator, not the scope of the comprehension/generator itself. When several comprehensions/generators are nested, the nearest function or global scope is used. Since the comprehension/generator scope can read closures and global variables, the assignment variable is readable in the comprehension as well. Assigning from a comprehension to a class scope is not valid.

print(some_global := "global")

def outer_function():
    print(some_closure := "closure")
    steps = [
        # v write to variable in containing scope
        (some_closure := some_closure + comp_local)
        #                 ^ read from variable in containing scope
        for comp_local in some_global
    ]
    return some_closure, steps

While the iteration variable is local to the comprehension in which it is bound, the target of the assignment expression does not create a local variable and is read from the outer scope:

? builtins           [print, ...]
??? globals            [some_global]
  ??? outer_function     [some_closure]
    ??? <listcomp>         [comp_local]

Specify the from user when sending email using the mail command

None of the above worked for me. And it took me long to figure it out, hopefully this helps the next guy.

I'm using Ubuntu 12.04 LTS with mailutils v2.1.

I found this solutions somewhere on the net, don't know where, can't find it again:

-aFrom:[email protected]

Full Command used:

cat /root/Reports/ServerName-Report-$DATE.txt | mail -s "Server-Name-Report-$DATE" [email protected] -aFrom:[email protected]

How to hide TabPage from TabControl

I also had this question. tabPage.Visible is not implemented as stated earlier, which was a great help (+1). I found you can override the control and this will work. A bit of necroposting, but I thought to post my solution here for others...

    [System.ComponentModel.DesignerCategory("Code")]
public class MyTabPage : TabPage
{
    private TabControl _parent;
    private bool _isVisible;
    private int _index;
    public new bool Visible
    {
        get { return _isVisible; }
        set
        {
            if (_parent == null) _parent = this.Parent as TabControl;
            if (_parent == null) return;

            if (_index < 0) _index = _parent.TabPages.IndexOf(this);
            if (value && !_parent.TabPages.Contains(this))
            {
                if (_index > 0) _parent.TabPages.Insert(_index, this);
                else _parent.TabPages.Add(this);
            }
            else if (!value && _parent.TabPages.Contains(this)) _parent.TabPages.Remove(this);

            _isVisible = value;
            base.Visible = value;
        }
    }

    protected override void InitLayout()
    {
        base.InitLayout();
        _parent = Parent as TabControl;
    }
}

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

I think the confusing aspect of this is the fact that BootStrap 3 is a mobile first responsive system and fails to explain how this affects the col-xx-n hierarchy in that part of the Bootstrap documentation. This makes you wonder what happens on smaller devices if you choose a value for larger devices and makes you wonder if there is a need to specify multiple values. (You don't)

I would attempt to clarify this by stating that... Lower grain types (xs, sm) attempt retain layout appearance on smaller screens and larger types (md,lg) will display correctly only on larger screens but will wrap columns on smaller devices. The values quoted in previous examples refer to the threshold as which bootstrap degrades the appearance to fit the available screen estate.

What this means in practice is that if you make the columns col-xs-n then they will retain correct appearance even on very small screens, until the window drops to a size that is so restrictive that the page cannot be displayed correctly. This should mean that devices that have a width of 768px or less should show your table as you designed it rather than in degraded (single or wrapped column form). Obviously this still depends on the content of the columns and that's the whole point. If the page attempts to display multiple columns of large data, side by side on a small screen then the columns will naturally wrap in a horrible way if you did not account for it. Therefore, depending on the data within the columns you can decide the point at which the layout is sacificed to display the content adequately.

e.g. If your page contains three col-sm-n columns bootstrap would wrap the columns into rows when the page width drops below 992px. This means that the data is still visible but will require vertical scrolling to view it. If you do not want your layout to degrade, choose xs (as long as your data can be adequately displayed on a lower resolution device in three columns)

If the horizontal position of the data is important then you should try to choose lower granularity values to retain the visual nature. If the position is less important but the page must be visible on all devices then a higher value should be used.

If you choose col-lg-n then the columns will display correctly until the screen width drops below the xs threshold of 1200px.

Comprehensive methods of viewing memory usage on Solaris

# echo ::memstat | mdb -k
Page Summary                Pages                MB  %Tot
------------     ----------------  ----------------  ----
Kernel                       7308                57   23%
Anon                         9055                70   29%
Exec and libs                1968                15    6%
Page cache                   2224                17    7%
Free (cachelist)             6470                50   20%
Free (freelist)              4641                36   15%

Total                       31666               247
Physical                    31256               244

How to scroll table's "tbody" independent of "thead"?

The missing part is:

thead, tbody {
    display: block;
}

Demo

How should you diagnose the error SEHException - External component has thrown an exception

Just another information... Had that problem today on a Windows 2012 R2 x64 TS system where the application was started from a unc/network path. The issue occured for one application for all terminal server users. Executing the application locally worked without problems. After a reboot it started working again - the SEHException's thrown had been Constructor init and TargetInvocationException

Oracle SQL escape character (for a '&')

the & is the default value for DEFINE, which allows you to use substitution variables. I like to turn it off using

SET DEFINE OFF

then you won't have to worry about escaping or CHR(38).

How to compare Boolean?

Regarding the performance of the direct operations and the method .equals(). The .equals() methods seems to be roughly 4 times slower than ==.

I ran the following tests..

For the performance of ==:

public class BooleanPerfCheck {

    public static void main(String[] args) {
        long frameStart;
        long elapsedTime;

        boolean heyderr = false;

        frameStart = System.currentTimeMillis();

        for (int i = 0; i < 999999999; i++) {
            if (heyderr == false) {
            }
        }

        elapsedTime = System.currentTimeMillis() - frameStart;
        System.out.println(elapsedTime);
    }
}

and for the performance of .equals():

public class BooleanPerfCheck {

    public static void main(String[] args) {
        long frameStart;
        long elapsedTime;

        Boolean heyderr = false;

        frameStart = System.currentTimeMillis();

        for (int i = 0; i < 999999999; i++) {
            if (heyderr.equals(false)) {
            }
        }

        elapsedTime = System.currentTimeMillis() - frameStart;
        System.out.println(elapsedTime);
    }
}

Total system time for == was 1

Total system time for .equals() varied from 3 - 5

Thus, it is safe to say that .equals() hinders performance and that == is better to use in most cases to compare Boolean.

Angular - ng: command not found

100% working solution

1) rm -rf /usr/local/lib/node_modules

2)brew uninstall node

3)echo prefix=~/.npm-packages >> ~/.npmrc

4)brew install node

5) npm install -g @angular/cli

Finally and most importantly

6) export PATH="$HOME/.npm-packages/bin:$PATH"

Also if any editor still shown err than write

7) point over there .

100% working

"ORA-01438: value larger than specified precision allowed for this column" when inserting 3

You can't update with a number greater than 1 for datatype number(2,2) is because, the first parameter is the total number of digits in the number and the second one (.i.e 2 here) is the number of digits in decimal part. I guess you can insert or update data < 1. i.e. 0.12, 0.95 etc.

Please check NUMBER DATATYPE in NUMBER Datatype.

How to use and style new AlertDialog from appCompat 22.1 and above

When creating the AlertDialog you can set a theme to use.

Example - Creating the Dialog

AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyAlertDialogStyle);
builder.setTitle("AppCompatDialog");
builder.setMessage("Lorem ipsum dolor...");
builder.setPositiveButton("OK", null);
builder.setNegativeButton("Cancel", null);
builder.show();

styles.xml - Custom style

<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    <!-- Used for the buttons -->
    <item name="colorAccent">#FFC107</item>
    <!-- Used for the title and text -->
    <item name="android:textColorPrimary">#FFFFFF</item>
    <!-- Used for the background -->
    <item name="android:background">#4CAF50</item>
</style>

Result

styled alertdialog

Edit

In order to change the Appearance of the Title, you can do the following. First add a new style:

<style name="MyTitleTextStyle">
    <item name="android:textColor">#FFEB3B</item>
    <item name="android:textAppearance">@style/TextAppearance.AppCompat.Title</item>
</style>

afterwards simply reference this style in your MyAlertDialogStyle:

<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    ...
    <item name="android:windowTitleStyle">@style/MyTitleTextStyle</item>
</style>

This way you can define a different textColor for the message via android:textColorPrimary and a different for the title via the style.