Programs & Examples On #Derived

Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code

I tried most of above. I was developing in Flutter so what worked for me was pub cache repair.

Xcode 10: A valid provisioning profile for this executable was not found

So this won't be the case for everyone but I thought I'd post it here anyway as there doesn't seem be any answers relating to it.

In my case I was working on an app that was being developed in ReactNative, my issue was that although my signing was correct on the main app target the test target did not have any signing applied to it.
For some reason React Native requires that both your app target and your test target are signed in order to install the app on a device.
It does specify this in the official documentation on building for device however its the only instance I have ever seen where the test target is built alongside the app for anything other than testing.

In order to sign your test target, go to your project settings by opening the project navigator (?1) and select your project at the top.

Inside the main editor select your main app target under Targets (should have the same name as your project) and ensure the signing is correct, then select the test target (likely just under your main app target, it should be the same name with Tests appended) and make sure its signed in the same way.

Rebuild your app and it should now install successfully.

Credit for this goes to Leo Lei, his answer here saved me a lot of headache: https://stackoverflow.com/a/48657358/732844

As an aside, if anyone knows why react native requires your test target be built alongside your app target could they let me know? The only reason I can think of is to streamline the interface so react can build a single app and do both running and testing without needing to rebuild but i'm just guessing with that one.

Problems after upgrading to Xcode 10: Build input file cannot be found

File>Project Settings>Change Build Systems to Legacy Build Systems

Xcode 10 Error: Multiple commands produce

In my case, Build archive error vs Xcode10

-1: Multiple commands produce '/Users/kk/Library/Developer/Xcode/DerivedData/react_carday_app-hjahojxsbvmmiyaklrhhuqljdfwv/Build/Intermediates.noindex/ArchiveIntermediates/react_carday_app/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/libyoga.a': 1) Target 'yoga' has a command with output '/Users/kk/Library/Developer/Xcode/DerivedData/react_carday_app-hjahojxsbvmmiyaklrhhuqljdfwv/Build/Intermediates.noindex/ArchiveIntermediates/react_carday_app/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/libyoga.a' 2) Target 'yoga' has a command with output '/Users/kk/Library/Developer/Xcode/DerivedData/react_carday_app-hjahojxsbvmmiyaklrhhuqljdfwv/Build/Intermediates.noindex/ArchiveIntermediates/react_carday_app/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/libyoga.a'

There should something like bellow in your Podfile

post_install do |installer|
  installer.pods_project.targets.each do |target|
    if target.name == "React"
      target.remove_from_project
    end

    if target.name == "yoga"
      target.remove_from_project
    end
  end
end

and then run pod install

How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps

As mentioned by Dan Abramov

Do it right inside render

We actually use that approach with memoise one for any kind of proxying props to state calculations.

Our code looks this way

// ./decorators/memoized.js  
import memoizeOne from 'memoize-one';

export function memoized(target, key, descriptor) {
  descriptor.value = memoizeOne(descriptor.value);
  return descriptor;
}

// ./components/exampleComponent.js
import React from 'react';
import { memoized } from 'src/decorators';

class ExampleComponent extends React.Component {
  buildValuesFromProps() {
    const {
      watchedProp1,
      watchedProp2,
      watchedProp3,
      watchedProp4,
      watchedProp5,
    } = this.props
    return {
      value1: buildValue1(watchedProp1, watchedProp2),
      value2: buildValue2(watchedProp1, watchedProp3, watchedProp5),
      value3: buildValue3(watchedProp3, watchedProp4, watchedProp5),
    }
  }

  @memoized
  buildValue1(watchedProp1, watchedProp2) {
    return ...;
  }

  @memoized
  buildValue2(watchedProp1, watchedProp3, watchedProp5) {
    return ...;
  }

  @memoized
  buildValue3(watchedProp3, watchedProp4, watchedProp5) {
    return ...;
  }

  render() {
    const {
      value1,
      value2,
      value3
    } = this.buildValuesFromProps();

    return (
      <div>
        <Component1 value={value1}>
        <Component2 value={value2}>
        <Component3 value={value3}>
      </div>
    );
  }
}

The benefits of it are that you don't need to code tons of comparison boilerplate inside getDerivedStateFromProps or componentWillReceiveProps and you can skip copy-paste initialization inside a constructor.

NOTE:

This approach is used only for proxying the props to state, in case you have some inner state logic it still needs to be handled in component lifecycles.

Getting Image from API in Angular 4/5+?

angular 5 :

 getImage(id: string): Observable<Blob> {
    return this.httpClient.get('http://myip/image/'+id, {responseType: "blob"});
}

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

In my case the reason of the error is library which was linked two times.

I use react-native so it was linked automatically using react-native link and manually in xcode.

How to register multiple implementations of the same interface in Asp.Net Core?

While the out of the box implementation doesn't offer it, here's a sample project that allows you to register named instances, and then inject INamedServiceFactory into your code and pull out instances by name. Unlike other facory solutions here, it will allow you to register multiple instances of same implementation but configured differently

https://github.com/macsux/DotNetDINamedInstances

error TS2339: Property 'x' does not exist on type 'Y'

Starting with TypeScript 2.2 using dot notation to access indexed properties is allowed. You won't get error TS2339 on your example.

See Dotted property for types with string index signatures in TypeScript 2.2 release note.

Understanding React-Redux and mapStateToProps()

Q: Is this ok?
A: yes

Q: Is this expected?
Yes, this is expected (if you are using react-redux).

Q: Is this an anti-pattern?
A: No, this is not an anti-pattern.

It's called "connecting" your component or "making it smart". It's by design.

It allows you to decouple your component from your state an additional time which increases the modularity of your code. It also allows you to simplify your component state as a subset of your application state which, in fact, helps you comply with the Redux pattern.

Think about it this way: a store is supposed to contain the entire state of your application.
For large applications, this could contain dozens of properties nested many layers deep.
You don't want to haul all that around on each call (expensive).

Without mapStateToProps or some analog thereof, you would be tempted to carve up your state another way to improve performance/simplify.

How can I delete derived data in Xcode 8?

Go to Xcode -> Project Settings

enter image description here

You can find the way to go to derived Data

enter image description here

How to extend / inherit components?

Angular 2 version 2.3 was just released, and it includes native component inheritance. It looks like you can inherit and override whatever you want, except for templates and styles. Some references:

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

Given a column of numbers:

lst = []
cols = ['A']
for a in range(100, 105):
    lst.append([a])
df = pd.DataFrame(lst, columns=cols, index=range(5))
df

    A
0   100
1   101
2   102
3   103
4   104

You can reference the previous row with shift:

df['Change'] = df.A - df.A.shift(1)
df

    A   Change
0   100 NaN
1   101 1.0
2   102 1.0
3   103 1.0
4   104 1.0

command/usr/bin/codesign failed with exit code 1- code sign error

This worked for me. Give it a try:

cd ~/Library/Developer/Xcode/DerivedData
xattr -rc .

ps command doesn't work in docker container

Firstly, run the command below:

apt-get update && apt-get install procps

and then run:

ps -ef

Undefined symbols for architecture x86_64 on Xcode 6.1

It turned out I forgot to write my @implementation part.

Command failed due to signal: Segmentation fault: 11

object.doubleValue = dict["doublevalue"] as! Int

I found the reason after rolling back each step I made.... force casting to Int for a Double variable

The given key was not present in the dictionary. Which key?

If you want to manage key misses you should use TryGetValue

https://msdn.microsoft.com/en-gb/library/bb347013(v=vs.110).aspx

string value = "";
if (openWith.TryGetValue("tif", out value))
{
    Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
    Console.WriteLine("Key = \"tif\" is not found.");
}

OS X Framework Library not loaded: 'Image not found'

So I managed to get it working, it's quite simple when you have the right instructions. What I was looking for was a 'private' framework which lives in the App bundle rather than being written to the system library folder.

Building The Framework

  1. Add a target to create a Cocoa Framework
  2. Within that targets 'Build Settings' configure the 'Installation Directory' to '@executable_path/../Frameworks'
  3. Build library, and access the .framework from the archive or products directory

Including The Framework

  1. Drag the created .framework file into the Xcode Project, be sure to tick 'Copy Files to Directory'
  2. In the containing applications target, add a new 'Copy File Build Phase'
  3. Set the 'Destination' to 'Frameworks'
  4. Drag in the created .framework

"The file "MyApp.app" couldn't be opened because you don't have permission to view it" when running app in Xcode 6 Beta 4

I would go to the folder where your Xcode docs are and hit command + I to get info. At the bottom, hit the lock to unlock the folder to edit permission. If permissions look good, check the box that says to apply to enclosed folders and let that do it's thing. I haven't seen this personally and not sure if that's what you were saying in your post when you edit the build permissions.

Duplicate symbols for architecture x86_64 under Xcode

I experienced this issue after installing Cocoapods. Now happens everytime I update some pods. Solution I've found:

Go to terminal:

1) pod deintegrate
2) pod install

Also, check the item "Always Embed Swift Libraries" in your Build Settings. It should be "faded" indicating it is using the default configuration. If its set to a manual YES, hit delete over it to revert it to the default configuration. This stopped the behavior.

Xcode - ld: library not found for -lPods

If you have multiple targets in your project, Cocoapods may have only integrated itself well with just one of them.

I had to manually link to libPods.a in "Link Binary With Libraries" for each additional target I had.

libPods.a in my list of frameworks

How to wrap async function calls into a sync function in Node.js or Javascript?

deasync turns async function into sync, implemented with a blocking mechanism by calling Node.js event loop at JavaScript layer. As a result, deasync only blocks subsequent code from running without blocking entire thread, nor incuring busy wait. With this module, here is the answer to the jsFiddle challenge:

function AnticipatedSyncFunction(){
  var ret;
  setTimeout(function(){
      ret = "hello";
  },3000);
  while(ret === undefined) {
    require('deasync').runLoopOnce();
  }
  return ret;    
}


var output = AnticipatedSyncFunction();
//expected: output=hello (after waiting for 3 sec)
console.log("output="+output);
//actual: output=hello (after waiting for 3 sec)

(disclaimer: I am the co-author of deasync. The module was created after posting this question and found no workable proposal.)

What is the logic behind the "using" keyword in C++?

In C++11, the using keyword when used for type alias is identical to typedef.

7.1.3.2

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

Bjarne Stroustrup provides a practical example:

typedef void (*PFD)(double);    // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double);    // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP

Pre-C++11, the using keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):

class Derived : public Base { 
public: 
    using Base::f;    // lift Base's f into Derived's scope -- works in C++98
    void f(char);     // provide a new f 
    void f(int);      // prefer this f to Base::f(int) 

    using Base::Base; // lift Base constructors Derived's scope -- C++11 only
    Derived(char);    // provide a new constructor 
    Derived(int);     // prefer this constructor to Base::Base(int) 
    // ...
}; 

Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard, Design decisions, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.


Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.

First let’s consider a toy example:

template <typename T>
class MyAlloc {/*...*/};

template <typename T, class A>
class MyVector {/*...*/};

template <typename T>

struct Vec {
typedef MyVector<T, MyAlloc<T> > type;
};
Vec<int>::type p; // sample usage

The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.

template <typename T> void foo (Vec<T>::type&);

So, the syntax is somewhat ugly. We would rather avoid the nested ::type We’d prefer something like the following:

template <typename T>
using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below
Vec<int> p; // sample usage

Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on Vec<T> in deducible context, and the syntax is improved as well. For example we could rewrite foo as:

template <typename T> void foo (Vec<T>&);

We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to foo(p) will succeed.


The follow-up paper n1489 explains why using instead of using typedef:

It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:

template<class T> 
    typedef std::vector<T, MyAllocator<T> > Vec;

That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template; Vec is not an alias for a type, and should not be taken for a typedef-name. The name Vec is a name for the family std::vector< [bullet] , MyAllocator< [bullet] > > – where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentence

template<class T>
    using Vec = std::vector<T, MyAllocator<T> >;

can be read/interpreted as: from now on, I’ll be using Vec<T> as a synonym for std::vector<T, MyAllocator<T> >. With that reading, the new syntax for aliasing seems reasonably logical.

I think the important distinction is made here, aliases instead of types. Another quote from the same document:

An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.

Summary, for the role of using:

  • template aliases (or template typedefs, the former is preferred namewise)
  • namespace aliases (i.e., namespace PO = boost::program_options and using PO = ... equivalent)
  • the document says A typedef declaration can be viewed as a special case of non-template alias-declaration. It's an aesthetic change, and is considered identical in this case.
  • bringing something into scope (for example, namespace std into the global scope), member functions, inheriting constructors

It cannot be used for:

int i;
using r = i; // compile-error

Instead do:

using r = decltype(i);

Naming a set of overloads.

// bring cos into scope
using std::cos;

// invalid syntax
using std::cos(double);

// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);

Concatenate string with field value in MySQL

MySQL uses CONCAT() to concatenate strings

SELECT * FROM tableOne 
LEFT JOIN tableTwo
ON tableTwo.query = CONCAT('category_id=', tableOne.category_id)

Undefined symbols for architecture arm64

Here are some explanations why build_active_architecture is set to NO. Xcode now detects which devices you have connected and will set the active architecture accordingly. So if you plug a 2nd generation iPod Touch into your computer, Xcode should set the active architecture to armv6. Building your target with the above Debug configuration will now only build the armv6 binary to save time (unless you have a huge project you may not notice the difference but I guess the seconds add up over time).

When you create a Distribution configuration for publishing to the App Store, you should make sure this option is not set, so that Xcode will instead build the fat universal binary http://useyourloaf.com/blog/2010/04/21/xcode-build-active-architecture-only.html

How to use a calculated column to calculate another column in the same view

You have to include the expression for your calculated column:

SELECT  
ColumnA,  
ColumnB,  
ColumnA + ColumnB AS calccolumn1  
(ColumnA + ColumnB) / ColumnC AS calccolumn2

