Programs & Examples On #Sizer

Sizer are the method of choice to define the layout of controls in containers in a GUI because of their ability to create visually appealing frames or dialogs independent of the platform, taking into account the differences in size and style of the individual controls.

Combination of async function + await + setTimeout

var testAwait = function () {
    var promise = new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Inside test await');
        }, 1000);
    });
    return promise;
}

var asyncFunction = async function() {
    await testAwait().then((data) => {
        console.log(data);
    })
    return 'hello asyncFunction';
}

asyncFunction().then((data) => {
    console.log(data);
});

//Inside test await
//hello asyncFunction

Google Chrome default opening position and size

Maybe a little late, but I found an easier way to set the defaults! You have to right-click on the right of your tab and choose "size", then click on your window, and it should keep it as the default size.

Configure Log4Net in web application

I also had the similar issue. Logs were not creating.

Please check logger attribute name should match with your LogManager.GetLogger("name")

<logger name="Mylog">
      <level value="All"></level>
      <appender-ref ref="RollingLogFileAppender" />
    </logger>



private static readonly ILog Log = LogManager.GetLogger("Mylog");

Switching between GCC and Clang/LLVM using CMake

CMake honors the environment variables CC and CXX upon detecting the C and C++ compiler to use:

$ export CC=/usr/bin/clang
$ export CXX=/usr/bin/clang++
$ cmake ..
-- The C compiler identification is Clang
-- The CXX compiler identification is Clang

The compiler specific flags can be overridden by putting them into a make override file and pointing the CMAKE_USER_MAKE_RULES_OVERRIDE variable to it. Create a file ~/ClangOverrides.txt with the following contents:

SET (CMAKE_C_FLAGS_INIT                "-Wall -std=c99")
SET (CMAKE_C_FLAGS_DEBUG_INIT          "-g")
SET (CMAKE_C_FLAGS_MINSIZEREL_INIT     "-Os -DNDEBUG")
SET (CMAKE_C_FLAGS_RELEASE_INIT        "-O3 -DNDEBUG")
SET (CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")

SET (CMAKE_CXX_FLAGS_INIT                "-Wall")
SET (CMAKE_CXX_FLAGS_DEBUG_INIT          "-g")
SET (CMAKE_CXX_FLAGS_MINSIZEREL_INIT     "-Os -DNDEBUG")
SET (CMAKE_CXX_FLAGS_RELEASE_INIT        "-O3 -DNDEBUG")
SET (CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")

The suffix _INIT will make CMake initialize the corresponding *_FLAGS variable with the given value. Then invoke cmake in the following way:

$ cmake -DCMAKE_USER_MAKE_RULES_OVERRIDE=~/ClangOverrides.txt ..

Finally to force the use of the LLVM binutils, set the internal variable _CMAKE_TOOLCHAIN_PREFIX. This variable is honored by the CMakeFindBinUtils module:

$ cmake -D_CMAKE_TOOLCHAIN_PREFIX=llvm- ..

Putting this all together you can write a shell wrapper which sets up the environment variables CC and CXX and then invokes cmake with the mentioned variable overrides.

Also see this CMake FAQ on make override files.

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

Here is an alternative implementation.

enter image description here

Basically if you able to edit page at other domain you can place another iframe page that belongs to your server which saving height to cookies. With an interval read cookies when it is updated, update the height of the iframe. That is all.

Edit: 2019 December

The solution above basically uses another iframe inside of an iframe 3rd iframe is belongs to the top page domain, which you call this page with a query string that saves size value to a cookie, outer page checks this query with some interval. But it is not a good solution so you should follow this one:

In Top page :

window.addEventListener("message", (m)=>{iframeResizingFunction(m)});

Here you can check m.origin to see where is it comes from.

In frame page:

window.parent.postMessage({ width: 640, height:480 }, "*")

Although, please don't forget this is not so secure way. To make it secure update * value (targetOrigin) with your desired value. Please follow documentation: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

DataGrid get selected rows' column values

After hours of finding ways on how to get the data from the row selected on a WPF DataGrid Control, as I was using MongoDB. I found this post and used Tony's answer. I revised the code to be relevant to my project. Maybe someone can use this to get an idea.

private void selectionChanged(object sender, SelectionChangedEventArgs e)
    {
        facultyData row = (facultyData)facultyDataGrid.SelectedItem;
        facultyID_Textbox.Text = row.facultyID;
        lastName_TextBox.Text = row.lastName;
        firstName_TextBox.Text = row.firstName;
        middleName_TextBox.Text = row.middleName;
        age_TextBox.Text = row.age.ToString();
    }

}

class facultyData
{
    public ObjectId _id { get; set; }
    public string facultyID { get; set; }
    public string acadYear { get; set; }
    public string program { get; set; }   
}

Which Python memory profiler is recommended?

Muppy is (yet another) Memory Usage Profiler for Python. The focus of this toolset is laid on the identification of memory leaks.

Muppy tries to help developers to identity memory leaks of Python applications. It enables the tracking of memory usage during runtime and the identification of objects which are leaking. Additionally, tools are provided which allow to locate the source of not released objects.

Mongod complains that there is no /data/db folder

This works for me, found in comments:

sudo chown -R $USER /data/db

Log record changes in SQL server in an audit table

This is the code with two bug fixes. The first bug fix was mentioned by Royi Namir in the comment on the accepted answer to this question. The bug is described on StackOverflow at Bug in Trigger Code. The second one was found by @Fandango68 and fixes columns with multiples words for their names.

ALTER TRIGGER [dbo].[TR_person_AUDIT]
ON [dbo].[person]
FOR UPDATE
AS
           DECLARE @bit            INT,
                   @field          INT,
                   @maxfield       INT,
                   @char           INT,
                   @fieldname      VARCHAR(128),
                   @TableName      VARCHAR(128),
                   @PKCols         VARCHAR(1000),
                   @sql            VARCHAR(2000),
                   @UpdateDate     VARCHAR(21),
                   @UserName       VARCHAR(128),
                   @Type           CHAR(1),
                   @PKSelect       VARCHAR(1000)


           --You will need to change @TableName to match the table to be audited.
           -- Here we made GUESTS for your example.
           SELECT @TableName = 'PERSON'

           SELECT @UserName = SYSTEM_USER,
                  @UpdateDate = CONVERT(NVARCHAR(30), GETDATE(), 126)

           -- Action
           IF EXISTS (
                  SELECT *
                  FROM   INSERTED
              )
               IF EXISTS (
                      SELECT *
                      FROM   DELETED
                  )
                   SELECT @Type = 'U'
               ELSE
                   SELECT @Type = 'I'
           ELSE
               SELECT @Type = 'D'

           -- get list of columns
           SELECT * INTO #ins
           FROM   INSERTED

           SELECT * INTO #del
           FROM   DELETED

           -- Get primary key columns for full outer join
           SELECT @PKCols = COALESCE(@PKCols + ' and', ' on') 
                  + ' i.[' + c.COLUMN_NAME + '] = d.[' + c.COLUMN_NAME + ']'
           FROM   INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk,
                  INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
           WHERE  pk.TABLE_NAME = @TableName
                  AND CONSTRAINT_TYPE = 'PRIMARY KEY'
                  AND c.TABLE_NAME = pk.TABLE_NAME
                  AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

           -- Get primary key select for insert
           SELECT @PKSelect = COALESCE(@PKSelect + '+', '') 
                  + '''<[' + COLUMN_NAME 
                  + ']=''+convert(varchar(100),
           coalesce(i.[' + COLUMN_NAME + '],d.[' + COLUMN_NAME + ']))+''>'''
           FROM   INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk,
                  INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
           WHERE  pk.TABLE_NAME = @TableName
                  AND CONSTRAINT_TYPE = 'PRIMARY KEY'
                  AND c.TABLE_NAME = pk.TABLE_NAME
                  AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

           IF @PKCols IS NULL
           BEGIN
               RAISERROR('no PK on table %s', 16, -1, @TableName)

               RETURN
           END

           SELECT @field = 0,
                  -- @maxfield = MAX(COLUMN_NAME) 
                  @maxfield = -- FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName


                  MAX(
                      COLUMNPROPERTY(
                          OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                          COLUMN_NAME,
                          'ColumnID'
                      )
                  )
           FROM   INFORMATION_SCHEMA.COLUMNS
           WHERE  TABLE_NAME = @TableName






           WHILE @field < @maxfield
           BEGIN
               SELECT @field = MIN(
                          COLUMNPROPERTY(
                              OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                              COLUMN_NAME,
                              'ColumnID'
                          )
                      )
               FROM   INFORMATION_SCHEMA.COLUMNS
               WHERE  TABLE_NAME = @TableName
                      AND COLUMNPROPERTY(
                              OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                              COLUMN_NAME,
                              'ColumnID'
                          ) > @field

               SELECT @bit = (@field - 1)% 8 + 1

               SELECT @bit = POWER(2, @bit - 1)

               SELECT @char = ((@field - 1) / 8) + 1





               IF SUBSTRING(COLUMNS_UPDATED(), @char, 1) & @bit > 0
                  OR @Type IN ('I', 'D')
               BEGIN
                   SELECT @fieldname = COLUMN_NAME
                   FROM   INFORMATION_SCHEMA.COLUMNS
                   WHERE  TABLE_NAME = @TableName
                          AND COLUMNPROPERTY(
                                  OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                                  COLUMN_NAME,
                                  'ColumnID'
                              ) = @field



                   SELECT @sql = 
                          '
           insert into Audit (    Type, 
           TableName, 
           PK, 
           FieldName, 
           OldValue, 
           NewValue, 
           UpdateDate, 
           UserName)
           select ''' + @Type + ''',''' 
                          + @TableName + ''',' + @PKSelect
                          + ',''' + @fieldname + ''''
                          + ',convert(varchar(1000),d.' + @fieldname + ')'
                          + ',convert(varchar(1000),i.' + @fieldname + ')'
                          + ',''' + @UpdateDate + ''''
                          + ',''' + @UserName + ''''
                          + ' from #ins i full outer join #del d'
                          + @PKCols
                          + ' where i.' + @fieldname + ' <> d.' + @fieldname 
                          + ' or (i.' + @fieldname + ' is null and  d.'
                          + @fieldname
                          + ' is not null)' 
                          + ' or (i.' + @fieldname + ' is not null and  d.' 
                          + @fieldname
                          + ' is null)' 



                   EXEC (@sql)
               END
           END

Is there a "do ... until" in Python?

There's no prepackaged "do-while", but the general Python way to implement peculiar looping constructs is through generators and other iterators, e.g.:

import itertools

def dowhile(predicate):
  it = itertools.repeat(None)
  for _ in it:
    yield
    if not predicate(): break

so, for example:

i=7; j=3
for _ in dowhile(lambda: i<j):
  print i, j
  i+=1; j-=1

executes one leg, as desired, even though the predicate's already false at the start.

It's normally better to encapsulate more of the looping logic into your generator (or other iterator) -- for example, if you often have cases where one variable increases, one decreases, and you need a do/while loop comparing them, you could code:

def incandec(i, j, delta=1):
  while True:
    yield i, j
    if j <= i: break
    i+=delta; j-=delta

which you can use like:

for i, j in incandec(i=7, j=3):
  print i, j

It's up to you how much loop-related logic you want to put inside your generator (or other iterator) and how much you want to have outside of it (just like for any other use of a function, class, or other mechanism you can use to refactor code out of your main stream of execution), but, generally speaking, I like to see the generator used in a for loop that has little (ideally none) "loop control logic" (code related to updating state variables for the next loop leg and/or making tests about whether you should be looping again or not).

MetadataException: Unable to load the specified metadata resource

I was having problems with this same error message. My issue was resolved by closing and re-opening Visual Studio 2010.

Most efficient way to find mode in numpy array

if you want to find mode as int Value here is the easiest way I was trying to find out mode of Array using Scipy Stats but the problem is that output of the code look like:

ModeResult(mode=array(2), count=array([[1, 2, 2, 2, 1, 2]])) , I only want the Integer output so if you want the same just try this

import numpy as np
from scipy import stats
numbers = list(map(int, input().split())) 
print(int(stats.mode(numbers)[0]))

Last line is enough to print Mode Value in Python: print(int(stats.mode(numbers)[0]))

phantomjs not waiting for "full" page load

I would rather periodically check for document.readyState status (https://developer.mozilla.org/en-US/docs/Web/API/document.readyState). Although this approach is a bit clunky, you can be sure that inside onPageReady function you are using fully loaded document.

var page = require("webpage").create(),
    url = "http://example.com/index.html";

function onPageReady() {
    var htmlContent = page.evaluate(function () {
        return document.documentElement.outerHTML;
    });

    console.log(htmlContent);

    phantom.exit();
}

page.open(url, function (status) {
    function checkReadyState() {
        setTimeout(function () {
            var readyState = page.evaluate(function () {
                return document.readyState;
            });

            if ("complete" === readyState) {
                onPageReady();
            } else {
                checkReadyState();
            }
        });
    }

    checkReadyState();
});

Additional explanation:

Using nested setTimeout instead of setInterval prevents checkReadyState from "overlapping" and race conditions when its execution is prolonged for some random reasons. setTimeout has a default delay of 4ms (https://stackoverflow.com/a/3580085/1011156) so active polling will not drastically affect program performance.

document.readyState === "complete" means that document is completely loaded with all resources (https://html.spec.whatwg.org/multipage/dom.html#current-document-readiness).

How to edit CSS style of a div using C# in .NET

Add the runat="server" attribute to the tag, then you can reference it from the codebehind.

Python 3: UnboundLocalError: local variable referenced before assignment

You can fix this by passing parameters rather than relying on Globals

def function(Var1, Var2): 
    if Var2 == 0 and Var1 > 0:
        print("Result One")
    elif Var2 == 1 and Var1 > 0:
        print("Result Two")
    elif Var1 < 1:
        print("Result Three")
    return Var1 - 1
function(1, 1)

How to append a char to a std::string?

Try the += operator link text, append() method link text, or push_back() method link text

The links in this post also contain examples of how to use the respective APIs.

html select option separator

This is an old thread, but since no one posted a similar response, I'll add this as it's my preferred way of separation.

I find using dashes and such to be somewhat of an eyesore since it could fall short of the width of the selection box. So, I prefer to use CSS to create my separators.. a simple background coloring.

_x000D_
_x000D_
<select>_x000D_
  <option style="background-color: #cccccc;" disabled selected>Select An Option</option>_x000D_
  <option>First Option</option>_x000D_
  <option>Second</option>_x000D_
  <option style="font-size: 1pt; background-color: #000000;" disabled>&nbsp;</option>_x000D_
  <option>Third</option>_x000D_
  <option>Fourth</option>_x000D_
  <option style="font-size: 1pt; background-color: #000000;" disabled>&nbsp;</option>_x000D_
  <option>Fifth</option>_x000D_
  <option>Sixth</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Convert Data URI to File then append to FormData

var BlobBuilder = (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder);

can be used without the try catch.

Thankx to check_ca. Great work.

How to implement the Android ActionBar back button?

Make sure your the ActionBar Home Button is enabled in the Activity:

Android, API 5+:

@Override
public void onBackPressed() {
     ...
     super.onBackPressed();
}

ActionBarSherlock and App-Compat, API 7+:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    ...
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

Android, API 11+:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    ...
    getActionBar().setDisplayHomeAsUpEnabled(true);
}

Example MainActivity that extends ActionBarActivity:

public class MainActivity extends ActionBarActivity {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Back button
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home: 
            // API 5+ solution
            onBackPressed();
            return true;

        default:
            return super.onOptionsItemSelected(item);
        }
    }
}

This way all the activities you want can have the backpress.

Android, API 16+:

http://developer.android.com/training/implementing-navigation/ancestral.html

AndroidManifest.xml:

<application ... >
    ...
    <!-- The main/home activity (it has no parent activity) -->
    <activity
        android:name="com.example.myfirstapp.MainActivity" ...>
        ...
    </activity>
    <!-- A child of the main activity -->
    <activity
        android:name="com.example.myfirstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >
        <!-- The meta-data element is needed for versions lower than 4.1 -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
    </activity>
</application>

Example MainActivity that extends ActionBarActivity:

public class MainActivity extends ActionBarActivity {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Back button
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Git cli: get user info from username

You can try this to get infos like:

  • username: git config --get user.name
  • user email: git config --get user.email

There's nothing like "first name" and "last name" for the user.

Hope this will help.

Checking if a website is up via Python

If by up, you simply mean "the server is serving", then you could use cURL, and if you get a response than it's up.

I can't give you specific advice because I'm not a python programmer, however here is a link to pycurl http://pycurl.sourceforge.net/.

javascript create array from for loop

even shorter if you can lose the yearStart value:

var yearStart = 2000;
var yearEnd = 2040;

var arr = [];

while(yearStart < yearEnd+1){
  arr.push(yearStart++);
}

UPDATE: If you can use the ES6 syntax you can do it the way proposed here:

let yearStart = 2000;
let yearEnd = 2040;
let years = Array(yearEnd-yearStart+1)
    .fill()
    .map(() => yearStart++);

Select From all tables - MySQL

As Suhel Meman said in the comments:

SELECT column1, column2, column3 FROM table 1
UNION
SELECT column1, column2, column3 FROM table 2
...

would work.

But all your SELECTS would have to consist of the same amount of columns. And because you are displaying it in one resulting table they should contain the same information.

What you might want to do, is a JOIN on Product ID or something like that. This way you would get more columns, which makes more sense most of the time.

Dart SDK is not configured

Just go to File > Settings > Languages & Frameworks > Dart

Click on check box Enable Dart Support for project 'projectName' Paste the Dart SDK path.

This is how you get Dart SDK path, follow the given steps copy the Dart SDK Path, which is in Flutter SDK, Go to location where your Flutter SDK Situated, then,

Flutter/bin/cache/dart-sdk , till dart-sdk, copy the path and paste it.

Functions that return a function

This is super useful in real life.

Working with Express.js

So your regular express route looks like this:

function itWorksHandler( req, res, next ) {
  res.send("It works!");
}

router.get("/check/works", itWorksHandler );

But what if you need to add some wrapper, error handler or smth?

Then you invoke your function off a wrapper.

function loggingWrapper( req, res, next, yourFunction ) {
  try {
    yourFunction( req, res );
  } catch ( err ) {
    console.error( err );
    next( err );
  }
}

router.get("/check/works", function( req, res, next ) {
  loggingWrapper( req, res, next, itWorksHandler );
});

Looks complicated? Well, how about this:

function function loggingWrapper( yourFunction ) => ( req, res, next ) {
  try {
    yourFunction( req, res, next );
  } catch ( err ) {
    console.error( err );
    next( err );
  }
}

router.get("/check/works", loggingWrapper( itWorksHandler ) );

See at the end you're passing a function loggingWrapper having one argument as another function itWorksHandler, and your loggingWrapper returns a new function which takes req, res, next as arguments.

How to quickly test some javascript code?

Install firebug: http://getfirebug.com/logging . You can use its console to test Javascript code. Google Chrome comes with Web Inspector in which you can do the same. IE and Safari also have Web Developer tools in which you can test Javascript.

Find the last time table was updated

If you want to see data updates you could use this technique with required permissions:

SELECT OBJECT_NAME(OBJECT_ID) AS DatabaseName, last_user_update,*
FROM sys.dm_db_index_usage_stats
WHERE database_id = DB_ID( 'DATABASE')
AND OBJECT_ID=OBJECT_ID('TABLE')

A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.

I'm Using the fix, Because Using Knockout in MVC5 views.

On action

return Json(ModelHelper.GetJsonModel<Core_User>(viewModel));

function

   public static TEntity GetJsonModel<TEntity>(TEntity Entity) where TEntity : class
    {
        TEntity Entity_ = Activator.CreateInstance(typeof(TEntity)) as TEntity;
        foreach (var item in Entity.GetType().GetProperties())
        {
            if (item.PropertyType.ToString().IndexOf("Generic.ICollection") == -1 && item.PropertyType.ToString().IndexOf("SaymenCore.DAL.") == -1)
                item.SetValue(Entity_, Entity.GetPropValue(item.Name));
        }
        return Entity_;  
    }

MVC Razor view nested foreach's model

The quick answer is to use a for() loop in place of your foreach() loops. Something like:

@for(var themeIndex = 0; themeIndex < Model.Theme.Count(); themeIndex++)
{
   @Html.LabelFor(model => model.Theme[themeIndex])

   @for(var productIndex=0; productIndex < Model.Theme[themeIndex].Products.Count(); productIndex++)
   {
      @Html.LabelFor(model=>model.Theme[themeIndex].Products[productIndex].name)
      @for(var orderIndex=0; orderIndex < Model.Theme[themeIndex].Products[productIndex].Orders; orderIndex++)
      {
          @Html.TextBoxFor(model => model.Theme[themeIndex].Products[productIndex].Orders[orderIndex].Quantity)
          @Html.TextAreaFor(model => model.Theme[themeIndex].Products[productIndex].Orders[orderIndex].Note)
          @Html.EditorFor(model => model.Theme[themeIndex].Products[productIndex].Orders[orderIndex].DateRequestedDeliveryFor)
      }
   }
}

But this glosses over why this fixes the problem.

There are three things that you have at least a cursory understanding before you can resolve this issue. I have to admit that I cargo-culted this for a long time when I started working with the framework. And it took me quite a while to really get what was going on.

Those three things are:

  • How do the LabelFor and other ...For helpers work in MVC?
  • What is an Expression Tree?
  • How does the Model Binder work?

All three of these concepts link together to get an answer.

How do the LabelFor and other ...For helpers work in MVC?

So, you've used the HtmlHelper<T> extensions for LabelFor and TextBoxFor and others, and you probably noticed that when you invoke them, you pass them a lambda and it magically generates some html. But how?

So the first thing to notice is the signature for these helpers. Lets look at the simplest overload for TextBoxFor

public static MvcHtmlString TextBoxFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression
) 

First, this is an extension method for a strongly typed HtmlHelper, of type <TModel>. So, to simply state what happens behind the scenes, when razor renders this view it generates a class. Inside of this class is an instance of HtmlHelper<TModel> (as the property Html, which is why you can use @Html...), where TModel is the type defined in your @model statement. So in your case, when you are looking at this view TModel will always be of the type ViewModels.MyViewModels.Theme.

Now, the next argument is a bit tricky. So lets look at an invocation

@Html.TextBoxFor(model=>model.SomeProperty);

It looks like we have a little lambda, And if one were to guess the signature, one might think that the type for this argument would simply be a Func<TModel, TProperty>, where TModel is the type of the view model and TProperty is inferred as the type of the property.

But thats not quite right, if you look at the actual type of the argument its Expression<Func<TModel, TProperty>>.

So when you normally generate a lambda, the compiler takes the lambda and compiles it down into MSIL, just like any other function (which is why you can use delegates, method groups, and lambdas more or less interchangeably, because they are just code references.)

However, when the compiler sees that the type is an Expression<>, it doesn't immediately compile the lambda down to MSIL, instead it generates an Expression Tree!

What is an Expression Tree?

So, what the heck is an expression tree. Well, it's not complicated but its not a walk in the park either. To quote ms:

| Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y.

Simply put, an expression tree is a representation of a function as a collection of "actions".

In the case of model=>model.SomeProperty, the expression tree would have a node in it that says: "Get 'Some Property' from a 'model'"

This expression tree can be compiled into a function that can be invoked, but as long as it's an expression tree, it's just a collection of nodes.

So what is that good for?

So Func<> or Action<>, once you have them, they are pretty much atomic. All you can really do is Invoke() them, aka tell them to do the work they are supposed to do.

Expression<Func<>> on the other hand, represents a collection of actions, which can be appended, manipulated, visited, or compiled and invoked.

So why are you telling me all this?

So with that understanding of what an Expression<> is, we can go back to Html.TextBoxFor. When it renders a textbox, it needs to generate a few things about the property that you are giving it. Things like attributes on the property for validation, and specifically in this case it needs to figure out what to name the <input> tag.

It does this by "walking" the expression tree and building a name. So for an expression like model=>model.SomeProperty, it walks the expression gathering the properties that you are asking for and builds <input name='SomeProperty'>.

For a more complicated example, like model=>model.Foo.Bar.Baz.FooBar, it might generate <input name="Foo.Bar.Baz.FooBar" value="[whatever FooBar is]" />

Make sense? It is not just the work that the Func<> does, but how it does its work is important here.

(Note other frameworks like LINQ to SQL do similar things by walking an expression tree and building a different grammar, that this case a SQL query)

How does the Model Binder work?

So once you get that, we have to briefly talk about the model binder. When the form gets posted, it's simply like a flat Dictionary<string, string>, we have lost the hierarchical structure our nested view model may have had. It's the model binder's job to take this key-value pair combo and attempt to rehydrate an object with some properties. How does it do this? You guessed it, by using the "key" or name of the input that got posted.

So if the form post looks like

Foo.Bar.Baz.FooBar = Hello

And you are posting to a model called SomeViewModel, then it does the reverse of what the helper did in the first place. It looks for a property called "Foo". Then it looks for a property called "Bar" off of "Foo", then it looks for "Baz"... and so on...

Finally it tries to parse the value into the type of "FooBar" and assign it to "FooBar".

PHEW!!!

And voila, you have your model. The instance the Model Binder just constructed gets handed into requested Action.


So your solution doesn't work because the Html.[Type]For() helpers need an expression. And you are just giving them a value. It has no idea what the context is for that value, and it doesn't know what to do with it.

Now some people suggested using partials to render. Now this in theory will work, but probably not the way that you expect. When you render a partial, you are changing the type of TModel, because you are in a different view context. This means that you can describe your property with a shorter expression. It also means when the helper generates the name for your expression, it will be shallow. It will only generate based on the expression it's given (not the entire context).

So lets say you had a partial that just rendered "Baz" (from our example before). Inside that partial you could just say:

@Html.TextBoxFor(model=>model.FooBar)

Rather than

@Html.TextBoxFor(model=>model.Foo.Bar.Baz.FooBar)

That means that it will generate an input tag like this:

<input name="FooBar" />

Which, if you are posting this form to an action that is expecting a large deeply nested ViewModel, then it will try to hydrate a property called FooBar off of TModel. Which at best isn't there, and at worst is something else entirely. If you were posting to a specific action that was accepting a Baz, rather than the root model, then this would work great! In fact, partials are a good way to change your view context, for example if you had a page with multiple forms that all post to different actions, then rendering a partial for each one would be a great idea.


Now once you get all of this, you can start to do really interesting things with Expression<>, by programatically extending them and doing other neat things with them. I won't get into any of that. But, hopefully, this will give you a better understanding of what is going on behind the scenes and why things are acting the way that they are.

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

I faced the same problem and was frustrated to see as to all options i tried and none of them work,

Turns out once you have configured everything correctly including settings.xml

just clear your local repository folder and try mvn commands. That greatly helped me

Hope this helps others

What is the best way to remove the first element from an array?

The size of arrays in Java cannot be changed. So, technically you cannot remove any elements from the array.

One way to simulate removing an element from the array is to create a new, smaller array, and then copy all of the elements from the original array into the new, smaller array.

String[] yourArray = Arrays.copyOfRange(oldArr, 1, oldArr.length);

However, I would not suggest the above method. You should really be using a List<String>. Lists allow you to add and remove items from any index. That would look similar to the following:

List<String> list = new ArrayList<String>(); // or LinkedList<String>();
list.add("Stuff");
// add lots of stuff
list.remove(0); // removes the first item

Download a file from HTTPS using download.file()

If using RCurl you get an SSL error on the GetURL() function then set these options before GetURL(). This will set the CurlSSL settings globally.

The extended code:

install.packages("RCurl")
library(RCurl)
options(RCurlOptions = list(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl")))   
URL <- "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv"
x <- getURL(URL)

Worked for me on Windows 7 64-bit using R3.1.0!

"X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE"

In certain cases, it might be necessary to restrict the display of a webpage to a document mode supported by an earlier version of Internet Explorer. You can do this by serving the page with an x-ua-compatible header. For more info, see Specifying legacy document modes.
- https://msdn.microsoft.com/library/cc288325

Thus this tag is used to future proof the webpage, such that the older / compatible engine is used to render it the same way as intended by the creator.

Make sure that you have checked it to work properly with the IE version you specify.

How can I show line numbers in Eclipse?

click on window tab and click on preferences

click on window tab

do this and check show line number

check show line number

Base64 length calculation?

If there is someone interested in achieve the @Pedro Silva solution in JS, I just ported this same solution for it:

const getBase64Size = (base64) => {
  let padding = base64.length
    ? getBase64Padding(base64)
    : 0
  return ((Math.ceil(base64.length / 4) * 3 ) - padding) / 1000
}

const getBase64Padding = (base64) => {
  return endsWith(base64, '==')
    ? 2
    : 1
}

const endsWith = (str, end) => {
  let charsFromEnd = end.length
  let extractedEnd = str.slice(-charsFromEnd)
  return extractedEnd === end
}

How to resize Image in Android?

You can use Matrix to resize your camera image ....

BitmapFactory.Options options=new BitmapFactory.Options();
InputStream is = getContentResolver().openInputStream(currImageURI);
bm = BitmapFactory.decodeStream(is,null,options);
int Height = bm.getHeight();
int Width = bm.getWidth();
int newHeight = 300;
int newWidth = 300;
float scaleWidth = ((float) newWidth) / Width;
float scaleHeight = ((float) newHeight) / Height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0,Width, Height, matrix, true);
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);

How do I clone a specific Git branch?

git --branch <branchname> <url>

But bash completion don't get this key: --branch

"Cannot GET /" with Connect on Node.js

You might be needed to restart the process if app.get not working. Press ctl+c and then restart node app.

Terminal Commands: For loop with echo

for ((i=0; i<=1000; i++)); do
    echo "http://example.com/$i.jpg"
done

Remove composer

Uninstall composer

To remove just composer package itself from Ubuntu 16.04 (Xenial Xerus) execute on terminal:

sudo apt-get remove composer

Uninstall composer and it's dependent packages

To remove the composer package and any other dependant package which are no longer needed from Ubuntu Xenial.

sudo apt-get remove --auto-remove composer

Purging composer

If you also want to delete configuration and/or data files of composer from Ubuntu Xenial then this will work:

sudo apt-get purge composer

To delete configuration and/or data files of composer and it's dependencies from Ubuntu Xenial then execute:

sudo apt-get purge --auto-remove composer

https://www.howtoinstall.co/en/ubuntu/xenial/composer?action=remove

How to reset the use/password of jenkins on windows?

I created a new user with "admin" and new password on the installation steps. But after sometime, i wanted to sign in again and that password was showing incorrect, so i used the initial password again to login.

The initial password can be found in the below location:-

C:\Program Files(x86)\Jenkins\secrets\initialAdminPassword

try this method

How to import a class from default package

From the Java language spec:

It is a compile time error to import a type from the unnamed package.

You'll have to access the class via reflection or some other indirect method.

"find: paths must precede expression:" How do I specify a recursive search that also finds files in the current directory?

In my case i was missing trailing / in path.

find /var/opt/gitlab/backups/ -name *.tar

How do I add a submodule to a sub-directory?

I had a similar issue, but had painted myself into a corner with GUI tools.

I had a subproject with a few files in it that I had so far just copied around instead of checking into their own git repo. I created a repo in the subfolder, was able to commit, push, etc just fine. But in the parent repo the subfolder wasn't treated as a submodule, and its files were still being tracked by the parent repo - no good.

To get out of this mess I had to tell Git to stop tracking the subfolder (without deleting the files):

proj> git rm -r --cached ./ui/jslib

Then I had to tell it there was a submodule there (which you can't do if anything there is currently being tracked by git):

proj> git submodule add ./ui/jslib

Update

The ideal way to handle this involves a couple more steps. Ideally, the existing repo is moved out to its own directory, free of any parent git modules, committed and pushed, and then added as a submodule like:

proj> git submodule add [email protected]:user/jslib.git ui/jslib

That will clone the git repo in as a submodule - which involves the standard cloning steps, but also several other more obscure config steps that git takes on your behalf to get that submodule to work. The most important difference is that it places a simple .git file there, instead of a .git directory, which contains a path reference to where the real git dir lives - generally at parent project root .git/modules/jslib.

If you don't do things this way they'll work fine for you, but as soon as you commit and push the parent, and another dev goes to pull that parent, you just made their life a lot harder. It will be very difficult for them to replicate the structure you have on your machine so long as you have a full .git dir in a subfolder of a dir that contains its own .git dir.

So, move, push, git add submodule, is the cleanest option.

How do I compare two strings in python?

>>> s1="abc def ghi"
>>> s2="def ghi abc"
>>> s1 == s2  # For string comparison 
False
>>> sorted(list(s1)) == sorted(list(s2)) # For comparing if they have same characters. 
True
>>> sorted(list(s1))
[' ', ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
>>> sorted(list(s2))
[' ', ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

Accessing an array out of bounds gives no error, why?

As I understand, local variables are allocated on stack, so going out of bounds on your own stack can only overwrite some other local variable, unless you go oob too much and exceed your stack size. Since you have no other variables declared in your function - it does not cause any side effects. Try declaring another variable/array right after your first one and see what will happen with it.

How to get line count of a large file cheaply in Python?

You could execute a subprocess and run wc -l filename

import subprocess

def file_len(fname):
    p = subprocess.Popen(['wc', '-l', fname], stdout=subprocess.PIPE, 
                                              stderr=subprocess.PIPE)
    result, err = p.communicate()
    if p.returncode != 0:
        raise IOError(err)
    return int(result.strip().split()[0])

How do you do block comments in YAML?

In Vim you can do one of the following:

  • Comment all lines: :%s/^/#
  • Comment lines 10 - 15: :10,15s/^/#
  • Comment line 10 to current line: :10,.s/^/#
  • Comment line 10 to end: :10,$s/^/#

or using visual block:

  1. Select a multiple-line column after entering visual block via Ctrl+v.
  2. Press r followed by # to comment out the multiple-line block replacing the selection, or Shift+i#Esc to insert comment characters before the selection.

An URL to a Windows shared folder

This depend on how you want to incorporate it. The scenario 1. click on a link 2. explorer window popped up

<a href="\\server\folder\path" target="_blank">click</a>

If there is a need in a fancy UI - then it will barely serve as a solution.

Empty set literal?

It depends on if you want the literal for a comparison, or for assignment.

If you want to make an existing set empty, you can use the .clear() metod, especially if you want to avoid creating a new object. If you want to do a comparison, use set() or check if the length is 0.

example:

#create a new set    
a=set([1,2,3,'foo','bar'])
#or, using a literal:
a={1,2,3,'foo','bar'}

#create an empty set
a=set()
#or, use the clear method
a.clear()

#comparison to a new blank set
if a==set():
    #do something

#length-checking comparison
if len(a)==0:
    #do something

PHP Warning: Module already loaded in Unknown on line 0

To fix this problem, you must edit your php.ini (or extensions.ini) file and comment-out the extensions that are already compiled-in. For example, after editing, your ini file may look like the lines below:

;extension=pcre.so
;extension=spl.so

Source: http://www.somacon.com/p520.php

All com.android.support libraries must use the exact same version specification

This error because of glide library. Try Picasso or other image libraries

How to increment a datetime by one day?

All of the current answers are wrong in some cases as they do not consider that timezones change their offset relative to UTC. So in some cases adding 24h is different from adding a calendar day.

Proposed solution

The following solution works for Samoa and keeps the local time constant.

def add_day(today):
    """
    Add a day to the current day.

    This takes care of historic offset changes and DST.

    Parameters
    ----------
    today : timezone-aware datetime object

    Returns
    -------
    tomorrow : timezone-aware datetime object
    """
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
                                              minute=today.minute,
                                              second=today.second)
    return tomorrow_utc_tz

Tested Code

# core modules
import datetime

# 3rd party modules
import pytz


# add_day methods
def add_day(today):
    """
    Add a day to the current day.

    This takes care of historic offset changes and DST.

    Parameters
    ----------
    today : timezone-aware datetime object

    Returns
    -------
    tomorrow : timezone-aware datetime object
    """
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
                                              minute=today.minute,
                                              second=today.second)
    return tomorrow_utc_tz


def add_day_datetime_timedelta_conversion(today):
    # Correct for Samoa, but dst shift
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    return tomorrow_utc_tz


def add_day_dateutil_relativedelta(today):
    # WRONG!
    from dateutil.relativedelta import relativedelta
    return today + relativedelta(days=1)


def add_day_datetime_timedelta(today):
    # WRONG!
    return today + datetime.timedelta(days=1)


# Test cases
def test_samoa(add_day):
    """
    Test if add_day properly increases the calendar day for Samoa.

    Due to economic considerations, Samoa went from 2011-12-30 10:00-11:00
    to 2011-12-30 10:00+13:00. Hence the country skipped 2011-12-30 in its
    local time.

    See https://stackoverflow.com/q/52084423/562769

    A common wrong result here is 2011-12-30T23:59:00-10:00. This date never
    happened in Samoa.
    """
    tz = pytz.timezone('Pacific/Apia')
    today_utc = datetime.datetime(2011, 12, 30, 9, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2011-12-29T23:59:00-10:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2011-12-31T23:59:00+14:00'


def test_dst(add_day):
    """Test if add_day properly increases the calendar day if DST happens."""
    tz = pytz.timezone('Europe/Berlin')
    today_utc = datetime.datetime(2018, 3, 25, 0, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2018-03-25T01:59:00+01:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2018-03-26T01:59:00+02:00'


to_test = [(add_day_dateutil_relativedelta, 'relativedelta'),
           (add_day_datetime_timedelta, 'timedelta'),
           (add_day_datetime_timedelta_conversion, 'timedelta+conversion'),
           (add_day, 'timedelta+conversion+dst')]
print('{:<25}: {:>5} {:>5}'.format('Method', 'Samoa', 'DST'))
for method, name in to_test:
    print('{:<25}: {:>5} {:>5}'
          .format(name,
                  test_samoa(method),
                  test_dst(method)))

Test results

Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1

How to filter (key, value) with ng-repeat in AngularJs?

Also you can use ng-repeat with ng-if:

<div ng-repeat="(key, value) in order" ng-if="value > 0">

Get div tag scroll position using JavaScript

you use the scrollTop attribute

var position = document.getElementById('id').scrollTop;

Code signing is required for product type Unit Test Bundle in SDK iOS 8.0

Hi I face the same problem today. After reading "Spentak"'s answer i tried to make code signing of my target to set to iOSDeveloper, and still did not work. But after i changing "Provisioning Profile" to "Automatic", the project got built and ran without any code signing errors.

Compare given date with today

To complete BoBby Jack, the use of DateTime OBject, if you have php 5.2.2+ :

if(new DateTime() > new DateTime($var)){
    // $var is before today so use it

}

Thymeleaf: how to use conditionals to dynamically add/remove a CSS class

Just to add my own opinion, in case it might be useful to someone. This is what I used.

<div th:class="${request.read ? 'mdl-color-text--grey-800 w500' : ''}"> </div>

Using the "animated circle" in an ImageView while loading stuff

For the ones developing in Kotlin, there is a sweet method provided by the Anko library that makes the process of displaying a ProgressDialog a breeze!

Based on that link:

val dialog = progressDialog(message = "Please wait a bit…", title = "Fetching data")
dialog.show()
//....
dialog.dismiss()

This will show a Progress Dialog with the progress % displayed (for which you have to pass the init parameter also to calculate the progress).

There is also the indeterminateProgressDialog() method, which provides the Spinning Circle animation indefinitely until dismissed:

indeterminateProgressDialog("Loading...").show()

Shout out to this blog which led me to this solution.

Exception in thread "main" java.lang.Error: Unresolved compilation problems

Check Following : 1) Package names 2) Import Statements (import every required packages) 3) Proper set of braces ,i.e { } 4) Check Syntax too.. i.e semicolons,commas,etc.

Compression/Decompression string with C#

The code to compress/decompress a string

public static void CopyTo(Stream src, Stream dest) {
    byte[] bytes = new byte[4096];

    int cnt;

    while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0) {
        dest.Write(bytes, 0, cnt);
    }
}

public static byte[] Zip(string str) {
    var bytes = Encoding.UTF8.GetBytes(str);

    using (var msi = new MemoryStream(bytes))
    using (var mso = new MemoryStream()) {
        using (var gs = new GZipStream(mso, CompressionMode.Compress)) {
            //msi.CopyTo(gs);
            CopyTo(msi, gs);
        }

        return mso.ToArray();
    }
}

public static string Unzip(byte[] bytes) {
    using (var msi = new MemoryStream(bytes))
    using (var mso = new MemoryStream()) {
        using (var gs = new GZipStream(msi, CompressionMode.Decompress)) {
            //gs.CopyTo(mso);
            CopyTo(gs, mso);
        }

        return Encoding.UTF8.GetString(mso.ToArray());
    }
}

static void Main(string[] args) {
    byte[] r1 = Zip("StringStringStringStringStringStringStringStringStringStringStringStringStringString");
    string r2 = Unzip(r1);
}

Remember that Zip returns a byte[], while Unzip returns a string. If you want a string from Zip you can Base64 encode it (for example by using Convert.ToBase64String(r1)) (the result of Zip is VERY binary! It isn't something you can print to the screen or write directly in an XML)

The version suggested is for .NET 2.0, for .NET 4.0 use the MemoryStream.CopyTo.

IMPORTANT: The compressed contents cannot be written to the output stream until the GZipStream knows that it has all of the input (i.e., to effectively compress it needs all of the data). You need to make sure that you Dispose() of the GZipStream before inspecting the output stream (e.g., mso.ToArray()). This is done with the using() { } block above. Note that the GZipStream is the innermost block and the contents are accessed outside of it. The same goes for decompressing: Dispose() of the GZipStream before attempting to access the data.

How do I increment a DOS variable in a FOR /F loop?

set TEXT_T="myfile.txt"
set /a c=1

FOR /F "tokens=1 usebackq" %%i in (%TEXT_T%) do (
    set /a c+=1
    set OUTPUT_FILE_NAME=output_%c%.txt
    echo Output file is %OUTPUT_FILE_NAME%
    echo %%i, %c%
)

Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined

To solve this problem just call jQuery file before the bootstrap file

How to get HTTP Response Code using Selenium WebDriver

You can use BrowserMob proxy to capture the requests and responses with a HttpRequestInterceptor. Here is an example in Java:

// Start the BrowserMob proxy
ProxyServer server = new ProxyServer(9978);
server.start();

server.addResponseInterceptor(new HttpResponseInterceptor()
{
    @Override
    public void process(HttpResponse response, HttpContext context)
        throws HttpException, IOException
    {
        System.out.println(response.getStatusLine());
    }
});

// Get selenium proxy
Proxy proxy = server.seleniumProxy();

// Configure desired capability for using proxy server with WebDriver
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, proxy);

// Set up driver
WebDriver driver = new FirefoxDriver(capabilities);

driver.get("http://stackoverflow.com/questions/6509628/webdriver-get-http-response-code");

// Close the browser
driver.quit();

what is the use of $this->uri->segment(3) in codeigniter pagination

CodeIgniter User Guide says:

$this->uri->segment(n)

Permits you to retrieve a specific segment. Where n is the segment number you wish to retrieve. Segments are numbered from left to right. For example, if your full URL is this: http://example.com/index.php/news/local/metro/crime_is_up

The segment numbers would be this:

1. news
2. local
3. metro
4. crime_is_up

So segment refers to your url structure segment. By the above example, $this->uri->segment(3) would be 'metro', while $this->uri->segment(4) would be 'crime_is_up'.

PostgreSQL IF statement

You could also use the the basic structure for the PL/pgSQL CASE with anonymous code block procedure block:

DO $$ BEGIN
    CASE
        WHEN boolean-expression THEN
          statements;
        WHEN boolean-expression THEN
          statements;
        ...
        ELSE
          statements;
    END CASE;
END $$;

References:

  1. http://www.postgresql.org/docs/current/static/sql-do.html
  2. https://www.postgresql.org/docs/current/static/plpgsql-control-structures.html

How do you change the text in the Titlebar in Windows Forms?

this.Text = "Your Text Here"

Place this under Initialize Component and it should change on form load.

Capture event onclose browser

http://docs.jquery.com/Events/unload#fn

jQuery:

$(window).unload( function () { alert("Bye now!"); } );

or javascript:

window.onunload = function(){alert("Bye now!");}

No suitable records were found verify your bundle identifier is correct

In my case the problem was that my application had literally no information filled in the App Store Connect

INSERT ... ON DUPLICATE KEY (do nothing)

Use ON DUPLICATE KEY UPDATE ...,
Negative : because the UPDATE uses resources for the second action.

Use INSERT IGNORE ...,
Negative : MySQL will not show any errors if something goes wrong, so you cannot handle the errors. Use it only if you don’t care about the query.

Change url query string value using jQuery

If you only need to modify the page num you can replace it:

var newUrl = location.href.replace("page="+currentPageNum, "page="+newPageNum);

How do I setup the dotenv file in Node.js?

The '.env' file should be in the root directory of your node js server file (server.js or for me).

If you placed the '.env' file at the root of your project, it won't work. My mistake was that I have the server.js file nested in a folder named 'controller'.

So I had to fix it by placing the .env file in the same directory as the server.js file.

Background images: how to fill whole div if image is small and vice versa

This worked perfectly for me

background-repeat: no-repeat;
background-size: 100% 100%;

How to var_dump variables in twig templates?

So I got it working, partly a bit hackish:

  1. Set twig: debug: 1 in app/config/config.yml
  2. Add this to config_dev.yml

    services:
        debug.twig.extension:
            class: Twig_Extensions_Extension_Debug
            tags: [{ name: 'twig.extension' }]
    
  3. sudo rm -fr app/cache/dev

  4. To use my own debug function instead of print_r(), I opened vendor/twig-extensions/lib/Twig/Extensions/Node/Debug.php and changed print_r( to d(

PS. I would still like to know how/where to grab the $twig environment to add filters and extensions.

How can I start an interactive console for Perl?

I always did:

rlwrap perl -wlne'eval;print$@if$@'

With 5.10, I've switched to:

rlwrap perl -wnE'say eval()//$@'

(rlwrap is optional)

Compiling Java 7 code via Maven

Please check you pom.xml for the below tags

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

it should point the required jdk version

Equivalent of varchar(max) in MySQL?

TLDR; MySql does not have an equivalent concept of varchar(max), this is a MS SQL Server feature.

What is VARCHAR(max)?

varchar(max) is a feature of Microsoft SQL Server.

The amount of data that a column could store in Microsoft SQL server versions prior to version 2005 was limited to 8KB. In order to store more than 8KB you would have to use TEXT, NTEXT, or BLOB columns types, these column types stored their data as a collection of 8K pages separate from the table data pages; they supported storing up to 2GB per row.

The big caveat to these column types was that they usually required special functions and statements to access and modify the data (e.g. READTEXT, WRITETEXT, and UPDATETEXT)

In SQL Server 2005, varchar(max) was introduced to unify the data and queries used to retrieve and modify data in large columns. The data for varchar(max) columns is stored inline with the table data pages.

As the data in the MAX column fills an 8KB data page an overflow page is allocated and the previous page points to it forming a linked list. Unlike TEXT, NTEXT, and BLOB the varchar(max) column type supports all the same query semantics as other column types.

So varchar(MAX) really means varchar(AS_MUCH_AS_I_WANT_TO_STUFF_IN_HERE_JUST_KEEP_GROWING) and not varchar(MAX_SIZE_OF_A_COLUMN).

MySql does not have an equivalent idiom.

In order to get the same amount of storage as a varchar(max) in MySql you would still need to resort to a BLOB column type. This article discusses a very effective method of storing large amounts of data in MySql efficiently.

jasmine: Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL

This is more of an observation than an answer, but it may help others who were as frustrated as I was.

I kept getting this error from two tests in my suite. I thought I had simply broken the tests with the refactoring I was doing, so after backing out changes didn't work, I reverted to earlier code, twice (two revisions back) thinking it'd get rid of the error. Doing so changed nothing. I chased my tail all day yesterday, and part of this morning without resolving the issue.

I got frustrated and checked out the code onto a laptop this morning. Ran the entire test suite (about 180 tests), no errors. So the errors were never in the code or tests. Went back to my dev box and rebooted it to clear anything in memory that might have been causing the issue. No change, same errors on the same two tests. So I deleted the directory from my machine, and checked it back out. Voila! No errors.

No idea what caused it, or how to fix it, but deleting the working directory and checking it back out fixed whatever it was.

Hope this helps someone.

How is a non-breaking space represented in a JavaScript string?

&nbsp; is a HTML entity. When doing .text(), all HTML entities are decoded to their character values.

Instead of comparing using the entity, compare using the actual raw character:

var x = td.text();
if (x == '\xa0') { // Non-breakable space is char 0xa0 (160 dec)
  x = '';
}

Or you can also create the character from the character code manually it in its Javascript escaped form:

var x = td.text();
if (x == String.fromCharCode(160)) { // Non-breakable space is char 160
  x = '';
}

More information about String.fromCharCode is available here:

fromCharCode - MDC Doc Center

More information about character codes for different charsets are available here:

Windows-1252 Charset
UTF-8 Charset

How to change Rails 3 server default port in develoment?

Create alias in your shell for command with a specified port.

How to get to a particular element in a List in java?

You have about 98% right. The only issue is that you're trying to print out an String[] which does not print the way you'd like. Instead try this...

for (String[] s : myEntries) {
    System.out.print("Next item: " + s[0]);
    for(int i = 1; i < s.length; i++) {
        System.out.print(", " + s[i]);
    }
    System.out.println("");
}

This way you're accessing each string in the array instead of the array itself.

Hope this helps!

How to return rows from left table not found in right table?

I can't add anything but a code example to the other two answers: however, I find it can be useful to see it in action (the other answers, in my opinion, are better because they explain it).

DECLARE @testLeft TABLE (ID INT, SomeValue VARCHAR(1))
DECLARE @testRight TABLE (ID INT, SomeOtherValue VARCHAR(1))

INSERT INTO @testLeft (ID, SomeValue) VALUES (1, 'A')
INSERT INTO @testLeft (ID, SomeValue) VALUES (2, 'B')
INSERT INTO @testLeft (ID, SomeValue) VALUES (3, 'C')


INSERT INTO @testRight (ID, SomeOtherValue) VALUES (1, 'X')
INSERT INTO @testRight (ID, SomeOtherValue) VALUES (3, 'Z')

SELECT l.*
FROM 
    @testLeft l
     LEFT JOIN 
    @testRight r ON 
        l.ID = r.ID
WHERE r.ID IS NULL 

How to find the kafka version in linux

Not sure if there's a convenient way, but you can just inspect your kafka/libs folder. You should see files like kafka_2.10-0.8.2-beta.jar, where 2.10 is Scala version and 0.8.2-beta is Kafka version.

How can I get log4j to delete old rotating log files?

RollingFileAppender does this. You just need to set maxBackupIndex to the highest value for the backup file.

DevTools failed to load SourceMap: Could not load content for chrome-extension

I do not think the warnings you have received are related. I had the same warnings which turned out to be the chrome extension React Dev Tools. Removed the extension and the errors have gone.

How to get thread id from a thread pool?

If you are using logging then thread names will be helpful. A thread factory helps with this:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class Main {

    static Logger LOG = LoggerFactory.getLogger(Main.class);

    static class MyTask implements Runnable {
        public void run() {
            LOG.info("A pool thread is doing this task");
        }
    }

    public static void main(String[] args) {
        ExecutorService taskExecutor = Executors.newFixedThreadPool(5, new MyThreadFactory());
        taskExecutor.execute(new MyTask());
        taskExecutor.shutdown();
    }
}

class MyThreadFactory implements ThreadFactory {
    private int counter;
    public Thread newThread(Runnable r) {
        return new Thread(r, "My thread # " + counter++);
    }
}

Output:

[   My thread # 0] Main         INFO  A pool thread is doing this task

Python int to binary string?

Python 3.6 added a new string formatting approach called formatted string literals or “f-strings”. Example:

name = 'Bob'
number = 42
f"Hello, {name}, your number is {number:>08b}"

Output will be 'Hello, Bob, your number is 00001010!'

A discussion of this question can be found here - Here

Return JSON response from Flask view

Prior to Flask 0.11, jsonfiy would not allow returning an array directly. Instead, pass the list as a keyword argument.

@app.route('/get_records')
def get_records():
    results = [
        {
          "rec_create_date": "12 Jun 2016",
          "rec_dietary_info": "nothing",
          "rec_dob": "01 Apr 1988",
          "rec_first_name": "New",
          "rec_last_name": "Guy",
        },
        {
          "rec_create_date": "1 Apr 2016",
          "rec_dietary_info": "Nut allergy",
          "rec_dob": "01 Feb 1988",
          "rec_first_name": "Old",
          "rec_last_name": "Guy",
        },
    ]
    return jsonify(results=list)

What is the difference between `new Object()` and object literal notation?

Everyone here is talking about the similarities of the two. I am gonna point out the differences.

  1. Using new Object() allows you to pass another object. The obvious outcome is that the newly created object will be set to the same reference. Here is a sample code:

    var obj1 = new Object();
    obj1.a = 1;
    var obj2 = new Object(obj1);
    obj2.a // 1
    
  2. The usage is not limited to objects as in OOP objects. Other types could be passed to it too. The function will set the type accordingly. For example if we pass integer 1 to it, an object of type number will be created for us.

    var obj = new Object(1);
    typeof obj // "number"
    
  3. The object created using the above method (new Object(1)) would be converted to object type if a property is added to it.

    var obj = new Object(1);
    typeof obj // "number"
    obj.a = 2;
    typeof obj // "object"
    
  4. If the object is a copy of a child class of object, we could add the property without the type conversion.

    var obj = new Object("foo");
    typeof obj // "object"
    obj === "foo" // true
    obj.a = 1;
    obj === "foo" // true
    obj.a // 1
    var str = "foo";
    str.a = 1;
    str.a // undefined
    

How do I resolve `The following packages have unmet dependencies`

This is a bug in the npm package regarding dependencies : https://askubuntu.com/questions/1088662/npm-depends-node-gyp-0-10-9-but-it-is-not-going-to-be-installed

Bugs have been reported. The above may not work depending what you have installed already, at least it didn't for me on an up to date Ubuntu 18.04 LTS.

I followed the suggested dependencies and installed them as the above link suggests:

sudo apt-get install nodejs-dev node-gyp libssl1.0-dev

and then

sudo apt-get install npm

Please subscribe to the bug if you're affected:

bugs.launchpad.net/ubuntu/+source/npm/+bug/1517491
bugs.launchpad.net/ubuntu/+source/npm/+bug/1809828

Stopping an Android app from console

you can use the following from the device console: pm disable com.my.app.package which will kill it. Then use pm enable com.my.app.package so that you can launch it again.

Importing data from a JSON file into R

First install the rjson package:

install.packages("rjson")

Then:

library("rjson")
json_file <- "http://api.worldbank.org/country?per_page=10&region=OED&lendingtype=LNX&format=json"
json_data <- fromJSON(paste(readLines(json_file), collapse=""))

Update: since version 0.2.1

json_data <- fromJSON(file=json_file)

Controller not a function, got undefined, while defining controllers globally

I got the same error while following an old tutorial with (not old enough) AngularJS 1.4.3. By far the simplest solution is to edit angular.js source from

function $ControllerProvider() {
  var controllers = {},
      globals = false;

to

function $ControllerProvider() {
  var controllers = {},
      globals = true;

and just follow the tutorial as-is, and the deprecated global functions just work as controllers.

C++ Returning reference to local variable

This code snippet:

int& func1()
{
    int i;
    i = 1;
    return i;
}

will not work because you're returning an alias (a reference) to an object with a lifetime limited to the scope of the function call. That means once func1() returns, int i dies, making the reference returned from the function worthless because it now refers to an object that doesn't exist.

int main()
{
    int& p = func1();
    /* p is garbage */
}

The second version does work because the variable is allocated on the free store, which is not bound to the lifetime of the function call. However, you are responsible for deleteing the allocated int.

int* func2()
{
    int* p;
    p = new int;
    *p = 1;
    return p;
}

int main()
{
    int* p = func2();
    /* pointee still exists */
    delete p; // get rid of it
}

Typically you would wrap the pointer in some RAII class and/or a factory function so you don't have to delete it yourself.

In either case, you can just return the value itself (although I realize the example you provided was probably contrived):

int func3()
{
    return 1;
}

int main()
{
    int v = func3();
    // do whatever you want with the returned value
}

Note that it's perfectly fine to return big objects the same way func3() returns primitive values because just about every compiler nowadays implements some form of return value optimization:

class big_object 
{ 
public:
    big_object(/* constructor arguments */);
    ~big_object();
    big_object(const big_object& rhs);
    big_object& operator=(const big_object& rhs);
    /* public methods */
private:
    /* data members */
};

big_object func4()
{
    return big_object(/* constructor arguments */);
}

int main()
{
     // no copy is actually made, if your compiler supports RVO
    big_object o = func4();    
}

Interestingly, binding a temporary to a const reference is perfectly legal C++.

int main()
{
    // This works! The returned temporary will last as long as the reference exists
    const big_object& o = func4();    
    // This does *not* work! It's not legal C++ because reference is not const.
    // big_object& o = func4();  
}

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

Hope this will help someone... Here's a little PHP script I wrote in case you need to copy some columns but not others, and/or the columns are not in the same order on both tables. As long as the columns are named the same, this will work. So if table A has [userid, handle, something] and tableB has [userID, handle, timestamp], then you'd "SELECT userID, handle, NOW() as timestamp FROM tableA", then get the result of that, and pass the result as the first parameter to this function ($z). $toTable is a string name for the table you're copying to, and $link_identifier is the db you're copying to. This is relatively fast for small sets of data. Not suggested that you try to move more than a few thousand rows at a time this way in a production setting. I use this primarily to back up data collected during a session when a user logs out, and then immediately clear the data from the live db to keep it slim.

 function mysql_multirow_copy($z,$toTable,$link_identifier) {
            $fields = "";
            for ($i=0;$i<mysql_num_fields($z);$i++) {
                if ($i>0) {
                    $fields .= ",";
                }
                $fields .= mysql_field_name($z,$i);
            }
            $q = "INSERT INTO $toTable ($fields) VALUES";
            $c = 0;
            mysql_data_seek($z,0); //critical reset in case $z has been parsed beforehand. !
            while ($a = mysql_fetch_assoc($z)) {
                foreach ($a as $key=>$as) {
                    $a[$key] = addslashes($as);
                    next ($a);
                }
                if ($c>0) {
                    $q .= ",";
                }
                $q .= "('".implode(array_values($a),"','")."')";
                $c++;
            }
            $q .= ";";
            $z = mysql_query($q,$link_identifier);
            return ($q);
        }

How do we update URL or query strings using javascript/jQuery without reloading the page?

Yes

document.location is the normal way.

However document.location is effectively the same as window.location, except for window.location is a bit more supported in older browsers so may be the prefferable choice.

Check out this thread on SO for more info:

What's the difference between window.location and document.location in JavaScript?

Verify External Script Is Loaded

Create the script tag with a specific ID and then check if that ID exists?

Alternatively, loop through script tags checking for the script 'src' and make sure those are not already loaded with the same value as the one you want to avoid ?

Edit: following feedback that a code example would be useful:

(function(){
    var desiredSource = 'https://sitename.com/js/script.js';
    var scripts       = document.getElementsByTagName('script');
    var alreadyLoaded = false;

    if(scripts.length){
        for(var scriptIndex in scripts) {
            if(!alreadyLoaded && desiredSource === scripts[scriptIndex].src) {
                alreadyLoaded = true;
            }
        }
    }
    if(!alreadyLoaded){
        // Run your code in this block?
    }
})();

As mentioned in the comments (https://stackoverflow.com/users/1358777/alwin-kesler), this may be an alternative (not benchmarked):

(function(){
    var desiredSource = 'https://sitename.com/js/script.js';
    var scripts = document.getElementsByTagName('script');
    var alreadyLoaded = false;

    for(var scriptIndex in document.scripts) {
        if(!alreadyLoaded && desiredSource === scripts[scriptIndex].src) {
            alreadyLoaded = true;
        }
    }
    if(!alreadyLoaded){
        // Run your code in this block?
    }
})();

Improve SQL Server query performance on large tables

One of the reasons your 1M test ran quicker is likely because the temp tables are entirely in memory and would only go to disk if your server experiences memory pressure. You can either re-craft your query to remove the order by, add a good clustered index and covering index(es) as previously mentioned, or query the DMV to check for IO pressure to see if hardware related.

-- From Glen Barry
-- Clear Wait Stats (consider clearing and running wait stats query again after a few minutes)
-- DBCC SQLPERF('sys.dm_os_wait_stats', CLEAR);

-- Check Task Counts to get an initial idea what the problem might be

-- Avg Current Tasks Count, Avg Runnable Tasks Count, Avg Pending Disk IO Count across all schedulers
-- Run several times in quick succession
SELECT AVG(current_tasks_count) AS [Avg Task Count], 
       AVG(runnable_tasks_count) AS [Avg Runnable Task Count],
       AVG(pending_disk_io_count) AS [Avg Pending DiskIO Count]
FROM sys.dm_os_schedulers WITH (NOLOCK)
WHERE scheduler_id < 255 OPTION (RECOMPILE);

-- Sustained values above 10 suggest further investigation in that area
-- High current_tasks_count is often an indication of locking/blocking problems
-- High runnable_tasks_count is a good indication of CPU pressure
-- High pending_disk_io_count is an indication of I/O pressure

How to find and replace with regex in excel

As an alternative to Regex, running:

Sub Replacer()
   Dim N As Long, i As Long
   N = Cells(Rows.Count, "A").End(xlUp).Row

   For i = 1 To N
      If Left(Cells(i, "A").Value, 9) = "texts are" Then
         Cells(i, "A").Value = "texts are replaced"
      End If
   Next i
End Sub

will produce:

enter image description here

Modifying Objects within stream in Java8 while iterating

To get rid from ConcurrentModificationException Use CopyOnWriteArrayList

What is use of c_str function In c++

In C/C++ programming there are two types of strings: the C strings and the standard strings. With the <string> header, we can use the standard strings. On the other hand, the C strings are just an array of normal chars. So, in order to convert a standard string to a C string, we use the c_str() function.

for example

// a string to a C-style string conversion//

const char *cstr1 = str1.c_str();
cout<<"Operation: *cstr1 = str1.c_str()"<<endl;
cout<<"The C-style string c_str1 is: "<<cstr1<<endl;
cout<<"\nOperation: strlen(cstr1)"<<endl;
cout<<"The length of C-style string str1 = "<<strlen(cstr1)<<endl;

And the output will be,

Operation: *cstr1 = str1.c_str()
The C-style string c_str1 is: Testing the c_str 
Operation: strlen(cstr1)
The length of C-style string str1 = 17

In Jenkins, how to checkout a project into a specific directory (using GIT)

The default git plugin for Jenkins does the job quite nicely.

After adding a new git repository (project configuration > Source Code Management > check the GIT option) to the project navigate to the bottom of the plugin settings, just above Repository browser region. There should be an Advanced button. After clicking it a new form should appear, with a value described as Local subdirectory for repo (optional). Setting this to folder will make the plugin to check out the repository into the folder relative to your workspace. This way you can have as many repositories in your project as you need, all in separate locations.

Alternatively, if the project you're using will allow that, you can use GIT sub modules, which are similar to external paths in SVN. In the GIT Book there is a section on that very topic. If that will not be against some policy, submodules are fairly simple to use, giving you powerful way to control the locations, versions/tags/branches that will be imported AND it will be available on your local repository as well giving you better portability.

Obviously the GIT plugin supports checking out submodules, so Jenkins can work with them quite effectively.

How to redirect to a 404 in Rails?

HTTP 404 Status

To return a 404 header, just use the :status option for the render method.

def action
  # here the code

  render :status => 404
end

If you want to render the standard 404 page you can extract the feature in a method.

def render_404
  respond_to do |format|
    format.html { render :file => "#{Rails.root}/public/404", :layout => false, :status => :not_found }
    format.xml  { head :not_found }
    format.any  { head :not_found }
  end
end

and call it in your action

def action
  # here the code

  render_404
end

If you want the action to render the error page and stop, simply use a return statement.

def action
  render_404 and return if params[:something].blank?

  # here the code that will never be executed
end

ActiveRecord and HTTP 404

Also remember that Rails rescues some ActiveRecord errors, such as the ActiveRecord::RecordNotFound displaying the 404 error page.

It means you don't need to rescue this action yourself

def show
  user = User.find(params[:id])
end

User.find raises an ActiveRecord::RecordNotFound when the user doesn't exist. This is a very powerful feature. Look at the following code

def show
  user = User.find_by_email(params[:email]) or raise("not found")
  # ...
end

You can simplify it by delegating to Rails the check. Simply use the bang version.

def show
  user = User.find_by_email!(params[:email])
  # ...
end

When should iteritems() be used instead of items()?

You cannot use items instead iteritems in all places in Python. For example, the following code:

class C:
  def __init__(self, a):
    self.a = a
  def __iter__(self):
    return self.a.iteritems()

>>> c = C(dict(a=1, b=2, c=3))
>>> [v for v in c]
[('a', 1), ('c', 3), ('b', 2)]

will break if you use items:

class D:
  def __init__(self, a):
    self.a = a
  def __iter__(self):
    return self.a.items()

>>> d = D(dict(a=1, b=2, c=3))
>>> [v for v in d]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __iter__ returned non-iterator of type 'list'

The same is true for viewitems, which is available in Python 3.

Also, since items returns a copy of the dictionary’s list of (key, value) pairs, it is less efficient, unless you want to create a copy anyway.

In Python 2, it is best to use iteritems for iteration. The 2to3 tool can replace it with items if you ever decide to upgrade to Python 3.

Split string with string as delimiter

I've found two older scripts that use an indefinite or even a specific string to split. As an approach, these are always helpful.

https://www.administrator.de/contentid/226533#comment-1059704 https://www.administrator.de/contentid/267522#comment-1000886

@echo off
:noOption
if "%~1" neq "" goto :nohelp
echo Gibt eine Ausgabe bis zur angebenen Zeichenfolge&echo(
echo %~n0 ist mit Eingabeumleitung zu nutzen
echo %~n0 "Zeichenfolge" ^<Quelldatei [^>Zieldatei]&echo(
echo    Zeichenfolge    die zu suchende Zeichenfolge wird mit FIND bestimmt
echo            ohne AusgabeUmleitung Ausgabe im CMD Fenster
exit /b
:nohelp
setlocal disabledelayedexpansion
set "intemp=%temp%%time::=%"
set "string=%~1"
set "stringlength=0"
:Laenge string bestimmen
for /f eol^=^

^ delims^= %%i in (' cmd /u /von /c "echo(!string!"^|find /v "" ') do set /a Stringlength += 1

:Eingabe temporär speichern
>"%intemp%" find /n /v ""

:suchen der Zeichenfolge und Zeile bestimmen und speichen
set "NRout="
for /f "tokens=*delims=" %%a in (' find "%string%"^<"%intemp%" ') do if not defined NRout (set "LineStr=%%a"
  for /f "delims=[]" %%b in ("%%a") do set "NRout=%%b"
)
if not defined NRout >&2 echo Zeichenfolge nicht gefunden.& set /a xcode=1 &goto :end
if %NRout% gtr 1 call :Line
call :LineStr

:end
del "%intemp%"
exit /b %xcode%

:LineStr Suche nur jeden ersten Buchstaben des Strings in der Treffer-Zeile dann Ausgabe bis dahin
for /f eol^=^

^ delims^= %%a in ('cmd /u /von /c "echo(!String!"^|findstr .') do (
  for /f "delims=[]" %%i in (' cmd /u /von /c "echo(!LineStr!"^|find /n "%%a" ') do (
    setlocal enabledelayedexpansion
    for /f %%n in ('set /a %%i-1') do if !LineStr:^~%%n^,%stringlength%! equ !string! (
      set "Lineout=!LineStr:~0,%%n!!string!"
      echo(!Lineout:*]=!
      exit /b
    )
) )
exit /b 

:Line vorige Zeilen ausgeben
for /f "usebackq tokens=* delims=" %%i in ("%intemp%") do (
  for /f "tokens=1*delims=[]" %%n in ("%%i") do if %%n EQU %NRout%  exit /b
  set "Line=%%i"
  setlocal enabledelayedexpansion 
  echo(!Line:*]=!
  endlocal
)
exit /b

@echo off
:: CUTwithWildcards.cmd
:noOption
if "%~1" neq "" goto :nohelp
echo Gibt eine Ausgabe ohne die angebene Zeichenfolge.
echo Der Rest wird abgeschnitten.&echo(
echo %~n0 "Zeichenfolge" B n E [/i] &echo(
echo    Zeichenfolge    String zum Durchsuchen
echo    B   Zeichen Wonach am Anfang gesucht wird
echo    n   Auszulassende Zeichenanzahl
echo    E   Zeichen was das Ende der Zeichen Bestimmt
echo    /i  Case intensive
exit /b
:nohelp
setlocal disabledelayedexpansion
set  "Original=%~1"
set     "Begin=%~2"
set /a    Excl=%~3 ||echo Syntaxfehler.>&2 &&exit /b 1
set       "End=%~4"
if not defined end echo Syntaxfehler.>&2 &exit /b 1
set   "CaseInt=%~5"
:: end Setting Input Param
set       "out="
set      "more="
call :read Original
if errorlevel 1 echo Zeichenfolge nicht gefunden.>&2
exit /b
:read VarName B # E [/i]
for /f "delims=[]" %%a in (' cmd /u /von /c "echo  !%~1!"^|find /n %CaseInt% "%Begin%" ') do (
  if defined out exit /b 0
  for /f "delims=[]" %%b in (' cmd /u /von /c "echo !%1!"^|more +%Excl%^|find /n %CaseInt% "%End%"^|find "[%%a]" ') do (
    set "out=1"
    setlocal enabledelayedexpansion
    set "In=  !Original!"
    set "In=!In:~,%%a!"
    echo !In:^~2!
    endlocal
) )
if not defined out exit /b 1 
exit /b

::oneliner for CMDLine
set "Dq=""
for %i in ("*S??E*") do @set "out=1" &for /f "delims=[]" %a in ('cmd/u/c "echo  %i"^|find /n "S"') do @if defined out for /f "delims=[]" %b in ('cmd/u/c "echo %i"^|more +2^|find /n "E"^|find "[%a]"') do @if %a equ %b set "out=" & set in= "%i" &cmd /v/c echo ren "%i" !in:^~0^,%a!!Dq!)

Foreign key referring to primary keys across multiple tables?

I know this is long stagnant topic, but in case anyone searches here is how I deal with multi table foreign keys. With this technique you do not have any DBA enforced cascade operations, so please make sure you deal with DELETE and such in your code.

Table 1 Fruit
pk_fruitid, name
1, apple
2, pear

Table 2 Meat
Pk_meatid, name
1, beef
2, chicken

Table 3 Entity's
PK_entityid, anme
1, fruit
2, meat
3, desert

Table 4 Basket (Table using fk_s)
PK_basketid, fk_entityid, pseudo_entityrow
1, 2, 2 (Chicken - entity denotes meat table, pseudokey denotes row in indictaed table)
2, 1, 1 (Apple)
3, 1, 2 (pear)
4, 3, 1 (cheesecake)

SO Op's Example would look like this

deductions
--------------
type    id      name
1      khce1   gold
2      khsn1   silver

types
---------------------
1 employees_ce
2 employees_sn

ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error

Your log indicates ClientAbortException, which occurs when your HTTP client drops the connection with the server and this happened before server could close the server socket Connection.

What is "pom" packaging in maven?

pom is basically a container of submodules, each submodule is represented by a subdirectory in the same directory as pom.xml with pom packaging.

Somewhere, nested within the project structure you will find artifacts (modules) with war packaging. Maven generally builds everything into /target subdirectories of each module. So after mvn install look into target subdirectory in a module with war packaging.

Of course:

$ find . -iname "*.war"

works equally well ;-).

How do you generate dynamic (parameterized) unit tests in Python?

Using unittest (since 3.4)

Since Python 3.4, the standard library unittest package has the subTest context manager.

See the documentation:

Example:

from unittest import TestCase

param_list = [('a', 'a'), ('a', 'b'), ('b', 'b')]

class TestDemonstrateSubtest(TestCase):
    def test_works_as_expected(self):
        for p1, p2 in param_list:
            with self.subTest():
                self.assertEqual(p1, p2)

You can also specify a custom message and parameter values to subTest():

with self.subTest(msg="Checking if p1 equals p2", p1=p1, p2=p2):

Using nose

The nose testing framework supports this.

Example (the code below is the entire contents of the file containing the test):

param_list = [('a', 'a'), ('a', 'b'), ('b', 'b')]

def test_generator():
    for params in param_list:
        yield check_em, params[0], params[1]

def check_em(a, b):
    assert a == b

The output of the nosetests command:

> nosetests -v
testgen.test_generator('a', 'a') ... ok
testgen.test_generator('a', 'b') ... FAIL
testgen.test_generator('b', 'b') ... ok

======================================================================
FAIL: testgen.test_generator('a', 'b')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python2.5/site-packages/nose-0.10.1-py2.5.egg/nose/case.py", line 203, in runTest
    self.test(*self.arg)
  File "testgen.py", line 7, in check_em
    assert a == b
AssertionError

----------------------------------------------------------------------
Ran 3 tests in 0.006s

FAILED (failures=1)

Strange "java.lang.NoClassDefFoundError" in Eclipse

I see that people have already talked about class path. Since there is no accepted answer, I assume it is not related to class path. So I would like to add that, not having package directive can also lead to class not found errors.

How to display list of repositories from subversion server

I was also looking to list repositories in SVN. I did something like this on shell prompt:

~$ svn list https://www.repo.rr.com/svn/main/team/gaurav

Test/
Test2/
Test3/
Test4/
Test5/
Test6/

CSS @font-face not working in ie

I read a lot of tutorials that suggested hacks, so I came up with this solution I think is better... It seems to work fine.

@font-face { 
    font-family: MyFont; src: url('myfont.ttf'); 
}
@font-face{ 
    font-family: MyFont_IE; src: url('myfont.eot'); 
}
.my_font{ 
    font-family: MyFont, MyFont_IE, Arial, Helvetica, sans-serif; 
}

How do I access an access array item by index in handlebars?

The following syntax can also be used if the array is not named (just the array is passed to the template):

  <ul id="luke_should_be_here">
  {{this.1.name}}
  </ul>

Set object property using reflection

Use somethings like this :

public static class PropertyExtension{       

   public static void SetPropertyValue(this object p_object, string p_propertyName, object value)
   {
    PropertyInfo property = p_object.GetType().GetProperty(p_propertyName);
    property.SetValue(p_object, Convert.ChangeType(value, property.PropertyType), null);
   }
}

or

public static class PropertyExtension{       

   public static void SetPropertyValue(this object p_object, string p_propertyName, object value)
   {
    PropertyInfo property = p_object.GetType().GetProperty(p_propertyName);
    Type t = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
    object safeValue = (value == null) ? null : Convert.ChangeType(value, t);

    property.SetValue(p_object, safeValue, null);
   }
}

ERROR: Sonar server 'http://localhost:9000' can not be reached

I got the same issue, and I changed to IP and it working well

Go to System References --> Network --> Advanced --> Open TCP/IP tabs --> copy the IPv4 Address.

change that IP instead localhost

Hope this can help

What is the use of the init() usage in JavaScript?

NB. Constructor function names should start with a capital letter to distinguish them from ordinary functions, e.g. MyClass instead of myClass.

Either you can call init from your constructor function:

var myObj = new MyClass(2, true);

function MyClass(v1, v2) 
{
    // ...

    // pub methods
    this.init = function() {
        // do some stuff        
    };

    // ...

    this.init(); // <------------ added this
}

Or more simply you could just copy the body of the init function to the end of the constructor function. No need to actually have an init function at all if it's only called once.

Can I concatenate multiple MySQL rows into one field?

Alternate syntax to concatenate multiple, individual rows

WARNING: This post will make you hungry.

Given:

I found myself wanting to select multiple, individual rows—instead of a group—and concatenate on a certain field.

Let's say you have a table of product ids and their names and prices:

+------------+--------------------+-------+
| product_id | name               | price |
+------------+--------------------+-------+
|         13 | Double Double      |     5 |
|         14 | Neapolitan Shake   |     2 |
|         15 | Animal Style Fries |     3 |
|         16 | Root Beer          |     2 |
|         17 | Lame T-Shirt       |    15 |
+------------+--------------------+-------+

Then you have some fancy-schmancy ajax that lists these puppies off as checkboxes.

Your hungry-hippo user selects 13, 15, 16. No dessert for her today...

Find:

A way to summarize your user's order in one line, with pure mysql.

Solution:

Use GROUP_CONCAT with the the IN clause:

mysql> SELECT GROUP_CONCAT(name SEPARATOR ' + ') AS order_summary FROM product WHERE product_id IN (13, 15, 16);

Which outputs:

+------------------------------------------------+
| order_summary                                  |
+------------------------------------------------+
| Double Double + Animal Style Fries + Root Beer |
+------------------------------------------------+

Bonus Solution:

If you want the total price too, toss in SUM():

mysql> SELECT GROUP_CONCAT(name SEPARATOR ' + ') AS order_summary, SUM(price) AS total FROM product WHERE product_id IN (13, 15, 16);
+------------------------------------------------+-------+
| order_summary                                  | total |
+------------------------------------------------+-------+
| Double Double + Animal Style Fries + Root Beer |    10 |
+------------------------------------------------+-------+

Bash loop ping successful

You don't need to use echo or grep. You could do this:

ping -oc 100000 8.8.8.8 > /dev/null && say "up" || say "down"

How to copy a file from one directory to another using PHP?

<?php  
  
// Copy the file from /user/desktop/geek.txt  
// to user/Downloads/geeksforgeeks.txt' 
// directory 
  
// Store the path of source file 
$source = '/user/Desktop/geek.txt';  
  
// Store the path of destination file 
$destination = 'user/Downloads/geeksforgeeks.txt';  
  
// Copy the file from /user/desktop/geek.txt  
// to user/Downloads/geeksforgeeks.txt' 
// directory 
if( !copy($source, $destination) ) {  
    echo "File can't be copied! \n";  
}  
else {  
    echo "File has been copied! \n";  
}  
  
?>  

fatal: 'origin' does not appear to be a git repository

This does not answer your question, but I faced a similar error message but due to a different reason. Allow me to make my post for the sake of information collection.

I have a git repo on a network drive. Let's call this network drive RAID. I cloned this repo on my local machine (LOCAL) and on my number crunching cluster (CRUNCHER). For convenience I mounted the user directory of my account on CRUNCHER on my local machine. So, I can manipulate files on CRUNCHER without the need to do the work in an SSH terminal.

Today, I was modifying files in the repo on CRUNCHER via my local machine. At some point I decided to commit the files, so a did a commit. Adding the modified files and doing the commit worked as I expected, but when I called git push I got an error message similar to the one posted in the question.

The reason was, that I called push from within the repo on CRUNCHER on LOCAL. So, all paths in the config file were plain wrong.

When I realized my fault, I logged onto CRUNCHER via Terminal and was able to push the commit.

Feel free to comment if my explanation can't be understood, or you find my post superfluous.

Exception: Serialization of 'Closure' is not allowed

As already stated: closures, out of the box, cannot be serialized.

However, using the __sleep(), __wakeup() magic methods and reflection u CAN manually make closures serializable. For more details see extending-php-5-3-closures-with-serialization-and-reflection

This makes use of reflection and the php function eval. Do note this opens up the possibility of CODE injection, so please take notice of WHAT you are serializing.

How to change dataframe column names in pyspark?

df = df.withColumnRenamed("colName", "newColName")\
       .withColumnRenamed("colName2", "newColName2")

Advantage of using this way: With long list of columns you would like to change only few column names. This can be very convenient in these scenarios. Very useful when joining tables with duplicate column names.

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

Agreed with jcadcell comments, but had to use JDK 1.8 because my eclipse need that. So I just copied the MSVCR71.DLL from jdk1.6 and pasted into jdk1.8 in both the folder jdk1.8.0_121\bin and jdk1.8.0_121\jre\bin

and it Worked .... Wow... Thanks :)

How to enable Ad Hoc Distributed Queries

You may check the following command

sp_configure 'show advanced options', 1;
RECONFIGURE;
GO  --Added        
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

SELECT a.*
FROM OPENROWSET('SQLNCLI', 'Server=Seattle1;Trusted_Connection=yes;',
     'SELECT GroupName, Name, DepartmentID
      FROM AdventureWorks2012.HumanResources.Department
      ORDER BY GroupName, Name') AS a;
GO

Or this documentation link

SQL Query to find the last day of the month

An excelent approach by me. Regards

DECLARE @MAXDATE INT=(SELECT MAX(DATEPART(YEAR,ORDERDATE)) FROM Orders)
DECLARE @MINDATE INT=(SELECT MIN(DATEPART(YEAR,ORDERDATE)) FROM Orders)
DECLARE @HORA INT=(SELECT MIN( DATEPART(HOUR,ORDERDATE)) FROM ORDERS)
DECLARE @DIA INT = 28

SELECT Employees.EmployeeID , Orders. OrderID , OrderDate  FROM Employees
INNER JOIN Orders 
ON Employees.EmployeeID = Orders.EmployeeID
Where  (DATEPART(YEAR,ORDERDATE)) >=@mindate and  (DATEPART(YEAR,ORDERDATE))<= @maxdate
and DATEPART(HOUR,ORDERDATE)=@HORA   and DATEPART(DAY,ORDERDATE) IN (30,31) OR DATEADD(DAY,0,DATEPART(DAY,ORDERDATE))=28 AND
DATEADD(MONTH,0,DATEPART(MONTH,ORDERDATE))=2
ORDER BY 1 ASC

How to use the ConfigurationManager.AppSettings

\if what you have posted is exactly what you are using then your problem is a bit obvious. Now assuming in your web.config you have you connection string defined like this

 <add name="SiteSqlServer" connectionString="Data Source=(local);Initial Catalog=some_db;User ID=sa;Password=uvx8Pytec" providerName="System.Data.SqlClient" />

In your code you should use the value in the name attribute to refer to the connection string you want (you could actually define several connection strings to different databases), so you would have

 con.ConnectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;

.map() a Javascript ES6 Map?

Using Array.from I wrote a Typescript function that maps the values:

function mapKeys<T, V, U>(m: Map<T, V>, fn: (this: void, v: V) => U): Map<T, U> {
  function transformPair([k, v]: [T, V]): [T, U] {
    return [k, fn(v)]
  }
  return new Map(Array.from(m.entries(), transformPair));
}

const m = new Map([[1, 2], [3, 4]]);
console.log(mapKeys(m, i => i + 1));
// Map { 1 => 3, 3 => 5 }

Unix: How to delete files listed in a file

cat 1.txt | xargs rm -f | bash Run the command will do the following for files only.

cat 1.txt | xargs rm -rf | bash Run the command will do the following recursive behaviour.

Select and display only duplicate records in MySQL

Try this query:

SELECT id, COUNT( payer_email ) `tot`
FROM paypal_ipn_orders
GROUP BY id
HAVING `tot` >1

Does it help?

Bootstrap 3 Gutter Size

I don't think Bass's answer is correct. Why touch the row margins? They have a negative margin to offset the column padding for the columns on the edge of the row. Messing with this will break any nested rows.

The answer is simple, just make the container padding equal to the gutter size:

e.g for default bootstrap:

.container {
    padding-left:30px;
    padding-right:30px;
}

http://jsfiddle.net/3wBE3/61/

ASP.NET MVC: What is the correct way to redirect to pages/actions in MVC?

RedirectToAction("actionName", "controllerName");

It has other overloads as well, please check up!

Also, If you are new and you are not using T4MVC, then I would recommend you to use it!

It gives you intellisence for actions,Controllers,views etc (no more magic strings)

Using module 'subprocess' with timeout

surprised nobody mentioned using timeout

timeout 5 ping -c 3 somehost

This won't for work for every use case obviously, but if your dealing with a simple script, this is hard to beat.

Also available as gtimeout in coreutils via homebrew for mac users.

Check if input is integer type in C

I've been searching for a simpler solution using only loops and if statements, and this is what I came up with. The program also works with negative integers and correctly rejects any mixed inputs that may contain both integers and other characters.


#include <stdio.h>
#include <stdlib.h> // Used for atoi() function
#include <string.h> // Used for strlen() function

#define TRUE 1
#define FALSE 0

int main(void)
{
    char n[10]; // Limits characters to the equivalent of the 32 bits integers limit (10 digits)
    int intTest;
    printf("Give me an int: ");

    do
    {        
        scanf(" %s", n);

        intTest = TRUE; // Sets the default for the integer test variable to TRUE

        int i = 0, l = strlen(n);
        if (n[0] == '-') // Tests for the negative sign to correctly handle negative integer values
            i++;
        while (i < l)
        {            
            if (n[i] < '0' || n[i] > '9') // Tests the string characters for non-integer values
            {              
                intTest = FALSE; // Changes intTest variable from TRUE to FALSE and breaks the loop early
                break;
            }
            i++;
        }
        if (intTest == TRUE)
            printf("%i\n", atoi(n)); // Converts the string to an integer and prints the integer value
        else
            printf("Retry: "); // Prints "Retry:" if tested FALSE
    }
    while (intTest == FALSE); // Continues to ask the user to input a valid integer value
    return 0;
}

How to prevent multiple definitions in C?

Including the implementation file (test.c) causes it to be prepended to your main.c and complied there and then again separately. So, the function test has two definitions -- one in the object code of main.c and once in that of test.c, which gives you a ODR violation. You need to create a header file containing the declaration of test and include it in main.c:

/* test.h */
#ifndef TEST_H
#define TEST_H
void test(); /* declaration */
#endif /* TEST_H */

What exactly is LLVM?

LLVM is a library that is used to construct, optimize and produce intermediate and/or binary machine code.

LLVM can be used as a compiler framework, where you provide the "front end" (parser and lexer) and the "back end" (code that converts LLVM's representation to actual machine code).

LLVM can also act as a JIT compiler - it has support for x86/x86_64 and PPC/PPC64 assembly generation with fast code optimizations aimed for compilation speed.

Unfortunately disabled since 2013, there was the ability to play with LLVM's machine code generated from C or C++ code at the demo page.

pandas: merge (join) two data frames on multiple columns

the problem here is that by using the apostrophes you are setting the value being passed to be a string, when in fact, as @Shijo stated from the documentation, the function is expecting a label or list, but not a string! If the list contains each of the name of the columns beings passed for both the left and right dataframe, then each column-name must individually be within apostrophes. With what has been stated, we can understand why this is inccorect:

new_df = pd.merge(A_df, B_df,  how='left', left_on='[A_c1,c2]', right_on = '[B_c1,c2]')

And this is the correct way of using the function:

new_df = pd.merge(A_df, B_df,  how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])

How to force 'cp' to overwrite directory instead of creating another one inside?

You can do this using -T option in cp.
See Man page for cp.

-T, --no-target-directory
    treat DEST as a normal file

So as per your example, following is the file structure.

$ tree test
test
|-- bar
|   |-- a
|   `-- b
`-- foo
    |-- a
    `-- b
2 directories, 4 files

You can see the clear difference when you use -v for Verbose.
When you use just -R option.

$ cp -Rv foo/ bar/
`foo/' -> `bar/foo'
`foo/b' -> `bar/foo/b'
`foo/a' -> `bar/foo/a'
 $ tree
 |-- bar
 |   |-- a
 |   |-- b
 |   `-- foo
 |       |-- a
 |       `-- b
 `-- foo
     |-- a
     `-- b
3 directories, 6 files

When you use the option -T it overwrites the contents, treating the destination like a normal file and not directory.

$ cp -TRv foo/ bar/
`foo/b' -> `bar/b'
`foo/a' -> `bar/a'

$ tree
|-- bar
|   |-- a
|   `-- b
`-- foo
    |-- a
    `-- b
2 directories, 4 files

This should solve your problem.

Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

This might work for you

public void save(String fileName) throws FileNotFoundException {
FileOutputStream fout= new FileOutputStream (fileName);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(clubs);
fout.close();
}

To read back you can have

public void read(String fileName) throws FileNotFoundException {
FileInputStream fin= new FileInputStream (fileName);
ObjectInputStream ois = new ObjectInputStream(fin);
clubs= (ArrayList<Clubs>)ois.readObject();
fin.close();
}

Improve subplot size/spacing with many subplots in matplotlib

Try using plt.tight_layout

As a quick example:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)
fig.tight_layout() # Or equivalently,  "plt.tight_layout()"

plt.show()

Without Tight Layout

enter image description here


With Tight Layout enter image description here

How to create a pulse effect using -webkit-animation - outward rings

You have a lot of unnecessary keyframes. Don't think of keyframes as individual frames, think of them as "steps" in your animation and the computer fills in the frames between the keyframes.

Here is a solution that cleans up a lot of code and makes the animation start from the center:

.gps_ring {
    border: 3px solid #999;
    -webkit-border-radius: 30px;
    height: 18px;
    width: 18px;
    position: absolute;
    left:20px;
    top:214px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    opacity: 0.0
}
@-webkit-keyframes pulsate {
    0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
    50% {opacity: 1.0;}
    100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}

You can see it in action here: http://jsfiddle.net/Fy8vD/

How to take character input in java

you can use a Scanner to read from input :

Scanner scanner = new Scanner(System.in); 
char c = scanner.next().charAt(0); //charAt() method returns the character at the specified index in a string. The index of the first character is 0, the second character is 1, and so on.

LINQ - Full Outer Join

Thank You everybody for the interesting posts!

I modified the code because in my case I needed

  • a personalized join predicate
  • a personalized union distinct comparer

For the ones interested this is my modified code (in VB, sorry)

    Module MyExtensions
        <Extension()>
        Friend Function FullOuterJoin(Of TA, TB, TResult)(ByVal a As IEnumerable(Of TA), ByVal b As IEnumerable(Of TB), ByVal joinPredicate As Func(Of TA, TB, Boolean), ByVal projection As Func(Of TA, TB, TResult), ByVal comparer As IEqualityComparer(Of TResult)) As IEnumerable(Of TResult)
            Dim joinL =
                From xa In a
                From xb In b.Where(Function(x) joinPredicate(xa, x)).DefaultIfEmpty()
                Select projection(xa, xb)
            Dim joinR =
                From xb In b
                From xa In a.Where(Function(x) joinPredicate(x, xb)).DefaultIfEmpty()
                Select projection(xa, xb)
            Return joinL.Union(joinR, comparer)
        End Function
    End Module

    Dim fullOuterJoin = lefts.FullOuterJoin(
        rights,
        Function(left, right) left.Code = right.Code And (left.Amount [...] Or left.Description.Contains [...]),
        Function(left, right) New CompareResult(left, right),
        New MyEqualityComparer
    )

    Public Class MyEqualityComparer
        Implements IEqualityComparer(Of CompareResult)

        Private Function GetMsg(obj As CompareResult) As String
            Dim msg As String = ""
            msg &= obj.Code & "_"
            [...]
            Return msg
        End Function

        Public Overloads Function Equals(x As CompareResult, y As CompareResult) As Boolean Implements IEqualityComparer(Of CompareResult).Equals
            Return Me.GetMsg(x) = Me.GetMsg(y)
        End Function

        Public Overloads Function GetHashCode(obj As CompareResult) As Integer Implements IEqualityComparer(Of CompareResult).GetHashCode
            Return Me.GetMsg(obj).GetHashCode
        End Function
    End Class

The operation cannot be completed because the DbContext has been disposed error

This can be as simple as adding ToList() in your repository. For example:

public IEnumerable<MyObject> GetMyObjectsForId(string id)
{
    using (var ctxt = new RcContext())
    {
        // causes an error
        return ctxt.MyObjects.Where(x => x.MyObjects.Id == id);
    }
}

Will yield the Db Context disposed error in the calling class but this can be resolved by explicitly exercising the enumeration by adding ToList() on the LINQ operation:

public IEnumerable<MyObject> GetMyObjectsForId(string id)
{
    using (var ctxt = new RcContext())
    {
        return ctxt.MyObjects.Where(x => x.MyObjects.Id == id).ToList();
    }
}

Where is NuGet.Config file located in Visual Studio project?

There are multiple nuget packages read in the following order:

  1. First the NuGetDefaults.Config file. You will find this in %ProgramFiles(x86)%\NuGet\Config.
  2. The computer-level file.
  3. The user-level file. You will find this in %APPDATA%\NuGet\nuget.config.
  4. Any file named nuget.config beginning from the root of your drive up to the directory where nuget.exe is called.
  5. The config file you specify in the -configfile option when calling nuget.exe

You can find more information here.

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

VBA subs are no macros. A VBA sub can be a macro, but it is not a must.

The term "macro" is only used for recorded user actions. from these actions a code is generated and stored in a sub. This code is simple and do not provide powerful structures like loops, for example Do .. until, for .. next, while.. do, and others.

The more elegant way is, to design and write your own VBA code without using the macro features!

VBA is a object based and event oriented language. Subs, or bette call it "sub routines", are started by dedicated events. The event can be the pressing of a button or the opening of a workbook and many many other very specific events.

If you focus to VB6 and not to VBA, then you can state, that there is always a main-window or main form. This form is started if you start the compiled executable "xxxx.exe".

In VBA you have nothing like this, but you have a XLSM file wich is started by Excel. You can attach some code to the Workbook_Open event. This event is generated, if you open your desired excel file which is called a workbook. Inside the workbook you have worksheets.

It is useful to get more familiar with the so called object model of excel. The workbook has several events and methods. Also the worksheet has several events and methods.

In the object based model you have objects, that have events and methods. methods are action you can do with a object. events are things that can happen to an object. An objects can contain another objects, and so on. You can create new objects, like sheets or charts.

Check if Cell value exists in Column, and then get the value of the NEXT Cell

How about this?

=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", INDIRECT(ADDRESS(MATCH(A1,B:B, 0), 3)))

The "3" at the end means for column C.

Pass by pointer & Pass by reference

Here is a good article on the matter - "Use references when you can, and pointers when you have to."

Java - How to find the redirected url of a url?

@balusC I did as you wrote . In my case , I've added cookie information to be able to reuse the session .

   // get the cookie if need
    String cookies = conn.getHeaderField("Set-Cookie");

    // open the new connnection again
    conn = (HttpURLConnection) new URL(newUrl).openConnection();
    conn.setRequestProperty("Cookie", cookies);

How can I store and retrieve images from a MySQL database using PHP?

Beware that serving images from DB is usually much, much much slower than serving them from disk.

You'll be starting a PHP process, opening a DB connection, having the DB read image data from the same disk and RAM for cache as filesystem would, transferring it over few sockets and buffers and then pushing out via PHP, which by default makes it non-cacheable and adds overhead of chunked HTTP encoding.

OTOH modern web servers can serve images with just few optimized kernel calls (memory-mapped file and that memory area passed to TCP stack), so that they don't even copy memory around and there's almost no overhead.

That's a difference between being able to serve 20 or 2000 images in parallel on one machine.

So don't do it unless you absolutely need transactional integrity (and actually even that can be done with just image metadata in DB and filesystem cleanup routines) and know how to improve PHP's handling of HTTP to be suitable for images.

Shell script to copy files from one location to another location and rename add the current date to every file

You could use a script like the below. You would just need to change the date options to match the format you wanted.

#!/bin/bash

for i in `ls -l /directroy`
do
cp $i /newDirectory/$i.`date +%m%d%Y`
done

How to square all the values in a vector in R?

This will also work

newData <- data*data

What is the current choice for doing RPC in Python?

Apache Thrift is a cross-language RPC option developed at Facebook. Works over sockets, function signatures are defined in text files in a language-independent way.

How to implement a binary tree?

you don't need to have two classes

class Tree:
    val = None
    left = None
    right = None

    def __init__(self, val):
        self.val = val


    def insert(self, val):
        if self.val is not None:
            if val < self.val:
                if self.left is not None:
                    self.left.insert(val)
                else:
                    self.left = Tree(val)
            elif val > self.val:
                if self.right is not None:
                    self.right.insert(val)
                else:
                    self.right = Tree(val)
            else:
                return
        else:
            self.val = val
            print("new node added")

    def showTree(self):
        if self.left is not None:
            self.left.showTree()
        print(self.val, end = ' ')
        if self.right is not None:
            self.right.showTree()

What does 'synchronized' mean?

synchronized simple means no two threads can access the block/method simultaneously. When we say any block/method of a class is synchronized it means only one thread can access them at a time. Internally the thread which tries to access it first take a lock on that object and as long as this lock is not available no other thread can access any of the synchronized methods/blocks of that instance of the class.

Note another thread can access a method of the same object which is not defined to be synchronized. A thread can release the lock by calling

Object.wait()

Set width of dropdown element in HTML select dropdown options

u can simply use "width" attribute of "style" to change the length of the dropdown box

<select class="my_dropdown" id="my_dropdown" style="width:APPROPRIATE WIDTH IN PIXLES">
<option value="1">LONG OPTION</option>
<option value="2">short</option>
</select>

e.g.

style="width:200px"

How to make a new line or tab in <string> XML (eclipse/android)?

Use \t to add tab and \n for new line, here is a simple example below.

<string name="list_with_tab_tag">\tbanana\torange\tblueberry\tmango</string>
<string name="sentence_with_new_line_tag">This is the first sentence\nThis is the second scentence\nThis is the third sentence</string>

How to execute Python scripts in Windows?

When you execute a script without typing "python" in front, you need to know two things about how Windows invokes the program. First is to find out what kind of file Windows thinks it is:

    C:\>assoc .py
    .py=Python.File

Next, you need to know how Windows is executing things with that extension. It's associated with the file type "Python.File", so this command shows what it will be doing:

    C:\>ftype Python.File
    Python.File="c:\python26\python.exe" "%1" %*

So on my machine, when I type "blah.py foo", it will execute this exact command, with no difference in results than if I had typed the full thing myself:

    "c:\python26\python.exe" "blah.py" foo

If you type the same thing, including the quotation marks, then you'll get results identical to when you just type "blah.py foo". Now you're in a position to figure out the rest of your problem for yourself.

(Or post more helpful information in your question, like actual cut-and-paste copies of what you see in the console. Note that people who do that type of thing get their questions voted up, and they get reputation points, and more people are likely to help them with good answers.)

Brought In From Comments:

Even if assoc and ftype display the correct information, it may happen that the arguments are stripped off. What may help in that case is directly fixing the relevant registry keys for Python. Set the

HKEY_CLASSES_ROOT\Applications\python26.exe\shell\open\command

key to:

"C:\Python26\python26.exe" "%1" %*

Likely, previously, %* was missing. Similarly, set

 HKEY_CLASSES_ROOT\py_auto_file\shell\open\command

to the same value. See http://eli.thegreenplace.net/2010/12/14/problem-passing-arguments-to-python-scripts-on-windows/

example registry setting for python.exe HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command The registry path may vary, use python26.exe or python.exe or whichever is already in the registry.

enter image description here HKEY_CLASSES_ROOT\py_auto_file\shell\open\command

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

Just delete these lines from the root build.gradle

android {
compileSdkVersion 19
buildToolsVersion '19.1' }

Now trying and compile again. It should work.

Getting an "ambiguous redirect" error

if you are using a variable name in the shell command, you must concatenate it with + sign.

for example :

if you have two files, and you are not going to hard code the file name, instead you want to use the variable name
"input.txt" = x
"output.txt" = y

then ('shell command within quotes' + x > + y)

it will work this way especially if you are using this inside a python program with os.system command probably

Connection Strings for Entity Framework

Unfortunately, combining multiple entity contexts into a single named connection isn't possible. If you want to use named connection strings from a .config file to define your Entity Framework connections, they will each have to have a different name. By convention, that name is typically the name of the context:

<add name="ModEntity" connectionString="metadata=res://*/ModEntity.csdl|res://*/ModEntity.ssdl|res://*/ModEntity.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=SomeServer;Initial Catalog=SomeCatalog;Persist Security Info=True;User ID=Entity;Password=SomePassword;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
<add name="Entity" connectionString="metadata=res://*/Entity.csdl|res://*/Entity.ssdl|res://*/Entity.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=SOMESERVER;Initial Catalog=SOMECATALOG;Persist Security Info=True;User ID=Entity;Password=Entity;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />

However, if you end up with namespace conflicts, you can use any name you want and simply pass the correct name to the context when it is generated:

var context = new Entity("EntityV2");

Obviously, this strategy works best if you are using either a factory or dependency injection to produce your contexts.

Another option would be to produce each context's entire connection string programmatically, and then pass the whole string in to the constructor (not just the name).

// Get "Data Source=SomeServer..."
var innerConnectionString = GetInnerConnectionStringFromMachinConfig();
// Build the Entity Framework connection string.
var connectionString = CreateEntityConnectionString("Entity", innerConnectionString);
var context = new EntityContext(connectionString);

How about something like this:

Type contextType = typeof(test_Entities);
string innerConnectionString = ConfigurationManager.ConnectionStrings["Inner"].ConnectionString;
string entConnection = 
    string.Format(
        "metadata=res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl;provider=System.Data.SqlClient;provider connection string=\"{1}\"",
        contextType.Name,
        innerConnectionString);
object objContext = Activator.CreateInstance(contextType, entConnection);
return objContext as test_Entities; 

... with the following in your machine.config:

<add name="Inner" connectionString="Data Source=SomeServer;Initial Catalog=SomeCatalog;Persist Security Info=True;User ID=Entity;Password=SomePassword;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />

This way, you can use a single connection string for every context in every project on the machine.

How to calculate UILabel height dynamically?

In my case, I was using a fixed size header for each section but with a dynamically cell size in each header. The cell's height, depends on the label's height.

Working with:

tableView.estimatedRowHeight = SomeNumber
tableView.rowHeight = UITableViewAutomaticDimension

Works but when using:

tableView.reloadSections(IndexSet(integer: sender.tag) , with: .automatic)

when a lot of headers are not collapsed, creates a lot of bugs such as header duplication (header type x below the same type) and weird animations when the framework reloads with animation, even when using with type .none (FYI, a fixed header height and cell height works).

The solution is making the use of heightForRowAt callback and calculate the height of the label by your self (plus the animation looks a lot better). Remember that the height is being called first.

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
    let object = dataDetailsController.getRowObject(forIndexPath: indexPath)
    let label = UILabel(frame: tableView.frame)
    let font = UIFont(name: "HelveticaNeue-Bold", size: 25)
    label.text = object?.name
    label.font = font
    label.numberOfLines = 0
    label.textAlignment = .center
    label.sizeToFit()
    let size = label.frame.height
    return Float(size) == 0 ? 34 : size
}

How can I strip all punctuation from a string in JavaScript using regex?

It depends on what you are trying to return. I used this recently:

return text.match(/[a-z]/i);

check if a string matches an IP address pattern in python?

#!/usr/bin/python
import sys
def check_ip(address):
    part=address.split(".")
    temp=True
    if len(part) != 4:
            temp=False
            return temp
    for p in part:
            if not 0<= int(p) <= 255:
                    temp=False
                    return temp
            else:
                    temp=True
    return temp
if __name__=="__main__":
    print check_ip(sys.argv[1])

Save the code with some name say- check_ip.py and run it as python check_ip.py 192.168.560.25
Note:- Above code fails for the below ip address-
023.65.029.33

Accessing dict_keys element by index in Python3

Not a full answer but perhaps a useful hint. If it is really the first item you want*, then

next(iter(q))

is much faster than

list(q)[0]

for large dicts, since the whole thing doesn't have to be stored in memory.

For 10.000.000 items I found it to be almost 40.000 times faster.

*The first item in case of a dict being just a pseudo-random item before Python 3.6 (after that it's ordered in the standard implementation, although it's not advised to rely on it).

The endpoint reference (EPR) for the Operation not found is

Open WSDL file and find:

<soap:operation soapAction="[actionNameIsHere]" style="document"/>

Add to the requests header [request send to service]:

'soapAction' : '[actionNameIsHere]'

This work for me.

For devs. using node-soap [ https://github.com/vpulim/node-soap ] - example:

var soap = require('soap');
var options = {
   ...your options...
   forceSoap12Headers: true
}
soap.createClient(
        wsdl, options,
            function(err, client) {
                if(err) {
                    return callBack(err, result);
                }
                client.addHttpHeader('soapAction', '[actionNameIsHere]');
                ...your code - request send...
            });

How to source virtualenv activate in a Bash script

Sourcing runs shell commands in your current shell. When you source inside of a script like you are doing above, you are affecting the environment for that script, but when the script exits, the environment changes are undone, as they've effectively gone out of scope.

If your intent is to run shell commands in the virtualenv, you can do that in your script after sourcing the activate script. If your intent is to interact with a shell inside the virtualenv, then you can spawn a sub-shell inside your script which would inherit the environment.

Multidimensional arrays in Swift

For future readers, here is an elegant solution(5x5):

var matrix = [[Int]](repeating: [Int](repeating: 0, count: 5), count: 5)

and a dynamic approach:

var matrix = [[Int]]() // creates an empty matrix
var row = [Int]() // fill this row
matrix.append(row) // add this row

How to find integer array size in java

I think you are confused between size() and length.

(1) The reason why size has a parentheses is because list's class is List and it is a class type. So List class can have method size().

(2) Array's type is int[], and it is a primitive type. So we can only use length

How to get my project path?

This gives you the root folder:

System.AppDomain.CurrentDomain.BaseDirectory

You can navigate from here using .. or ./ etc.. , Appending .. takes you to folder where .sln file can be found

For .NET framework (thanks to Adiono comment)

Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"..\\..\\"))

For .NET core here is a way to do it (thanks to nopara73 comment)

Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..\\..\\..\\")) ;

Querying Windows Active Directory server using ldapsearch from command line

The short answer is "yes". A sample ldapsearch command to query an Active Directory server is:

ldapsearch \
    -x -h ldapserver.mydomain.com \
    -D "[email protected]" \
    -W \
    -b "cn=users,dc=mydomain,dc=com" \
    -s sub "(cn=*)" cn mail sn

This would connect to an AD server at hostname ldapserver.mydomain.com as user [email protected], prompt for the password on the command line and show name and email details for users in the cn=users,dc=mydomain,dc=com subtree.

See Managing LDAP from the Command Line on Linux for more samples. See LDAP Query Basics for Microsoft Exchange documentation for samples using LDAP queries with Active Directory.

Modify the legend of pandas bar plot

This is slightly an edge case but I think it can add some value to the other answers.

If you add more details to the graph (say an annotation or a line) you'll soon discover that it is relevant when you call legend on the axis: if you call it at the bottom of the script it will capture different handles for the legend elements, messing everything.

For instance the following script:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))

ax.legend(["AAA", "BBB"]); #quickfix: move this at the third line

Will give you this figure, which is wrong: enter image description here

While this a toy example which can be easily fixed by changing the order of the commands, sometimes you'll need to modify the legend after several operations and hence the next method will give you more flexibility. Here for instance I've also changed the fontsize and position of the legend:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]);

# do potentially more stuff here

h,l = ax.get_legend_handles_labels()
ax.legend(h[:2],["AAA", "BBB"], loc=3, fontsize=12)

This is what you'll get:

enter image description here

Remove all special characters with RegExp

var desired = stringToReplace.replace(/[^\w\s]/gi, '')

As was mentioned in the comments it's easier to do this as a whitelist - replace the characters which aren't in your safelist.

The caret (^) character is the negation of the set [...], gi say global and case-insensitive (the latter is a bit redundant but I wanted to mention it) and the safelist in this example is digits, word characters, underscores (\w) and whitespace (\s).

Regex match entire words only

If you are doing it in Notepad++

[\w]+ 

Would give you the entire word, and you can add parenthesis to get it as a group. Example: conv1 = Conv2D(64, (3, 3), activation=LeakyReLU(alpha=a), padding='valid', kernel_initializer='he_normal')(inputs). I would like to move LeakyReLU into its own line as a comment, and replace the current activation. In notepad++ this can be done using the follow find command:

([\w]+)( = .+)(LeakyReLU.alpha=a.)(.+)

and the replace command becomes:

\1\2'relu'\4 \n    # \1 = LeakyReLU\(alpha=a\)\(\1\)

The spaces is to keep the right formatting in my code. :)

Quickly create a large file on a Linux system

To make a 1 GB file:

dd if=/dev/zero of=filename bs=1G count=1

How to supply value to an annotation from a Constant java

Does someone know how I can use a String constant or String[] constant to supply value to an annotation?

Unfortunately, you can't do this with arrays. With non-array variables, the value must be final static.

Truncate a string straight JavaScript

Yes, substring works great:

stringTruncate('Hello world', 5); //output "Hello..."
stringTruncate('Hello world', 20);//output "Hello world"

var stringTruncate = function(str, length){
  var dots = str.length > length ? '...' : '';
  return str.substring(0, length)+dots;
};

javascript cell number validation

If number is your form element, then its length will be undefined since elements don't have length. You want

if (number.value.length != 10) { ... }

An easier way to do all the validation at once, though, would be with a regex:

var val = number.value
if (/^\d{10}$/.test(val)) {
    // value is ok, use it
} else {
    alert("Invalid number; must be ten digits")
    number.focus()
    return false
}

\d means "digit," and {10} means "ten times." The ^ and $ anchor it to the start and end, so something like asdf1234567890asdf does not match.

border-radius not working

Im just highlighting part of @Ethan May answer which is

overflow: hidden;

It would most probably do the work for your case.

JavaScript isset() equivalent

Provide the object path as a string, then you can break this string into a path and resolve hasOwnProperty at each step while overwriting the object itself with each iteration.

If you are coding in ES6 environment, take a look at this stackoverflow Ques.

_x000D_
_x000D_
var a;_x000D_
_x000D_
a = {_x000D_
    b: {_x000D_
        c: 'e'_x000D_
    }_x000D_
};_x000D_
_x000D_
function isset (obj, path) {_x000D_
    var stone;_x000D_
_x000D_
    path = path || '';_x000D_
_x000D_
    if (path.indexOf('[') !== -1) {_x000D_
        throw new Error('Unsupported object path notation.');_x000D_
    }_x000D_
_x000D_
    _x000D_
    path = path.split('.');_x000D_
    _x000D_
    do {_x000D_
        if (obj === undefined) {_x000D_
            return false;_x000D_
        }_x000D_
_x000D_
        stone = path.shift();_x000D_
        _x000D_
        if (!obj.hasOwnProperty(stone)) {_x000D_
            return false;_x000D_
        }_x000D_
        _x000D_
        obj = obj[stone];_x000D_
        _x000D_
    } while (path.length);_x000D_
_x000D_
    return true;_x000D_
}_x000D_
_x000D_
console.log(_x000D_
    isset(a, 'b') == true,_x000D_
    isset(a, 'b.c') == true,_x000D_
    isset(a, 'b.c.d') == false,_x000D_
    isset(a, 'b.c.d.e') == false,_x000D_
    isset(a, 'b.c.d.e.f') == false_x000D_
);
_x000D_
_x000D_
_x000D_

Arrays in type script

You can also do this as well (shorter cut) instead of having to do instance declaration. You do this in JSON instead.

class Book {
    public BookId: number;
    public Title: string;
    public Author: string;
    public Price: number;
    public Description: string;
}

var bks: Book[] = [];

 bks.push({BookId: 1, Title:"foo", Author:"foo", Price: 5, Description: "foo"});   //This is all done in JSON.

Easy way to concatenate two byte arrays

This is my way to do it!

public static byte[] concatByteArrays(byte[]... inputs) {
    int i = inputs.length - 1, len = 0;
    for (; i >= 0; i--) {
        len += inputs[i].length;
    }
    byte[] r = new byte[len];
    for (i = inputs.length - 1; i >= 0; i--) {
        System.arraycopy(inputs[i], 0, r, len -= inputs[i].length, inputs[i].length);
    }
    return r;
}

Features:

  • Use varargs (...) to be called with any number of byte[].
  • Use System.arraycopy() that is implemented with machine specific native code, to ensure high speed operation.
  • Create a new byte[] with the exact size that is need it.
  • Allocate little less int variables by reusing the i and len variables.
  • Faster comparison with constants.

Keep in mind:

The better way to do this, is by copy the @Jonathan code. The issue comes from the native variable arrays, because Java create new variables when this data type is passed to another function.

Spark java.lang.OutOfMemoryError: Java heap space

The location to set the memory heap size (at least in spark-1.0.0) is in conf/spark-env. The relevant variables are SPARK_EXECUTOR_MEMORY & SPARK_DRIVER_MEMORY. More docs are in the deployment guide

Also, don't forget to copy the configuration file to all the slave nodes.

JList add/remove Item

The problem is

listModel.addElement(listaRosa.getSelectedValue());
listModel.removeElement(listaRosa.getSelectedValue());

you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.

Try

private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                       

    DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
    DefaultListModel lm1  = (DefaultListModel) listaRosa.getModel();
    if(lm2 == null)
    {
        lm2 = new DefaultListModel();
        listaTitolari.setModel(lm2);
    }
    lm2.addElement(listaTitolari.getSelectedValue());
    lm1.removeElement(listaTitolari.getSelectedValue());        
} 

Group list by values

Howard's answer is concise and elegant, but it's also O(n^2) in the worst case. For large lists with large numbers of grouping key values, you'll want to sort the list first and then use itertools.groupby:

>>> from itertools import groupby
>>> from operator import itemgetter
>>> seq = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
>>> seq.sort(key = itemgetter(1))
>>> groups = groupby(seq, itemgetter(1))
>>> [[item[0] for item in data] for (key, data) in groups]
[['A', 'C'], ['B'], ['D', 'E']]

Edit:

I changed this after seeing eyequem's answer: itemgetter(1) is nicer than lambda x: x[1].

Most common C# bitwise operations on enums

To test a bit you would do the following: (assuming flags is a 32 bit number)

Test Bit:

if((flags & 0x08) == 0x08)
(If bit 4 is set then its true) Toggle Back (1 - 0 or 0 - 1):
flags = flags ^ 0x08;
Reset Bit 4 to Zero:
flags = flags & 0xFFFFFF7F;

Why am I getting "Thread was being aborted" in ASP.NET?

I got this error when I did a Response.Redirect after a successful login of the user.

I fixed it by doing a FormsAuthentication.RedirectFromLoginPage instead.

Print second last column/field in awk

Small addition to Chris Kannon' accepted answer: only print if there actually is a second last column.

(
echo       | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1     | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1 2   | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1 2 3 | awk 'NF && NF-1 { print ( $(NF-1) ) }'
)

Find by key deep in a nested array

@Iulian Pinzaru's answer was almost exactly what I needed, but it doesn't work if your objects have any null values. This version fixes that.

function  deepSearch (object, key, predicate) {
  if (object.hasOwnProperty(key) && predicate(key, object[key]) === true) return object

  for (let i = 0; i < Object.keys(object).length; i++) {
    const nextObject = object[Object.keys(object)[i]];
    if (nextObject && typeof nextObject === "object") {
      let o = deepSearch(nextObject, key, predicate)
      if (o != null) return o
    }
  }
  return null
}

C++ delete vector, objects, free memory

If you need to use the vector over and over again and your current code declares it repeatedly within your loop or on every function call, it is likely that you will run out of memory. I suggest that you declare it outside, pass them as pointers in your functions and use:

my_arr.resize()

This way, you keep using the same memory sequence for your vectors instead of requesting for new sequences every time. Hope this helped. Note: resizing it to different sizes may add random values. Pass an integer such as 0 to initialise them, if required.

Display all post meta keys and meta values of the same post ID in wordpress

$myvals = get_post_meta( get_the_ID());
foreach($myvals as $key=>$val){
  foreach($val as $vals){
    if ($key=='Youtube'){
       echo $vals 
    }
   }
 }

Key = Youtube videos all meta keys for youtube videos and value

Get response from PHP file using AJAX

<?php echo 'apple'; ?> is pretty much literally all you need on the server.

as for the JS side, the output of the server-side script is passed as a parameter to the success handler function, so you'd have

success: function(data) {
   alert(data); // apple
}

if else statement in AngularJS templates

A possibility for Angular: I had to include an if - statement in the html part, I had to check if all variables of an URL that I produce are defined. I did it the following way and it seems to be a flexible approach. I hope it will be helpful for somebody.

The html part in the template:

    <div  *ngFor="let p of poemsInGrid; let i = index" >
        <a [routerLink]="produceFassungsLink(p[0],p[3])" routerLinkActive="active">
    </div>

And the typescript part:

  produceFassungsLink(titel: string, iri: string) {
      if(titel !== undefined && iri !== undefined) {
         return titel.split('/')[0] + '---' + iri.split('raeber/')[1];
      } else {
         return 'Linkinformation has not arrived yet';
      }
  }

Thanks and best regards,

Jan

Display PNG image as response to jQuery AJAX request

You'll need to send the image back base64 encoded, look at this: http://php.net/manual/en/function.base64-encode.php

Then in your ajax call change the success function to this:

$('.div_imagetranscrits').html('<img src="data:image/png;base64,' + data + '" />');

Printing all properties in a Javascript Object

Your syntax is incorrect. The var keyword in your for loop must be followed by a variable name, in this case its propName

var propValue;
for(var propName in nyc) {
    propValue = nyc[propName]

    console.log(propName,propValue);
}

I suggest you have a look here for some basics:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

How to tell whether a point is to the right or left side of a line

I wanted to provide with a solution inspired by physics.

Imagine a force applied along the line and you are measuring the torque of the force about the point. If the torque is positive (counterclockwise) then the point is to the "left" of the line, but if the torque is negative the point is the "right" of the line.

So if the force vector equals the span of the two points defining the line

fx = x_2 - x_1
fy = y_2 - y_1

you test for the side of a point (px,py) based on the sign of the following test

var torque = fx*(py-y_1)-fy*(px-x_1)
if  torque>0  then
     "point on left side"
else if torque <0 then
     "point on right side"  
else
     "point on line"
end if

What JSON library to use in Scala?

Play released its module for dealing with JSON independently from Play Framework, Play WS

Made a blog post about that, check it out at http://pedrorijo.com/blog/scala-json/

Using case classes, and Play WS (already included in Play Framework) you case convert between json and case classes with a simple one-liner implicit

case class User(username: String, friends: Int, enemies: Int, isAlive: Boolean)

object User {
  implicit val userJsonFormat = Json.format[User]
}

Installing MySQL in Docker fails with error message "Can't connect to local MySQL server through socket"

Check out what's in your database.yml file. If you already have your plain Rails app and simply wrapping it with Docker, you should change (inside database.yml):

socket: /var/run/mysqld/mysqld.sock #just comment it out

to

host: db 

where db is the name of my db-service from docker-compose.yml. And here's my docker-compose.yml:

version: '3'
services:
  web:
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    links:
      - db
  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: root

You start your app in console (in app folder) as docker-compose up. Then WAIT 1 MINUTE (let your mysql service to completely load) until some new logs stop appearing in console. Usually the last line should be like

db_1 | 2017-12-24T12:25:20.397174Z 0 [Note] End of list of non-natively partitioned tables

Then (in a new terminal window) apply:

docker-compose run web rake db:create

and then

docker-compose run web rake db:migrate

After you finish your work stop the loaded images with

docker-compose stop

Don't use docker-compose down here instead because if you do, you will erase your database content.

Next time when you want to resume your work apply:

docker-compose start

The rest of the things do exactly as explained here: https://docs.docker.com/compose/rails/

How do I ignore a directory with SVN?

Thanks for all the contributions above. I would just like to share some additional information from my experiences while ignoring files.


When the folders are already under revision control

After svn import and svn co the files, what we usually do for the first time.

All runtime cache, attachments folders will be under version control. so, before svn ps svn:ignore, we need to delete it from the repository.

With SVN version 1.5 above we can use svn del --keep-local your_folder, but for an earlier version, my solution is:

  1. svn export a clean copy of your folders (without .svn hidden folder)
  2. svn del the local and repository,
  3. svn ci
  4. Copy back the folders
  5. Do svn st and confirm the folders are flagged as '?'
  6. Now we can do svn ps according to the solutions

When we need more than one folder to be ignored

  • In one directory I have two folders that need to be set as svn:ignore
  • If we set one, the other will be removed.
  • Then we wonder we need svn pe

svn pe will need to edit the text file, and you can use this command if required to set your text editor using vi:

export SVN_EDITOR=vi
  1. With "o" you can open a new line
  2. Type in all the folder names you want to ignore
  3. Hit 'esc' key to escape from edit mode
  4. Type ":wq" then hit Enter to save and quit

The file looks something simply like this:

runtime
cache
attachments
assets

SSIS Text was truncated with status value 4

I suspect the or one or more characters had no match in the target code page part of the error.

If you remove the rows with values in that column, does it load? Can you identify, in other words, the rows which cause the package to fail? It could be the data is too long, or it could be that there's some funky character in there SQL Server doesn't like.

How do you connect to multiple MySQL databases on a single webpage?

Warning : mysql_xx functions are deprecated since php 5.5 and removed since php 7.0 (see http://php.net/manual/intro.mysql.php), use mysqli_xx functions or see the answer below from @Troelskn


You can make multiple calls to mysql_connect(), but if the parameters are the same you need to pass true for the '$new_link' (fourth) parameter, otherwise the same connection is reused. For example:

$dbh1 = mysql_connect($hostname, $username, $password); 
$dbh2 = mysql_connect($hostname, $username, $password, true); 

mysql_select_db('database1', $dbh1);
mysql_select_db('database2', $dbh2);

Then to query database 1 pass the first link identifier:

mysql_query('select * from tablename', $dbh1);

and for database 2 pass the second:

mysql_query('select * from tablename', $dbh2);

If you do not pass a link identifier then the last connection created is used (in this case the one represented by $dbh2) e.g.:

mysql_query('select * from tablename');

Other options

If the MySQL user has access to both databases and they are on the same host (i.e. both DBs are accessible from the same connection) you could:

  • Keep one connection open and call mysql_select_db() to swap between as necessary. I am not sure this is a clean solution and you could end up querying the wrong database.
  • Specify the database name when you reference tables within your queries (e.g. SELECT * FROM database2.tablename). This is likely to be a pain to implement.

Also please read troelskn's answer because that is a better approach if you are able to use PDO rather than the older extensions.

What is "Advanced" SQL?

At my previous job, we had a technical test which all candidates were asked to sit. 10ish questions, took about an hour. In all honesty though, 90% of failures could be screened out because they couldn't write an INNER JOIN statement. Not even an outer.

I'd consider that a prerequisite for any job description involving SQL and would leave well alone until that was mastered. From there though, talk to them - any further info on what they're actually looking for will, worst case scenario, be a useful list of things to learn as part of your professional development.

How do I create a self-signed certificate for code signing on Windows?

Updated Answer

If you are using the following Windows versions or later: Windows Server 2012, Windows Server 2012 R2, or Windows 8.1 then MakeCert is now deprecated, and Microsoft recommends using the PowerShell Cmdlet New-SelfSignedCertificate.

If you're using an older version such as Windows 7, you'll need to stick with MakeCert or another solution. Some people suggest the Public Key Infrastructure Powershell (PSPKI) Module.

Original Answer

While you can create a self-signed code-signing certificate (SPC - Software Publisher Certificate) in one go, I prefer to do the following:

Creating a self-signed certificate authority (CA)

makecert -r -pe -n "CN=My CA" -ss CA -sr CurrentUser ^
         -a sha256 -cy authority -sky signature -sv MyCA.pvk MyCA.cer

(^ = allow batch command-line to wrap line)

This creates a self-signed (-r) certificate, with an exportable private key (-pe). It's named "My CA", and should be put in the CA store for the current user. We're using the SHA-256 algorithm. The key is meant for signing (-sky).

The private key should be stored in the MyCA.pvk file, and the certificate in the MyCA.cer file.

Importing the CA certificate

Because there's no point in having a CA certificate if you don't trust it, you'll need to import it into the Windows certificate store. You can use the Certificates MMC snapin, but from the command line:

certutil -user -addstore Root MyCA.cer

Creating a code-signing certificate (SPC)

makecert -pe -n "CN=My SPC" -a sha256 -cy end ^
         -sky signature ^
         -ic MyCA.cer -iv MyCA.pvk ^
         -sv MySPC.pvk MySPC.cer

It is pretty much the same as above, but we're providing an issuer key and certificate (the -ic and -iv switches).

We'll also want to convert the certificate and key into a PFX file:

pvk2pfx -pvk MySPC.pvk -spc MySPC.cer -pfx MySPC.pfx

If you want to protect the PFX file, add the -po switch, otherwise PVK2PFX creates a PFX file with no passphrase.

Using the certificate for signing code

signtool sign /v /f MySPC.pfx ^
              /t http://timestamp.url MyExecutable.exe

(See why timestamps may matter)

If you import the PFX file into the certificate store (you can use PVKIMPRT or the MMC snapin), you can sign code as follows:

signtool sign /v /n "Me" /s SPC ^
              /t http://timestamp.url MyExecutable.exe

Some possible timestamp URLs for signtool /t are:

  • http://timestamp.verisign.com/scripts/timstamp.dll
  • http://timestamp.globalsign.com/scripts/timstamp.dll
  • http://timestamp.comodoca.com/authenticode

Full Microsoft documentation

Downloads

For those who are not .NET developers, you will need a copy of the Windows SDK and .NET framework. A current link is available here: SDK & .NET (which installs makecert in C:\Program Files\Microsoft SDKs\Windows\v7.1). Your mileage may vary.

MakeCert is available from the Visual Studio Command Prompt. Visual Studio 2015 does have it, and it can be launched from the Start Menu in Windows 7 under "Developer Command Prompt for VS 2015" or "VS2015 x64 Native Tools Command Prompt" (probably all of them in the same folder).

How to display multiple notifications in android

Simple notification_id needs to be changable.

Just create random number for notification_id.

    Random random = new Random();
    int m = random.nextInt(9999 - 1000) + 1000;

or you can use this method for creating random number as told by tieorange (this will never get repeated):

    int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);

and replace this line to add parameter for notification id as to generate random number

    notificationManager.notify(m, notification);

SQLAlchemy create_all() does not create tables

If someone is having issues with creating tables by using files dedicated to each model, be aware of running the "create_all" function from a file different from the one where that function is declared. So, if the filesystem is like this:

Root  
--app.py     <-- file from which app will be run
--models
----user.py      <-- file with "User" model
----order.py    <-- file with "Order" model
----database.py <-- file with database and "create_all" function declaration

Be careful about calling the "create_all" function from app.py.

This concept is explained better by the answer to this thread posted by @SuperShoot