Can I safely delete contents of Xcode Derived data folder?

 $ du -h -d=1 ~/Library/Developer/Xcode/*

shows at least two folders are huge:

 1.5G   /Users/horace/Library/Developer/Xcode/DerivedData
 9.4G   /Users/horace/Library/Developer/Xcode/iOS DeviceSupport

Feel free to remove stuff in the folders:

 rm -rf ~/Library/Developer/Xcode/DerivedData/*

and some in:

 open ~/Library/Developer/Xcode/iOS\ DeviceSupport/

How to get raw text from pdf file using java

Hi we can extract the pdf files using Apache Tika

The Example is :

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;

public class WebPagePdfExtractor {

    public Map<String, Object> processRecord(String url) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            InputStream input = null;
            if (entity != null) {
                try {
                    input = entity.getContent();
                    BodyContentHandler handler = new BodyContentHandler();
                    Metadata metadata = new Metadata();
                    AutoDetectParser parser = new AutoDetectParser();
                    ParseContext parseContext = new ParseContext();
                    parser.parse(input, handler, metadata, parseContext);
                    map.put("text", handler.toString().replaceAll("\n|\r|\t", " "));
                    map.put("title", metadata.get(TikaCoreProperties.TITLE));
                    map.put("pageCount", metadata.get("xmpTPg:NPages"));
                    map.put("status_code", response.getStatusLine().getStatusCode() + "");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (input != null) {
                        try {
                            input.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return map;
    }

    public static void main(String arg[]) {
        WebPagePdfExtractor webPagePdfExtractor = new WebPagePdfExtractor();
        Map<String, Object> extractedMap = webPagePdfExtractor.processRecord("http://math.about.com/library/q20.pdf");
        System.out.println(extractedMap.get("text"));
    }

}

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

ORDER BY column OFFSET 0 ROWS

Surprisingly makes it work, what a strange feature.

A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:

;WITH cte AS (
    SELECT .....long select statement here....
)

SELECT * FROM 
(
    SELECT * FROM 
    ( -- necessary to nest selects for union to work with where & order clauses
        SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS 
    ) first
    UNION ALL
    SELECT * FROM 
    (  
        SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS 
    ) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example

So we get all results ordered by MainCol

But the results with MainCol = 1 get ordered by ColX

And the results with MainCol = 0 get ordered by ColY

creating triggers for After Insert, After Update and After Delete in SQL

(Update: overlooked a fault in the matter, I have corrected)

(Update2: I wrote from memory the code screwed up, repaired it)

(Update3: check on SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150)
    ,Questions nvarchar(100)
    ,Answer nvarchar(100)
    )

go

CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
        inner join deleted d on i.BusinessUnit = d.BusinessUnit
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
    FROM 
        deleted d
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

delete Derived_Values;

and then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


Record Count: 0;

BUSINESSUNIT    QUESTIONS   ANSWER
Updated Record -- After Update Trigger.BU1  Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1  Q11 A11
Updated Record -- After Update Trigger.BU1  Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1  Q12 A12
Updated Record -- After Update Trigger.BU2  Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2  Q21 A21
Updated Record -- After Update Trigger.BU2  Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2  Q22 A22

(Update4: If you want to sync: SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

CREATE TRIGGER trgAfterInsert ON  [Derived_Values]
FOR INSERT
AS  
begin
    insert
        [Derived_Values_Test]
        (BusinessUnit,Questions,Answer)
    SELECT 
        i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
end

go


CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    update
        [Derived_Values_Test]
    set
        --BusinessUnit = i.BusinessUnit
        --,Questions = i.Questions
        Answer = i.Answer
    from
        [Derived_Values]
        inner join inserted i 
    on
        [Derived_Values].BusinessUnit = i.BusinessUnit
        and
        [Derived_Values].Questions = i.Questions
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR DELETE
AS  
begin
    delete 
        [Derived_Values_Test]
    from
        [Derived_Values_Test]
        inner join deleted d 
    on
        [Derived_Values_Test].BusinessUnit = d.BusinessUnit
        and
        [Derived_Values_Test].Questions = d.Questions
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

--delete Derived_Values;

And then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

$location / switching between html5 and hashbang mode / link rewriting

Fur future readers, if you are using Angular 1.6, you also need to change the hashPrefix:

appModule.config(['$locationProvider', function($locationProvider) {
    $locationProvider.html5Mode(true);
    $locationProvider.hashPrefix('');
}]);

Don't forget to set the base in your HTML <head>:

<head>
    <base href="/">
    ...
</head>

More info about the changelog here.

C# : Converting Base Class to Child Class

I don't think you can downcast an object, however there is a simple way to "downcast" the object outside the box. It isn't type safe, but it works. First serialize the object into json, then deserialize it into the child class object. It works the same as if you were passing the object between apis. So, while there are some people who may say "this doesn't work or isn't good", I would argue that it is exactly the way our internet currently works, so... why not use that method? No mapping required as long as parameter names are the same, and they will be if it is a child class. Note: This will likely not copy any private fields; if you have a constructor with parameters, this probably needs to be tested as well to ensure there aren't side effects.

Here's my toolbox:

public static string ConvertToJson<T>(this T obj)
{
    return JsonConvert.SerializeObject(obj);
}
public static T ConvertToObject<T>(this string json)
{
    if (string.IsNullOrEmpty(json))
    {
        return Activator.CreateInstance<T>();
    }
    return JsonConvert.DeserializeObject<T>(json);
}

Here's how to use it:

var sfcl = networkClient.ConvertToJson().ConvertToObject<SkyfilterClient>();

C++ calling base class constructors

In c++, compiler always ensure that functions in object hierarchy are called successfully. These functions are constructors and destructors and object hierarchy means inheritance tree.

According to this rule we can guess compiler will call constructors and destructors for each object in inheritance hierarchy even if we don't implement it. To perform this operation compiler will synthesize the undefined constructors and destructors for us and we name them as a default constructors and destructors.Then, compiler will call default constructor of base class and then calls constructor of derived class.

In your case you don't call base class constructor but compiler does that for you by calling default constructor of base class because if compiler didn't do it your derived class which is Rectangle in your example will not be complete and it might cause disaster because maybe you will use some member function of base class in your derived class. So for the sake of safety compiler always need all constructor calls.

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

SSIS Convert Between Unicode and Non-Unicode Error

The missing piece here is Data Conversion object. It should be in between OLE DB Source and Destination object.

enter image description here

How to use order by with union all in sql?

You don't really need to have parenthesis. You can sort directly:

SELECT *, 1 AS RN FROM TABLE_A
UNION ALL 
SELECT *, 2 AS RN FROM TABLE_B
ORDER BY RN, COLUMN_1

MVC 4 client side validation not working

the line below shows you haven't set an DataAttribute like required on AgreementNumber

<input id="AgreementNumber" name="AgreementNumber" size="30" type="text" value="387893" />

you need

[Required]
public String AgreementNumber{get;set;}

Xcode stuck on Indexing

Nothing worked for me, my project is too big (merging objective c, c++, swift, and java files with j2obj). I've disabled Xcode indexing and worked without code completion for months (and it's a pain). But finally I've found a workaround. The idea is to keep Xcode indexing the code, but to limit its CPU usage with an external tool like cputhrottle.

So first you need to install cputhrottle in terminal

brew install cputhrottle

Then limit the Xcode indexing process like this (20 = 20%)

sudo cputhrottle $(pgrep -f com.apple.dt.SKAgent) 20

I've exposed my "solution" here with mode details : How to prevent Xcode using 100% of CPU when indexing big projects

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

I had this problem, except the type it couldn't load was System.Reflection.AssemblyMetadataAttribute. The web application was built on a machine with .NET 4.5 installed (runs fine there), with 4.0 as the target framework, but the error presented itself when it was run on a web server with only 4.0 installed. I then tried it on a web server with 4.5 installed and there was no error. So, as others have said, this is all due to the screwy way Microsoft released 4.5, which basically is an upgrade to (and overwrite of) version 4.0. The System.Reflection assembly references a type that doesn't exist in 4.0 (AssemblyMetadataAttribute) so it will fail if you don't have the new System.Reflection.dll.

You can either install .NET 4.5 on the target web server, or build the application on a machine that does not have 4.5 installed. Far from an ideal resolution.

how to fix the issue "Command /bin/sh failed with exit code 1" in iphone

I did all above and spent an hour on the issue.

Tried everything above as well as restarted Xcode.

Finally, restarted computer and everything working normally again!

Oracle: not a valid month

To know the actual date format, insert a record by using sysdate. That way you can find the actual date format. for example

insert into emp values(7936, 'Mac', 'clerk', 7782, sysdate, 1300, 300, 10);

now, select the inserted record.

select ename, hiredate from emp where ename='Mac';

the result is

ENAME   HIREDATE
Mac     06-JAN-13

voila, now your actual date format is found.

Convert base class to derived class

No, there's no built-in way to convert a class like you say. The simplest way to do this would be to do what you suggested: create a DerivedClass(BaseClass) constructor. Other options would basically come out to automate the copying of properties from the base to the derived instance, e.g. using reflection.

The code you posted using as will compile, as I'm sure you've seen, but will throw a null reference exception when you run it, because myBaseObject as DerivedClass will evaluate to null, since it's not an instance of DerivedClass.

How to bind WPF button to a command in ViewModelBase?

 <Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>

the code behind for the window:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModelBase();
    }
}

The ViewModel:

public class ViewModelBase
{
    private ICommand _clickCommand;
    public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
        }
    }
     public bool CanExecute
     {
        get
        {
            // check if executing is allowed, i.e., validate, check if a process is running, etc. 
            return true/false;
        }
     }

    public void MyAction()
    {

    }
}

Command Handler:

 public class CommandHandler : ICommand
{
    private Action _action;
    private Func<bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action action, Func<bool> canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute.Invoke();
    }

    public void Execute(object parameter)
    {
        _action();
    }
}

I hope this will give you the idea.

Use the XmlInclude or SoapInclude attribute to specify types that are not known statically

Just solved the issue. After digging around for a while longer, I found this SO post which covers the exact same situation. It got me in the right track.

Basically, the XmlSerializer needs to know the default namespace if derived classes are included as extra types. The exact reason why this has to happen is still unknown but, still, serialization is working now.

Sending files using POST with HttpURLConnection

To upload file on server with some parameter using MultipartUtility in simple way.

MultipartUtility.java

public class MultipartUtility {

    private final String boundary;
    private static final String LINE_FEED = "\r\n";
    private HttpURLConnection httpConn;
    private String charset;
    private OutputStream outputStream;
    private PrintWriter writer;

    /**
     * This constructor initializes a new HTTP POST request with content type
     * is set to multipart/form-data
     *
     * @param requestURL
     * @param charset
     * @throws IOException
     */
    public MultipartUtility(String requestURL, String charset)
            throws IOException {
        this.charset = charset;

        // creates a unique boundary based on time stamp
        boundary = "===" + System.currentTimeMillis() + "===";

        URL url = new URL(requestURL);
        Log.e("URL", "URL : " + requestURL.toString());
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);
        httpConn.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + boundary);
        httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
        httpConn.setRequestProperty("Test", "Bonjour");
        outputStream = httpConn.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
                true);
    }

    /**
     * Adds a form field to the request
     *
     * @param name  field name
     * @param value field value
     */
    public void addFormField(String name, String value) {
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
                .append(LINE_FEED);
        writer.append("Content-Type: text/plain; charset=" + charset).append(
                LINE_FEED);
        writer.append(LINE_FEED);
        writer.append(value).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Adds a upload file section to the request
     *
     * @param fieldName  name attribute in <input type="file" name="..." />
     * @param uploadFile a File to be uploaded
     * @throws IOException
     */
    public void addFilePart(String fieldName, File uploadFile)
            throws IOException {
        String fileName = uploadFile.getName();
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append(
                "Content-Disposition: form-data; name=\"" + fieldName
                        + "\"; filename=\"" + fileName + "\"")
                .append(LINE_FEED);
        writer.append(
                "Content-Type: "
                        + URLConnection.guessContentTypeFromName(fileName))
                .append(LINE_FEED);
        writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
        writer.append(LINE_FEED);
        writer.flush();

        FileInputStream inputStream = new FileInputStream(uploadFile);
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.flush();
        inputStream.close();

        writer.append(LINE_FEED);
        writer.flush();
    }

    /**
     * Adds a header field to the request.
     *
     * @param name  - name of the header field
     * @param value - value of the header field
     */
    public void addHeaderField(String name, String value) {
        writer.append(name + ": " + value).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Completes the request and receives response from the server.
     *
     * @return a list of Strings as response in case the server returned
     * status OK, otherwise an exception is thrown.
     * @throws IOException
     */
    public String finish() throws IOException {
        StringBuffer response = new StringBuffer();

        writer.append(LINE_FEED).flush();
        writer.append("--" + boundary + "--").append(LINE_FEED);
        writer.close();

        // checks server's status code first
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpConn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            httpConn.disconnect();
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }

        return response.toString();
    }
}

To upload you file along with parameters.

NOTE : put this code below in non-ui-thread to get response.

String charset = "UTF-8";
String requestURL = "YOUR_URL";

MultipartUtility multipart = new MultipartUtility(requestURL, charset);
multipart.addFormField("param_name_1", "param_value");
multipart.addFormField("param_name_2", "param_value");
multipart.addFormField("param_name_3", "param_value");
multipart.addFilePart("file_param_1", new File(file_path));
String response = multipart.finish(); // response from server.

How to use LINQ Distinct() with multiple fields

public List<ItemCustom2> GetBrandListByCat(int id)
    {

        var OBJ = (from a in db.Items
                   join b in db.Brands on a.BrandId equals b.Id into abc1
                   where (a.ItemCategoryId == id)
                   from b in abc1.DefaultIfEmpty()
                   select new
                   {
                       ItemCategoryId = a.ItemCategoryId,
                       Brand_Name = b.Name,
                       Brand_Id = b.Id,
                       Brand_Pic = b.Pic,

                   }).Distinct();


        List<ItemCustom2> ob = new List<ItemCustom2>();
        foreach (var item in OBJ)
        {
            ItemCustom2 abc = new ItemCustom2();
            abc.CategoryId = item.ItemCategoryId;
            abc.BrandId = item.Brand_Id;
            abc.BrandName = item.Brand_Name;
            abc.BrandPic = item.Brand_Pic;
            ob.Add(abc);
        }
        return ob;

    }

Command /Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1

My problem was that under Build Phases -> Compile Sources, I added a compiler flag for a file, but I had misspelled it. It was supposed to be:

-fno-obj-arc

to show that this file does not use ARC.

Calling the base class constructor from the derived class constructor

First off, a PetStore is not a farm.

Let's get past this though. You actually don't need access to the private members, you have everything you need in the public interface:

Animal_* getAnimal_(int i);
void addAnimal_(Animal_* newAnimal);

These are the methods you're given access to and these are the ones you should use.

I mean I did this Inheritance so I can add animals to my PetStore but now since sizeF is private how can I do that ??

Simple, you call addAnimal. It's public and it also increments sizeF.

Also, note that

PetStore()
{
 idF=0;
};

is equivalent to

PetStore() : Farm()
{
 idF=0;
};

i.e. the base constructor is called, base members are initialized.

Copying a HashMap in Java

Since the OP has mentioned he does not have access to the base class inside of which exists a HashMap - I am afraid there are very few options available.

One (painfully slow and resource intensive) way of performing a deep copy of an object in Java is to abuse the 'Serializable' interface which many classes either intentionally - or unintentionally extend - and then utilise this to serialise your class to ByteStream. Upon de-serialisation you will have a deep copy of the object in question.

A guide for this can be found here: https://www.avajava.com/tutorials/lessons/how-do-i-perform-a-deep-clone-using-serializable.html

How to fix System.NullReferenceException: Object reference not set to an instance of an object

I had the same problem but it only occurred on the published website on Godaddy. It was no problem in my local host.

The error came from an aspx.cs (code behind file) where I tried to assign a value to a label. It appeared that from within the code behind, that the label Text appears to be null. So all I did with change all my Label Text properties in the ASPX file from Text="" to Text=" ".

The problem disappeared. I don’t know why the error happens from the hosted version but not on my localhost and don’t have time to figure out why. But it works fine now.

What is the purpose of the "final" keyword in C++11 for functions?

Nothing to add to the semantic aspects of "final".

But I'd like to add to chris green's comment that "final" might become a very important compiler optimization technique in the not so distant future. Not only in the simple case he mentioned, but also for more complex real-world class hierarchies which can be "closed" by "final", thus allowing compilers to generate more efficient dispatching code than with the usual vtable approach.

One key disadvantage of vtables is that for any such virtual object (assuming 64-bits on a typical Intel CPU) the pointer alone eats up 25% (8 of 64 bytes) of a cache line. In the kind of applications I enjoy to write, this hurts very badly. (And from my experience it is the #1 argument against C++ from a purist performance point of view, i.e. by C programmers.)

In applications which require extreme performance, which is not so unusual for C++, this might indeed become awesome, not requiring to workaround this problem manually in C style or weird Template juggling.

This technique is known as Devirtualization. A term worth remembering. :-)

There is a great recent speech by Andrei Alexandrescu which pretty well explains how you can workaround such situations today and how "final" might be part of solving similar cases "automatically" in the future (discussed with listeners):

http://channel9.msdn.com/Events/GoingNative/2013/Writing-Quick-Code-in-Cpp-Quickly

How to check if a class inherits another class without instantiating it?

To check for assignability, you can use the Type.IsAssignableFrom method:

typeof(SomeType).IsAssignableFrom(typeof(Derived))

This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.

To check for strict inheritance, you can use Type.IsSubclassOf:

typeof(Derived).IsSubclassOf(typeof(SomeType))

Json.net serialize/deserialize derived types?

You have to enable Type Name Handling and pass that to the (de)serializer as a settings parameter.

Base object1 = new Base() { Name = "Object1" };
Derived object2 = new Derived() { Something = "Some other thing" };
List<Base> inheritanceList = new List<Base>() { object1, object2 };

JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
string Serialized = JsonConvert.SerializeObject(inheritanceList, settings);
List<Base> deserializedList = JsonConvert.DeserializeObject<List<Base>>(Serialized, settings);

This will result in correct deserialization of derived classes. A drawback to it is that it will name all the objects you are using, as such it will name the list you are putting the objects in.

How can prepared statements protect from SQL injection attacks?

In SQL Server, using a prepared statement is definitely injection-proof because the input parameters don't form the query. It means that the executed query is not a dynamic query. Example of an SQL injection vulnerable statement.

string sqlquery = "select * from table where username='" + inputusername +"' and password='" + pass + "'";

Now if the value in the inoutusername variable is something like a' or 1=1 --, this query now becomes:

select * from table where username='a' or 1=1 -- and password=asda

And the rest is commented after --, so it never gets executed and bypassed as using the prepared statement example as below.

Sqlcommand command = new sqlcommand("select * from table where username = @userinput and password=@pass");
command.Parameters.Add(new SqlParameter("@userinput", 100));
command.Parameters.Add(new SqlParameter("@pass", 100));
command.prepare();

So in effect you cannot send another parameter in, thus avoiding SQL injection...

Computed / calculated / virtual / derived columns in PostgreSQL

A lightweight solution with Check constraint:

CREATE TABLE example (
    discriminator INTEGER DEFAULT 0 NOT NULL CHECK (discriminator = 0)
);

How can I initialize base class member variables in derived class constructor?

# include<stdio.h>
# include<iostream>
# include<conio.h>

using namespace std;

class Base{
    public:
        Base(int i, float f, double d): i(i), f(f), d(d)
        {
        }
    virtual void Show()=0;
    protected:
        int i;
        float f;
        double d;
};


class Derived: public Base{
    public:
        Derived(int i, float f, double d): Base( i, f, d)
        {
        }
        void Show()
        {
            cout<< "int i = "<<i<<endl<<"float f = "<<f<<endl <<"double d = "<<d<<endl;
        }
};

int main(){
    Base * b = new Derived(10, 1.2, 3.89);
    b->Show();
    return 0;
}

It's a working example in case you want to initialize the Base class data members present in the Derived class object, whereas you want to push these values interfacing via Derived class constructor call.

Removing spaces from string

String  input = EditTextinput.getText().toString();
input = input.replace(" ", "");

Sometimes you would want to remove only the spaces at the beginning or end of the String (not the ones in the middle). If that's the case you can use trim:

input = input.trim();

100% width table overflowing div container

Try adding to td:

display: -webkit-box; // to make td as block
word-break: break-word; // to make content justify

overflowed tds will align with new row.

is inaccessible due to its protection level

In your Main method, you're trying to access, for instance, club (which is protected), when you should be accessing myclub which is the public property that you created.

Create a temporary table in a SELECT statement without a separate CREATE TABLE

In addition to psparrow's answer if you need to add an index to your temporary table do:

CREATE TEMPORARY TABLE IF NOT EXISTS 
  temp_table ( INDEX(col_2) ) 
ENGINE=MyISAM 
AS (
  SELECT col_1, coll_2, coll_3
  FROM mytable
)

It also works with PRIMARY KEY

Get all inherited classes of an abstract class

Assuming they are all defined in the same assembly, you can do:

IEnumerable<AbstractDataExport> exporters = typeof(AbstractDataExport)
    .Assembly.GetTypes()
    .Where(t => t.IsSubclassOf(typeof(AbstractDataExport)) && !t.IsAbstract)
    .Select(t => (AbstractDataExport)Activator.CreateInstance(t));

Apple Mach-O Linker Error when compiling for device

In my case i has include .m file thats why compiler shows this type of error.

you should check the latest file import that is not .m file " Sometime i"

C++ cast to derived class

dynamic_cast should be what you are looking for.

EDIT:

DerivedType m_derivedType = m_baseType; // gives same error

The above appears to be trying to invoke the assignment operator, which is probably not defined on type DerivedType and accepting a type of BaseType.

DerivedType * m_derivedType = (DerivedType*) & m_baseType; // gives same error

You are on the right path here but the usage of the dynamic_cast will attempt to safely cast to the supplied type and if it fails, a NULL will be returned.

Going on memory here, try this (but note the cast will return NULL as you are casting from a base type to a derived type):

DerivedType * m_derivedType = dynamic_cast<DerivedType*>(&m_baseType);

If m_baseType was a pointer and actually pointed to a type of DerivedType, then the dynamic_cast should work.

Hope this helps!

How to use LogonUser properly to impersonate domain user from workgroup client

I have been successfull at impersonating users in another domain, but only with a trust set up between the 2 domains.

var token = IntPtr.Zero;
var result = LogonUser(userID, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token);
if (result)
{
    return WindowsIdentity.Impersonate(token);
}

symbol(s) not found for architecture i386

In my case none of the posted solutions worked. I had to delete the project and make a fresh checkout from the SVN server. Lucky me the project was hosted in a version control system. Don't know what I'd do otherwise.

Element count of an array in C++

_countof(my_array) in MSVC

I can thing of only one case: the array contains elements that are of different derived types of the type of the array.

Elements of an array in C++ are objects, not pointers, so you cannot have derived type object as an element.

And like mentioned above, sizeof(my_array) (like _countof() as well) will work just in the scope of array definition.

When to use Common Table Expression (CTE)

It is very useful when you want to perform an "ordered update".

MS SQL does not allow you to use ORDER BY with UPDATE, but with help of CTE you can do it that way:

WITH cte AS
(
    SELECT TOP(5000) message_compressed, message, exception_compressed, exception
    FROM logs
    WHERE Id >= 5519694 
    ORDER BY Id
)
UPDATE  cte
SET     message_compressed = COMPRESS(message), exception_compressed = COMPRESS(exception)

Look here for more info: How to update and order by using ms sql

Check if a Class Object is subclass of another Class Object in Java

//Inheritance

    class A {
      int i = 10;
      public String getVal() {
        return "I'm 'A'";
      }
    }

    class B extends A {
      int j = 20;
      public String getVal() {
        return "I'm 'B'";
      }
    }

    class C extends B {
        int k = 30;
        public String getVal() {
          return "I'm 'C'";
        }
    }

//Methods

    public static boolean isInheritedClass(Object parent, Object child) {
      if (parent == null || child == null) {
        return false;
      } else {
        return isInheritedClass(parent.getClass(), child.getClass());
      }
    }

    public static boolean isInheritedClass(Class<?> parent, Class<?> child) {
      if (parent == null || child == null) {
        return false;
      } else {
        if (parent.isAssignableFrom(child)) {
          // is child or same class
          return parent.isAssignableFrom(child.getSuperclass());
        } else {
          return false;
        }
      }
    }

// Test the code

    System.out.println("isInheritedClass(new A(), new B()):" + isInheritedClass(new A(), new B()));
    System.out.println("isInheritedClass(new A(), new C()):" + isInheritedClass(new A(), new C()));
    System.out.println("isInheritedClass(new A(), new A()):" + isInheritedClass(new A(), new A()));
    System.out.println("isInheritedClass(new B(), new A()):" + isInheritedClass(new B(), new A()));


    System.out.println("isInheritedClass(A.class, B.class):" + isInheritedClass(A.class, B.class));
    System.out.println("isInheritedClass(A.class, C.class):" + isInheritedClass(A.class, C.class));
    System.out.println("isInheritedClass(A.class, A.class):" + isInheritedClass(A.class, A.class));
    System.out.println("isInheritedClass(B.class, A.class):" + isInheritedClass(B.class, A.class));

//Result

    isInheritedClass(new A(), new B()):true
    isInheritedClass(new A(), new C()):true
    isInheritedClass(new A(), new A()):false
    isInheritedClass(new B(), new A()):false
    isInheritedClass(A.class, B.class):true
    isInheritedClass(A.class, C.class):true
    isInheritedClass(A.class, A.class):false
    isInheritedClass(B.class, A.class):false

How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers

For a solution that uses no branches and only 1 mod, you can do the following

// Works for other sizes too,
// assuming you change 63 to the appropriate value
int64_t mod(int64_t x, int64_t div) {
  return (x % div) + (((x >> 63) ^ (div >> 63)) & div);
}

With MySQL, how can I generate a column containing the record index in a table?

I know the OP is asking for a mysql answer but since I found the other answers not working for me,

  • Most of them fail with order by
  • Or they are simply very inefficient and make your query very slow for a fat table

So to save time for others like me, just index the row after retrieving them from database

example in PHP:

$users = UserRepository::loadAllUsersAndSortByScore();

foreach($users as $index=>&$user){
    $user['rank'] = $index+1;
}

example in PHP using offset and limit for paging:

$limit = 20; //page size
$offset = 3; //page number

$users = UserRepository::loadAllUsersAndSortByScore();

foreach($users as $index=>&$user){
    $user['rank'] = $index+1+($limit*($offset-1));
}

Why do we need virtual functions in C++?

It helps if you know the underlying mechanisms. C++ formalizes some coding techniques used by C programmers, "classes" replaced using "overlays" - structs with common header sections would be used to handle objects of different types but with some common data or operations. Normally the base struct of the overlay (the common part) has a pointer to a function table which points to a different set of routines for each object type. C++ does the same thing but hides the mechanisms i.e. the C++ ptr->func(...) where func is virtual as C would be (*ptr->func_table[func_num])(ptr,...), where what changes between derived classes is the func_table contents. [A non-virtual method ptr->func() just translates to mangled_func(ptr,..).]

The upshot of that is that you only need to understand the base class in order to call the methods of a derived class, i.e. if a routine understands class A, you can pass it a derived class B pointer then the virtual methods called will be those of B rather than A since you go through the function table B points at.

How to call base.base.method()?

In cases where you do not have access to the derived class source, but need all the source of the derived class besides the current method, then I would recommended you should also do a derived class and call the implementation of the derived class.

Here is an example:

//No access to the source of the following classes
public class Base
{
     public virtual void method1(){ Console.WriteLine("In Base");}
}
public class Derived : Base
{
     public override void method1(){ Console.WriteLine("In Derived");}
     public void method2(){ Console.WriteLine("Some important method in Derived");}
}

//Here should go your classes
//First do your own derived class
public class MyDerived : Base
{         
}

//Then derive from the derived class 
//and call the bass class implementation via your derived class
public class specialDerived : Derived
{
     public override void method1()
     { 
          MyDerived md = new MyDerived();
          //This is actually the base.base class implementation
          MyDerived.method1();  
     }         
}

What is the error "Every derived table must have its own alias" in MySQL?

I arrived here because I thought I should check in SO if there are adequate answers, after a syntax error that gave me this error, or if I could possibly post an answer myself.

OK, the answers here explain what this error is, so not much more to say, but nevertheless I will give my 2 cents using my words:

This error is caused by the fact that you basically generate a new table with your subquery for the FROM command.

That's what a derived table is, and as such, it needs to have an alias (actually a name reference to it).

So given the following hypothetical query:

SELECT id, key1
FROM (
    SELECT t1.ID id, t2.key1 key1, t2.key2 key2, t2.key3 key3
    FROM table1 t1 
    LEFT JOIN table2 t2 ON t1.id = t2.id
    WHERE t2.key3 = 'some-value'
) AS tt

So, at the end, the whole subquery inside the FROM command will produce the table that is aliased as tt and it will have the following columns id, key1, key2, key3.

So, then with the initial SELECT from that table we finally select the id and key1 from the tt.

Convert List<DerivedClass> to List<BaseClass>

You can also use the System.Runtime.CompilerServices.Unsafe NuGet package to create a reference to the same List:

using System.Runtime.CompilerServices;
...
class Tool { }
class Hammer : Tool { }
...
var hammers = new List<Hammer>();
...
var tools = Unsafe.As<List<Tool>>(hammers);

Given the sample above, you can access the existing Hammer instances in the list using the tools variable. Adding Tool instances to the list throws an ArrayTypeMismatchException exception because tools references the same variable as hammers.

Resolve absolute path from relative path and/or file name

SET CD=%~DP0

SET REL_PATH=%CD%..\..\build\

call :ABSOLUTE_PATH    ABS_PATH   %REL_PATH%

ECHO %REL_PATH%

ECHO %ABS_PATH%

pause

exit /b

:ABSOLUTE_PATH

SET %1=%~f2

exit /b

event Action<> vs event EventHandler<>

The main difference will be that if you use Action<> your event will not follow the design pattern of virtually any other event in the system, which I would consider a drawback.

One upside with the dominating design pattern (apart from the power of sameness) is that you can extend the EventArgs object with new properties without altering the signature of the event. This would still be possible if you used Action<SomeClassWithProperties>, but I don't really see the point with not using the regular approach in that case.

WPF: Grid with column/row margin/padding?

Though you can't add margin or padding to a Grid, you could use something like a Frame (or similar container), that you can apply it to.

That way (if you show or hide the control on a button click say), you won't need to add margin on every control that may interact with it.

Think of it as isolating the groups of controls into units, then applying style to those units.

SQL Error with Order By in Subquery

This is the error you get (emphasis mine):

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.

So, how can you avoid the error? By specifying TOP, would be one possibility, I guess.

SELECT (
  SELECT TOP 100 PERCENT
  COUNT(1) FROM Seanslar WHERE MONTH(tarihi) = 4
  GROUP BY refKlinik_id
  ORDER BY refKlinik_id
) as dorduncuay

How to call a Parent Class's method from Child Class in Python?

There's a super() in Python too. It's a bit wonky, because of Python's old- and new-style classes, but is quite commonly used e.g. in constructors:

class Foo(Bar):
    def __init__(self):
        super(Foo, self).__init__()
        self.baz = 5

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

Expanding on @ybo's answer - it isn't possible because the instance you have of the base class isn't actually an instance of the derived class. It only knows about the members of the base class, and doesn't know anything about those of the derived class.

The reason that you can cast an instance of the derived class to an instance of the base class is because the derived class actually already is an instance of the base class, since it has those members already. The opposite cannot be said.

How do I correctly clone a JavaScript object?

To do this for any object in JavaScript will not be simple or straightforward. You will run into the problem of erroneously picking up attributes from the object's prototype that should be left in the prototype and not copied to the new instance. If, for instance, you are adding a clone method to Object.prototype, as some answers depict, you will need to explicitly skip that attribute. But what if there are other additional methods added to Object.prototype, or other intermediate prototypes, that you don't know about? In that case, you will copy attributes you shouldn't, so you need to detect unforeseen, non-local attributes with the hasOwnProperty method.

In addition to non-enumerable attributes, you'll encounter a tougher problem when you try to copy objects that have hidden properties. For example, prototype is a hidden property of a function. Also, an object's prototype is referenced with the attribute __proto__, which is also hidden, and will not be copied by a for/in loop iterating over the source object's attributes. I think __proto__ might be specific to Firefox's JavaScript interpreter and it may be something different in other browsers, but you get the picture. Not everything is enumerable. You can copy a hidden attribute if you know its name, but I don't know of any way to discover it automatically.

Yet another snag in the quest for an elegant solution is the problem of setting up the prototype inheritance correctly. If your source object's prototype is Object, then simply creating a new general object with {} will work, but if the source's prototype is some descendant of Object, then you are going to be missing the additional members from that prototype which you skipped using the hasOwnProperty filter, or which were in the prototype, but weren't enumerable in the first place. One solution might be to call the source object's constructor property to get the initial copy object and then copy over the attributes, but then you still will not get non-enumerable attributes. For example, a Date object stores its data as a hidden member:

function clone(obj) {
    if (null == obj || "object" != typeof obj) return obj;
    var copy = obj.constructor();
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
    }
    return copy;
}

var d1 = new Date();

/* Executes function after 5 seconds. */
setTimeout(function(){
    var d2 = clone(d1);
    alert("d1 = " + d1.toString() + "\nd2 = " + d2.toString());
}, 5000);

The date string for d1 will be 5 seconds behind that of d2. A way to make one Date the same as another is by calling the setTime method, but that is specific to the Date class. I don't think there is a bullet-proof general solution to this problem, though I would be happy to be wrong!

When I had to implement general deep copying I ended up compromising by assuming that I would only need to copy a plain Object, Array, Date, String, Number, or Boolean. The last 3 types are immutable, so I could perform a shallow copy and not worry about it changing. I further assumed that any elements contained in Object or Array would also be one of the 6 simple types in that list. This can be accomplished with code like the following:

function clone(obj) {
    var copy;

    // Handle the 3 simple types, and null or undefined
    if (null == obj || "object" != typeof obj) return obj;

    // Handle Date
    if (obj instanceof Date) {
        copy = new Date();
        copy.setTime(obj.getTime());
        return copy;
    }

    // Handle Array
    if (obj instanceof Array) {
        copy = [];
        for (var i = 0, len = obj.length; i < len; i++) {
            copy[i] = clone(obj[i]);
        }
        return copy;
    }

    // Handle Object
    if (obj instanceof Object) {
        copy = {};
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
        }
        return copy;
    }

    throw new Error("Unable to copy obj! Its type isn't supported.");
}

The above function will work adequately for the 6 simple types I mentioned, as long as the data in the objects and arrays form a tree structure. That is, there isn't more than one reference to the same data in the object. For example:

// This would be cloneable:
var tree = {
    "left"  : { "left" : null, "right" : null, "data" : 3 },
    "right" : null,
    "data"  : 8
};

// This would kind-of work, but you would get 2 copies of the 
// inner node instead of 2 references to the same copy
var directedAcylicGraph = {
    "left"  : { "left" : null, "right" : null, "data" : 3 },
    "data"  : 8
};
directedAcyclicGraph["right"] = directedAcyclicGraph["left"];

// Cloning this would cause a stack overflow due to infinite recursion:
var cyclicGraph = {
    "left"  : { "left" : null, "right" : null, "data" : 3 },
    "data"  : 8
};
cyclicGraph["right"] = cyclicGraph;

It will not be able to handle any JavaScript object, but it may be sufficient for many purposes as long as you don't assume that it will just work for anything you throw at it.

What languages are Windows, Mac OS X and Linux written in?

Windows is obviously not written in C# (!)

Simply see the source code of Windows and you'll see...

Getting the class name of an instance?

You can simply use __qualname__ which stands for qualified name of a function or class

Example:

>>> class C:
...     class D:
...         def meth(self):
...             pass
...
>>> C.__qualname__
'C'
>>> C.D.__qualname__
'C.D'
>>> C.D.meth.__qualname__
'C.D.meth'

documentation link qualname

Safely override C++ virtual functions

Something like C#'s override keyword is not part of C++.

In gcc, -Woverloaded-virtual warns against hiding a base class virtual function with a function of the same name but a sufficiently different signature that it doesn't override it. It won't, though, protect you against failing to override a function due to mis-spelling the function name itself.

Check if a class is derived from a generic class

(Reposted due to a massive rewrite)

JaredPar's code answer is fantastic, but I have a tip that would make it unnecessary if your generic types are not based on value type parameters. I was hung up on why the "is" operator would not work, so I have also documented the results of my experimentation for future reference. Please enhance this answer to further enhance its clarity.

TIP:

If you make certain that your GenericClass implementation inherits from an abstract non-generic base class such as GenericClassBase, you could ask the same question without any trouble at all like this:

typeof(Test).IsSubclassOf(typeof(GenericClassBase))

IsSubclassOf()

My testing indicates that IsSubclassOf() does not work on parameterless generic types such as

typeof(GenericClass<>)

whereas it will work with

typeof(GenericClass<SomeType>)

Therefore the following code will work for any derivation of GenericClass<>, assuming you are willing to test based on SomeType:

typeof(Test).IsSubclassOf(typeof(GenericClass<SomeType>))

The only time I can imagine that you would want to test by GenericClass<> is in a plug-in framework scenario.


Thoughts on the "is" operator

At design-time C# does not allow the use of parameterless generics because they are essentially not a complete CLR type at that point. Therefore, you must declare generic variables with parameters, and that is why the "is" operator is so powerful for working with objects. Incidentally, the "is" operator also can not evaluate parameterless generic types.

The "is" operator will test the entire inheritance chain, including interfaces.

So, given an instance of any object, the following method will do the trick:

bool IsTypeof<T>(object t)
{
    return (t is T);
}

This is sort of redundant, but I figured I would go ahead and visualize it for everybody.

Given

var t = new Test();

The following lines of code would return true:

bool test1 = IsTypeof<GenericInterface<SomeType>>(t);

bool test2 = IsTypeof<GenericClass<SomeType>>(t);

bool test3 = IsTypeof<Test>(t);

On the other hand, if you want something specific to GenericClass, you could make it more specific, I suppose, like this:

bool IsTypeofGenericClass<SomeType>(object t)
{
    return (t is GenericClass<SomeType>);
}

Then you would test like this:

bool test1 = IsTypeofGenericClass<SomeType>(t);

How to call a parent class function from derived class function?

I'll take the risk of stating the obvious: You call the function, if it's defined in the base class it's automatically available in the derived class (unless it's private).

If there is a function with the same signature in the derived class you can disambiguate it by adding the base class's name followed by two colons base_class::foo(...). You should note that unlike Java and C#, C++ does not have a keyword for "the base class" (super or base) since C++ supports multiple inheritance which may lead to ambiguity.

class left {
public:
    void foo();
};

class right {
public:
    void foo();
};

class bottom : public left, public right {
public:
    void foo()
    {
        //base::foo();// ambiguous
        left::foo();
        right::foo();

        // and when foo() is not called for 'this':
        bottom b;
        b.left::foo();  // calls b.foo() from 'left'
        b.right::foo();  // call b.foo() from 'right'
    }
};

Incidentally, you can't derive directly from the same class twice since there will be no way to refer to one of the base classes over the other.

class bottom : public left, public left { // Illegal
};

In Java, how do I call a base class's method from the overriding method in a derived class?

super.MyMethod() should be called inside the MyMethod() of the class B. So it should be as follows

class A {
    public void myMethod() { /* ... */ }
}

class B extends A {
    public void myMethod() { 
        super.MyMethod();
        /* Another code */ 
    }
}

Using "super" in C++

Bjarne Stroustrup mentions in Design and Evolution of C++ that super as a keyword was considered by the ISO C++ Standards committee the first time C++ was standardized.

Dag Bruck proposed this extension, calling the base class "inherited." The proposal mentioned the multiple inheritance issue, and would have flagged ambiguous uses. Even Stroustrup was convinced.

After discussion, Dag Bruck (yes, the same person making the proposal) wrote that the proposal was implementable, technically sound, and free of major flaws, and handled multiple inheritance. On the other hand, there wasn't enough bang for the buck, and the committee should handle a thornier problem.

Michael Tiemann arrived late, and then showed that a typedef'ed super would work just fine, using the same technique that was asked about in this post.

So, no, this will probably never get standardized.

If you don't have a copy, Design and Evolution is well worth the cover price. Used copies can be had for about $10.

Virtual network interface in Mac OS X

i have resorted to running PFSense, a BSD based router/firewall to achieve this goal….

why? because OS X Server gets so FREAKY without a Static IP…

so after wrestling with it for DAYS to make NAT and DHCP and firewall and …

I'm trying this is parallels…

will let ya know how it goes...

Split pandas dataframe in two if it has more than 10 rows

Below is a simple function implementation which splits a DataFrame to chunks and a few code examples:

import pandas as pd

def split_dataframe_to_chunks(df, n):
    df_len = len(df)
    count = 0
    dfs = []

    while True:
        if count > df_len-1:
            break

        start = count
        count += n
        #print("%s : %s" % (start, count))
        dfs.append(df.iloc[start : count])
    return dfs


# Create a DataFrame with 10 rows
df = pd.DataFrame([i for i in range(10)])

# Split the DataFrame to chunks of maximum size 2
split_df_to_chunks_of_2 = split_dataframe_to_chunks(df, 2)
print([len(i) for i in split_df_to_chunks_of_2])
# prints: [2, 2, 2, 2, 2]

# Split the DataFrame to chunks of maximum size 3
split_df_to_chunks_of_3 = split_dataframe_to_chunks(df, 3)
print([len(i) for i in split_df_to_chunks_of_3])
# prints [3, 3, 3, 1]

Invalid column count in CSV input on line 1 Error

You will need to skip first row (where column names are defined) and you will need to check which "character" is separating cells (usually is ,, but in my case was ;)

Bellow is the picture of my import:

enter image description here

CRC32 C or C++ implementation

The SNIPPETS C Source Code Archive has a CRC32 implementation that is freely usable:

/* Copyright (C) 1986 Gary S. Brown.  You may use this program, or
   code or tables extracted from it, as desired without restriction.*/

(Unfortunately, c.snippets.org seems to have died. Fortunately, the Wayback Machine has it archived.)

In order to be able to compile the code, you'll need to add typedefs for BYTE as an unsigned 8-bit integer and DWORD as an unsigned 32-bit integer, along with the header files crc.h & sniptype.h.

The only critical item in the header is this macro (which could just as easily go in CRC_32.c itself:

#define UPDC32(octet, crc) (crc_32_tab[((crc) ^ (octet)) & 0xff] ^ ((crc) >> 8))

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE

MySQL will assume the part before the equals references the columns named in the INSERT INTO clause, and the second part references the SELECT columns.

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, 
                inact, inadur, inadist, 
                smlct, smldur, smldist, 
                larct, lardur, lardist, 
                emptyct, emptydur)
SELECT id, uid, t.location, t.animal, t.starttime, t.endtime, t.entct, 
       t.inact, t.inadur, t.inadist, 
       t.smlct, t.smldur, t.smldist, 
       t.larct, t.lardur, t.lardist, 
       t.emptyct, t.emptydur 
FROM tmp t WHERE uid=x
ON DUPLICATE KEY UPDATE entct=t.entct, inact=t.inact, ...

How can I check if a string is a number?

int num;
bool isNumeric = int.TryParse("123", out num);

How to wait for async method to complete?

Actually I found this more helpful for functions that return IAsyncAction.

            var task = asyncFunction();
            while (task.Status == AsyncStatus.Completed) ;

Fundamental difference between Hashing and Encryption algorithms

when it comes to security for transmitting data i.e Two way communication you use encryption.All encryption requires a key

when it comes to authorization you use hashing.There is no key in hashing

Hashing takes any amount of data (binary or text) and creates a constant-length hash representing a checksum for the data. For example, the hash might be 16 bytes. Different hashing algorithms produce different size hashes. You obviously cannot re-create the original data from the hash, but you can hash the data again to see if the same hash value is generated. One-way Unix-based passwords work this way. The password is stored as a hash value, and to log onto a system, the password you type is hashed, and the hash value is compared against the hash of the real password. If they match, then you must've typed the correct password

why is hashing irreversible :

Hashing isn't reversible because the input-to-hash mapping is not 1-to-1. Having two inputs map to the same hash value is usually referred to as a "hash collision". For security purposes, one of the properties of a "good" hash function is that collisions are rare in practical use.

How to normalize a histogram in MATLAB?

For some Distributions, Cauchy I think, I have found that trapz will overestimate the area, and so the pdf will change depending on the number of bins you select. In which case I do

[N,h]=hist(q_f./theta,30000); % there Is a large range but most of the bins will be empty
plot(h,N/(sum(N)*mean(diff(h))),'+r')

CSS3 Transition not working

Transition is more like an animation.

div.sicon a {
    background:-moz-radial-gradient(left, #ffffff 24%, #cba334 88%);
    transition: background 0.5s linear;
    -moz-transition: background 0.5s linear; /* Firefox 4 */
    -webkit-transition: background 0.5s linear; /* Safari and Chrome */
    -o-transition: background 0.5s linear; /* Opera */
    -ms-transition: background 0.5s linear; /* Explorer 10 */
}

So you need to invoke that animation with an action.

div.sicon a:hover {
    background:-moz-radial-gradient(left, #cba334 24%, #ffffff 88%);
}

Also check for browser support and if you still have some problem with whatever you're trying to do! Check css-overrides in your stylesheet and also check out for behavior: ***.htc css hacks.. there may be something overriding your transition!

You should check this out: http://www.w3schools.com/css/css3_transitions.asp

Drop-down box dependent on the option selected in another drop-down box

I hope the following code will help or solve your problem or you think not that understandable visit http://phppot.com/jquery/jquery-dependent-dropdown-list-countries-and-states/.

HTML DYNAMIC DEPENDENT SELECT

<div class="frmDronpDown">
<div class="row">
    <label>Country:</label><br/>
    <select name="country" id="country-list" class="demoInputBox" onChange="getState(this.value);">
    <option value="">Select Country</option>
    <?php
    foreach($results as $country) {
    ?>
    <option value="<?php echo $country["id"]; ?>"><?php echo $country["name"]; ?></option>
    <?php
    }
    ?>
    </select>
</div>
<div class="row">
    <label>State:</label><br/>
    <select name="state" id="state-list" class="demoInputBox">
    <option value="">Select State</option>
    </select>
</div>

GETTING STATES VIA AJAX

<script> function getState(val) { $.ajax({
type: "POST",
url: "get_state.php",
data:'country_id='+val,
success: function(data){
    $("#state-list").html(data);
}
});} </script>

READ STATE DATABASE USING PHP

<?php require_once("dbcontroller.php"); $db_handle = new DBController();if(!empty($_POST["country_id"])) {
$query ="SELECT * FROM states WHERE countryID = '" . $_POST["country_id"] . "'";
$results = $db_handle->runQuery($query); ?> <option value="">Select State</option><?php foreach($results as $state) { ?> <option value="<?php echo $state["id"]; ?>"><?php echo $state["name"]; ?></option><?php } } ?>

Does adding a duplicate value to a HashSet/HashMap replace the previous value

The first thing you need to know is that HashSet acts like a Set, which means you add your object directly to the HashSet and it cannot contain duplicates. You just add your value directly in HashSet.

However, HashMap is a Map type. That means every time you add an entry, you add a key-value pair.

In HashMap you can have duplicate values, but not duplicate keys. In HashMap the new entry will replace the old one. The most recent entry will be in the HashMap.

Understanding Link between HashMap and HashSet:

Remember, HashMap can not have duplicate keys. Behind the scene HashSet uses a HashMap.

When you attempt to add any object into a HashSet, this entry is actually stored as a key in the HashMap - the same HashMap that is used behind the scene of HashSet. Since this underlying HashMap needs a key-value pair, a dummy value is generated for us.

Now when you try to insert another duplicate object into the same HashSet, it will again attempt to be insert it as a key in the HashMap lying underneath. However, HashMap does not support duplicates. Hence, HashSet will still result in having only one value of that type. As a side note, for every duplicate key, since the value generated for our entry in HashSet is some random/dummy value, the key is not replaced at all. it will be ignored as removing the key and adding back the same key (the dummy value is the same) would not make any sense at all.

Summary:

HashMap allows duplicate values, but not keys. HashSet cannot contains duplicates.

To play with whether the addition of an object is successfully completed or not, you can check the boolean value returned when you call .add() and see if it returns true or false. If it returned true, it was inserted.

How to make a simple collection view with Swift

This project has been tested with Xcode 10 and Swift 4.2.

Create a new project

It can be just a Single View App.

Add the code

Create a new Cocoa Touch Class file (File > New > File... > iOS > Cocoa Touch Class). Name it MyCollectionViewCell. This class will hold the outlets for the views that you add to your cell in the storyboard.

import UIKit
class MyCollectionViewCell: UICollectionViewCell {
    
    @IBOutlet weak var myLabel: UILabel!
}

We will connect this outlet later.

Open ViewController.swift and make sure you have the following content:

import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    
    let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
    var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"]
    
    
    // MARK: - UICollectionViewDataSource protocol
    
    // tell the collection view how many cells to make
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.items.count
    }
    
    // make a cell for each cell index path
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        // get a reference to our storyboard cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell
        
        // Use the outlet in our custom class to get a reference to the UILabel in the cell
        cell.myLabel.text = self.items[indexPath.row] // The row value is the same as the index of the desired text within the array.
        cell.backgroundColor = UIColor.cyan // make cell more visible in our example project
        
        return cell
    }
    
    // MARK: - UICollectionViewDelegate protocol
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // handle tap events
        print("You selected cell #\(indexPath.item)!")
    }
}

Notes

  • UICollectionViewDataSource and UICollectionViewDelegate are the protocols that the collection view follows. You could also add the UICollectionViewFlowLayout protocol to change the size of the views programmatically, but it isn't necessary.
  • We are just putting simple strings in our grid, but you could certainly do images later.

Set up the storyboard

Drag a Collection View to the View Controller in your storyboard. You can add constraints to make it fill the parent view if you like.

enter image description here

Make sure that your defaults in the Attribute Inspector are also

  • Items: 1
  • Layout: Flow

The little box in the top left of the Collection View is a Collection View Cell. We will use it as our prototype cell. Drag a Label into the cell and center it. You can resize the cell borders and add constraints to center the Label if you like.

enter image description here

Write "cell" (without quotes) in the Identifier box of the Attributes Inspector for the Collection View Cell. Note that this is the same value as let reuseIdentifier = "cell" in ViewController.swift.

enter image description here

And in the Identity Inspector for the cell, set the class name to MyCollectionViewCell, our custom class that we made.

enter image description here

Hook up the outlets

  • Hook the Label in the collection cell to myLabel in the MyCollectionViewCell class. (You can Control-drag.)
  • Hook the Collection View delegate and dataSource to the View Controller. (Right click Collection View in the Document Outline. Then click and drag the plus arrow up to the View Controller.)

enter image description here

Finished

Here is what it looks like after adding constraints to center the Label in the cell and pinning the Collection View to the walls of the parent.

enter image description here

Making Improvements

The example above works but it is rather ugly. Here are a few things you can play with:

Background color

In the Interface Builder, go to your Collection View > Attributes Inspector > View > Background.

Cell spacing

Changing the minimum spacing between cells to a smaller value makes it look better. In the Interface Builder, go to your Collection View > Size Inspector > Min Spacing and make the values smaller. "For cells" is the horizontal distance and "For lines" is the vertical distance.

Cell shape

If you want rounded corners, a border, and the like, you can play around with the cell layer. Here is some sample code. You would put it directly after cell.backgroundColor = UIColor.cyan in code above.

cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 8

See this answer for other things you can do with the layer (shadow, for example).

Changing the color when tapped

It makes for a better user experience when the cells respond visually to taps. One way to achieve this is to change the background color while the cell is being touched. To do that, add the following two methods to your ViewController class:

// change background color when user touches cell
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.backgroundColor = UIColor.red
}

// change background color back when user releases touch
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.backgroundColor = UIColor.cyan
}

Here is the updated look:

enter image description here

Further study

UITableView version of this Q&A

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

This solution will change the git file permissions from 100755 to 100644 and push changes back to the bitbucket remote repo.

  1. Take a look at your repo's file permissions: git ls-files --stage

  2. If 100755 and you want 100644

Then run this command: git ls-files --stage | sed 's/\t/ /g' | cut -d' ' -f4 | xargs git update-index --chmod=-x

  1. Now check your repo's file permissions again: git ls-files --stage

  2. Now commit your changes:

git status

git commit -m "restored proper file permissions"

git push

Remove characters from NSString?

You could use:

NSString *stringWithoutSpaces = [myString 
   stringByReplacingOccurrencesOfString:@" " withString:@""];

How can I escape white space in a bash loop list?

find . -print0|while read -d $'\0' file; do echo "$file"; done

How do I get the IP address into a batch-file variable?

This will print the IP addresses in the output of ipconfig:

@echo off
set ip_address_string="IPv4 Address"
rem Uncomment the following line when using older versions of Windows without IPv6 support (by removing "rem")
rem set ip_address_string="IP Address"
echo Network Connection Test
for /f "usebackq tokens=2 delims=:" %%f in (`ipconfig ^| findstr /c:%ip_address_string%`) do echo Your IP Address is: %%f

To only print the first IP address, just add goto :eof (or another label to jump to instead of :eof) after the echo, or in a more readable form:

set ip_address_string="IPv4 Address"
rem Uncomment the following line when using older versions of Windows without IPv6 support (by removing "rem")
rem set ip_address_string="IP Address"
for /f "usebackq tokens=2 delims=:" %%f in (`ipconfig ^| findstr /c:%ip_address_string%`) do (
    echo Your IP Address is: %%f
    goto :eof
)

A more configurable way would be to actually parse the output of ipconfig /all a little bit, that way you can even specify the adapter whose IP address you want:

@echo off
setlocal enabledelayedexpansion
::just a sample adapter here:
set "adapter=Ethernet adapter VirtualBox Host-Only Network"
set adapterfound=false
echo Network Connection Test
for /f "usebackq tokens=1-2 delims=:" %%f in (`ipconfig /all`) do (
    set "item=%%f"
    if /i "!item!"=="!adapter!" (
        set adapterfound=true
    ) else if not "!item!"=="!item:IP Address=!" if "!adapterfound!"=="true" (
        echo Your IP Address is: %%g
        set adapterfound=false
    )
)

Nesting CSS classes

Not possible with vanilla CSS. However you can use something like:

Sass makes CSS fun again. Sass is an extension of CSS3, adding nested rules, variables, mixins, selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-framework plugin.

Or

Rather than constructing long selector names to specify inheritance, in Less you can simply nest selectors inside other selectors. This makes inheritance clear and style sheets shorter.

Example:

#header {
  color: red;
  a {
    font-weight: bold;
    text-decoration: none;
  }
}

mysql.h file can't be found

For CentOS/RHEL:

yum install mysql-devel -y

How can I access localhost from another computer in the same network?

You need to find what your local network's IP of that computer is. Then other people can access to your site by that IP.

You can find your local network's IP by go to Command Prompt or press Windows + R then type in ipconfig. It will give out some information and your local IP should look like 192.168.1.x.

Skip first line(field) in loop using CSV file?

csvreader.next() Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

How to set the height of an input (text) field in CSS?

Form controls are notoriously difficult to style cross-platform/browser. Some browsers will honor a CSS height rule, some won't.

You can try line-height (may need display:block; or display:inline-block;) or top and bottom padding also. If none of those work, that's pretty much it - use a graphic, position the input in the center and set border:none; so it looks like the form control is big but it actually isn't...

php date validation

Try This

/^(19[0-9]{2}|2[0-9]{3})\-(0[1-9]|1[0-2])\-(0[1-9]|1[0-9]|2[0-9]|3[0-1])((T|\s)(0[0-9]{1}|1[0-9]{1}|2[0-3]{1})\:(0[0-9]{1}|1[0-9]{1}|2[0-9]{1}|3[0-9]{1}|4[0-9]{1}|5[0-9]{1})\:(0[0-9]{1}|1[0-9]{1}|2[0-9]{1}|3[0-9]{1}|4[0-9]{1}|5[0-9]{1})((\+|\.)[\d+]{4,8})?)?$/

this regular expression valid for :

  • 2017-01-01T00:00:00+0000
  • 2017-01-01 00:00:00+00:00
  • 2017-01-01T00:00:00+00:00
  • 2017-01-01 00:00:00+0000
  • 2017-01-01

Remember that this will be cover all case of date and date time with (-) character

How to debug when Kubernetes nodes are in 'Not Ready' state

I was having similar issue because of a different reason:

Error:

cord@node1:~$ kubectl get nodes
NAME    STATUS     ROLES    AGE     VERSION
node1   Ready      master   17h     v1.13.5
node2   Ready      <none>   17h     v1.13.5
node3   NotReady   <none>   9m48s   v1.13.5

cord@node1:~$ kubectl describe node node3
Name:               node3
Conditions:
  Type             Status  LastHeartbeatTime                 LastTransitionTime                Reason                       Message
  ----             ------  -----------------                 ------------------                ------                       -------
  Ready            False   Thu, 18 Apr 2019 01:15:46 -0400   Thu, 18 Apr 2019 01:03:48 -0400   KubeletNotReady              runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:docker: network plugin is not ready: cni config uninitialized
Addresses:
  InternalIP:  192.168.2.6
  Hostname:    node3

cord@node3:~$ journalctl -u kubelet

Apr 18 01:24:50 node3 kubelet[54132]: W0418 01:24:50.649047   54132 cni.go:149] Error loading CNI config list file /etc/cni/net.d/10-calico.conflist: error parsing configuration list: no 'plugins' key
Apr 18 01:24:50 node3 kubelet[54132]: W0418 01:24:50.649086   54132 cni.go:203] Unable to update cni config: No valid networks found in /etc/cni/net.d
Apr 18 01:24:50 node3 kubelet[54132]: E0418 01:24:50.649402   54132 kubelet.go:2192] Container runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:docker: network plugin is not ready: cni config uninitialized
Apr 18 01:24:55 node3 kubelet[54132]: W0418 01:24:55.650816   54132 cni.go:149] Error loading CNI config list file /etc/cni/net.d/10-calico.conflist: error parsing configuration list: no 'plugins' key
Apr 18 01:24:55 node3 kubelet[54132]: W0418 01:24:55.650845   54132 cni.go:203] Unable to update cni config: No valid networks found in /etc/cni/net.d
Apr 18 01:24:55 node3 kubelet[54132]: E0418 01:24:55.651056   54132 kubelet.go:2192] Container runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:docker: network plugin is not ready: cni config uninitialized
Apr 18 01:24:57 node3 kubelet[54132]: I0418 01:24:57.248519   54132 setters.go:72] Using node IP: "192.168.2.6"

Issue:

My file: 10-calico.conflist was incorrect. Verified it from a different node and from sample file in the same directory "calico.conflist.template".

Resolution:

Changing the file, "10-calico.conflist" and restarting the service using "systemctl restart kubelet", resolved my issue:

NAME    STATUS   ROLES    AGE   VERSION
node1   Ready    master   18h   v1.13.5
node2   Ready    <none>   18h   v1.13.5
node3   Ready    <none>   48m   v1.13.5

AngularJS Error: $injector:unpr Unknown Provider

Your angular module needs to be initialized properly. The global object app needs to be defined and initialized correctly to inject the service.

Please see below sample code for reference:

app.js

var app = angular.module('SampleApp',['ngRoute']); //You can inject the dependencies within the square bracket    

app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
  $routeProvider
    .when('/', {
      templateUrl:"partials/login.html",
      controller:"login"
    });

  $locationProvider
    .html5Mode(true);
}]);

app.factory('getSettings', ['$http', '$q', function($http, $q) {
  return {
    //Code edited to create a function as when you require service it returns object by default so you can't return function directly. That's what understand...
    getSetting: function (type) { 
      var q = $q.defer();
      $http.get('models/settings.json').success(function (data) {
        q.resolve(function() {
          var settings = jQuery.parseJSON(data);
          return settings[type];
        });
      });
      return q.promise;
    }
  }
}]);

app.controller("globalControl", ['$scope','getSettings', function ($scope,getSettings) {
  //Modified the function call for updated service
  var loadSettings = getSettings.getSetting('global');
  loadSettings.then(function(val) {
    $scope.settings = val;
  });
}]);

Sample HTML code should be like this:

<!DOCTYPE html>
<html>
    <head lang="en">
        <title>Sample Application</title>
    </head>
    <body ng-app="SampleApp" ng-controller="globalControl">
        <div>
            Your UI elements go here
        </div>
        <script src="app.js"></script>
    </body>
</html>

Please note that the controller is not binding to an HTML tag but to the body tag. Also, please try to include your custom scripts at end of the HTML page as this is a standard practice to follow for performance reasons.

I hope this will solve your basic injection issue.

Post a json object to mvc controller with jquery and ajax

I see in your code that you are trying to pass an ARRAY to POST action. In that case follow below working code -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    function submitForm() {
        var roles = ["role1", "role2", "role3"];

        jQuery.ajax({
            type: "POST",
            url: "@Url.Action("AddUser")",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(roles),
            success: function (data) { alert(data); },
            failure: function (errMsg) {
                alert(errMsg);
            }
        });
    }
</script>

<input type="button" value="Click" onclick="submitForm()"/>

And the controller action is going to be -

    public ActionResult AddUser(List<String> Roles)
    {
        return null;
    }

Then when you click on the button -

enter image description here

How do I keep two side-by-side divs the same height?

If you don't mind one of the divs being a master and dictating the height for both divs there is this:

Fiddle

No matter what, the div on the right will expand or squish&overflow to match the height of the div on the left.

Both divs must be immediate children of a container, and have to specify their widths within it.

Relevant CSS:

.container {
    background-color: gray;
    display: table;
    width: 70%;
    position:relative;
}

.container .left{
    background-color: tomato;
    width: 35%;
}

.container .right{
    position:absolute;
    top:0px;
    left:35%;
    background-color: orange;
    width: 65%;
    height:100%;
    overflow-y: auto;
}

LINQ Join with Multiple Conditions in On Clause

Here you go with:

from b in _dbContext.Burden 
join bl in _dbContext.BurdenLookups on
new { Organization_Type = b.Organization_Type_ID, Cost_Type = b.Cost_Type_ID } equals
new { Organization_Type = bl.Organization_Type_ID, Cost_Type = bl.Cost_Type_ID }

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

Why does this iterative list-growing code give IndexError: list assignment index out of range?

I think the Python method insert is what you're looking for:

Inserts element x at position i. list.insert(i,x)

array = [1,2,3,4,5]

array.insert(1,20)

print(array)

# prints [1,2,20,3,4,5]

How to do scanf for single char in C

The only code that worked for me is:

scanf(" %c",&c);

I was having the same problem, and only with single characters. After an hour of random testing I can not report an issue yet. One would think that C would have by now a bullet-proof function to retrieve single characters from the keyboard, and not an array of possible hackarounds... Just saying...

How to Convert Boolean to String

function ToStr($Val=null,$T=0){

    return is_string($Val)?"$Val"
    :
    (
        is_numeric($Val)?($T?"$Val":$Val)
        :
        (
            is_null($Val)?"NULL"
            :
            (
                is_bool($Val)?($Val?"TRUE":"FALSE")
                :
                (
                    is_array($Val)?@StrArr($Val,$T)
                    :
                    false
                )
            )
        )
    );

}
function StrArr($Arr,$T=0)
{
    $Str="";
    $i=-1;
    if(is_array($Arr))
    foreach($Arr AS $K => $V)
    $Str.=((++$i)?", ":null).(is_string($K)?"\"$K\"":$K)." => ".(is_string($V)?"\"$V\"":@ToStr($V,$T+1));
    return "array( ".($i?@ToStr($Arr):$Str)." )".($T?null:";");
}

$A = array(1,2,array('a'=>'b'),array('a','b','c'),true,false,ToStr(100));
echo StrArr($A); // OR ToStr($A) // OR ToStr(true) // OR StrArr(true)

How can I format the output of a bash command in neat columns

column(1) is your friend.

$ column -t <<< '"option-y"      yank-pop
> "option-z"      execute-last-named-cmd
> "option-|"      vi-goto-column
> "option-~"      _bash_complete-word
> "option-control-?"      backward-kill-word
> "control-_"     undo
> "control-?"     backward-delete-char
> '
"option-y"          yank-pop
"option-z"          execute-last-named-cmd
"option-|"          vi-goto-column
"option-~"          _bash_complete-word
"option-control-?"  backward-kill-word
"control-_"         undo
"control-?"         backward-delete-char

Run jQuery function onclick

Using obtrusive JavaScript (i.e. inline code) as in your example, you can attach the click event handler to the div element with the onclick attribute like so:

 <div id="some-id" class="some-class" onclick="slideonlyone('sms_box');">
     ...
 </div>

However, the best practice is unobtrusive JavaScript which you can easily achieve by using jQuery's on() method or its shorthand click(). For example:

 $(document).ready( function() {
     $('.some-class').on('click', slideonlyone('sms_box'));
     // OR //
     $('.some-class').click(slideonlyone('sms_box'));
 });

Inside your handler function (e.g. slideonlyone() in this case) you can reference the element that triggered the event (e.g. the div in this case) with the $(this) object. For example, if you need its ID, you can access it with $(this).attr('id').


EDIT

After reading your comment to @fmsf below, I see you also need to dynamically reference the target element to be toggled. As @fmsf suggests, you can add this information to the div with a data-attribute like so:

<div id="some-id" class="some-class" data-target="sms_box">
    ...
</div>

To access the element's data-attribute you can use the attr() method as in @fmsf's example, but the best practice is to use jQuery's data() method like so:

 function slideonlyone() {
     var trigger_id = $(this).attr('id'); // This would be 'some-id' in our example
     var target_id  = $(this).data('target'); // This would be 'sms_box'
     ...
 }

Note how data-target is accessed with data('target'), without the data- prefix. Using data-attributes you can attach all sorts of information to an element and jQuery would automatically add them to the element's data object.

com.apple.WebKit.WebContent drops 113 error: Could not find specified service

On OS X, it's necessary to make sure Sandbox capabilities are set-up properly in order to use WKWebView.

This link made this clear to me: https://forums.developer.apple.com/thread/92265

Sharing hoping that it will help someone.


Select the Project File in the Navigator, select Capabilities, then make sure that:
* App Sandbox is OFF,
OR
* App Sandbox is ON AND Outgoing Connections (Client) is checked.

Make an HTTP request with android

Use Volley as suggested above. Add following into build.gradle (Module: app)

implementation 'com.android.volley:volley:1.1.1'

Add following into AndroidManifest.xml:

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

And add following to you Activity code:

public void httpCall(String url) {

    RequestQueue queue = Volley.newRequestQueue(this);

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // enjoy your response
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // enjoy your error status
                }
    });

    queue.add(stringRequest);
}

It replaces http client and it is very simple.

What is difference between Errors and Exceptions?

Error and Exception both extend Throwable, but mostly Error is thrown by JVM in a scenario which is fatal and there is no way for the application program to recover from that error. For instance OutOfMemoryError.

Though even application can raise an Error but its just not a good a practice, instead applications should use checked exceptions for recoverable conditions and runtime exceptions for programming errors.

How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?

I think you're a little confused. PYTHONPATH sets the search path for importing python modules, not for executing them like you're trying.

PYTHONPATH Augment the default search path for module files. The format is the same as the shell’s PATH: one or more directory pathnames separated by os.pathsep (e.g. colons on Unix or semicolons on Windows). Non-existent directories are silently ignored.

In addition to normal directories, individual PYTHONPATH entries may refer to zipfiles containing pure Python modules (in either source or compiled form). Extension modules cannot be imported from zipfiles.

The default search path is installation dependent, but generally begins with prefix/lib/pythonversion (see PYTHONHOME above). It is always appended to PYTHONPATH.

An additional directory will be inserted in the search path in front of PYTHONPATH as described above under Interface options. The search path can be manipulated from within a Python program as the variable sys.path.

http://docs.python.org/2/using/cmdline.html#envvar-PYTHONPATH

What you're looking for is PATH.

export PATH=$PATH:/home/randy/lib/python 

However, to run your python script as a program, you also need to set a shebang for Python in the first line. Something like this should work:

#!/usr/bin/env python

And give execution privileges to it:

chmod +x /home/randy/lib/python/gbmx.py

Then you should be able to simply run gmbx.py from anywhere.

Exception : javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

In my case I was using a JDK 8 client and the server was using insecure old ciphers. The server is Apache and I added this line to the Apache config:

SSLCipherSuite ALL:!ADH:RC4+RSA:+HIGH:!MEDIUM:!LOW:!SSLv2:!EXPORT

You should use a tool like this to verify your SSL configuration is currently secure: https://www.ssllabs.com/ssltest/analyze.html

How to position a Bootstrap popover?

I had to make the following changes for the popover to position below with some overlap and to show the arrow correctly.

js

case 'bottom-right':  
    tp = {top: pos.top + pos.height + 10, left: pos.left + pos.width - 40}  
    break  

css

    .popover.bottom-right .arrow {  
      left: 20px; /* MODIFIED */  
      margin-left: -11px;  
      border-top-width: 0;  
      border-bottom-color: #999;  
      border-bottom-color: rgba(0, 0, 0, 0.25);  
      top: -11px;  
    }  
    .popover.bottom-right .arrow:after {  
      top: 1px;  
      margin-left: -10px;  
      border-top-width: 0;  
      border-bottom-color: #ffffff;  
    }  

This can be extended for arrow locations elsewhere .. enjoy!

How do I exit from a function?

Use the return keyword.

return; //exit this event

test if event handler is bound to an element in jQuery

With reference to SJG's answer and from W3Schools.com

As of jQuery version 1.7, the off() method is the new replacement for the unbind(), die() and undelegate() methods. This method brings a lot of consistency to the API, and we recommend that you use this method, as it simplifies the jQuery code base.

This gives:

$("#someid").off("click").live("click",function(){...

or

$("#someid").off("click").bind("click",function(){...

JAXB :Need Namespace Prefix to all the elements

marshaller.setProperty only works on the JAX-B marshaller from Sun. The question was regarding the JAX-B marshaller from SpringSource, which does not support setProperty.

Plot yerr/xerr as shaded region rather than error bars

This is basically the same answer provided by Evert, but extended to show-off some cool options of fill_between

enter image description here

from matplotlib import pyplot as pl
import numpy as np

pl.clf()
pl.hold(1)

x = np.linspace(0, 30, 100)
y = np.sin(x) * 0.5
pl.plot(x, y, '-k')


x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape) +.1
y += np.random.normal(0, 0.1, size=y.shape)

pl.plot(x, y, 'k', color='#CC4F1B')
pl.fill_between(x, y-error, y+error,
    alpha=0.5, edgecolor='#CC4F1B', facecolor='#FF9848')

y = np.cos(x/6*np.pi)    
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#1B2ACC')
pl.fill_between(x, y-error, y+error,
    alpha=0.2, edgecolor='#1B2ACC', facecolor='#089FFF',
    linewidth=4, linestyle='dashdot', antialiased=True)



y = np.cos(x/6*np.pi)  + np.sin(x/3*np.pi)  
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#3F7F4C')
pl.fill_between(x, y-error, y+error,
    alpha=1, edgecolor='#3F7F4C', facecolor='#7EFF99',
    linewidth=0)



pl.show()

Adjust width and height of iframe to fit with content in it

If you can live with a fixed aspect ratio and you would like a responsive iframe, this code will be useful to you. It's just CSS rules.

.iframe-container {
  overflow: hidden;
  /* Calculated from the aspect ration of the content (in case of 16:9 it is 9/16= 
  0.5625) */
  padding-top: 56.25%;
  position: relative;
}
.iframe-container iframe {
  border: 0;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0;
  width: 100%;
}

The iframe must have a div as container.

<div class="iframe-container">
   <iframe src="http://example.org"></iframe>
</div>

The source code is based on this site and Ben Marshall has a good explanation.

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

Louis' answer is great, but I thought I would try to sum it up succinctly:

The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".

Ctrl+click doesn't work in Eclipse Juno

For me it helped to simply close the edited source file and reopen it. If this doesn't work THEN you can try restarting whole IDE.

Get DateTime.Now with milliseconds precision

public long millis() {
  return (long.MaxValue + DateTime.Now.ToBinary()) / 10000;
}

If you want microseconds, just change 10000 to 10, and if you want the 10th of micro, delete / 10000.

Putting an if-elif-else statement on one line?

People have already mentioned ternary expressions. Sometimes with a simple conditional assignment as your example, it is possible to use a mathematical expression to perform the conditional assignment. This may not make your code very readable, but it does get it on one fairly short line. Your example could be written like this:

x = 2*(i>100) | 1*(i<100)

The comparisons would be True or False, and when multiplying with numbers would then be either 1 or 0. One could use a + instead of an | in the middle.

How to clear/delete the contents of a Tkinter Text widget?

I checked on my side by just adding '1.0' and it start working

tex.delete('1.0', END)

you can also try this

How to use XPath contains() here?

This is a new answer to an old question about a common misconception about contains() in XPath...

Summary: contains() means contains a substring, not contains a node.

Detailed Explanation

This XPath is often misinterpreted:

//ul[contains(li, 'Model')]

Wrong interpretation: Select those ul elements that contain an li element with Model in it.

This is wrong because

  1. contains(x,y) expects x to be a string, and
  2. the XPath rule for converting multiple elements to a string is this:

    A node-set is converted to a string by returning the string-value of the node in the node-set that is first in document order. If the node-set is empty, an empty string is returned.

Right interpretation: Select those ul elements whose first li child has a string-value that contains a Model substring.

Examples

XML

<r>
  <ul id="one">
    <li>Model A</li>
    <li>Foo</li>
  </ul>
  <ul id="two">
    <li>Foo</li>
    <li>Model A</li>
  </ul>
</r> 

XPaths

  • //ul[contains(li, 'Model')] selects the one ul element.

    Note: The two ul element is not selected because the string-value of the first li child of the two ul is Foo, which does not contain the Model substring.

  • //ul[li[contains(.,'Model')]] selects the one and two ul elements.

    Note: Both ul elements are selected because contains() is applied to each li individually. (Thus, the tricky multiple-element-to-string conversion rule is avoided.) Both ul elements do have an li child whose string value contains the Model substring -- position of the li element no longer matters.

See also

jQuery Ajax Request inside Ajax Request

Call second ajax from 'complete'

Here is the example

   var dt='';
   $.ajax({
    type: "post",
    url: "ajax/example.php",
    data: 'page='+btn_page,
    success: function(data){
        dt=data;
        /*Do something*/
    },
    complete:function(){
        $.ajax({
           var a=dt; // This line shows error.
           type: "post",
           url: "example.php",
           data: 'page='+a,
           success: function(data){
              /*do some thing in second function*/
           },
       });
    }
});

TensorFlow: "Attempting to use uninitialized value" in variable initialization

It's not 100% clear from the code example, but if the list initial_parameters_of_hypothesis_function is a list of tf.Variable objects, then the line session.run(init) will fail because TensorFlow isn't (yet) smart enough to figure out the dependencies in variable initialization. To work around this, you should change the loop that creates parameters to use initial_parameters_of_hypothesis_function[i].initialized_value(), which adds the necessary dependency:

parameters = []
for i in range(0, number_of_attributes, 1):
    parameters.append(tf.Variable(
        initial_parameters_of_hypothesis_function[i].initialized_value()))

Java : Sort integer array without using Arrays.sort()

Array Sorting without using built in functions in java ......just make new File unsing this name -> (ArraySorting.java) ..... Run the Project and Enjoy it !!!!!

    import java.io.*;
    import java.util.Arrays;
    import java.util.Scanner;
    public class ArraySorting 
    {
    public static void main(String args[])
    {
      int temp=0;   
      Scanner user_input=new Scanner(System.in);
       System.out.println("enter Size of Array...");
    int Size=user_input.nextInt();

    int[] a=new int[Size];
    System.out.println("Enter element Of an Array...");
    for(int j=0;j<Size;j++)
    {
        a[j]=user_input.nextInt();
    }     
    for(int index=0;index<a.length;index++)
    {
        for(int j=index+1;j<a.length;j++)
        {
             if(a[index] > a[j] ) 
             {
                 temp = a[index];
                 a[index] = a[j];
                 a[j] = temp;
             }
        }
    }
    System.out.print("Output is:- ");
    for(int i=0;i<a.length;i++)
    {
        System.out.println(a[i]);
    }

}
}

How to populate a dropdownlist with json data in jquery?

try this one its worked for me

_x000D_
_x000D_
$(document).ready(function(e){_x000D_
        $.ajax({_x000D_
           url:"fetch",_x000D_
           processData: false,_x000D_
           dataType:"json",_x000D_
           type: 'POST',_x000D_
           cache: false,_x000D_
           success: function (data, textStatus, jqXHR) {_x000D_
                        _x000D_
                         $.each(data.Table,function(i,tweet){_x000D_
      $("#list").append('<option value="'+tweet.actor_id+'">'+tweet.first_name+'</option>');_x000D_
   });}_x000D_
        });_x000D_
    });
_x000D_
_x000D_
_x000D_

java.lang.IllegalStateException: The specified child already has a parent

When you override OnCreateView in your RouteSearchFragment class, do you have the

if(view != null) {
    return view; 
}

code segment?

If so, removing the return statement should solve your problem.

You can keep the code and return the view if you don't want to regenerate view data, and onDestroyView() method you remove this view from its parent like so:

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (view != null) {
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null) {
                parent.removeAllViews();
            }
        }
    }

/usr/bin/codesign failed with exit code 1

Same issue with ambiguous (matches "iPhone Developer: [me] " and /// tweetdeck's library privatedata file. Fixed it by moving file to the trash and re-logging into Tweetdeck, setting up passwords again. What a pain.

How to get value of checked item from CheckedListBox?

Egypt Development Blog : Get value of checked item in CheckedListBox in vb.net

after bind CheckedListBox with data you can get value of checked items

For i As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
                    Dim XDRV As DataRowView = CType(CheckedListBox1.CheckedItems(i), DataRowView)
                    Dim XDR As DataRow = XDRV.Row
                    Dim XDisplayMember As String = XDR(CheckedListBox1.DisplayMember).ToString()
                    Dim XValueMember As String = XDR(CheckedListBox1.ValueMember).ToString()
                    MsgBox("DisplayMember : " & XDisplayMember & "   - ValueMember : " & XValueMember )
Next

now you can use the value or Display of checked items in CheckedListBox from the 2 variable XDisplayMember And XValueMember in the loop

hope to be useful.

What is sharding and why is it important?

Sharding does more than just horizontal partitioning. According to the wikipedia article,

Horizontal partitioning splits one or more tables by row, usually within a single instance of a schema and a database server. It may offer an advantage by reducing index size (and thus search effort) provided that there is some obvious, robust, implicit way to identify in which partition a particular row will be found, without first needing to search the index, e.g., the classic example of the 'CustomersEast' and 'CustomersWest' tables, where their zip code already indicates where they will be found.

Sharding goes beyond this: it partitions the problematic table(s) in the same way, but it does this across potentially multiple instances of the schema. The obvious advantage would be that search load for the large partitioned table can now be split across multiple servers (logical or physical), not just multiple indexes on the same logical server.

Also,

Splitting shards across multiple isolated instances requires more than simple horizontal partitioning. The hoped-for gains in efficiency would be lost, if querying the database required both instances to be queried, just to retrieve a simple dimension table. Beyond partitioning, sharding thus splits large partitionable tables across the servers, while smaller tables are replicated as complete units

Remove substring from the string

If you only have one occurrence of the target string you can use:

str[target] = ''

or

str.sub(target, '')

If you have multiple occurrences of target use:

str.gsub(target, '')

For instance:

asdf = 'foo bar'
asdf['bar'] = ''
asdf #=> "foo "

asdf = 'foo bar'
asdf.sub('bar', '') #=> "foo "
asdf = asdf + asdf #=> "foo barfoo bar"
asdf.gsub('bar', '') #=> "foo foo "

If you need to do in-place substitutions use the "!" versions of gsub! and sub!.

Get index of a row of a pandas dataframe as an integer

The easier is add [0] - select first value of list with one element:

dfb = df[df['A']==5].index.values.astype(int)[0]
dfbb = df[df['A']==8].index.values.astype(int)[0]

dfb = int(df[df['A']==5].index[0])
dfbb = int(df[df['A']==8].index[0])

But if possible some values not match, error is raised, because first value not exist.

Solution is use next with iter for get default parameetr if values not matched:

dfb = next(iter(df[df['A']==5].index), 'no match')
print (dfb)
4

dfb = next(iter(df[df['A']==50].index), 'no match')
print (dfb)
no match

Then it seems need substract 1:

print (df.loc[dfb:dfbb-1,'B'])
4    0.894525
5    0.978174
6    0.859449
Name: B, dtype: float64

Another solution with boolean indexing or query:

print (df[(df['A'] >= 5) & (df['A'] < 8)])
   A         B
4  5  0.894525
5  6  0.978174
6  7  0.859449

print (df.loc[(df['A'] >= 5) & (df['A'] < 8), 'B'])
4    0.894525
5    0.978174
6    0.859449
Name: B, dtype: float64

print (df.query('A >= 5 and A < 8'))
   A         B
4  5  0.894525
5  6  0.978174
6  7  0.859449

Difference between binary semaphore and mutex

Mutex work on blocking critical region, But Semaphore work on count.

How to format DateTime in Flutter , How to get current time in flutter?

Use String split method to remove :00.000

var formatedTime = currentTime.toString().split(':')
Text(formatedTime[0])

======= OR USE BELOW code for YYYY-MM-DD HH:MM:SS format without using library ====

var stringList =  DateTime.now().toIso8601String().split(new RegExp(r"[T\.]"));
var formatedDate = "${stringList[0]} ${stringList[1]}";

The FastCGI process exited unexpectedly

You might be using C:/[your-php-directory]/php.exe in Handler mapping of IIS just change it C:/[your-php-directory]/php-cgi.exe.

How to merge a specific commit in Git

We will have to use git cherry-pick <commit-number>

Scenario: I am on a branch called release and I want to add only few changes from master branch to release branch.

Step 1: checkout the branch where you want to add the changes

git checkout release

Step 2: get the commit number of the changes u want to add

for example

git cherry-pick 634af7b56ec

Step 3: git push

Note: Every time your merge there is a separate commit number create. Do not take the commit number for merge that won't work. Instead, the commit number for any regular commit u want to add.

Are there other whitespace codes like &nbsp for half-spaces, em-spaces, en-spaces etc useful in HTML?

Not sure if this is what you're referring to, but this is the list of HTML entities you can use:

List of XML and HTML character entity references

Using the content within the 'Name' column you can just wrap these in an & and ;

E.g. &nbsp;, &emsp;, etc.

Replace all occurrences of a string in a data frame

Here is a dplyr solution

library(dplyr)
library(stringr)

Censor_consistently <-  function(x){
  str_replace(x, '^\\s*([<>])\\s*(\\d+)', '\\1\\2')
}


test_df <- tibble(x = c('0.001', '<0.002', ' < 0.003', ' >  100'),  y = 4:1)

mutate_all(test_df, funs(Censor_consistently))

# A tibble: 4 × 2
x     y
<chr> <chr>
1  0.001     4
2 <0.002     3
3 <0.003     2
4   >100     1

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>/

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

It's useful in situations where you have hidden internal state such as a cache. For example:

class HashTable
{
...
public:
    string lookup(string key) const
    {
        if(key == lastKey)
            return lastValue;

        string value = lookupInternal(key);

        lastKey = key;
        lastValue = value;

        return value;
    }

private:
    mutable string lastKey, lastValue;
};

And then you can have a const HashTable object still use its lookup() method, which modifies the internal cache.

Assign result of dynamic sql to variable

You should try this while getting SEQUENCE value in a variable from the dynamic table.

DECLARE @temp table (#temp varchar (MAX));
DECLARE @SeqID nvarchar(150);
DECLARE @Name varchar(150); 

SET @Name = (Select Name from table)
SET @SeqID = 'SELECT NEXT VALUE FOR '+ @Name + '_Sequence'
insert @temp exec (@SeqID)

SET @SeqID = (select * from @temp )
PRINT @SeqID

Result:

(1 row(s) affected)
 1

How to set the value for Radio Buttons When edit?

For those who might be in need for a solution in pug template engine and NodeJs back-end, you can use this:

If values are not boolean(IE: true or false), code below works fine:

input(type='radio' name='sex' value='male' checked=(dbResult.sex ==='male') || (dbResult.sex === 'newvalue') )
input(type='radio' name='sex' value='female' checked=(dbResult.sex ==='female) || (dbResult.sex === 'newvalue'))

If values are boolean(ie: true or false), use this instead:

input(type='radio' name='isInsurable' value='true' checked=singleModel.isInsurable || (singleModel.isInsurable === 'true') )
input(type='radio' name='isInsurable' value='false' checked=!singleModel.isInsurable || (singleModel.isInsurable === 'false'))

the reason for this || operator is to re-display new values if editing fails due to validation error and you have a logic to send back the new values to your front-end

Opening Android Settings programmatically

Use this intent to open security and location screen in settings app of android device

    startActivity(new Intent(Settings.ACTION_SECURITY_SETTINGS));

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

Just Create New User for MySQL do not use root. there is a problem its security issue

sudo mysql -p -u root

Login into MySQL or MariaDB with root privileges

CREATE USER 'troy121'@'%' IDENTIFIED BY 'mypassword123';

login and create a new user

GRANT ALL PRIVILEGES ON *.* TO 'magento121121'@'%' WITH GRANT OPTION;

and grant privileges to access "." and "@" "%" any location not just only 'localhost'

exit;

if you want to see your privilege table SHOW GRANTS; & Enjoy.

Is it possible to use the SELECT INTO clause with UNION [ALL]?

This works in SQL Server:

SELECT * INTO tmpFerdeen FROM (
  SELECT top 100 * 
  FROM Customers
  UNION All
  SELECT top 100 * 
  FROM CustomerEurope
  UNION All
  SELECT top 100 * 
  FROM CustomerAsia
  UNION All
  SELECT top 100 * 
  FROM CustomerAmericas
) as tmp

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

For complete the accepted answer, Had the same issue. First specified the remote

git remote add origin https://github.com/XXXX/YYY.git

git fetch 

Then get the code

git pull origin master

placeholder for select tag

EDIT: This did/does work at the time I wrote it, but as Blexen pointed out, it's not in the spec.

Add an option like so:

<option default>Select Your Beverage</option>

The correct way:

<option selected="selected">Select Your Beverage</option>

WPF Datagrid set selected row

I came across this fairly recent (compared to the age of the question) TechNet article that includes some of the best techniques I could find on the topic:

WPF: Programmatically Selecting and Focusing a Row or Cell in a DataGrid

It includes details that should cover most requirements. It is important to remember that if you specify custom templates for the DataGridRow for some rows that these won't have DataGridCells inside and then the normal selection mechanisms of the grid doesn't work.

You'll need to be more specific on what datasource you've given the grid to answer the first part of your question, as the others have stated.

Secure Web Services: REST over HTTPS vs SOAP + WS-Security. Which is better?

The answer actually depends on your specific requirements.

For instance, do you need to protect your web messages or confidentiality is not required and all you need is to authenticate end parties and ensure message integrity? If this is the case - and it often is with web services - HTTPS is probably the wrong hammer.

However - from my experience - do not overlook the complexity of the system you're building. Not only HTTPS is easier to deploy correctly, but an application that relies on the transport layer security is easier to debug (over plain HTTP).

Good luck.

Update query using Subquery in Sql Server

you can join both tables even on UPDATE statements,

UPDATE  a
SET     a.marks = b.marks
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

for faster performance, define an INDEX on column marks on both tables.

using SUBQUERY

UPDATE  tempDataView 
SET     marks = 
        (
          SELECT marks 
          FROM tempData b 
          WHERE tempDataView.Name = b.Name
        )

How to call a web service from jQuery

EDIT:

The OP was not looking to use cross-domain requests, but jQuery supports JSONP as of v1.5. See jQuery.ajax(), specificically the crossDomain parameter.

The regular jQuery Ajax requests will not work cross-site, so if you want to query a remote RESTful web service, you'll probably have to make a proxy on your server and query that with a jQuery get request. See this site for an example.

If it's a SOAP web service, you may want to try the jqSOAPClient plugin.

How can I run a php without a web server?

You should normally be able to run a php file (after a successful installation) just by running this command:

$ /path/to/php myfile.php // unix way
C:\php\php.exe myfile.php // windows way

You can read more about running PHP in CLI mode here.


It's worth adding that PHP from version 5.4 onwards is able to run a web server on its own. You can do it by running this code in a folder which you want to serve the pages from:

$ php -S localhost:8000

You can read more about running a PHP in a Web Server mode here.

SQL Server: SELECT only the rows with MAX(DATE)

And u can also use that select statement as left join query... Example :

... left join (select OrderNO,
   PartCode,
   Quantity from (select OrderNO,
         PartCode,
         Quantity,
         row_number() over(partition by OrderNO order by DateEntered desc) as rn
  from YourTable) as T where rn = 1 ) RESULT on ....

Hope this help someone that search for this :)

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

if you wanted to create a separate list of results in the controller you could apply a filter

function MyCtrl($scope, filterFilter) {
  $scope.results = {
    year:2013,
    subjects:[
      {title:'English',grade:'A'},
      {title:'Maths',grade:'A'},
      {title:'Science',grade:'B'},
      {title:'Geography',grade:'C'}
    ]
  };
  //create a filtered array of results 
  //with grade 'C' or subjects that have been failed
  $scope.failedSubjects = filterFilter($scope.results.subjects, {'grade':'C'});
}

Then you can reference failedSubjects the same way you would reference the results object

you can read more about it here https://docs.angularjs.org/guide/filter

since this answer angular have updated the documentation they now recommend calling the filter

// update 
// eg: $filter('filter')(array, expression, comparator, anyPropertyKey);
// becomes
$scope.failedSubjects = $filter('filter')($scope.results.subjects, {'grade':'C'});

Check if character is number?

Use combination of isNaN and parseInt functions:

var character = ... ; // your character
var isDigit = ! isNaN( parseInt(character) );

Another notable way - multiplication by one (like character * 1 instead of parseInt(character)) - makes a number not only from any numeric string, but also a 0 from empty string and a string containing only spaces so it is not suitable here.

DateTime.TryParseExact() rejecting valid formats

This is the Simple method, Use ParseExact

CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result;
String dateString = "Sun 08 Jun 2013 8:30 AM -06:00";
String format = "ddd dd MMM yyyy h:mm tt zzz";
result = DateTime.ParseExact(dateString, format, provider);

This should work for you.

OS X Sprite Kit Game Optimal Default Window Size

You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.

Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.

You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.

The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.

You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.

Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.

But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).

You should provide @2x images for the Retina Macbook Pro and future Retina Macs.

jquery: $(window).scrollTop() but no $(window).scrollBottom()

// Back to bottom button
$(window).scroll(function () {
    var scrollBottom = $(this).scrollTop() + $(this).height();
    var scrollTop = $(this).scrollTop();
    var pageHeight = $('html, body').height();//Fixed

    if ($(this).scrollTop() > pageHeight - 700) {
        $('.back-to-bottom').fadeOut('slow');
    } else {
        if ($(this).scrollTop() < 100) {
            $('.back-to-bottom').fadeOut('slow');
        }
        else {
            $('.back-to-bottom').fadeIn('slow');
        }
    }
});
$('.back-to-bottom').click(function () {
    var pageHeight = $('html, body').height();//Fixed
    $('html, body').animate({ scrollTop: pageHeight }, 1500, 'easeInOutExpo');
    return false;
});

Change the Arrow buttons in Slick slider

its very easy. Use the bellow code, Its works for me. Here I have used fontawesome icon but you can use anything as image or any other Icon's code.

    $(document).ready(function(){
        $('.slider').slick({
            autoplay:true,
            arrows: true,
            prevArrow:"<button type='button' class='slick-prev pull-left'><i class='fa fa-angle-left' aria-hidden='true'></i></button>",
            nextArrow:"<button type='button' class='slick-next pull-right'><i class='fa fa-angle-right' aria-hidden='true'></i></button>"
        });
    });

How to add a vertical Separator?

I like to use the "Line" control. It gives you exact control over where the separator starts and ends. Although it isn't exactly a separator, it functions is the same way, especially in a StackPanel.

The line control works within a grid too. I prefer to use the StackPanel because you don't have to worry about different controls overlapping.

<StackPanel Orientation="Horizontal">
    <Button Content="Button 1" Height="20" Width="70"/>
    <Line X1="0" X2="0" Y1="0" Y2="20" Stroke="Black" StrokeThickness="0.5" Margin="5,0,10,0"/>
    <Button Content="Button 2" Height="20" Width="70"/>
</StackPanel>

X1 = x starting position (should be 0 for a vertical line)

X2 = x ending position (X1 = X2 for a vertical line)

Y1 = y starting position (should be 0 for a vertical line)

Y2 = y ending position (Y2 = desired line height)

I use "margin" to add padding on any side of the vertical line. In this instance, there are 5 pixels on the left and 10 pixels on the right of the vertical line.

Since the line control lets you pick the x and y coordinates of the start and end of the line, you can also use it for horizontal lines and lines at any angle in between.

How to get the real path of Java application at runtime?

I use this method to get complete path to jar or exe.

File pto = new File(YourClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());

pto.getAbsolutePath());

ionic build Android | error: No installed build tools found. Please install the Android build tools

I added <preference name="android-minSdkVersion" value="19" /> to my conf.xml and the build was successful.

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

Easiest way to loop through a filtered list with VBA?

I used the RowHeight property of a range (which means cells as well). If it's zero then it's hidden. So just loop through all rows as you would normally but in the if condition check for that property as in If myRange.RowHeight > 0 then DoStuff where DoStuff is something you want to do with the visible cells.

How to set xlim and ylim for a subplot in matplotlib

You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.* function are thin wrappers that basically do gca().*.

plt.subplot returns an axes object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.

import matplotlib.pyplot as plt

ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])


ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])

and so on for as many axes as you want.

or better, wrap it all up in a loop:

import matplotlib.pyplot as plt

DATA_x = ([1, 2],
          [2, 3],
          [3, 4])

DATA_y = DATA_x[::-1]

XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3

for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
    ax = plt.subplot(1, 3, j + 1)
    ax.scatter(x, y)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

clear cache of browser by command line

You can run Rundll32.exe for IE Options control panel applet and achieve following tasks.


Deletes ALL History - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255

Deletes History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1

Deletes Cookies Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2

Deletes Temporary Internet Files Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8

Deletes Form Data Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16

Deletes Password History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32

There is already an open DataReader associated with this Command which must be closed first

I had the same error, when I tried to update some records within read loop. I've tried the most voted answer MultipleActiveResultSets=true and found, that it's just workaround to get the next error 

New transaction is not allowed because there are other threads running in the session

The best approach, that will work for huge ResultSets is to use chunks and open separate context for each chunk as described in  SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

How to randomize (or permute) a dataframe rowwise and columnwise?

Random Samples and Permutations ina dataframe If it is in matrix form convert into data.frame use the sample function from the base package indexes = sample(1:nrow(df1), size=1*nrow(df1)) Random Samples and Permutations

Android map v2 zoom to show all the markers

So

I needed to use addOnGlobalLayoutListener to get the appropriate sample

for example, your Google Map is inside RelativeLayout:

RelativeLayout mapLayout = (RelativeLayout)findViewById(R.id.map_layout);
mapLayout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            //and write code, which you can see in answer above
        }
    });

matplotlib savefig in jpeg format

To clarify and update @neo useful answer and the original question. A clean solution consists of installing Pillow, which is an updated version of the Python Imaging Library (PIL). This is done using

pip install pillow

Once Pillow is installed, the standard Matplotlib commands

import matplotlib.pyplot as plt

plt.plot([1, 2])
plt.savefig('image.jpg')

will save the figure into a JPEG file and will not generate a ValueError any more.

Contrary to @amillerrhodes answer, as of Matplotlib 3.1, JPEG files are still not supported. If I remove the Pillow package I still receive a ValueError about an unsupported file type.

Picasso v/s Imageloader v/s Fresco vs Glide

Fresco sources | off site
(-)

  • Huge size of library
  • No Callback with View, Bitmap parameters
  • SimpleDraweeView doesn't support wrap_content
  • Huge size of cache
    (+)
  • Pretty fast image loader (for small && medium images)
  • A lot of functionality(streaming, drawing tools, memory management, etc)
  • Possibility to setup directly in xml (for example round corners)
  • GIF support
  • WebP and Animated Webp support


Picasso sources | off site
(-)

  • Slow loading big images from internet into ListView
    (+)
  • Tinny size of library
  • Small size of cache
  • Simple to use
  • UI does not freeze
  • WebP support


Glide sources

(-)

  • Big size of library
    (+)
  • Tinny size of cache
  • Simple to use
  • GIF support
  • WebP support
  • Fast loading big images from internet into ListView
  • UI does not freeze
  • BitmapPool to re-use memory and thus lesser GC events


Universal Image Loader sources

(-)

  • Limited functionality (limited image processing)
  • Project support has stopped since 27.11.2015
    (+)
  • Tinny size of library
  • Simple to use

Tested by me on SGS2 (Android 4.1) (WiFi 8.43 Mbps)
Official versions for Java, not for Xamarin!
October 19 2015

I prefer to use Glide.
Read more here.
How to write cache to External Storage (SD Card) with Glide.

"SMTP Error: Could not authenticate" in PHPMailer

I experienced the same error when configuring the WP-Mail-SMTP plugin in Wordpress.

The problem would persist even when I have 'triple checked' the settings and login credentials, and am able to log in manually using a browser.

There's a list of steps you can take to fix this.

  1. Create a new password for the Gmail account you want to use
  2. Enable less secure apps in Google Security settings
  3. Use the Display Unlock Captcha page to give your app or website permission to sign in to Gmail. Click Continue or follow the instructions.
  4. Sign in using the app or website. The smtp settings that work for me are 1) SMTP Host: smtp.gmail.com 2) SMTP port: 587 3) Encryption: TLS 4) Authentication: SMTP authentication 5) Username: [email protected] 6) Password: examplesecret

Passing Javascript variable to <a href >

<script>
   var scrt_var = 10;
   document.getElementById("link").setAttribute("href",scrt_var);
</script>
<a id="link">this is a link</a>

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

All the model fields which have definite types, those should be validated when returned to Controller. If any of the model fields are not matching with their defined type, then ModelState.IsValid will return false. Because, These errors will be added in ModelState.

Angular: conditional class with *ngClass

Angular version 2+ provides several ways to add classes conditionally:

type one

[class.my-class]="step === 'step1'"

type two

[ngClass]="{'my-class': step === 'step1'}"

and multiple option:

[ngClass]="{'my-class': step === 'step1', 'my-class2':step === 'step2' }"

type three

[ngClass]="{1:'my-class1',2:'my-class2',3:'my-class4'}[step]"

type four

[ngClass]="(step=='step1')?'my-class1':'my-class2'"

How to calculate the CPU usage of a process by PID in Linux from C?

Take a look at the "pidstat" command, sounds like exactly what you require.

How to put a link on a button with bootstrap?

Combining the above answers i find a simply solution that probably will help you too:

<button type="submit" onclick="location.href = 'your_link';">Login</button>

by just adding inline JS code you can transform a button in a link and keeping his design.

jquery clear input default value

Just a shorthand

$(document).ready(function() {
    $(".input").val("Email Address");
        $(".input").on("focus click", function(){
            $(this).val("");
        });
    });
</script>

Query to count the number of tables I have in MySQL

SELECT COUNT(*) FROM information_schema.tables

My httpd.conf is empty

The /etc/apache2/httpd.conf is empty in Ubuntu, because the Apache configuration resides in /etc/apache2/apache2.conf!

“httpd.conf is for user options.” No it isn't, it's there for historic reasons.

Using Apache server, all user options should go into a new *.conf-file inside /etc/apache2/conf.d/. This method should be "update-safe", as httpd.conf or apache2.conf may get overwritten on the next server update.

Inside /etc/apache2/apache2.conf, you will find the following line, which includes those files:

# Include generic snippets of statements
Include conf.d/

As of Apache 2.4+ the user configuration directory is /etc/apache2/conf-available/. Use a2enconf FILENAME_WITHOUT_SUFFIX to enable the new configuration file or manually create a symlink in /etc/apache2/conf-enabled/. Be aware that as of Apache 2.4 the configuration files must have the suffix .conf (e.g. conf-available/my-settings.conf);

Resizing an iframe based on content

Work with jquery on load (cross browser):

 <iframe src="your_url" marginwidth="0"  marginheight="0" scrolling="No" frameborder="0"  hspace="0" vspace="0" id="containiframe" onload="loaderIframe();" height="100%"  width="100%"></iframe>

function loaderIframe(){
var heightIframe = $('#containiframe').contents().find('body').height();
$('#frame').css("height", heightFrame);
 }  

on resize in responsive page:

$(window).resize(function(){
if($('#containiframe').length !== 0) {
var heightIframe = $('#containiframe').contents().find('body').height();
 $('#frame').css("height", heightFrame);
}
});

Accessing localhost of PC from USB connected Android mobile device

I've read numerous forums and tried play apps but not found a solution until now.

My scenario I believe is similar to yours, but I will clarify to help others. I have a locally hosted website and web services to be used by my android application. I need to have this working on the road for demonstration with only my laptop and no network connection.

Note: Using my iPhone as a wifi hotspot and connecting both my pc and my android device worked, but the iPhone 4S connection is slow and dropped out regularly.

My solution is as follows:

  • Unplug network cables on PC and turn off wifi.
  • Turn off wifi on android device
  • Connect android to pc via USB
  • Turn on "USB Tethering" in the android menu. (Under networks->more...->Tethering and portable hotspot")
  • Get the IP of your computer that has been assigned by the USB tether cable. (open command prompt and type "ipconfig" then look for the IP that the USB network adapter has assigned)
  • Open a browser on the PC using the IP address found instead of localhost to test. i.e. http://192.168.1.1/myWebSite
  • Open a browser on the android and test it works

Detach (move) subdirectory into separate Git repository

Proper way now is the following:

git filter-branch --prune-empty --subdirectory-filter FOLDER_NAME [first_branch] [another_branch]

GitHub now even have small article about such cases.

But be sure to clone your original repo to separate directory first (as it would delete all the files and other directories and you probable need to work with them).

So your algorithm should be:

  1. clone your remote repo to another directory
  2. using git filter-branch left only files under some subdirectory, push to new remote
  3. create commit to remove this subdirectory from your original remote repo

SASS and @font-face

In case anyone was wondering - it was probably my css...

@font-face
  font-family: "bingo"
  src: url('bingo.eot')
  src: local('bingo')
  src: url('bingo.svg#bingo') format('svg')
  src: url('bingo.otf') format('opentype')

will render as

@font-face {
  font-family: "bingo";
  src: url('bingo.eot');
  src: local('bingo');
  src: url('bingo.svg#bingo') format('svg');
  src: url('bingo.otf') format('opentype'); }

which seems to be close enough... just need to check the SVG rendering

How to delete columns in a CSV file?

Use of Pandas module will be much easier.

import pandas as pd
f=pd.read_csv("test.csv")
keep_col = ['day','month','lat','long']
new_f = f[keep_col]
new_f.to_csv("newFile.csv", index=False)

And here is short explanation:

>>>f=pd.read_csv("test.csv")
>>> f
   day  month  year  lat  long
0    1      4  2001   45   120
1    2      4  2003   44   118
>>> keep_col = ['day','month','lat','long'] 
>>> f[keep_col]
    day  month  lat  long
0    1      4   45   120
1    2      4   44   118
>>>

Objective-C ARC: strong vs retain and weak vs assign

Clang's document on Objective-C Automatic Reference Counting (ARC) explains the ownership qualifiers and modifiers clearly:

There are four ownership qualifiers:

  • __autoreleasing
  • __strong
  • __*unsafe_unretained*
  • __weak

A type is nontrivially ownership-qualified if it is qualified with __autoreleasing, __strong, or __weak.

Then there are six ownership modifiers for declared property:

  • assign implies __*unsafe_unretained* ownership.
  • copy implies __strong ownership, as well as the usual behavior of copy semantics on the setter.
  • retain implies __strong ownership.
  • strong implies __strong ownership.
  • *unsafe_unretained* implies __*unsafe_unretained* ownership.
  • weak implies __weak ownership.

With the exception of weak, these modifiers are available in non-ARC modes.

Semantics wise, the ownership qualifiers have different meaning in the five managed operations: Reading, Assignment, Initialization, Destruction and Moving, in which most of times we only care about the difference in Assignment operation.

Assignment occurs when evaluating an assignment operator. The semantics vary based on the qualification:

  • For __strong objects, the new pointee is first retained; second, the lvalue is loaded with primitive semantics; third, the new pointee is stored into the lvalue with primitive semantics; and finally, the old pointee is released. This is not performed atomically; external synchronization must be used to make this safe in the face of concurrent loads and stores.
  • For __weak objects, the lvalue is updated to point to the new pointee, unless the new pointee is an object currently undergoing deallocation, in which case the lvalue is updated to a null pointer. This must execute atomically with respect to other assignments to the object, to reads from the object, and to the final release of the new pointee.
  • For __*unsafe_unretained* objects, the new pointee is stored into the lvalue using primitive semantics.
  • For __autoreleasing objects, the new pointee is retained, autoreleased, and stored into the lvalue using primitive semantics.

The other difference in Reading, Init, Destruction and Moving, please refer to Section 4.2 Semantics in the document.

Difference between innerText, innerHTML and value?

The only difference between innerText and innerHTML is that innerText insert string as it is into the element, while innerHTML run it as html content.

_x000D_
_x000D_
const ourstring = 'My name is <b class="name">Satish chandra Gupta</b>.';_x000D_
document.getElementById('innertext').innerText = ourstring;_x000D_
document.getElementById('innerhtml').innerHTML = ourstring;
_x000D_
.name{_x000D_
color:red;_x000D_
}
_x000D_
<h3>Inner text below. It inject string as it is into the element.</h3>_x000D_
<div id="innertext"></div>_x000D_
<br />_x000D_
<h3>Inner html below. It renders the string into the element and treat as part of html document.</h3>_x000D_
<div id="innerhtml"></div>
_x000D_
_x000D_
_x000D_

checking for typeof error in JS

You can use Object.prototype.toString to easily check if an object is an Error, which will work for different frames as well.

function isError(obj){
    return Object.prototype.toString.call(obj) === "[object Error]";
}

_x000D_
_x000D_
function isError(obj){
    return Object.prototype.toString.call(obj) === "[object Error]";
}
console.log("Error:", isError(new Error));
console.log("RangeError:", isError(new RangeError));
console.log("SyntaxError:", isError(new SyntaxError));
console.log("Object:", isError({}));
console.log("Array:", isError([]));
_x000D_
_x000D_
_x000D_

This behavior is guaranteed by the ECMAScript Language Specification.

Object.prototype.toString:

When the toString method is called, the following steps are taken:

  1. If the this value is undefined, return "[object Undefined]".
  2. If the this value is null, return "[object Null]".
  3. Let O be the result of calling ToObject passing the this value as the argument.
  4. Let class be the value of the [[Class]] internal property of O.
  5. Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".

Properties of Error Instances:

Error instances inherit properties from the Error prototype object and their [[Class]] internal property value is "Error". Error instances have no special properties.

What is the difference between private and protected members of C++ classes?

Private member can be accessed only in same class where it has declared where as protected member can be accessed in class where it is declared along with the classes which are inherited by it .

PostgreSQL: how to convert from Unix epoch to date?

select to_timestamp(cast(epoch_ms/1000 as bigint))::date

worked for me

Loading .sql files from within PHP

This may be helpful -->

More or less what it does is to first take the string given to the function (the file_get_contents() value of your file.sql) and remove all the line breaks. Then it splits the data by the ";" character. Next it goes into a while loop, looking at each line of the array that is created. If the line contains the " ` " character, it will know it is a query and execture the myquery() function for the given line data.

Code:

function myquery($query) {

mysql_connect(dbhost, dbuser, dbpass);

mysql_select_db(dbname);

$result = mysql_query($query);

if (!mysql_errno() && @mysql_num_rows($result) > 0) {
}

else {

$result="not";
}
mysql_close();

return $result;

}



function mybatchquery ($str) {

$sql = str_replace("\n","",$str)

$sql = explode(";",$str);

$x=0;

while (isset($str[$x])) {

if (preg_match("/(\w|\W)+`(\w|\W)+) {

myquery($str[$x]);

}

$x++

}

return TRUE;

}




function myrows($result) {

$rows = @mysql_num_rows($result);

return $rows;
}




function myarray($result) {

$array = mysql_fetch_array($result);

return $array;
}




function myescape($query) {

$escape = mysql_escape_string($query);

return $escape;
}



$str = file_get_contents("foo.sql");
mybatchquery($str);

Change the name of a key in dictionary

pop'n'fresh

>>>a = {1:2, 3:4}
>>>a[5] = a.pop(1)
>>>a
{3: 4, 5: 2}
>>> 

Join between tables in two different databases?

SELECT <...>
FROM A.table1 t1 JOIN B.table2 t2 ON t2.column2 = t1.column1;

Just make sure that in the SELECT line you specify which table columns you are using, either by full reference, or by alias. Any of the following will work:

SELECT *
SELECT t1.*,t2.column2
SELECT A.table1.column1, t2.*
etc.

How to insert array of data into mysql using php

First of all you should stop using mysql_*. MySQL supports multiple inserting like

INSERT INTO example
VALUES
  (100, 'Name 1', 'Value 1', 'Other 1'),
  (101, 'Name 2', 'Value 2', 'Other 2'),
  (102, 'Name 3', 'Value 3', 'Other 3'),
  (103, 'Name 4', 'Value 4', 'Other 4');

You just have to build one string in your foreach loop which looks like that

$values = "(100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1')";

and then insert it after the loop

$sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) VALUES ".$values;

Another way would be Prepared Statements, which are even more suited for your situation.

Determine the number of rows in a range

I am sure that you probably wanted the answer that @GSerg gave. There is also a worksheet function called rows that will give you the number of rows.

So, if you have a named data range called Data that has 7 rows, then =ROWS(Data) will show 7 in that cell.

How do I convert Int/Decimal to float in C#?

You don't even need to cast, it is implicit.

int i = 3;

float f = i;

A full list/table of implicit numeric conversions can be seen here http://msdn.microsoft.com/en-us/library/y5b434w4.aspx

HTTP Error 503. The service is unavailable. App pool stops on accessing website

I had a similar issue, all my app pools were stopping whenever a web request was made to them. Although I was getting the following error in the Event Viewer:

The worker process for application pool 'appPoolName' encountered an error 'Configuration file is not well-formed XML ' trying to read configuration data from file '\?\C:\inetpub\temp\apppools\appPoolName\appPoolName.config', line number '3'. The data field contains the error code.

Which told me that there were errors in the application.config at:

C:\Windows\System32\inetsrv\config\applicationHost.config

In my scenario, I edited the web.config on deploy with an element IIS clearly dislikes, the applicationHost.config scraped the web.config and inserted this bad element and wouldn't resolve until I manually removed it

How to tell which row number is clicked in a table?

You can use object.rowIndex property which has an index starting at 0.

$("table tr").click(function(){
    alert (this.rowIndex);
});

See a working demo

org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

Below solution worked for me: Navigate to Project->Clean.. Clean all the projects referenced by Tomcat server Refresh the project you're trying to run on Tomcat

Try to run the server afterwards

What exactly is nullptr?

0 used to be the only integer value that could be used as a cast-free initializer for pointers: you can not initialize pointers with other integer values without a cast. You can consider 0 as a consexpr singleton syntactically similar to an integer literal. It can initiate any pointer or integer. But surprisingly, you'll find that it has no distinct type: it is an int. So how come 0 can initialize pointers and 1 cannot? A practical answer was we need a means of defining pointer null value and direct implicit conversion of int to a pointer is error-prone. Thus 0 became a real freak weirdo beast out of the prehistoric era. nullptr was proposed to be a real singleton constexpr representation of null value to initialize pointers. It can not be used to directly initialize integers and eliminates ambiguities involved with defining NULL in terms of 0. nullptr could be defined as a library using std syntax but semantically looked to be a missing core component. NULL is now deprecated in favor of nullptr, unless some library decides to define it as nullptr.

how do I set height of container DIV to 100% of window height?

Did you set the CSS:

html, body
{
    height: 100%;
}

You need this to be able to make the div take up all the space. :)

Excel select a value from a cell having row number calculated

You could use the INDIRECT function. This takes a string and converts it into a range

More info here

=INDIRECT("K"&A2)

But it's preferable to use INDEX as it is less volatile.

=INDEX(K:K,A2)

This returns a value or the reference to a value from within a table or range

More info here

Put either function into cell B2 and fill down.

How do I handle newlines in JSON?

well, it is not really necessary to create a function for this when it can be done simply with 1 CSS class.

just wrap your text around this class and see the magic :D

 <p style={{whiteSpace: 'pre-line'}}>my json text goes here \n\n</p>

note: because you will always present your text in frontend with HTML you can add the style={{whiteSpace: 'pre-line'}} to any tag, not just the p tag.

Change text color with Javascript?

innerHTML is a string representing the contents of the element.

You want to modify the element itself. Drop the .innerHTML part.

Equivalent of shell 'cd' command to change the working directory?

You can change the working directory with:

import os

os.chdir(path)

There are two best practices to follow when using this method:

  1. Catch the exception (WindowsError, OSError) on invalid path. If the exception is thrown, do not perform any recursive operations, especially destructive ones. They will operate on the old path and not the new one.
  2. Return to your old directory when you're done. This can be done in an exception-safe manner by wrapping your chdir call in a context manager, like Brian M. Hunt did in his answer.

Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use os.chdir() to change the CWD of the calling process.

window.open(url, '_blank'); not working on iMac/Safari

Taken from the accepted answers comment by Steve on Dec 20, 2013:

Actually, there's a very easy way to do it: just click off "Block popup windows" in the iMac/Safari browser and it does what I want.

To clarify, when running Safari on Mac OS X El Capitan:

  1. Safari -> Preferences
  2. Security -> Uncheck 'Block pop-up windows'

Break promise chain and call a function based on the step in the chain where it is broken (rejected)

Try ro use this like libs:

https://www.npmjs.com/package/promise-chain-break

    db.getData()
.then(pb((data) => {
    if (!data.someCheck()) {
        tellSomeone();

        // All other '.then' calls will be skiped
        return pb.BREAK;
    }
}))
.then(pb(() => {
}))
.then(pb(() => {
}))
.catch((error) => {
    console.error(error);
});

Calling @Html.Partial to display a partial view belonging to a different controller

That's no problem.

@Html.Partial("../Controller/View", model)

or

@Html.Partial("~/Views/Controller/View.cshtml", model)

Should do the trick.

If you want to pass through the (other) controller, you can use:

@Html.Action("action", "controller", parameters)

or any of the other overloads

References with text in LaTeX

I think you can do this with the hyperref package, although I've not tried it myself. From the relevant LaTeX Wikibook section:

The hyperref package introduces another useful command; \autoref{}. This command creates a reference with additional text corresponding to the targets type, all of which will be a hyperlink. For example, the command \autoref{sec:intro} would create a hyperlink to the \label{sec:intro} command, wherever it is. Assuming that this label is pointing to a section, the hyperlink would contain the text "section 3.4", or similar (capitalization rules will be followed, which makes this very convenient). You can customize the prefixed text by redefining \typeautorefname to the prefix you want, as in:

\def\subsectionautorefname{section}

CORS: credentials mode is 'include'

Customizing CORS for Angular 5 and Spring Security (Cookie base solution)

On the Angular side required adding option flag withCredentials: true for Cookie transport:

constructor(public http: HttpClient) {
}

public get(url: string = ''): Observable<any> {
    return this.http.get(url, { withCredentials: true });
}

On Java server-side required adding CorsConfigurationSource for configuration CORS policy:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // This Origin header you can see that in Network tab
        configuration.setAllowedOrigins(Arrays.asList("http:/url_1", "http:/url_2")); 
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.setAllowedHeaders(Arrays.asList("content-type"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()...
    }
}

Method configure(HttpSecurity http) by default will use corsConfigurationSource for http.cors()

Unable to find valid certification path to requested target - error even after cert imported

Check if the file $JAVA_HOME/lib/security/cacerts exists! In my case it was not a file but a link to /etc/ssl/certs/java/cacerts and also this was a link to itself (WHAT???) so due to it JVM can't find the file.

Solution: Copy the real cacerts file (you can do it from another JDK) to /etc/ssl/certs/java/ directory and it'll solve your problem :)

How large is a DWORD with 32- and 64-bit code?

No ... on all Windows platforms DWORD is 32 bits. LONGLONG or LONG64 is used for 64 bit types.

How do you find out the type of an object (in Swift)?

Swift 2.0:

The proper way to do this kind of type introspection would be with the Mirror struct,

    let stringObject:String = "testing"
    let stringArrayObject:[String] = ["one", "two"]
    let viewObject = UIView()
    let anyObject:Any = "testing"

    let stringMirror = Mirror(reflecting: stringObject)
    let stringArrayMirror = Mirror(reflecting: stringArrayObject)
    let viewMirror = Mirror(reflecting: viewObject)
    let anyMirror = Mirror(reflecting: anyObject)

Then to access the type itself from the Mirror struct you would use the property subjectType like so:

    // Prints "String"
    print(stringMirror.subjectType)

    // Prints "Array<String>"
    print(stringArrayMirror.subjectType)

    // Prints "UIView"
    print(viewMirror.subjectType)

    // Prints "String"
    print(anyMirror.subjectType)

You can then use something like this:

    if anyMirror.subjectType == String.self {
        print("anyObject is a string!")
    } else {
        print("anyObject is not a string!")
    }

How to get instance variables in Python?

Use vars()

class Foo(object):
    def __init__(self):
        self.a = 1
        self.b = 2

vars(Foo()) #==> {'a': 1, 'b': 2}
vars(Foo()).keys() #==> ['a', 'b']

How to define hash tables in Bash?

Bash 3 solution:

In reading some of the answers I put together a quick little function I would like to contribute back that might help others.

# Define a hash like this
MYHASH=("firstName:Milan"
        "lastName:Adamovsky")

# Function to get value by key
getHashKey()
 {
  declare -a hash=("${!1}")
  local key
  local lookup=$2

  for key in "${hash[@]}" ; do
   KEY=${key%%:*}
   VALUE=${key#*:}
   if [[ $KEY == $lookup ]]
   then
    echo $VALUE
   fi
  done
 }

# Function to get a list of all keys
getHashKeys()
 {
  declare -a hash=("${!1}")
  local KEY
  local VALUE
  local key
  local lookup=$2

  for key in "${hash[@]}" ; do
   KEY=${key%%:*}
   VALUE=${key#*:}
   keys+="${KEY} "
  done

  echo $keys
 }

# Here we want to get the value of 'lastName'
echo $(getHashKey MYHASH[@] "lastName")


# Here we want to get all keys
echo $(getHashKeys MYHASH[@])

How to save a Seaborn plot into a file

You should just be able to use the savefig method of sns_plot directly.

sns_plot.savefig("output.png")

For clarity with your code if you did want to access the matplotlib figure that sns_plot resides in then you can get it directly with

fig = sns_plot.fig

In this case there is no get_figure method as your code assumes.

What is the common header format of Python files?

Its all metadata for the Foobar module.

The first one is the docstring of the module, that is already explained in Peter's answer.

How do I organize my modules (source files)? (Archive)

The first line of each file shoud be #!/usr/bin/env python. This makes it possible to run the file as a script invoking the interpreter implicitly, e.g. in a CGI context.

Next should be the docstring with a description. If the description is long, the first line should be a short summary that makes sense on its own, separated from the rest by a newline.

All code, including import statements, should follow the docstring. Otherwise, the docstring will not be recognized by the interpreter, and you will not have access to it in interactive sessions (i.e. through obj.__doc__) or when generating documentation with automated tools.

Import built-in modules first, followed by third-party modules, followed by any changes to the path and your own modules. Especially, additions to the path and names of your modules are likely to change rapidly: keeping them in one place makes them easier to find.

Next should be authorship information. This information should follow this format:

__author__ = "Rob Knight, Gavin Huttley, and Peter Maxwell"
__copyright__ = "Copyright 2007, The Cogent Project"
__credits__ = ["Rob Knight", "Peter Maxwell", "Gavin Huttley",
                    "Matthew Wakefield"]
__license__ = "GPL"
__version__ = "1.0.1"
__maintainer__ = "Rob Knight"
__email__ = "[email protected]"
__status__ = "Production"

Status should typically be one of "Prototype", "Development", or "Production". __maintainer__ should be the person who will fix bugs and make improvements if imported. __credits__ differs from __author__ in that __credits__ includes people who reported bug fixes, made suggestions, etc. but did not actually write the code.

Here you have more information, listing __author__, __authors__, __contact__, __copyright__, __license__, __deprecated__, __date__ and __version__ as recognized metadata.

python - find index position in list based of partial string

spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"]

index=spell_list.index("Annual")
print(index)

Align nav-items to right side in bootstrap-4

In last versions, it is easier. Just put a ml-auto class in the ul like so:

<ul class="nav navbar-nav ml-auto">

How can I mimic the bottom sheet from the Maps app?

I don't know how exactly the bottom sheet of the new Maps app, responds to user interactions. But you can create a custom view that looks like the one in the screenshots and add it to the main view.

I assume you know how to:

1- create view controllers either by storyboards or using xib files.

2- use googleMaps or Apple's MapKit.

Example

1- Create 2 view controllers e.g, MapViewController and BottomSheetViewController. The first controller will host the map and the second is the bottom sheet itself.

Configure MapViewController

Create a method to add the bottom sheet view.

func addBottomSheetView() {
    // 1- Init bottomSheetVC
    let bottomSheetVC = BottomSheetViewController()

    // 2- Add bottomSheetVC as a child view 
    self.addChildViewController(bottomSheetVC)
    self.view.addSubview(bottomSheetVC.view)
    bottomSheetVC.didMoveToParentViewController(self)

    // 3- Adjust bottomSheet frame and initial position.
    let height = view.frame.height
    let width  = view.frame.width
    bottomSheetVC.view.frame = CGRectMake(0, self.view.frame.maxY, width, height)
}

And call it in viewDidAppear method:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    addBottomSheetView()
}

Configure BottomSheetViewController

1) Prepare background

Create a method to add blur and vibrancy effects

func prepareBackgroundView(){
    let blurEffect = UIBlurEffect.init(style: .Dark)
    let visualEffect = UIVisualEffectView.init(effect: blurEffect)
    let bluredView = UIVisualEffectView.init(effect: blurEffect)
    bluredView.contentView.addSubview(visualEffect)

    visualEffect.frame = UIScreen.mainScreen().bounds
    bluredView.frame = UIScreen.mainScreen().bounds

    view.insertSubview(bluredView, atIndex: 0)
}

call this method in your viewWillAppear

override func viewWillAppear(animated: Bool) {
   super.viewWillAppear(animated)
   prepareBackgroundView()
}

Make sure that your controller's view background color is clearColor.

2) Animate bottomSheet appearance

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    UIView.animateWithDuration(0.3) { [weak self] in
        let frame = self?.view.frame
        let yComponent = UIScreen.mainScreen().bounds.height - 200
        self?.view.frame = CGRectMake(0, yComponent, frame!.width, frame!.height)
    }
}

3) Modify your xib as you want.

4) Add Pan Gesture Recognizer to your view.

In your viewDidLoad method add UIPanGestureRecognizer.

override func viewDidLoad() {
    super.viewDidLoad()

    let gesture = UIPanGestureRecognizer.init(target: self, action: #selector(BottomSheetViewController.panGesture))
    view.addGestureRecognizer(gesture)

}

And implement your gesture behaviour:

func panGesture(recognizer: UIPanGestureRecognizer) {
    let translation = recognizer.translationInView(self.view)
    let y = self.view.frame.minY
    self.view.frame = CGRectMake(0, y + translation.y, view.frame.width, view.frame.height)
     recognizer.setTranslation(CGPointZero, inView: self.view)
}

Scrollable Bottom Sheet:

If your custom view is a scroll view or any other view that inherits from, so you have two options:

First:

Design the view with a header view and add the panGesture to the header. (bad user experience).

Second:

1 - Add the panGesture to the bottom sheet view.

2 - Implement the UIGestureRecognizerDelegate and set the panGesture delegate to the controller.

3- Implement shouldRecognizeSimultaneouslyWith delegate function and disable the scrollView isScrollEnabled property in two case:

  • The view is partially visible.
  • The view is totally visible, the scrollView contentOffset property is 0 and the user is dragging the view downwards.

Otherwise enable scrolling.

  func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
      let gesture = (gestureRecognizer as! UIPanGestureRecognizer)
      let direction = gesture.velocity(in: view).y

      let y = view.frame.minY
      if (y == fullView && tableView.contentOffset.y == 0 && direction > 0) || (y == partialView) {
          tableView.isScrollEnabled = false
      } else {
        tableView.isScrollEnabled = true
      }

      return false
  }

NOTE

In case you set .allowUserInteraction as an animation option, like in the sample project, so you need to enable scrolling on the animation completion closure if the user is scrolling up.

Sample Project

I created a sample project with more options on this repo which may give you better insights about how to customise the flow.

In the demo, addBottomSheetView() function controls which view should be used as a bottom sheet.

Sample Project Screenshots

- Partial View

enter image description here

- FullView

enter image description here

- Scrollable View

enter image description here

Play infinitely looping video on-load in HTML5

You can do this the following two ways:

1) Using loop attribute in video element (mentioned in the first answer):

2) and you can use the ended media event:

window.addEventListener('load', function(){
    var newVideo = document.getElementById('videoElementId');
    newVideo.addEventListener('ended', function() {
        this.currentTime = 0;
        this.play();
    }, false);

    newVideo.play();

});

How to search all loaded scripts in Chrome Developer Tools?

In Windows Control+Shift+F. Also make sure to search in content scripts as well. Go to Settings->Sources-> Search in anonymous and content script.

Difference between dangling pointer and memory leak

A dangling pointer is one that has a value (not NULL) which refers to some memory which is not valid for the type of object you expect. For example if you set a pointer to an object then overwrote that memory with something else unrelated or freed the memory if it was dynamically allocated.

A memory leak is when you dynamically allocate memory from the heap but never free it, possibly because you lost all references to it.

They are related in that they are both situations relating to mismanaged pointers, especially regarding dynamically allocated memory. In one situation (dangling pointer) you have likely freed the memory but tried to reference it afterwards; in the other (memory leak), you have forgotten to free the memory entirely!

What is the command to exit a Console application in C#?

You can use Environment.Exit(0) and Application.Exit.

Environment.Exit(): terminates this process and gives the underlying operating system the specified exit code.

Javascript: Unicode string to hex

Remember that a JavaScript code unit is 16 bits wide. Therefore the hex string form will be 4 digits per code unit.

usage:

var str = "\u6f22\u5b57"; // "\u6f22\u5b57" === "??"
alert(str.hexEncode().hexDecode());

String to hex form:

String.prototype.hexEncode = function(){
    var hex, i;

    var result = "";
    for (i=0; i<this.length; i++) {
        hex = this.charCodeAt(i).toString(16);
        result += ("000"+hex).slice(-4);
    }

    return result
}

Back again:

String.prototype.hexDecode = function(){
    var j;
    var hexes = this.match(/.{1,4}/g) || [];
    var back = "";
    for(j = 0; j<hexes.length; j++) {
        back += String.fromCharCode(parseInt(hexes[j], 16));
    }

    return back;
}

Create a HTML table where each TR is a FORM

You may have issues with column width, but you can set those explicitly.

<table>
  <tr>
    <td>
       <form>
         <table>
           <tr>
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
           </tr>
         </table>
       </form>
     </td>
    </tr>
  <tr>
    <td>
       <form>
         <table>
           <tr>
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
           </tr>
         </table>
       </form>
     </td>
    </tr>
  </table>

You may want to also consider making it a single form, and then using jQuery to select the form elements from the row you want, serialize them, and submit them as the form.

See: http://api.jquery.com/serialize/

Also, there are a number of very nice grid plugins: http://www.google.com/search?q=jquery+grid&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a

Typescript: How to extend two classes?

I found an up-to-date & unparalleled solution: https://www.npmjs.com/package/ts-mixer

You are welcome :)

Looping through a Scripting.Dictionary using index/item number

Using d.Keys()(i) method is a very bad idea, because on each call it will re-create a new array (you will have significant speed reduction).

Here is an analogue of Scripting.Dictionary called "Hash Table" class from @TheTrick, that support such enumerator: http://www.cyberforum.ru/blogs/354370/blog2905.html

Dim oDict As clsTrickHashTable

Sub aaa()
    Set oDict = New clsTrickHashTable

    oDict.Add "a", "aaa"
    oDict.Add "b", "bbb"

    For i = 0 To oDict.Count - 1
        Debug.Print oDict.Keys(i) & " - " & oDict.Items(i)
    Next
End Sub

How to convert JSON data into a Python object

The lightest solution I think is

import json
from typing import NamedTuple

_j = '{"name":"????","age":37,"mother":{"name":"?????","age":58},"children":["????","?????","????"],"married": true,' \
     '"dog":null} '


class PersonNameAge(NamedTuple):
    name: str
    age: int


class UserInfo(NamedTuple):
    name: str
    age: int
    mother: PersonNameAge
    children: list
    married: bool
    dog: str


j = json.loads(_j)
u = UserInfo(**j)

print(u.name, u.age, u.mother, u.children, u.married, u.dog)

>>> Ivan 37 {'name': 'Olga', 'age': 58} ['Mary', 'Igor', 'Jane'] True None

How to read all of Inputstream in Server Socket JAVA

You can read your BufferedInputStream like this. It will read data till it reaches end of stream which is indicated by -1.

inputS = new BufferedInputStream(inBS);
byte[] buffer = new byte[1024];    //If you handle larger data use a bigger buffer size
int read;
while((read = inputS.read(buffer)) != -1) {
    System.out.println(read);
    // Your code to handle the data
}

Creating a Zoom Effect on an image on hover using CSS?

 -webkit-transition: all 1s ease; /* Safari and Chrome */
-moz-transition: all 1s ease; /* Firefox */
-ms-transition: all 1s ease; /* IE 9 */
-o-transition: all 1s ease; /* Opera */
transition: all 1s ease;  

just want to make a note on the above transitions only need

 -webkit-transition: all 1s ease; /* Safari and Chrome */
transition: all 1s ease;

and -ms- certainly doenst work for IE 9 i dont know where you got that idea from.

Build not visible in itunes connect

To update @cdescours' answer, uploaded builds can now be seen in the "Activity" tab in "Processing" state.

How to navigate a few folders up?

This is what worked best for me:

string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../"));

Getting the 'right' path wasn't the problem, adding '../' obviously does that, but after that, the given string isn't usable, because it will just add the '../' at the end. Surrounding it with Path.GetFullPath() will give you the absolute path, making it usable.

Get everything after the dash in a string in JavaScript

myString.split('-').splice(1).join('-')

How to access a dictionary element in a Django template?

you can use the dot notation:

Dot lookups can be summarized like this: when the template system encounters a dot in a variable name, it tries the following lookups, in this order:

  • Dictionary lookup (e.g., foo["bar"])
  • Attribute lookup (e.g., foo.bar)
  • Method call (e.g., foo.bar())
  • List-index lookup (e.g., foo[2])

The system uses the first lookup type that works. It’s short-circuit logic.

How can I get the current screen orientation?

int rotation =  getWindowManager().getDefaultDisplay().getRotation();

this will gives all orientation like normal and reverse

and handle it like

int angle = 0;
switch (rotation) {
    case Surface.ROTATION_90:
        angle = -90;
        break;
    case Surface.ROTATION_180:
        angle = 180;
        break;
    case Surface.ROTATION_270:
        angle = 90;
        break;
    default:
        angle = 0;
        break;
}

CustomErrors mode="Off"

You can also try bringing up the website in a browser on the server machine. I don't do a lot of ASP.NET development, but I remember the custom errors thing has a setting for only displaying full error text on the server, as a security measure.

How to add data via $.ajax ( serialize() + extra data ) like this

What kind of data?

data: $('#myForm').serialize() + "&moredata=" + morevalue

The "data" parameter is just a URL encoded string. You can append to it however you like. See the API here.

How to beautifully update a JPA entity in Spring Data?

Even better then @Tanjim Rahman answer you can using Spring Data JPA use the method T getOne(ID id)

Customer customerToUpdate = customerRepository.getOne(id);
customerToUpdate.setName(customerDto.getName);
customerRepository.save(customerToUpdate);

Is's better because getOne(ID id) gets you only a reference (proxy) object and does not fetch it from the DB. On this reference you can set what you want and on save() it will do just an SQL UPDATE statement like you expect it. In comparsion when you call find() like in @Tanjim Rahmans answer spring data JPA will do an SQL SELECT to physically fetch the entity from the DB, which you dont need, when you are just updating.

How to open warning/information/error dialog in Swing?

JOptionPane.showOptionDialog
JOptionPane.showMessageDialog
....

Have a look on this tutorial on how to make dialogs.

How could I put a border on my grid control in WPF?

If someone is interested in the similar problem, but is not working with XAML, here's my solution:

var B1 = new Border();
B1.BorderBrush = Brushes.Black;
B1.BorderThickness = new Thickness(0, 1, 0, 0); // You can specify here which borders do you want
YourPanel.Children.Add(B1);

Why can't I define a static method in a Java interface?

  • "Is there a particular reason that static methods cannot be overridden".

Let me re-word that question for your by filling in the definitions.

  • "Is there a particular reason that methods resolved at compile time cannot be resolved at runtime."

Or, to put in more completely, If I want to call a method without an instance, but knowing the class, how can I have it resolved based upon the instance that I don't have.

How can I stop Chrome from going into debug mode?

There are a couple of reasons for this:

  1. You've toggled on the Pause On Caught Exceptions button. So, toggle it off.

    Enter image description here

  2. You've toggled a line (or more) to be paused on exception. So, toggle it off.

    Enter image description here

How to catch segmentation fault in Linux?

C++ solution found here (http://www.cplusplus.com/forum/unices/16430/)

#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void ouch(int sig)
{
    printf("OUCH! - I got signal %d\n", sig);
}
int main()
{
    struct sigaction act;
    act.sa_handler = ouch;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    sigaction(SIGINT, &act, 0);
    while(1) {
        printf("Hello World!\n");
        sleep(1);
    }
}

What is $@ in Bash?

Yes. Please see the man page of bash ( the first thing you go to ) under Special Parameters

Special Parameters

The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed.

* Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.

@ Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).

Currency Formatting in JavaScript

You can use standard JS toFixed method

var num = 5.56789;
var n=num.toFixed(2);

//5.57

In order to add commas (to separate 1000's) you can add regexp as follows (where num is a number):

num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")

//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000

Complete example:

var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");

//document.write(num) would write value as follows: $1,250.22

Separation character depends on country and locale. For some countries it may need to be .

Convert pyspark string to date format

In the accepted answer's update you don't see the example for the to_date function, so another solution using it would be:

from pyspark.sql import functions as F

df = df.withColumn(
            'new_date',
                F.to_date(
                    F.unix_timestamp('STRINGCOLUMN', 'MM-dd-yyyy').cast('timestamp')))

Batch Renaming of Files in a Directory

directoryName = "Photographs"
filePath = os.path.abspath(directoryName)
filePathWithSlash = filePath + "\\"

for counter, filename in enumerate(os.listdir(directoryName)):

    filenameWithPath = os.path.join(filePathWithSlash, filename)

    os.rename(filenameWithPath, filenameWithPath.replace(filename,"DSC_" + \
          str(counter).zfill(4) + ".jpg" ))

# e.g. filename = "photo1.jpg", directory = "c:\users\Photographs"        
# The string.replace call swaps in the new filename into 
# the current filename within the filenameWitPath string. Which    
# is then used by os.rename to rename the file in place, using the  
# current (unmodified) filenameWithPath.

# os.listdir delivers the filename(s) from the directory
# however in attempting to "rename" the file using os 
# a specific location of the file to be renamed is required.

# this code is from Windows 

Regex that matches integers in between whitespace or start/end of string only

Similar to manojlds but includes the optional negative/positive numbers:

var regex = /^[-+]?\d+$/;

EDIT

If you don't want to allow zeros in the front (023 becomes invalid), you could write it this way:

var regex = /^[-+]?[1-9]\d*$/;

EDIT 2

As @DmitriyLezhnev pointed out, if you want to allow the number 0 to be valid by itself but still invalid when in front of other numbers (example: 0 is valid, but 023 is invalid). Then you could use

var regex = /^([+-]?[1-9]\d*|0)$/

Adding Image to xCode by dragging it from File

You can't add image from desktop to UIimageView, you only can add image (dragging) into project folders and then select the name image into UIimageView properties (inspector).

Tutorial on how to do that: http://conecode.com/news/2011/06/ios-tutorial-creating-an-image-view-uiimageview/

How to return a PNG image from Jersey REST service method to the browser

I'm not convinced its a good idea to return image data in a REST service. It ties up your application server's memory and IO bandwidth. Much better to delegate that task to a proper web server that is optimized for this kind of transfer. You can accomplish this by sending a redirect to the image resource (as a HTTP 302 response with the URI of the image). This assumes of course that your images are arranged as web content.

Having said that, if you decide you really need to transfer image data from a web service you can do so with the following (pseudo) code:

@Path("/whatever")
@Produces("image/png")
public Response getFullImage(...) {

    BufferedImage image = ...;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "png", baos);
    byte[] imageData = baos.toByteArray();

    // uncomment line below to send non-streamed
    // return Response.ok(imageData).build();

    // uncomment line below to send streamed
    // return Response.ok(new ByteArrayInputStream(imageData)).build();
}

Add in exception handling, etc etc.

How to set all elements of an array to zero or any same value?

You could use memset, if you sure about the length.

memset(ptr, 0x00, length)

How to process POST data in Node.js?

You can easily send and get the response of POST request by using "Request - Simplified HTTP client" and Javascript Promise.

var request = require('request');

function getData() {
    var options = {
        url: 'https://example.com',
        headers: {
            'Content-Type': 'application/json'
        }
    };

    return new Promise(function (resolve, reject) {
        var responseData;
        var req = request.post(options, (err, res, body) => {
            if (err) {
                console.log(err);
                reject(err);
            } else {
                console.log("Responce Data", JSON.parse(body));
                responseData = body;
                resolve(responseData);
            }
        });
    });
}

Using JQuery hover with HTML image map

I found this wonderful mapping script (mapper.js) that I have used in the past. What's different about it is you can hover over the map or a link on your page to make the map area highlight. Sadly it's written in javascript and requires a lot of in-line coding in the HTML - I would love to see this script ported over to jQuery :P

Also, check out all the demos! I think this example could almost be made into a simple online game (without using flash) - make sure you click on the different camera angles.

Retrieve data from website in android app

You can use jsoup to parse any kind of web page. Here you can find the jsoup library and full source code.

Here is an example: http://desicoding.blogspot.com/2011/03/how-to-parse-html-in-java-jsoup.html

To install in Eclipse:

  1. Right Click on project
  2. BuildPath
  3. Add External Archives
  4. select the .jar file

You can parse according to tag/parent/child very comfortably

What is the single most influential book every programmer should read?

This isn't a direct answer to the question, because I feel it's already been answered above, however, one of the books that definitely had an impact on how I code is Code Reading, Volume 1: The Open Source Perspective.

alt text http://g.bookpool.com/covers/405/0201799405_140_30O.gif

Remove spaces from a string in VB.NET

To remove ALL spaces:

 myString = myString.Replace(" ", "")

To remove leading and trailing spaces:

myString = myString.Trim()

Note: this removes any white space, so newlines, tabs, etc. would be removed.

java.lang.IllegalArgumentException: View not attached to window manager

Here is my "bullet proof" solution, which is compilation of all good answers that I found on this topic (thanks to @Damjan and @Kachi). Here the exception is swallowed only if all other ways of detection did not succeeded. In my case I need to close the dialog automatically and this is the only way to protect the app from crash. I hope it will help you! Please, vote and leave comments if you have remarks or better solution. Thank you!

public void dismissWithCheck(Dialog dialog) {
        if (dialog != null) {
            if (dialog.isShowing()) {

                //get the Context object that was used to great the dialog
                Context context = ((ContextWrapper) dialog.getContext()).getBaseContext();

                // if the Context used here was an activity AND it hasn't been finished or destroyed
                // then dismiss it
                if (context instanceof Activity) {

                    // Api >=17
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                        if (!((Activity) context).isFinishing() && !((Activity) context).isDestroyed()) {
                            dismissWithTryCatch(dialog);
                        }
                    } else {

                        // Api < 17. Unfortunately cannot check for isDestroyed()
                        if (!((Activity) context).isFinishing()) {
                            dismissWithTryCatch(dialog);
                        }
                    }
                } else
                    // if the Context used wasn't an Activity, then dismiss it too
                    dismissWithTryCatch(dialog);
            }
            dialog = null;
        }
    }

    public void dismissWithTryCatch(Dialog dialog) {
        try {
            dialog.dismiss();
        } catch (final IllegalArgumentException e) {
            // Do nothing.
        } catch (final Exception e) {
            // Do nothing.
        } finally {
            dialog = null;
        }
    }

How to add Apache HTTP API (legacy) as compile-time dependency to build.grade for Android M?

For API 23:

Top level build.gradle - /build.gradle

buildscript {
    ...
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.1'
    }
}
...

Module specific build.gradle - /app/build.gradle

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.0"
    useLibrary 'org.apache.http.legacy'
    ...
}

Official docs (for preview though): http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client

Latest android gradle plugin changelog: http://tools.android.com/tech-docs/new-build-system

How to get the Facebook user id using the access token

in FacebookSDK v2.1 (I can't check older version). We have

NSString *currentUserFBID = [FBSession activeSession].accessTokenData.userID;

However according to the comment in FacebookSDK

@discussion This may not be populated for login behaviours such as the iOS system account.

So may be you should check if it is available, and then whether use it, or call the request to get the user id

UICollectionView - Horizontal scroll, horizontal layout?

for xcode 8 i did this and it worked:

mysql update multiple columns with same now()

MySQL evaluates now() once per statement when the statement commences execution. So it is safe to have multiple visible now() calls per statement.

select now(); select now(), sleep(10), now(); select now();
+---------------------+
| now()               |
+---------------------+
| 2018-11-05 16:54:00 |
+---------------------+
1 row in set (0.00 sec)

+---------------------+-----------+---------------------+
| now()               | sleep(10) | now()               |
+---------------------+-----------+---------------------+
| 2018-11-05 16:54:00 |         0 | 2018-11-05 16:54:00 |
+---------------------+-----------+---------------------+
1 row in set (10.00 sec)

+---------------------+
| now()               |
+---------------------+
| 2018-11-05 16:54:10 |
+---------------------+
1 row in set (0.00 sec)

How can I open a .tex file?

I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.

I have to assume you are using windows because you have mentioned notepad++.

  1. Use notepad++. Right click on the file and choose "edit with notepad++"

  2. Use notepad Change the filename extension to .txt and double click the file.

  3. Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"

If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.

jQuery - getting custom attribute from selected option

The easiest one,

$('#location').find('option:selected').attr('myTag');

How to view/delete local storage in Firefox?

To inspect your localStorage items you may type console.log(localStorage); in your javascript console (firebug for example or in new FF versions the shipped js console).

You can use this line of Code to get rid of the browsers localStorage contents. Just execute it in your javascript console:

localStorage.clear();

What is the Swift equivalent of isEqualToString in Objective-C?

Actually, it feels like swift is trying to promote strings to be treated less like objects and more like values. However this doesn't mean under the hood swift doesn't treat strings as objects, as am sure you all noticed that you can still invoke methods on strings and use their properties.

For example:-

//example of calling method (String to Int conversion)
let intValue = ("12".toInt())
println("This is a intValue now \(intValue)")


//example of using properties (fetching uppercase value of string)
let caUpperValue = "ca".uppercaseString
println("This is the uppercase of ca \(caUpperValue)")

In objectC you could pass the reference to a string object through a variable, on top of calling methods on it, which pretty much establishes the fact that strings are pure objects.

Here is the catch when you try to look at String as objects, in swift you cannot pass a string object by reference through a variable. Swift will always pass a brand new copy of the string. Hence, strings are more commonly known as value types in swift. In fact, two string literals will not be identical (===). They are treated as two different copies.

let curious = ("ca" === "ca")
println("This will be false.. and the answer is..\(curious)")

As you can see we are starting to break aways from the conventional way of thinking of strings as objects and treating them more like values. Hence .isEqualToString which was treated as an identity operator for string objects is no more a valid as you can never get two identical string objects in Swift. You can only compare its value, or in other words check for equality(==).

 let NotSoCuriousAnyMore = ("ca" == "ca")
 println("This will be true.. and the answer is..\(NotSoCuriousAnyMore)")

This gets more interesting when you look at the mutability of string objects in swift. But thats for another question, another day. Something you should probably look into, cause its really interesting. :) Hope that clears up some confusion. Cheers!

HTML.ActionLink method

Html.ActionLink(article.Title, "Login/" + article.ArticleID, 'Item")