Programs & Examples On #Cics

CICS (Customer Information Control System) is a transaction server that runs primarily on IBM mainframe systems under z/OS and z/VSE.

How do I check how many options there are in a dropdown menu?

$('#idofdropdown option').length;

That should do it.

Using FileUtils in eclipse

FileUtils is class from apache org.apache.commons.io package, you need to download org.apache.commons.io.jar and then configure that jar file in your class path.

Android SDK Setup under Windows 7 Pro 64 bit

Found a solution that modifies the android.bat to allow you to start and run the android sdk and avd manager on the x64 jdk. So far I've been able to start it updating, but I don't know what other implications running the emulator and compiling against the x64 jdk will have.

http://code.google.com/p/android/issues/detail?id=3917

good luck.

jQuery/JavaScript: accessing contents of an iframe

Have you tried the classic, waiting for the load to complete using jQuery's builtin ready function?

$(document).ready(function() {
    $('some selector', frames['nameOfMyIframe'].document).doStuff()
} );

K

What does getActivity() mean?

getActivity()- Return the Activity this fragment is currently associated with.

CMake does not find Visual C++ compiler

Menu ? Visual Studio 2015 ? MSBuild Command Prompt for Visual Studio 2015. Then CMake can find cl.exe.

set PATH="c:\Program Files (x86)\Windows Kits\10\bin\10.0.16299.0\x64\";%PATH%

Change the upper path to where your Windows SDK is installed.

CMake can find rc.exe.

cd to the path of CMakeLists.txt and do:

md .build
cd .build
cmake .. -G "Visual Studio 14 2015 Win64" -DCMAKE_BUILD_TYPE=Release
cmake --build .

The param after -G should be fetched by CMake. Use --help; you may or may not have the generator.

JPA OneToMany not deleting child

You can try this:

@OneToOne(cascade = CascadeType.REFRESH) 

or

@OneToMany(cascade = CascadeType.REFRESH)

Exit Shell Script Based on Process Exit Code

http://cfaj.freeshell.org/shell/cus-faq-2.html#11

  1. How do I get the exit code of cmd1 in cmd1|cmd2

    First, note that cmd1 exit code could be non-zero and still don't mean an error. This happens for instance in

    cmd | head -1
    

    You might observe a 141 (or 269 with ksh93) exit status of cmd1, but it's because cmd was interrupted by a SIGPIPE signal when head -1 terminated after having read one line.

    To know the exit status of the elements of a pipeline cmd1 | cmd2 | cmd3

    a. with Z shell (zsh):

    The exit codes are provided in the pipestatus special array. cmd1 exit code is in $pipestatus[1], cmd3 exit code in $pipestatus[3], so that $? is always the same as $pipestatus[-1].

    b. with Bash:

    The exit codes are provided in the PIPESTATUS special array. cmd1 exit code is in ${PIPESTATUS[0]}, cmd3 exit code in ${PIPESTATUS[2]}, so that $? is always the same as ${PIPESTATUS: -1}.

    ...

    For more details see Z shell.

MySQL - Selecting data from multiple tables all with same structure but different data

The union statement cause a deal time in huge data. It is good to perform the select in 2 steps:

  1. select the id
  2. then select the main table with it

SQL Server: Attach incorrect version 661

SQL Server 2008 databases are version 655. SQL Server 2008 R2 databases are 661. You are trying to attach an 2008 R2 database (v. 661) to an 2008 instance and this is not supported. Once the database has been upgraded to an 2008 R2 version, it cannot be downgraded. You'll have to either upgrade your 2008 SP2 instance to R2, or you have to copy out the data in that database into an 2008 database (eg using the data migration wizard, or something equivalent).

The message is misleading, to say the least, it says 662 because SQL Server 2008 SP2 does support 662 as a database version, this is when 15000 partitions are enabled in the database, see Support for 15000 Partitions.docx. Enabling the support bumps the DB version to 662, disabling it moves it back to 655. But SQL Server 2008 SP2 does not support 661 (the R2 version).

Get user profile picture by Id

From the Graph API documentation.

  • /OBJECT_ID/picture returns a redirect to the object's picture (in this case the users)
  • /OBJECT_ID/?fields=picture returns the picture's URL

Examples:

<img src="https://graph.facebook.com/4/picture"/> uses a HTTP 301 redirect to Zuck's profile picture

https://graph.facebook.com/4?fields=picture returns the URL itself

Center Align on a Absolutely Positioned Div

To center it both vertically and horizontally do this:

div#thing {
   position: absolute;
   left: 50%;
   top: 50%;
   transform: translate(-50%, -50%);
}

how to use Spring Boot profiles

The @Profile annotation allows you to indicate that a component is eligible for registration when one or more specified profiles are active. Using our example above, we can rewrite the dataSource configuration as follows:

@Configuration
@Profile("dev")
public class StandaloneDataConfig {

    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.HSQL)
            .addScript("classpath:com/bank/config/sql/schema.sql")
            .addScript("classpath:com/bank/config/sql/test-data.sql")
            .build();
    }
}

And other one:

@Configuration
@Profile("production")
public class JndiDataConfig {

    @Bean(destroyMethod="")
    public DataSource dataSource() throws Exception {
        Context ctx = new InitialContext();
        return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
    }
}

How to find the Windows version from the PowerShell command line

If you want to differentiate between Windows 8.1 (6.3.9600) and Windows 8 (6.2.9200) use

(Get-CimInstance Win32_OperatingSystem).Version 

to get the proper version. [Environment]::OSVersion doesn't work properly in Windows 8.1 (it returns a Windows 8 version).

Excel: replace part of cell's string value

You have a character = STQ8QGpaM4CU6149665!7084880820, and you have a another column = 7084880820.

If you want to get only this in excel using the formula: STQ8QGpaM4CU6149665!, use this:

=REPLACE(H11,SEARCH(J11,H11),LEN(J11),"")

H11 is an old character and for starting number use search option then for no of character needs to replace use len option then replace to new character. I am replacing this to blank.

Generate HTML table from 2D JavaScript array

An es6 version of Daniel Williams' answer:

  function get_table(data) {
    let result = ['<table border=1>'];
    for(let row of data) {
        result.push('<tr>');
        for(let cell of row){
            result.push(`<td>${cell}</td>`);
        }
        result.push('</tr>');
    }
    result.push('</table>');
    return result.join('\n');
  }

How do you find out the type of an object (in Swift)?

//: Playground - noun: a place where people can play

import UIKit

class A {
    class func a() {
        print("yeah")
    }

    func getInnerValue() {
        self.dynamicType.a()
    }
}

class B: A {
    override class func a() {
        print("yeah yeah")
    }
}

B.a() // yeah yeah
A.a() // yeah
B().getInnerValue() // yeah yeah
A().getInnerValue() // yeah

How to switch between frames in Selenium WebDriver using Java

to switchto a frame:

driver.switchTo.frame("Frame_ID");

to switch to the default again.

driver.switchTo().defaultContent();

How do I collapse sections of code in Visual Studio Code for Windows?

v1.42 is adding some nice refinements to how folds look and function. See https://github.com/microsoft/vscode-docs/blob/vnext/release-notes/v1_42.md#folded-range-highlighting:

Folded Range Highlighting

Folded ranges now are easier to discover thanks to a background color for all folded ranges.

fold highlight

Fold highlight color Theme: Dark+

The feature is controled by the setting editor.foldingHighlight and the color can be customized with the color editor.foldBackground.

"workbench.colorCustomizations": { "editor.foldBackground": "#355000" }

Folding Refinements

Shift + Click on the folding indicator first only folds the inner ranges. Shift + Click again (when all inner ranges are already folded) will also fold the parent. Shift + Click again unfolds all.

fold shift click

When using the Fold command (kb(editor.fold))] on an already folded range, the next unfolded parent range will be folded.

How do I show a running clock in Excel?

See the below code (taken from this post)

Put this code in a Module in VBA (Developer Tab -> Visual Basic)

Dim TimerActive As Boolean
Sub StartTimer()
    Start_Timer
End Sub
Private Sub Start_Timer()
    TimerActive = True
    Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End Sub
Private Sub Stop_Timer()
    TimerActive = False
End Sub
Private Sub Timer()
    If TimerActive Then
        ActiveSheet.Cells(1, 1).Value = Time
        Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
    End If
End Sub

You can invoke the "StartTimer" function when the workbook opens and have it repeat every minute by adding the below code to your workbooks Visual Basic "This.Workbook" class in the Visual Basic editor.

Private Sub Workbook_Open()
    Module1.StartTimer
End Sub

Now, every time 1 minute passes the Timer procedure will be invoked, and set cell A1 equal to the current time.

how to count length of the JSON array element

I think you should try

data = {"shareInfo":[{"id":"1","a":"sss","b":"sss","question":"whi?"},
{"id":"2","a":"sss","b":"sss","question":"whi?"},
{"id":"3","a":"sss","b":"sss","question":"whi?"},
{"id":"4","a":"sss","b":"sss","question":"whi?"}]};

ShareInfoLength = data.shareInfo.length;
alert(ShareInfoLength);
for(var i=0; i<ShareInfoLength; i++)
{
alert(Object.keys(data.shareInfo[i]).length);
}

Add custom message to thrown exception while maintaining stack trace in Java

Exceptions are usually immutable: you can't change their message after they've been created. What you can do, though, is chain exceptions:

throw new TransactionProblemException(transNbr, originalException);

The stack trace will look like

TransactionProblemException : transNbr
at ...
at ...
caused by OriginalException ...
at ...
at ...

Rails 4 image-path, image-url and asset-url no longer work in SCSS files

Rails 4.0.0 will look image defined with image-url in same directory structure with your css file.

For example, if your css in assets/stylesheets/main.css.scss, image-url('logo.png') becomes url(/assets/logo.png).

If you move your css file to assets/stylesheets/cpanel/main.css.scss, image-url('logo.png') becomes /assets/cpanel/logo.png.

If you want to use image directly under assets/images directory, you can use asset-url('logo.png')

HTML.HiddenFor value set

The @ symbol when specifying HtmlAttributes is used when the "thing" you are trying to set is a keyword c#. So for instance the word class, you cannot specify class, you must use @class.

Loop through all the rows of a temp table and call a stored procedure for each row

you could use a cursor:

DECLARE @id int
DECLARE @pass varchar(100)

DECLARE cur CURSOR FOR SELECT Id, Password FROM @temp
OPEN cur

FETCH NEXT FROM cur INTO @id, @pass

WHILE @@FETCH_STATUS = 0 BEGIN
    EXEC mysp @id, @pass ... -- call your sp here
    FETCH NEXT FROM cur INTO @id, @pass
END

CLOSE cur    
DEALLOCATE cur

Adding a column to a dataframe in R

That is a pretty standard use case for apply():

R> vec <- 1:10
R> DF <- data.frame(start=c(1,3,5,7), end=c(2,6,7,9))
R> DF$newcol <- apply(DF,1,function(row) mean(vec[ row[1] : row[2] ] ))
R> DF
  start end newcol
1     1   2    1.5
2     3   6    4.5
3     5   7    6.0
4     7   9    8.0
R> 

You can also use plyr if you prefer but here is no real need to go beyond functions from base R.

How to create multiple output paths in Webpack config

I actually wound up just going into index.js in the file-loader module and changing where the contents were emitted to. This is probably not the optimal solution, but until there's some other way, this is fine since I know exactly what's being handled by this loader, which is just fonts.

//index.js
var loaderUtils = require("loader-utils");
module.exports = function(content) {
    this.cacheable && this.cacheable();
    if(!this.emitFile) throw new Error("emitFile is required from module system");
    var query = loaderUtils.parseQuery(this.query);
    var url = loaderUtils.interpolateName(this, query.name || "[hash].[ext]", {
        context: query.context || this.options.context,
        content: content,
        regExp: query.regExp
    });
    this.emitFile("fonts/"+ url, content);//changed path to emit contents to "fonts" folder rather than project root
    return "module.exports = __webpack_public_path__ + " + JSON.stringify( url) + ";";
}
module.exports.raw = true;

MVC3 EditorFor readOnly

<div class="editor-field">
        @Html.EditorFor(model => model.userName)
</div>

Use jquery to disable

<script type="text/javascript">
   $(document).ready(function () {
      $('#userName').attr('disabled', true);
     });
</script>

Android: How do bluetooth UUIDs work?

It usually represents some common service (protocol) that bluetooth device supports.

When creating your own rfcomm server (with listenUsingRfcommWithServiceRecord), you should specify your own UUID so that the clients connecting to it could identify it; it is one of the reasons why createRfcommSocketToServiceRecord requires an UUID parameter.

Otherwise, some common services have the same UUID, just find one you need and use it.

See here

HashMap and int as key

I don't understand why I should add a dimension (ie: making the int into an array) since I only need to store a digit as key.

An array is also an Object, so HashMap<int[], MyObject> is a valid construct that uses int arrays as keys.

Compiler doesn't know what you want or what you need, it just sees a language construct that is almost correct, and warns what's missing for it to be fully correct.

Change the Value of h1 Element within a Form with JavaScript

Try:


document.getElementById("yourH1_element_Id").innerHTML = "yourTextHere";

Structs data type in php?

Only associative arrays are structs in PHP.

And you can't make them strict on their own.

But you can sort of fake structure strictness with classes and interfaces, but beware that unlike structures, class instances are not passed in arguments, their identifiers are!


You can define a struct through an interface (or at least close to it)

Structs enforce a certain structure on an object.

PHP (<= 7.3) does not have native structs, but you can get around it with interfaces and type hinting:

interface FooStruct 
{
    public function name() : string;
}
interface BarStruct 
{
    public function id() : int;
}
interface MyStruct 
{
   public function foo() : FooStruct;
   public function bar() : BarStruct;
}

Any class implementing MyStruct will be a MyStruct.

The way it's build up is not up to the struct, it just ensures that the data returned is correct.


What about setting data?

Setting struct data is problematic as we end up with getters and setters and it's something that is close to an anemic object or a DTO and is considered an anti-pattern by some people

Wrong example:

interface FooStruct 
{
    public function getName() : string;
    public function setName(string $value) : FooStruct;
}
interface BarStruct 
{
    public function getId() : int;
    public function setId(int $value) : BarStruct;
}
interface MyStruct 
{
   public function getFoo() : FooStruct;
   public function setFoo(FooStruct $value) : MyStruct;
   public function getBar() : BarStruct;
   public function setBar(BarStruct $value) : MyStruct;
}

Then we end up with class implementations that might be mutable, and a struct must not mutate, this is to make it a "data type", just like int, string. Yet there's no way to restrict that with interfaces in PHP, meaning people will be able to implement your struct interface in a class that is not a struct. Make sure to keep the instance immutable

Also a struct may then be instantiated without the correct data and trigger errors when trying to access the data.

An easy and reliable way to set data in a PHP struct class is through its constructor

interface FooStruct 
{
    public function name() : string;
}
interface BarStruct 
{
    public function id() : int;
}
interface MyStruct 
{
   public function foo() : FooStruct;
   public function bar() : BarStruct;
}

class Foo implements FooStruct 
{
   protected $name;
   public function __construct(string $name)
   {
       $this->name = $name;
   }
   public function name() : string
   {
       return $this->name;
   }
}

class Bar implements BarStruct 
{
   protected $id;
   public function __construct(string $id)
   {
       $this->id = $id;
   }
   public function id() : int
   {
       return $this->id;
   }
}

class My implements MyStruct 
{
   protected $foo, $bar;
   public function __construct(FooStruct $foo, BarStruct $bar)
   {
       $this->foo = $foo;
       $this->bar = $bar;
   }
   public function foo() : FooStruct
   {
       return $this->foo;
   }
   public function bar() : BarStruct
   {
       return $this->bar;
   }
}

Type hinting using interfaces: (if your IDE supports it)

If you don't mind not having the strict type checking, then another way would be using interfaces or classes with comments for the IDE.

/**
 * Interface My
 * @property Foo $foo
 * @property Bar $bar
 */
interface My 
{

}

/**
 * Interface Foo
 * @property string|integer $id
 * @property string $name
 */
interface Foo 
{

}

/**
 * Interface Bar
 * @property integer $id
 */
interface Bar
{

}

The reason to use interfaces instead of classes is for the same reason why interfaces exist in the first place, because then many classes with many implementations can have this same structure and each method/function that uses it will support every class with this interface.

This depends on your IDE, so you might need to use classes instead or just live without it.

Note: Remember that you have to validate/sanitize the data in the instance elsewhere in the code to match the comment.

How to get a list of installed android applications and pick one to run

Another way to filter on system apps (works with the example of king9981):

/**
 * Return whether the given PackageInfo represents a system package or not.
 * User-installed packages (Market or otherwise) should not be denoted as
 * system packages.
 * 
 * @param pkgInfo
 * @return
 */
private boolean isSystemPackage(PackageInfo pkgInfo) {
    return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
}

How to format x-axis time scale values in Chart.js v2

as per the Chart js documentation page tick configuration section. you can format the value of each tick using the callback function. for example I wanted to change locale of displayed dates to be always German. in the ticks parts of the axis options

ticks: {
    callback: function(value) { 
        return new Date(value).toLocaleDateString('de-DE', {month:'short', year:'numeric'}); 
    },
},

Why use Ruby's attr_accessor, attr_reader and attr_writer?

Not all attributes of an object are meant to be directly set from outside the class. Having writers for all your instance variables is generally a sign of weak encapsulation and a warning that you're introducing too much coupling between your classes.

As a practical example: I wrote a design program where you put items inside containers. The item had attr_reader :container, but it didn't make sense to offer a writer, since the only time the item's container should change is when it's placed in a new one, which also requires positioning information.

How to compare strings in Bash

The following script reads from a file named "testonthis" line by line and then compares each line with a simple string, a string with special characters and a regular expression. If it doesn't match, then the script will print the line, otherwise not.

Space in Bash is so much important. So the following will work:

[ "$LINE" != "table_name" ] 

But the following won't:

["$LINE" != "table_name"] 

So please use as is:

cat testonthis | while read LINE
do
if [ "$LINE" != "table_name" ] && [ "$LINE" != "--------------------------------" ] && [[ "$LINE" =~ [^[:space:]] ]] && [[ "$LINE" != SQL* ]]; then
echo $LINE
fi
done

What is the purpose of nameof?

Let's say you need to print the name of a variable in your code. If you write:

int myVar = 10;
print("myVar" + " value is " + myVar.toString());

and then if someone refactors the code and uses another name for myVar, he/she would have to look for the string value in your code and change it accordingly.

Instead, if you write:

print(nameof(myVar) + " value is " + myVar.toString());

It would help to refactor automatically!

Fragment Inside Fragment

I solved this problem. You can use Support library and ViewPager. If you don't need swiping by gesture you can disable swiping. So here is some code to improve my solution:

public class TestFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.frag, container, false);
    final ArrayList<Fragment> list = new ArrayList<Fragment>();

    list.add(new TrFrag());
    list.add(new TrFrag());
    list.add(new TrFrag());

    ViewPager pager = (ViewPager) v.findViewById(R.id.pager);
    pager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
        @Override
        public Fragment getItem(int i) {
            return list.get(i);
        }

        @Override
        public int getCount() {
            return list.size();
        }
    });
    return v;
}
}

P.S.It is ugly code for test, but it improves that it is possible.

P.P.S Inside fragment ChildFragmentManager should be passed to ViewPagerAdapter

C++ Convert string (or char*) to wstring (or wchar_t*)

std::string -> wchar_t[] with safe mbstowcs_s function:

auto ws = std::make_unique<wchar_t[]>(s.size() + 1);
mbstowcs_s(nullptr, ws.get(), s.size() + 1, s.c_str(), s.size());

This is from my sample code

How to set menu to Toolbar in Android

Also you need this, to implement some action to every options of menu.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_help:
            Toast.makeText(this, "This is teh option help", Toast.LENGTH_LONG).show();
            break;
        default:
            break;
    }
    return true;
}

How can I tell gcc not to inline a function?

In case you get a compiler error for __attribute__((noinline)), you can just try:

noinline int func(int arg)
{
    ....
}

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

I know this is an old post and that it wants an answer for .NET 1.1 but there's already a very good answer for that. I thought it would be good to have an answer for those people who land on this post that may have a more recent version of the .Net framework, such as myself when I went looking for an answer to the same question.

In those cases there is an even simpler way to write the contents of a StringBuilder to a text file. It can be done with one line of code. It may not be the most efficient but that wasn't really the question now was it.

System.IO.File.WriteAllText(@"C:\MyDir\MyNewTextFile.txt",sbMyStringBuilder.ToString());

Open directory using C

Some feedback on the segment of code, though for the most part, it should work...

void main(int c,char **args)
  • int main - the standard defines main as returning an int.
  • c and args are typically named argc and argv, respectfully, but you are allowed to name them anything

...

{
DIR *dir;
struct dirent *dent;
char buffer[50];
strcpy(buffer,args[1]);
  • You have a buffer overflow here: If args[1] is longer than 50 bytes, buffer will not be able to hold it, and you will write to memory that you shouldn't. There's no reason I can see to copy the buffer here, so you can sidestep these issues by just not using strcpy...

...

dir=opendir(buffer);   //this part

If this returning NULL, it can be for a few reasons:

  • The directory didn't exist. (Did you type it right? Did it have a space in it, and you typed ./your_program my directory, which will fail, because it tries to opendir("my"))
  • You lack permissions to the directory
  • There's insufficient memory. (This is unlikely.)

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

I would like to suggest another framework: Apache Pivot http://pivot.apache.org/.

I tried it briefly and was impressed by what it can offer as an RIA (Rich Internet Application) framework ala Flash.

It renders UI using Java2D, thus minimizing the impact of (IMO, bloated) legacies of Swing and AWT.

How do I rotate a picture in WinForms

Richard Cox has a good solution to this https://stackoverflow.com/a/5200280/1171321 I have used in the past. It is also worth noting the DPI must be 96 for this to work correctly. Several of the solutions on this page do not work at all.

Why use argparse rather than optparse?

There are also new kids on the block!

  • Besides the already mentioned deprecated optparse. [DO NOT USE]
  • argparse was also mentioned, which is a solution for people not willing to include external libs.
  • docopt is an external lib worth looking at, which uses a documentation string as the parser for your input.
  • click is also external lib and uses decorators for defining arguments. (My source recommends: Why Click)
  • python-inquirer For selection focused tools and based on Inquirer.js (repo)

If you need a more in-depth comparison please read this and you may end up using docopt or click. Thanks to Kyle Purdon!

Remove all non-"word characters" from a String in Java, leaving accented characters?

You might want to remove the accents and diacritic signs first, then on each character position check if the "simplified" string is an ascii letter - if it is, the original position shall contain word characters, if not, it can be removed.

How can I represent an 'Enum' in Python?

I had need of some symbolic constants in pyparsing to represent left and right associativity of binary operators. I used class constants like this:

# an internal class, not intended to be seen by client code
class _Constants(object):
    pass


# an enumeration of constants for operator associativity
opAssoc = _Constants()
opAssoc.LEFT = object()
opAssoc.RIGHT = object()

Now when client code wants to use these constants, they can import the entire enum using:

import opAssoc from pyparsing

The enumerations are unique, they can be tested with 'is' instead of '==', they don't take up a big footprint in my code for a minor concept, and they are easily imported into the client code. They don't support any fancy str() behavior, but so far that is in the YAGNI category.

How to set value to variable using 'execute' in t-sql?

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Andrew Foster
-- Create date: 28 Mar 2013
-- Description: Allows the dynamic pull of any column value up to 255 chars from regUsers table
-- =============================================
ALTER PROCEDURE dbo.PullTableColumn
(
    @columnName varchar(255),
    @id int
)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    DECLARE @columnVal TABLE (columnVal nvarchar(255));

    DECLARE @sql nvarchar(max);
    SET @sql = 'SELECT ' + @columnName + ' FROM regUsers WHERE id=' + CAST(@id AS varchar(10));
    INSERT @columnVal EXEC sp_executesql @sql;

    SELECT * FROM @columnVal;
END
GO

res.sendFile absolute path

I use Node.Js and had the same problem... I solved just adding a '/' in the beggining of every script and link to an css static file.

Before:

<link rel="stylesheet" href="assets/css/bootstrap/bootstrap.min.css">

After:

<link rel="stylesheet" href="/assets/css/bootstrap/bootstrap.min.css">

How to get scrollbar position with Javascript?

If you are using jQuery there is a perfect function for you: .scrollTop()

doc here -> http://api.jquery.com/scrollTop/

note: you can use this function to retrieve OR set the position.

see also: http://api.jquery.com/?s=scroll

Turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server

It's in the app.config file.

<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceDebug includeExceptionDetailInFaults="true"/>

Increase distance between text and title on the y-axis

From ggplot2 2.0.0 you can use the margin = argument of element_text() to change the distance between the axis title and the numbers. Set the values of the margin on top, right, bottom, and left side of the element.

ggplot(mpg, aes(cty, hwy)) + geom_point()+
  theme(axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))

margin can also be used for other element_text elements (see ?theme), such as axis.text.x, axis.text.y and title.

addition

in order to set the margin for axis titles when the axis has a different position (e.g., with scale_x_...(position = "top"), you'll need a different theme setting - e.g. axis.title.x.top. See https://github.com/tidyverse/ggplot2/issues/4343.

How to install sklearn?

You didn't provide us which operating system are you on? If it is a Linux, make sure you have scipy installed as well, after that just do

pip install -U scikit-learn

If you are on windows you might want to check out these pages.

Cannot find libcrypto in Ubuntu

ld is trying to find libcrypto.sowhich is not present as seen in your locate output. You can make a copy of the libcrypto.so.0.9.8 and name it as libcrypto.so. Put this is your ld path. ( If you do not have root access then you can put it in a local path and specify the path manually )

$watch'ing for data changes in an Angular directive

You need to enable deep object dirty checking. By default angular only checks the reference of the top level variable that you watch.

App.directive('d3Visualization', function() {
    return {
        restrict: 'E',
        scope: {
            val: '='
        },
        link: function(scope, element, attrs) {
            scope.$watch('val', function(newValue, oldValue) {
                if (newValue)
                    console.log("I see a data change!");
            }, true);
        }
    }
});

see Scope. The third parameter of the $watch function enables deep dirty checking if it's set to true.

Take note that deep dirty checking is expensive. So if you just need to watch the children array instead of the whole data variable the watch the variable directly.

scope.$watch('val.children', function(newValue, oldValue) {}, true);

version 1.2.x introduced $watchCollection

Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties)

scope.$watchCollection('val.children', function(newValue, oldValue) {});

Could not connect to React Native development server on Android

and first of all I appreciate you for posting your doubt. It's mainly because maybe your expo or the app in which you run your react native project may not be in the same local connected wifi or LAN. Also, there is a chance that there is disturbance in your connection frequently due to which it loses its connectivity.

I too face this problem and I personally clear the cache and then restart again and boom it restarts perfectly. I hope this works for you too!

case statement in SQL, how to return multiple variables?

A CASE statement can return only one value.

You may be able to turn this into a subquery and then JOIN it to whatever other relations you're working with. For example (using SQL Server 2K5+ CTEs):

WITH C1 AS (
  SELECT a1 AS value1, b1 AS value2
  FROM table
  WHERE condition1
), C2 AS (
  SELECT a2 AS value1, b2 AS value2
  FROM table
  WHERE condition2
), C3 AS (
  SELECT a3 AS value1, b3 AS value2
  FROM table
  WHERE condition3
)
SELECT value1, value2
FROM -- some table, joining C1, C2, C3 CTEs to get the cased values
;

How Stuff and 'For Xml Path' work in SQL Server?

PATH mode is used in generating XML from a SELECT query

1. SELECT   
       ID,  
       Name  
FROM temp1
FOR XML PATH;  

Ouput:
<row>
<ID>1</ID>
<Name>aaa</Name>
</row>

<row>
<ID>1</ID>
<Name>bbb</Name>
</row>

<row>
<ID>1</ID>
<Name>ccc</Name>
</row>

<row>
<ID>1</ID>
<Name>ddd</Name>
</row>

<row>
<ID>1</ID>
<Name>eee</Name>
</row>

The Output is element-centric XML where each column value in the resulting rowset is wrapped in an row element. Because the SELECT clause does not specify any aliases for the column names, the child element names generated are the same as the corresponding column names in the SELECT clause.

For each row in the rowset a tag is added.

2.
SELECT   
       ID,  
       Name  
FROM temp1
FOR XML PATH('');

Ouput:
<ID>1</ID>
<Name>aaa</Name>
<ID>1</ID>
<Name>bbb</Name>
<ID>1</ID>
<Name>ccc</Name>
<ID>1</ID>
<Name>ddd</Name>
<ID>1</ID>
<Name>eee</Name>

For Step 2: If you specify a zero-length string, the wrapping element is not produced.

3. 

    SELECT   

           Name  
    FROM temp1
    FOR XML PATH('');

    Ouput:
    <Name>aaa</Name>
    <Name>bbb</Name>
    <Name>ccc</Name>
    <Name>ddd</Name>
    <Name>eee</Name>

4. SELECT   
        ',' +Name  
FROM temp1
FOR XML PATH('')

Ouput:
,aaa,bbb,ccc,ddd,eee

In Step 4 we are concatenating the values.

5. SELECT ID,
    abc = (SELECT   
            ',' +Name  
    FROM temp1
    FOR XML PATH('') )
FROM temp1

Ouput:
1   ,aaa,bbb,ccc,ddd,eee
1   ,aaa,bbb,ccc,ddd,eee
1   ,aaa,bbb,ccc,ddd,eee
1   ,aaa,bbb,ccc,ddd,eee
1   ,aaa,bbb,ccc,ddd,eee


6. SELECT ID,
    abc = (SELECT   
            ',' +Name  
    FROM temp1
    FOR XML PATH('') )
FROM temp1 GROUP by iD

Ouput:
ID  abc
1   ,aaa,bbb,ccc,ddd,eee

In Step 6 we are grouping the date by ID.

STUFF( source_string, start, length, add_string ) Parameters or Arguments source_string The source string to modify. start The position in the source_string to delete length characters and then insert add_string. length The number of characters to delete from source_string. add_string The sequence of characters to insert into the source_string at the start position.

SELECT ID,
    abc = 
    STUFF (
        (SELECT   
                ',' +Name  
        FROM temp1
        FOR XML PATH('')), 1, 1, ''
    )
FROM temp1 GROUP by iD

Output:
-----------------------------------
| Id        | Name                |
|---------------------------------|
| 1         | aaa,bbb,ccc,ddd,eee |
-----------------------------------

Creating a jQuery object from a big HTML-string

var jQueryObject = $('<div></div>').html( string ).children();

This creates a dummy jQuery object in which you can put the string as HTML. Then, you get the children only.

Data was not saved: object references an unsaved transient instance - save the transient instance before flushing

I had the same problem. In my case it arises, because the lookup-table "country" has an existing record with countryId==0 and a primitive primary key and I try to save a User with a countryID==0. Change the primary key of country to Integer. Now Hibernate can identify new records.

For the recommendation of using wrapper classes as primary key see this stackoverflow question

Want to show/hide div based on dropdown box selection

The core problem is the js errors:

$('#purpose').on('change', function () {
    // if (this.value == '1'); { No semicolon and I used === instead of ==
    if (this.value === '1'){
        $("#business").show();
    } else {
        $("#business").hide();
    }
});
// }); remove

http://jsfiddle.net/Bushwazi/2kGzZ/3/

I had to clean up the html & js...I couldn't help myself.

HTML:

<select id='purpose'>
    <option value="0">Personal use</option>
    <option value="1">Business use</option>
    <option value="2">Passing on to a client</option>
</select>
<form id="business">
    <label for="business">Business Name</label>
    <input type='text' class='text' name='business' value size='20' />
</form>

CSS:

#business {
  display:none;
}

JS:

$('#purpose').on('change', function () {
    if(this.value === "1"){
        $("#business").show();
    } else {
        $("#business").hide();
    }
});

Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier

You can only use - on the numeric entries, so you can use decreasing and negate the ones you want in increasing order:

DT[order(x,-v,decreasing=TRUE),]
      x y v
 [1,] c 1 7
 [2,] c 3 8
 [3,] c 6 9
 [4,] b 1 1
 [5,] b 3 2
 [6,] b 6 3
 [7,] a 1 4
 [8,] a 3 5
 [9,] a 6 6

c++ integer->std::string conversion. Simple function?

Like mentioned earlier, I'd recommend boost lexical_cast. Not only does it have a fairly nice syntax:

#include <boost/lexical_cast.hpp>
std::string s = boost::lexical_cast<std::string>(i);

it also provides some safety:

try{
  std::string s = boost::lexical_cast<std::string>(i);
}catch(boost::bad_lexical_cast &){
 ...
}

Stylesheet not loaded because of MIME-type

As mentioned solutions in this post, some of the solutions worked for me, but CSS does not apply on the page.

Simply, I just moved the "css" directory into the "Assest/" directory and everything works fine.

<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="assets/css/site.css" >

Laravel Password & Password_Confirmation Validation

Try doing it this way, it worked for me:

$this->validate($request, [
'name' => 'required|min:3|max:50',
'email' => 'email',
'vat_number' => 'max:13',
'password' => 'min:6|required_with:password_confirmation|same:password_confirmation',
'password_confirmation' => 'min:6'
]);`

Seems like the rule always has the validation on the first input among the pair...

print call stack in C or C++

You can use the Boost libraries to print the current callstack.

#include <boost/stacktrace.hpp>

// ... somewhere inside the `bar(int)` function that is called recursively:
std::cout << boost::stacktrace::stacktrace();

Man here: https://www.boost.org/doc/libs/1_65_1/doc/html/stacktrace.html

How to check if a subclass is an instance of a class at runtime?

Maybe I'm missing something, but wouldn't this suffice:

if (view instanceof B) {
    // this view is an instance of B
}

How do I find out what all symbols are exported from a shared object?

Do you have a "shared object" (usually a shared library on AIX), a UNIX shared library, or a Windows DLL? These are all different things, and your question conflates them all :-(

  • For an AIX shared object, use dump -Tv /path/to/foo.o.
  • For an ELF shared library, use readelf -Ws /path/to/libfoo.so, or (if you have GNU nm) nm -D /path/to/libfoo.so.
  • For a non-ELF UNIX shared library, please state which UNIX you are interested in.
  • For a Windows DLL, use dumpbin /EXPORTS foo.dll.

Permission denied on CopyFile in VBS

You can do this:

fso.CopyFile "C:\Minecraft\options.txt", "H:\Minecraft\.minecraft\options.txt"

Include the filename in the folder that you copy to.

AngularJS + JQuery : How to get dynamic content working in angularjs

Addition to @jwize's answer

Because angular.element(document).injector() was giving error injector is not defined So, I have created function that you can run after AJAX call or when DOM is changed using jQuery.

  function compileAngularElement( elSelector) {

        var elSelector = (typeof elSelector == 'string') ? elSelector : null ;  
            // The new element to be added
        if (elSelector != null ) {
            var $div = $( elSelector );

                // The parent of the new element
                var $target = $("[ng-app]");

              angular.element($target).injector().invoke(['$compile', function ($compile) {
                        var $scope = angular.element($target).scope();
                        $compile($div)($scope);
                        // Finally, refresh the watch expressions in the new element
                        $scope.$apply();
                    }]);
            }

        }

use it by passing just new element's selector. like this

compileAngularElement( '.user' ) ; 

How to make custom error pages work in ASP.NET MVC 4

In web.config add this under system.webserver tag as below,

<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404"/>
  <remove statusCode="500"/>
  <error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound"/>
  <error statusCode="500" responseMode="ExecuteURL"path="/Error/ErrorPage"/>
</httpErrors>

and add a controller as,

public class ErrorController : Controller
{
    //
    // GET: /Error/
    [GET("/Error/NotFound")]
    public ActionResult NotFound()
    {
        Response.StatusCode = 404;

        return View();
    }

    [GET("/Error/ErrorPage")]
    public ActionResult ErrorPage()
    {
        Response.StatusCode = 500;

        return View();
    }
}

and add their respected views, this will work definitely I guess for all.

This solution I found it from: Neptune Century

C# Call a method in a new thread

Once a thread is started, it is not necessary to retain a reference to the Thread object. The thread continues to execute until the thread procedure ends.

new Thread(new ThreadStart(SecondFoo)).Start();

Add new item in existing array in c#.net

That could be a solution;

Array.Resize(ref array, newsize);
array[newsize - 1] = "newvalue"

But for dynamic sized array I would prefer list too.

Creating a chart in Excel that ignores #N/A or blank cells

Select the labels above the bar. Format Data Labels. Instead of selecting "VALUE" (unclick). SELECT Value from cells. Select the value. Use the following statement: if(cellvalue="","",cellvalue) where cellvalue is what ever the calculation is in the cell.

How to bind 'touchstart' and 'click' events but not respond to both?

I succeeded by the following way.

Easy Peasy...

$(this).on('touchstart click', function(e){
  e.preventDefault();
  //do your stuff here
});

Inserting data to table (mysqli insert)

Okay, of course the question has been answered, but no-one seems to notice the third line of your code. It continuosly bugged me.

    <?php
    mysqli_connect("localhost","root","","web_table");
    mysql_select_db("web_table") or die(mysql_error());

for some reason, you made a mysqli connection to server, but you are trying to make a mysql connection to database.To get going, rather use

       $link = mysqli_connect("localhost","root","","web_table");
       mysqli_select_db ($link , "web_table" ) or die.....

or for where i began

     <?php $connection = mysqli_connect("localhost","root","","web_table");       
      global $connection; // global connection to databases - kill it once you're done

or just query with a $connection parameter as the other argument like above. Get rid of that third line.

Table is marked as crashed and should be repaired

This means your MySQL table is corrupted and you need to repair it. Use

myisamchk -r /DB_NAME/wp_posts

from the command line. While you running the repair you should shut down your website temporarily so that no new connections are attempted to your database while its being repaired.

How to cast DATETIME as a DATE in mysql?

Use DATE() function:

select * from follow_queue group by DATE(follow_date)

Rails Root directory path?

Simply By writing Rails.root and append anything by Rails.root.join(*%w( app assets)).to_s

Ruby array to string conversion

array.inspect.inspect.gsub(/\[|\]/, "") could do the trick

How do I update a Linq to SQL dbml file?

There is a nuance to updating tables then updating the DBML... Foreign key relationships are not immediately always brought over if changes are made to existing tables. The work around is to do a build of the project and then re-add the tables again. I reported this to MS and its being fixed for VS2010.

DBML display does not show new foreign key constraints


Note that the instructions given in the main answer are not clear. To update the table

  1. Open up the dbml design surface
  2. Select all tables with Right->Click->Select All or CTRLa
  3. CTRLx (Cut)
  4. CTRLv (Paste)
  5. Save and rebuild solution.

What are .dex files in Android?

About the .dex File :

One of the most remarkable features of the Dalvik Virtual Machine (the workhorse under the Android system) is that it does not use Java bytecode. Instead, a homegrown format called DEX was introduced and not even the bytecode instructions are the same as Java bytecode instructions.

Compiled Android application code file.

Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created by automatically translating compiled applications written in the Java programming language.

Dex file format:

 1. File Header
 2. String Table
 3. Class List
 4. Field Table
 5. Method Table
 6. Class Definition Table
 7. Field List
 8. Method List
 9. Code Header
10. Local Variable List

Android has documentation on the Dalvik Executable Format (.dex files). You can find out more over at the official docs: Dex File Format

.dex files are similar to java class files, but they were run under the Dalkvik Virtual Machine (DVM) on older Android versions, and compiled at install time on the device to native code with ART on newer Android versions.

You can decompile .dex using the dexdump tool which is provided in android-sdk.

There are also some Reverse Engineering Techniques to make a jar file or java class file from a .dex file.

Accessing a Shared File (UNC) From a Remote, Non-Trusted Domain With Credentials

While I don't know myself, I would certainly hope that #2 is incorrect...I'd like to think that Windows isn't going to AUTOMATICALLY give out my login information (least of all my password!) to any machine, let alone one that isn't part of my trust.

Regardless, have you explored the impersonation architecture? Your code is going to look similar to this:

using (System.Security.Principal.WindowsImpersonationContext context = System.Security.Principal.WindowsIdentity.Impersonate(token))
{
    // Do network operations here

    context.Undo();
}

In this case, the token variable is an IntPtr. In order to get a value for this variable, you'll have to call the unmanaged LogonUser Windows API function. A quick trip to pinvoke.net gives us the following signature:

[System.Runtime.InteropServices.DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(
    string lpszUsername,
    string lpszDomain,
    string lpszPassword,
    int dwLogonType,
    int dwLogonProvider,
    out IntPtr phToken
);

Username, domain, and password should seem fairly obvious. Have a look at the various values that can be passed to dwLogonType and dwLogonProvider to determine the one that best suits your needs.

This code hasn't been tested, as I don't have a second domain here where I can verify, but this should hopefully put you on the right track.

Easier way to create circle div than using an image?

Give width and height depending on the size but,keep both equal

_x000D_
_x000D_
.circle {_x000D_
  background-color: gray;_x000D_
  height: 400px;_x000D_
  width: 400px;_x000D_
  border-radius: 100%;_x000D_
}
_x000D_
<div class="circle">_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I write text on a HTML5 canvas element?

Canvas text support is actually pretty good - you can control font, size, color, horizontal alignment, vertical alignment, and you can also get text metrics to get the text width in pixels. In addition, you can also use canvas transforms to rotate, stretch and even invert text.

Double border with different color

Use of pseudo-element as suggested by Terry has one PRO and one CON:

  1. PRO - great cross-browser compatibility because pseudo-element are supported also on older IE.
  2. CON - it requires to create an extra (even if generated) element, that infact is defined pseudo-element.

Anyway is a great solution.


OTHER SOLUTIONS:

If you can accept compatibility since IE9 (IE8 does not have support for this), you can achieve desired result in other two possible ways:

  1. using outline property combined with border and a single inset box-shadow
  2. using two box-shadow combined with border.

Here a jsFiddle with Terry's modified code that shows, side by side, these other possible solutions. Main specific properties for each one are the following (others are shared in .double-border class):

.left
{
  outline: 4px solid #fff;
  box-shadow:inset 0 0 0 4px #fff;
}

.right
{
  box-shadow:0 0 0 4px #fff, inset 0 0 0 4px #fff;
}

LESS code:

You asked for possible advantages about using a pre-processor like LESS. I this specific case, utility is not so great, but anyway you could optimize something, declaring colors and border/ouline/shadow with @variable.

Here an example of my CSS code, declared in LESS (changing colors and border-width becomes very quick):

@double-border-size:4px;
@inset-border-color:#fff;
@content-color:#ccc;

.double-border 
{
  background-color: @content-color;
  border: @double-border-size solid @content-color;
  padding: 2em;
  width: 16em;
  height: 16em;
  float:left;
  margin-right:20px;
  text-align:center;
}

.left
{
  outline: @double-border-size solid @inset-border-color;
  box-shadow:inset 0 0 0 @double-border-size @inset-border-color;
}

.right
{
  box-shadow:0 0 0 @double-border-size @inset-border-color, inset 0 0 0 @double-border-size @inset-border-color;
}

How do I print the content of httprequest request?

In case someone also want to dump response like me. i avoided to dump response body. following code just dump the StatusCode and Headers.

static private String dumpResponse(HttpServletResponse resp){
    StringBuilder sb = new StringBuilder();

    sb.append("Response Status = [" + resp.getStatus() + "], ");
    String headers = resp.getHeaderNames().stream()
                    .map(headerName -> headerName + " : " + resp.getHeaders(headerName) )
                    .collect(Collectors.joining(", "));

    if (headers.isEmpty()) {
        sb.append("Response headers: NONE,");
    } else {
        sb.append("Response headers: "+headers+",");
    }

    return sb.toString();
}

SQL Server: Filter output of sp_who2

You could try something like

DECLARE @Table TABLE(
        SPID INT,
        Status VARCHAR(MAX),
        LOGIN VARCHAR(MAX),
        HostName VARCHAR(MAX),
        BlkBy VARCHAR(MAX),
        DBName VARCHAR(MAX),
        Command VARCHAR(MAX),
        CPUTime INT,
        DiskIO INT,
        LastBatch VARCHAR(MAX),
        ProgramName VARCHAR(MAX),
        SPID_1 INT,
        REQUESTID INT
)

INSERT INTO @Table EXEC sp_who2

SELECT  *
FROM    @Table
WHERE ....

And filter on what you require.

How to read values from the querystring with ASP.NET Core?

Some of the comments mention this as well, but asp net core does all this work for you.

If you have a query string that matches the name it will be available in the controller.

https://myapi/some-endpoint/123?someQueryString=YayThisWorks

[HttpPost]
[Route("some-endpoint/{someValue}")]
public IActionResult SomeEndpointMethod(int someValue, string someQueryString)
    {
        Debug.WriteLine(someValue);
        Debug.WriteLine(someQueryString);
        return Ok();
    }

Ouputs:

123

YayThisWorks

Angular.js: set element height on page load

I came across your post as I was looking for a solution to the same problem for myself. I put together the following solution using a directive based on a number of posts. You can try it here (try resizing the browser window): http://jsfiddle.net/zbjLh/2/

View:

<div ng-app="miniapp" ng-controller="AppController" ng-style="style()" resize>
    window.height: {{windowHeight}} <br />
    window.width: {{windowWidth}} <br />
</div>

Controller:

var app = angular.module('miniapp', []);

function AppController($scope) {
    /* Logic goes here */
}

app.directive('resize', function ($window) {
    return function (scope, element) {
        var w = angular.element($window);
        scope.getWindowDimensions = function () {
            return { 'h': w.height(), 'w': w.width() };
        };
        scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
            scope.windowHeight = newValue.h;
            scope.windowWidth = newValue.w;

            scope.style = function () {
                return { 
                    'height': (newValue.h - 100) + 'px',
                    'width': (newValue.w - 100) + 'px' 
                };
            };

        }, true);

        w.bind('resize', function () {
            scope.$apply();
        });
    }
})

FYI I originally had it working in a controller (http://jsfiddle.net/zbjLh/), but from subsequent reading found that this is uncool from Angular's perspective, so I have now converted it to use a directive.

Importantly, note the true flag at the end of the 'watch' function, for comparing the getWindowDimensions return object's equality (remove or change to false if not using an object).

How to read file binary in C#?

Generally, I don't really see a possible way to do this. I've exhausted all of the options that the earlier comments gave you, and they don't seem to work. You could try this:

        `private void button1_Click(object sender, EventArgs e)
    {
        Stream myStream = null;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.InitialDirectory = "This PC\\Documents";
        openFileDialog1.Filter = "All Files (*.*)|*.*";
        openFileDialog1.FilterIndex = 1;
        openFileDialog1.RestoreDirectory = true;
        openFileDialog1.Title = "Open a file with code";

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string exeCode = string.Empty;
            using (BinaryReader br = new BinaryReader(File.OpenRead(openFileDialog1.FileName))) //Sets a new integer to the BinaryReader
            {
                br.BaseStream.Seek(0x4D, SeekOrigin.Begin); //The seek is starting from 0x4D
                exeCode = Encoding.UTF8.GetString(br.ReadBytes(1000000000)); //Reads as many bytes as it can from the beginning of the .exe file
            }
            using (BinaryReader br = new BinaryReader(File.OpenRead(openFileDialog1.FileName)))
                br.Close(); //Closes the BinaryReader. Without it, opening the file with any other command will result the error "This file is being used by another process".

            richTextBox1.Text = exeCode;
        }
    }`
  • That's the code for the "Open..." button, but here's the code for the "Save..." button:

    ` private void button2_Click(object sender, EventArgs e) { SaveFileDialog save = new SaveFileDialog();

        save.Filter = "All Files (*.*)|*.*";
        save.Title = "Save Your Changes";
        save.InitialDirectory = "This PC\\Documents";
        save.FilterIndex = 1;
    
        if (save.ShowDialog() == DialogResult.OK)
        {
    
            using (BinaryWriter bw = new BinaryWriter(File.OpenWrite(save.FileName))) //Sets a new integer to the BinaryReader
            {
                bw.BaseStream.Seek(0x4D, SeekOrigin.Begin); //The seek is starting from 0x4D
                bw.Write(richTextBox1.Text);
            }
        }
    }`
    
    • That's the save button. This works fine, but only shows the '!This cannot be run in DOS-Mode!' - Otherwise, if you can fix this, I don't know what to do.

    • My Site

std::string formatting like sprintf

There can be problems, if the buffer is not large enough to print the string. You must determine the length of the formatted string before printing a formatted message in there. I make own helper to this (tested on Windows and Linux GCC), and you can try use it.

String.cpp: http://pastebin.com/DnfvzyKP
String.h: http://pastebin.com/7U6iCUMa

String.cpp:

#include <cstdio>
#include <cstdarg>
#include <cstring>
#include <string>

using ::std::string;

#pragma warning(disable : 4996)

#ifndef va_copy
#ifdef _MSC_VER
#define va_copy(dst, src) dst=src
#elif !(__cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__))
#define va_copy(dst, src) memcpy((void*)dst, (void*)src, sizeof(*src))
#endif
#endif

///
/// \breif Format message
/// \param dst String to store formatted message
/// \param format Format of message
/// \param ap Variable argument list
///
void toString(string &dst, const char *format, va_list ap) throw() {
  int length;
  va_list apStrLen;
  va_copy(apStrLen, ap);
  length = vsnprintf(NULL, 0, format, apStrLen);
  va_end(apStrLen);
  if (length > 0) {
    dst.resize(length);
    vsnprintf((char *)dst.data(), dst.size() + 1, format, ap);
  } else {
    dst = "Format error! format: ";
    dst.append(format);
  }
}

///
/// \breif Format message
/// \param dst String to store formatted message
/// \param format Format of message
/// \param ... Variable argument list
///
void toString(string &dst, const char *format, ...) throw() {
  va_list ap;
  va_start(ap, format);
  toString(dst, format, ap);
  va_end(ap);
}

///
/// \breif Format message
/// \param format Format of message
/// \param ... Variable argument list
///
string toString(const char *format, ...) throw() {
  string dst;
  va_list ap;
  va_start(ap, format);
  toString(dst, format, ap);
  va_end(ap);
  return dst;
}

///
/// \breif Format message
/// \param format Format of message
/// \param ap Variable argument list
///
string toString(const char *format, va_list ap) throw() {
  string dst;
  toString(dst, format, ap);
  return dst;
}


int main() {
  int a = 32;
  const char * str = "This works!";

  string test(toString("\nSome testing: a = %d, %s\n", a, str));
  printf(test.c_str());

  a = 0x7fffffff;
  test = toString("\nMore testing: a = %d, %s\n", a, "This works too..");
  printf(test.c_str());

  a = 0x80000000;
  toString(test, "\nMore testing: a = %d, %s\n", a, "This way is cheaper");
  printf(test.c_str());

  return 0;
}

String.h:

#pragma once
#include <cstdarg>
#include <string>

using ::std::string;

///
/// \breif Format message
/// \param dst String to store formatted message
/// \param format Format of message
/// \param ap Variable argument list
///
void toString(string &dst, const char *format, va_list ap) throw();
///
/// \breif Format message
/// \param dst String to store formatted message
/// \param format Format of message
/// \param ... Variable argument list
///
void toString(string &dst, const char *format, ...) throw();
///
/// \breif Format message
/// \param format Format of message
/// \param ... Variable argument list
///
string toString(const char *format, ...) throw();

///
/// \breif Format message
/// \param format Format of message
/// \param ap Variable argument list
///
string toString(const char *format, va_list ap) throw();

Why does the C preprocessor interpret the word "linux" as the constant "1"?

In the Old Days (pre-ANSI), predefining symbols such as unix and vax was a way to allow code to detect at compile time what system it was being compiled for. There was no official language standard back then (beyond the reference material at the back of the first edition of K&R), and C code of any complexity was typically a complex maze of #ifdefs to allow for differences between systems. These macro definitions were generally set by the compiler itself, not defined in a library header file. Since there were no real rules about which identifiers could be used by the implementation and which were reserved for programmers, compiler writers felt free to use simple names like unix and assumed that programmers would simply avoid using those names for their own purposes.

The 1989 ANSI C standard introduced rules restricting what symbols an implementation could legally predefine. A macro predefined by the compiler could only have a name starting with two underscores, or with an underscore followed by an uppercase letter, leaving programmers free to use identifiers not matching that pattern and not used in the standard library.

As a result, any compiler that predefines unix or linux is non-conforming, since it will fail to compile perfectly legal code that uses something like int linux = 5;.

As it happens, gcc is non-conforming by default -- but it can be made to conform (reasonably well) with the right command-line options:

gcc -std=c90 -pedantic ... # or -std=c89 or -ansi
gcc -std=c99 -pedantic
gcc -std=c11 -pedantic

See the gcc manual for more details.

gcc will be phasing out these definitions in future releases, so you shouldn't write code that depends on them. If your program needs to know whether it's being compiled for a Linux target or not it can check whether __linux__ is defined (assuming you're using gcc or a compiler that's compatible with it). See the GNU C preprocessor manual for more information.

A largely irrelevant aside: the "Best One Liner" winner of the 1987 International Obfuscated C Code Contest, by David Korn (yes, the author of the Korn Shell) took advantage of the predefined unix macro:

main() { printf(&unix["\021%six\012\0"],(unix)["have"]+"fun"-0x60);}

It prints "unix", but for reasons that have absolutely nothing to do with the spelling of the macro name.

How to remove gem from Ruby on Rails application?

You are using some sort of revision control, right? Then it should be quite simple to restore to the commit before you added the gem, or revert the one where you added it if you have several revisions after that you wish to keep.

How to get an input text value in JavaScript

The reason you function doesn't work when lol is defined outside it, is because the DOM isn't loaded yet when the JavaScript is first run. Because of that, getElementById will return null (see MDN).

You've already found the most obvious solution: by calling getElementById inside the function, the DOM will be loaded and ready by the time the function is called, and the element will be found like you expect it to.

There are a few other solutions. One is to wait until the entire document is loaded, like this:

<script type="text/javascript">
    var lolz;
    function onload() { 
        lolz = document.getElementById('lolz');
    }
    function kk(){
        alert(lolz.value);
    }
</script>

<body onload="onload();">
    <input type="text" name="enter" class="enter" value="" id="lolz"/>
    <input type="button" value="click" onclick="kk();"/>
</body>

Note the onload attribute of the <body> tag. (On a side note: the language attribute of the <script> tag is deprecated. Don't use it.)

There is, however, a problem with onload: it waits until everything (including images, etc.) is loaded.

The other option is to wait until the DOM is ready (which is usually much earlier than onload). This can be done with "plain" JavaScript, but it's much easier to use a DOM library like jQuery.

For example:

<script type="text/javascript">
    $(document).ready(function() {
        var lolz = $('#lolz');
        var kk = $('#kk');
        kk.click(function() {
            alert(lolz.val());
        });
    });
</script>

<body>
    <input type="text" name="enter" class="enter" value="" id="lolz"/>
    <input type="button" value="click" id="kk" />
</body>

jQuery's .ready() takes a function as an argument. The function will be run as soon as the DOM is ready. This second example also uses .click() to bind kk's onclick handler, instead of doing that inline in the HTML.

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

I had almost the same example as you in this notebook where I wanted to illustrate the usage of an adjacent module's function in a DRY manner.

My solution was to tell Python of that additional module import path by adding a snippet like this one to the notebook:

import os
import sys
module_path = os.path.abspath(os.path.join('..'))
if module_path not in sys.path:
    sys.path.append(module_path)

This allows you to import the desired function from the module hierarchy:

from project1.lib.module import function
# use the function normally
function(...)

Note that it is necessary to add empty __init__.py files to project1/ and lib/ folders if you don't have them already.

Javascript: Extend a Function

The other methods are great but they don't preserve any prototype functions attached to init. To get around that you can do the following (inspired by the post from Nick Craver).

(function () {
    var old_prototype = init.prototype;
    var old_init = init;
    init = function () {
        old_init.apply(this, arguments);
        // Do something extra
    };
    init.prototype = old_prototype;
}) ();

File Not Found when running PHP with Nginx

Probably it's too late to answer but a couple things since this is a really annoying error. Following solution worked on Mac OS X Yosemite.

  1. It's the best if you have

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

  1. The include with fast cgi params should go above that line.

  2. All your directories down to the PHP file you're executing (including that file too) should have a+x permissions, e.g.

sudo chmod a+x /Users/
sudo chmod a+x /Users/oleg/
sudo chmod a+x /Users/oleg/www/
sudo chmod a+x /Users/oleg/www/a.php

How to open child forms positioned within MDI parent in VB.NET?

   Private Sub FileMenu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) handles FileMenu.Click

    Form1.MdiParent = Me
    Form1.Dock = DockStyle.Fill
    Form1.Show()
End Sub

Include CSS and Javascript in my django template

Read this https://docs.djangoproject.com/en/dev/howto/static-files/:

For local development, if you are using runserver or adding staticfiles_urlpatterns to your URLconf, you’re done with the setup – your static files will automatically be served at the default (for newly created projects) STATIC_URL of /static/.

And try:

~/tmp$ django-admin.py startproject myprj
~/tmp$ cd myprj/
~/tmp/myprj$ chmod a+x manage.py
~/tmp/myprj$ ./manage.py startapp myapp

Then add 'myapp' to INSTALLED_APPS (myprj/settings.py).

~/tmp/myprj$ cd myapp/
~/tmp/myprj/myapp$ mkdir static
~/tmp/myprj/myapp$ echo 'alert("hello!");' > static/hello.js
~/tmp/myprj/myapp$ mkdir templates
~/tmp/myprj/myapp$ echo '<script src="{{ STATIC_URL }}hello.js"></script>' > templates/hello.html

Edit myprj/urls.py:

from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView

class HelloView(TemplateView):
    template_name = "hello.html"

urlpatterns = patterns('',
    url(r'^$', HelloView.as_view(), name='hello'),
)

And run it:

~/tmp/myprj/myapp$ cd ..
~/tmp/myprj$ ./manage.py runserver

It works!

How can you search Google Programmatically Java API

As an alternative to BalusC answer as it has been deprecated and you have to use proxies, you can use this package. Code sample:

Map<String, String> parameter = new HashMap<>();
parameter.put("q", "Coffee");
parameter.put("location", "Portland");
GoogleSearchResults serp = new GoogleSearchResults(parameter);

JsonObject data = serp.getJson();
JsonArray results = (JsonArray) data.get("organic_results");
JsonObject first_result = results.get(0).getAsJsonObject();
System.out.println("first coffee: " + first_result.get("title").getAsString());

Library on GitHub

Remove insignificant trailing zeros from a number?

Pure regex answer

n.replace(/(\.[0-9]*[1-9])0+$|\.0*$/,'$1');

I wonder why no one gave one!

What is __pycache__?

When you run a program in python, the interpreter compiles it to bytecode first (this is an oversimplification) and stores it in the __pycache__ folder. If you look in there you will find a bunch of files sharing the names of the .py files in your project's folder, only their extensions will be either .pyc or .pyo. These are bytecode-compiled and optimized bytecode-compiled versions of your program's files, respectively.

As a programmer, you can largely just ignore it... All it does is make your program start a little faster. When your scripts change, they will be recompiled, and if you delete the files or the whole folder and run your program again, they will reappear (unless you specifically suppress that behavior).

When you're sending your code to other people, the common practice is to delete that folder, but it doesn't really matter whether you do or don't. When you're using version control (git), this folder is typically listed in the ignore file (.gitignore) and thus not included.

If you are using cpython (which is the most common, as it's the reference implementation) and you don't want that folder, then you can suppress it by starting the interpreter with the -B flag, for example

python -B foo.py

Another option, as noted by tcaswell, is to set the environment variable PYTHONDONTWRITEBYTECODE to any value (according to python's man page, any "non-empty string").

R - Concatenate two dataframes?

you can use the function

bind_rows(a,b)

from the dplyr library

Proper way to catch exception from JSON.parse

This promise will not resolve if the argument of JSON.parse() can not be parsed into a JSON object.

Promise.resolve(JSON.parse('{"key":"value"}')).then(json => {
    console.log(json);
}).catch(err => {
    console.log(err);
});

Do you (really) write exception safe code?

  • Do you really write exception safe code? [There's no such thing. Exceptions are a paper shield to errors unless you have a managed environment. This applies to first three questions.]

  • Do you know and/or actually use alternatives that work? [Alternative to what? The problem here is people don't separate actual errors from normal program operation. If it's normal program operation (ie a file not found), it's not really error handling. If it's an actual error, there is no way to 'handle' it or it's not an actual error. Your goal here is to find out what went wrong and either stop the spreadsheet and log an error, restart the driver to your toaster, or just pray that the jetfighter can continue flying even when it's software is buggy and hope for the best.]

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

Here is a pretty simple stored procedure that does the trick as well...

    CREATE PROCEDURE GetBCPTable
    @table_name varchar(200)
AS
BEGIN
    DECLARE @raw_sql nvarchar(3000)

    DECLARE @columnHeader VARCHAR(8000)
    SELECT @columnHeader = COALESCE(@columnHeader+',' ,'')+ ''''+column_name +'''' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table_name

    DECLARE @ColumnList VARCHAR(8000)
    SELECT @ColumnList = COALESCE(@ColumnList+',' ,'')+ 'CAST('+column_name +' AS VARCHAR)' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table_name

    SELECT @raw_sql = 'SELECT '+ @columnHeader +' UNION ALL SELECT ' + @ColumnList + ' FROM ' + @table_name
    --PRINT @raw_SQL
    EXECUTE sp_executesql  @raw_sql
END
GO

Retina displays, high-res background images

Here's a solution that also includes High(er)DPI (MDPI) devices > ~160 dots per inch like quite a few non-iOS Devices (f.e.: Google Nexus 7 2012):

.box {
    background: url( 'img/box-bg.png' ) no-repeat top left;
    width: 200px;
    height: 200px;
}
@media only screen and ( -webkit-min-device-pixel-ratio: 1.3 ),
       only screen and (    min--moz-device-pixel-ratio: 1.3 ),
       only screen and (      -o-min-device-pixel-ratio: 2.6/2 ), /* returns 1.3, see Dev.Opera */
       only screen and (         min-device-pixel-ratio: 1.3 ),
       only screen and ( min-resolution: 124.8dpi ),
       only screen and ( min-resolution: 1.3dppx ) {

       .box {
           background: url( 'img/[email protected]' ) no-repeat top left / 200px 200px;
       }

}

As @3rror404 included in his edit after receiving feedback from the comments, there's a world beyond Webkit/iPhone. One thing that bugs me with most solutions around so far like the one referenced as source above at CSS-Tricks, is that this isn't taken fully into account.
The original source went already further.

As an example the Nexus 7 (2012) screen is a TVDPI screen with a weird device-pixel-ratio of 1.325. When loading the images with normal resolution they are upscaled via interpolation and therefore blurry. For me applying this rule in the media query to include those devices succeeded in best customer feedback.

Convert line endings

Some options:

Using tr

tr -d '\15\32' < windows.txt > unix.txt

OR

tr -d '\r' < windows.txt > unix.txt 

Using perl

perl -p -e 's/\r$//' < windows.txt > unix.txt

Using sed

sed 's/^M$//' windows.txt > unix.txt

OR

sed 's/\r$//' windows.txt > unix.txt

To obtain ^M, you have to type CTRL-V and then CTRL-M.

C# Java HashMap equivalent

Check out the documentation on MSDN for the Hashtable class.

Represents a collection of key-and-value pairs that are organized based on the hash code of the key.

Also, keep in mind that this is not thread-safe.

PHP mysql insert date format

Try Something like this..

echo "The time is " . date("2:50:20");
$d=strtotime("3.00pm july 28 2014");
echo "Created date is " . date("d-m-y h:i:sa",$d);

How do I convert NSInteger to NSString datatype?

NSNumber may be good for you in this case.

NSString *inStr = [NSString stringWithFormat:@"%d", 
                    [NSNumber numberWithInteger:[month intValue]]];

Array initializing in Scala

scala> val arr = Array("Hello","World")
arr: Array[java.lang.String] = Array(Hello, World)

Items in JSON object are out of order using "json.dumps"?

Both Python dict (before Python 3.7) and JSON object are unordered collections. You could pass sort_keys parameter, to sort the keys:

>>> import json
>>> json.dumps({'a': 1, 'b': 2})
'{"b": 2, "a": 1}'
>>> json.dumps({'a': 1, 'b': 2}, sort_keys=True)
'{"a": 1, "b": 2}'

If you need a particular order; you could use collections.OrderedDict:

>>> from collections import OrderedDict
>>> json.dumps(OrderedDict([("a", 1), ("b", 2)]))
'{"a": 1, "b": 2}'
>>> json.dumps(OrderedDict([("b", 2), ("a", 1)]))
'{"b": 2, "a": 1}'

Since Python 3.6, the keyword argument order is preserved and the above can be rewritten using a nicer syntax:

>>> json.dumps(OrderedDict(a=1, b=2))
'{"a": 1, "b": 2}'
>>> json.dumps(OrderedDict(b=2, a=1))
'{"b": 2, "a": 1}'

See PEP 468 – Preserving Keyword Argument Order.

If your input is given as JSON then to preserve the order (to get OrderedDict), you could pass object_pair_hook, as suggested by @Fred Yankowski:

>>> json.loads('{"a": 1, "b": 2}', object_pairs_hook=OrderedDict)
OrderedDict([('a', 1), ('b', 2)])
>>> json.loads('{"b": 2, "a": 1}', object_pairs_hook=OrderedDict)
OrderedDict([('b', 2), ('a', 1)])

How to remove whitespace from a string in typescript?

Problem

The trim() method removes whitespace from both sides of a string.

Source

Solution

You can use a Javascript replace method to remove white space like

"hello world".replace(/\s/g, "");

Example

_x000D_
_x000D_
var out = "hello world".replace(/\s/g, "");_x000D_
console.log(out);
_x000D_
_x000D_
_x000D_

Hide text within HTML?

Use the CSS property visibility and set it to hidden.

You can see more here.

How to install Visual Studio 2015 on a different drive

Anyone tried this approach?

Doing a dir /s vs_ultimate.exe from the root prompt will find it. Mine was in <C:\ProgramData\Package Cache\{[guid]}>. Once I navigated there and ran vs_community_ENU.exe /uninstall /force it uninstalled all the Visual Studio assets I believe.

Got the advice from this post.

Empty ArrayList equals null

No, this will not work. The best you will be able to do is to iterate through all values and check them yourself:

boolean empty = true;
for (Object item : arrayList) {
    if (item != null) {
        empty = false;
        break;
    }
}

Pass a PHP string to a JavaScript variable (and escape newlines)

The paranoid version: Escaping every single character.

function javascript_escape($str) {
  $new_str = '';

  $str_len = strlen($str);
  for($i = 0; $i < $str_len; $i++) {
    $new_str .= '\\x' . sprintf('%02x', ord(substr($str, $i, 1)));
  }

  return $new_str;
}

EDIT: The reason why json_encode() may not be appropriate is that sometimes, you need to prevent " to be generated, e.g.

<div onclick="alert(???)" />

The right way of setting <a href=""> when it's a local file

The href value inside the base tag will become your reference point for all your relative paths and thus override your current directory path value otherwise - the '~' is the root of your site

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

How to undo 'git reset'?

Old question, and the posted answers work great. I'll chime in with another option though.

git reset ORIG_HEAD

ORIG_HEAD references the commit that HEAD previously referenced.

How might I find the largest number contained in a JavaScript array?

You can use the apply function, to call Math.max:

var array = [267, 306, 108];
var largest = Math.max.apply(Math, array); // 306

How does it work?

The apply function is used to call another function, with a given context and arguments, provided as an array. The min and max functions can take an arbitrary number of input arguments: Math.max(val1, val2, ..., valN)

So if we call:

Math.min.apply(Math, [1, 2, 3, 4]);

The apply function will execute:

Math.min(1, 2, 3, 4);

Note that the first parameter, the context, is not important for these functions since they are static. They will work regardless of what is passed as the context.

configure Git to accept a particular self-signed server certificate for a particular https remote

Briefly:

  1. Get the self signed certificate
  2. Put it into some (e.g. ~/git-certs/cert.pem) file
  3. Set git to trust this certificate using http.sslCAInfo parameter

In more details:

Get self signed certificate of remote server

Assuming, the server URL is repos.sample.com and you want to access it over port 443.

There are multiple options, how to get it.

Get certificate using openssl

$ openssl s_client -connect repos.sample.com:443

Catch the output into a file cert.pem and delete all but part between (and including) -BEGIN CERTIFICATE- and -END CERTIFICATE-

Content of resulting file ~/git-certs/cert.pem may look like this:

-----BEGIN CERTIFICATE-----
MIIDnzCCAocCBE/xnXAwDQYJKoZIhvcNAQEFBQAwgZMxCzAJBgNVBAYTAkRFMRUw
EwYDVQQIEwxMb3dlciBTYXhvbnkxEjAQBgNVBAcTCVdvbGZzYnVyZzEYMBYGA1UE
ChMPU2FhUy1TZWN1cmUuY29tMRowGAYDVQQDFBEqLnNhYXMtc2VjdXJlLmNvbTEj
MCEGCSqGSIb3DQEJARYUaW5mb0BzYWFzLXNlY3VyZS5jb20wHhcNMTIwNzAyMTMw
OTA0WhcNMTMwNzAyMTMwOTA0WjCBkzELMAkGA1UEBhMCREUxFTATBgNVBAgTDExv
d2VyIFNheG9ueTESMBAGA1UEBxMJV29sZnNidXJnMRgwFgYDVQQKEw9TYWFTLVNl
Y3VyZS5jb20xGjAYBgNVBAMUESouc2Fhcy1zZWN1cmUuY29tMSMwIQYJKoZIhvcN
AQkBFhRpbmZvQHNhYXMtc2VjdXJlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEP
ADCCAQoCggEBAMUZ472W3EVFYGSHTgFV0LR2YVE1U//sZimhCKGFBhH3ZfGwqtu7
mzOhlCQef9nqGxgH+U5DG43B6MxDzhoP7R8e1GLbNH3xVqMHqEdcek8jtiJvfj2a
pRSkFTCVJ9i0GYFOQfQYV6RJ4vAunQioiw07OmsxL6C5l3K/r+qJTlStpPK5dv4z
Sy+jmAcQMaIcWv8wgBAxdzo8UVwIL63gLlBz7WfSB2Ti5XBbse/83wyNa5bPJPf1
U+7uLSofz+dehHtgtKfHD8XpPoQBt0Y9ExbLN1ysdR9XfsNfBI5K6Uokq/tVDxNi
SHM4/7uKNo/4b7OP24hvCeXW8oRyRzpyDxMCAwEAATANBgkqhkiG9w0BAQUFAAOC
AQEAp7S/E1ZGCey5Oyn3qwP4q+geQqOhRtaPqdH6ABnqUYHcGYB77GcStQxnqnOZ
MJwIaIZqlz+59taB6U2lG30u3cZ1FITuz+fWXdfELKPWPjDoHkwumkz3zcCVrrtI
ktRzk7AeazHcLEwkUjB5Rm75N9+dOo6Ay89JCcPKb+tNqOszY10y6U3kX3uiSzrJ
ejSq/tRyvMFT1FlJ8tKoZBWbkThevMhx7jk5qsoCpLPmPoYCEoLEtpMYiQnDZgUc
TNoL1GjoDrjgmSen4QN5QZEGTOe/dsv1sGxWC+Tv/VwUl2GqVtKPZdKtGFqI8TLn
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----

Get certificate using your web browser

I use Redmine with Git repositories and I access the same URL for web UI and for git command line access. This way, I had to add exception for that domain into my web browser.

Using Firefox, I went to Options -> Advanced -> Certificates -> View Certificates -> Servers, found there the selfsigned host, selected it and using Export button I got exactly the same file, as created using openssl.

Note: I was a bit surprised, there is no name of the authority visibly mentioned. This is fine.

Having the trusted certificate in dedicated file

Previous steps shall result in having the certificate in some file. It does not matter, what file it is as long as it is visible to your git when accessing that domain. I used ~/git-certs/cert.pem

Note: If you need more trusted selfsigned certificates, put them into the same file:

-----BEGIN CERTIFICATE-----
MIIDnzCCAocCBE/xnXAwDQYJKoZIhvcNAQEFBQAwgZMxCzAJBgNVBAYTAkRFMRUw
...........
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
AnOtHeRtRuStEdCeRtIfIcAtEgOeShErExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxw
...........
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----

This shall work (but I tested it only with single certificate).

Configure git to trust this certificate

$ git config --global http.sslCAInfo /home/javl/git-certs/cert.pem

You may also try to do that system wide, using --system instead of --global.

And test it: You shall now be able communicating with your server without resorting to:

$ git config --global http.sslVerify false #NO NEED TO USE THIS

If you already set your git to ignorance of ssl certificates, unset it:

$ git config --global --unset http.sslVerify

and you may also check, that you did it all correctly, without spelling errors:

$ git config --global --list

what should list all variables, you have set globally. (I mispelled http to htt).

Using multiple IF statements in a batch file

is there a special guideline that should be followed

There is no "standard" way to do batch files, because the vast majority of their authors and maintainers either don't understand programming concepts, or they think they don't apply to batch files.

But I am a programmer. I'm used to compiling, and I'm used to debuggers. Batch files aren't compiled, and you can't run them through a debugger, so they make me nervous. I suggest you be extra strict on what you write, so you can be very sure it will do what you think it does.

There are some coding standards that say: If you write an if statement, you must use braces, even if you don't have an else clause. This saves you from subtle, hard-to-debug problems, and is unambiguously readable. I see no reason you couldn't apply this reasoning to batch files.

Let's take a look at your code.

IF EXIST somefile.txt IF EXIST someotherfile.txt SET var=somefile.txt,someotherfile.txt

And the IF syntax, from the command, HELP IF:

IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXISTS filename command

...

IF EXIST filename (
  command
) ELSE (
  other command
)

So you are chaining IF's as commands.

If you use the common coding-standard rule I mentioned above, you would always want to use parens. Here is how you would do so for your example code:

IF EXIST "somefile.txt" (
  IF EXIST "someotherfile.txt" (
    SET var="somefile.txt,someotherfile.txt"
  )
)

Make sure you cleanly format, and do some form of indentation. You do it in code, and you should do it in your batch scripts.

Also, you should also get in the habit of always quoting your file names, and getting the quoting right. There is some verbiage under HELP FOR and HELP SET that will help you with removing extra quotes when re-quoting strings.

Edit

From your comments, and re-reading your original question, it seems like you want to build a comma separated list of files that exist. For this case, you could simply use a bunch of if/else statements, but that would result in a bunch of duplicated logic, and would not be at all clean if you had more than two files.

A better way is to write a sub-routine that checks for a single file's existence, and appends to a variable if the file specified exists. Then just call that subroutine for each file you want to check for:

@ECHO OFF
SETLOCAL

REM Todo: Set global script variables here
CALL :MainScript
GOTO :EOF

REM MainScript()
:MainScript
  SETLOCAL

  CALL :AddIfExists "somefile.txt" "%files%" "files"
  CALL :AddIfExists "someotherfile.txt" "%files%" "files"

  ECHO.Files: %files%

  ENDLOCAL
GOTO :EOF

REM AddIfExists(filename, existingFilenames, returnVariableName)
:AddIfExists
  SETLOCAL

  IF EXIST "%~1" (
    SET "result=%~1"
  ) ELSE (
    SET "result="
  )

  (
    REM Cleanup, and return result - concatenate if necessary
    ENDLOCAL

    IF "%~2"=="" (
      SET "%~3=%result%"
    ) ELSE (
      SET "%~3=%~2,%result%"
    )
  )
GOTO :EOF

Pandas: ValueError: cannot convert float NaN to integer

Also, even at the lastest versions of pandas if the column is object type you would have to convert into float first, something like:

df['column_name'].astype(np.float).astype("Int32")

NB: You have to go through numpy float first and then to nullable Int32, for some reason.

The size of the int if it's 32 or 64 depends on your variable, be aware you may loose some precision if your numbers are to big for the format.

Split Java String by New Line

A new method lines has been introduced to String class in , which returns Stream<String>

Returns a stream of substrings extracted from this string partitioned by line terminators.

Line terminators recognized are line feed "\n" (U+000A), carriage return "\r" (U+000D) and a carriage return followed immediately by a line feed "\r\n" (U+000D U+000A).

Here are a few examples:

jshell> "lorem \n ipusm \n sit".lines().forEach(System.out::println)
lorem
 ipusm
 sit

jshell> "lorem \n ipusm \r  sit".lines().forEach(System.out::println)
lorem
 ipusm
  sit

jshell> "lorem \n ipusm \r\n  sit".lines().forEach(System.out::println)
lorem
 ipusm
  sit

String#lines()

When should I use cross apply over inner join?

The essence of the APPLY operator is to allow correlation between left and right side of the operator in the FROM clause.

In contrast to JOIN, the correlation between inputs is not allowed.

Speaking about correlation in APPLY operator, I mean on the right hand side we can put:

  • a derived table - as a correlated subquery with an alias
  • a table valued function - a conceptual view with parameters, where the parameter can refer to the left side

Both can return multiple columns and rows.

How to Replace dot (.) in a string in Java

If you want to replace a simple string and you don't need the abilities of regular expressions, you can just use replace, not replaceAll.

replace replaces each matching substring but does not interpret its argument as a regular expression.

str = xpath.replace(".", "/*/");

How to convert FileInputStream to InputStream?

InputStream is = new FileInputStream("c://filename");
return is;

How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

An easy approach is to leverage this code:

<a href="javascript:void(0);">Link Title</a>

This approach doesn't force a page refresh, so the scrollbar stays in place. Also, it allows you to programmatically change the onclick event and handle client side event binding using jQuery.

For these reasons, the above solution is better than:

<a href="javascript:myClickHandler();">Link Title</a>
<a href="#" onclick="myClickHandler(); return false;">Link Title</a>

where the last solution will avoid the scroll-jump issue if and only if the myClickHandler method doesn't fail.

Extracting date from a string in Python

Using Pygrok, you can define abstracted extensions to the Regular Expression syntax.

The custom patterns can be included in your regex in the format %{PATTERN_NAME}.

You can also create a label for that pattern, by separating with a colon: %s{PATTERN_NAME:matched_string}. If the pattern matches, the value will be returned as part of the resulting dictionary (e.g. result.get('matched_string'))

For example:

from pygrok import Grok

input_string = 'monkey 2010-07-10 love banana'
date_pattern = '%{YEAR:year}-%{MONTHNUM:month}-%{MONTHDAY:day}'

grok = Grok(date_pattern)
print(grok.match(input_string))

The resulting value will be a dictionary:

{'month': '07', 'day': '10', 'year': '2010'}

If the date_pattern does not exist in the input_string, the return value will be None. By contrast, if your pattern does not have any labels, it will return an empty dictionary {}

References:

Find the last time table was updated

Why not just run this: No need for special permissions

SELECT
    name, 
    object_id, 
    create_date, 
    modify_date
FROM
    sys.tables 
WHERE 
    name like '%yourTablePattern%'
ORDER BY
    modify_date

Can I have multiple :before pseudo-elements for the same element?

I've resolved this using:

.element:before {
    font-family: "Font Awesome 5 Free" , "CircularStd";
    content: "\f017" " Date";
}

Using the font family "font awesome 5 free" for the icon, and after, We have to specify the font that we are using again because if we doesn't do this, navigator will use the default font (times new roman or something like this).

Getting a machine's external IP address with Python

If you're just writing for yourself and not for a generalized application, you might be able to find the address on the setup page for your router and then scrape it from that page's html. This worked fine for me with my SMC router. One read and one simple RE search and I've found it.

My particular interest in doing this was to let me know my home IP address when I was away from home, so I could get back in via VNC. A few more lines of Python stores the address in Dropbox for outside access, and even emails me if it sees a change. I've scheduled it to happen on boot and once an hour thereafter.

How to retrieve available RAM from Windows command line?

wmic OS get TotalVisibleMemorySize /Value

Note not TotalPhysicalMemory as suggested elsewhere

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

One thing I found is the path of your image must be relative to wherever the notebook was originally loaded from. if you cd to a different directory, such as Pictures your Markdown path is still relative to the original loading directory.

Is it ok to run docker from inside docker?

It's OK to run Docker-in-Docker (DinD) and in fact Docker (the company) has an official DinD image for this.

The caveat however is that it requires a privileged container, which depending on your security needs may not be a viable alternative.

The alternative solution of running Docker using sibling containers (aka Docker-out-of-Docker or DooD) does not require a privileged container, but has a few drawbacks that stem from the fact that you are launching the container from within a context that is different from that one in which it's running (i.e., you launch the container from within a container, yet it's running at the host's level, not inside the container).

I wrote a blog describing the pros/cons of DinD vs DooD here.

Having said this, Nestybox (a startup I just founded) is working on a solution that runs true Docker-in-Docker securely (without using privileged containers). You can check it out at www.nestybox.com.

How to send parameters with jquery $.get()

Try this:

$.ajax({
    type: 'get',
    url: 'manageproducts.do',
    data: 'option=1',
    success: function(data) {

        availableProductNames = data.split(",");

        alert(availableProductNames);

    }
});

Also You have a few errors in your sample code, not sure if that was causing the error or it was just a typo upon entering the question.

On - window.location.hash - Change?

There are a lot of tricks to deal with History and window.location.hash in IE browsers:

  • As original question said, if you go from page a.html#b to a.html#c, and then hit the back button, the browser doesn't know that page has changed. Let me say it with an example: window.location.href will be 'a.html#c', no matter if you are in a.html#b or a.html#c.

  • Actually, a.html#b and a.html#c are stored in history only if elements '<a name="#b">' and '<a name="#c">' exists previously in the page.

  • However, if you put an iframe inside a page, navigate from a.html#b to a.html#c in that iframe and then hit the back button, iframe.contentWindow.document.location.href changes as expected.

  • If you use 'document.domain=something' in your code, then you can't access to iframe.contentWindow.document.open()' (and many History Managers does that)

I know this isn't a real response, but maybe IE-History notes are useful to somebody.

What is the difference between null and undefined in JavaScript?

Undefined means a variable has been declared but has no value:

var var1;
alert(var1); //undefined
alert(typeof var1); //undefined

Null is an assignment:

var var2= null;
alert(var2); //null
alert(typeof var2); //object

Find size of Git repository

You could use git-sizer. In the --verbose setting, the example output is (below). Look for the Total size of files line.

$ git-sizer --verbose
Processing blobs: 1652370
Processing trees: 3396199
Processing commits: 722647
Matching commits to trees: 722647
Processing annotated tags: 534
Processing references: 539
| Name                         | Value     | Level of concern               |
| ---------------------------- | --------- | ------------------------------ |
| Overall repository size      |           |                                |
| * Commits                    |           |                                |
|   * Count                    |   723 k   | *                              |
|   * Total size               |   525 MiB | **                             |
| * Trees                      |           |                                |
|   * Count                    |  3.40 M   | **                             |
|   * Total size               |  9.00 GiB | ****                           |
|   * Total tree entries       |   264 M   | *****                          |
| * Blobs                      |           |                                |
|   * Count                    |  1.65 M   | *                              |
|   * Total size               |  55.8 GiB | *****                          |
| * Annotated tags             |           |                                |
|   * Count                    |   534     |                                |
| * References                 |           |                                |
|   * Count                    |   539     |                                |
|                              |           |                                |
| Biggest objects              |           |                                |
| * Commits                    |           |                                |
|   * Maximum size         [1] |  72.7 KiB | *                              |
|   * Maximum parents      [2] |    66     | ******                         |
| * Trees                      |           |                                |
|   * Maximum entries      [3] |  1.68 k   | *                              |
| * Blobs                      |           |                                |
|   * Maximum size         [4] |  13.5 MiB | *                              |
|                              |           |                                |
| History structure            |           |                                |
| * Maximum history depth      |   136 k   |                                |
| * Maximum tag depth      [5] |     1     |                                |
|                              |           |                                |
| Biggest checkouts            |           |                                |
| * Number of directories  [6] |  4.38 k   | **                             |
| * Maximum path depth     [7] |    13     | *                              |
| * Maximum path length    [8] |   134 B   | *                              |
| * Number of files        [9] |  62.3 k   | *                              |
| * Total size of files    [9] |   747 MiB |                                |
| * Number of symlinks    [10] |    40     |                                |
| * Number of submodules       |     0     |                                |

[1]  91cc53b0c78596a73fa708cceb7313e7168bb146
[2]  2cde51fbd0f310c8a2c5f977e665c0ac3945b46d
[3]  4f86eed5893207aca2c2da86b35b38f2e1ec1fc8 (refs/heads/master:arch/arm/boot/dts)
[4]  a02b6794337286bc12c907c33d5d75537c240bd0 (refs/heads/master:drivers/gpu/drm/amd/include/asic_reg/vega10/NBIO/nbio_6_1_sh_mask.h)
[5]  5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c (refs/tags/v2.6.11)
[6]  1459754b9d9acc2ffac8525bed6691e15913c6e2 (589b754df3f37ca0a1f96fccde7f91c59266f38a^{tree})
[7]  78a269635e76ed927e17d7883f2d90313570fdbc (dae09011115133666e47c35673c0564b0a702db7^{tree})
[8]  ce5f2e31d3bdc1186041fdfd27a5ac96e728f2c5 (refs/heads/master^{tree})
[9]  532bdadc08402b7a72a4b45a2e02e5c710b7d626 (e9ef1fe312b533592e39cddc1327463c30b0ed8d^{tree})
[10] f29a5ea76884ac37e1197bef1941f62fda3f7b99 (f5308d1b83eba20e69df5e0926ba7257c8dd9074^{tree})

jQuery iframe load() event?

Without code in iframe + animate:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script language="javascript" type="text/javascript">

function resizeIframe(obj) {

    jQuery(document).ready(function($) {

        $(obj).animate({height: obj.contentWindow.document.body.scrollHeight + 'px'}, 500)

    });

}    
</script>
<iframe width="100%" src="iframe.html" height="0" frameborder="0" scrolling="no" onload="resizeIframe(this)" >

Convert HTML to PDF in .NET

I recently performed a PoC regarding HTML to PDF conversion and wanted to share my results.

My favorite by far is OpenHtmlToPdf

Advantages of this tool:

  • Very good HTML compatibility (e.g. it was the only tool in my example that correctly repeated table headers when a table spanned multiple pages)
  • Fluent API
  • Free and OpenSource (Creative Commons Attribution 3.0 license)
  • Available via NuGet

Other tools tested:

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

Yes strings must be quoted and in some cases like in applescript, quotes must be escaped

do JavaScript "document.querySelector('span[" & attrName & "=\"" & attrValue & "\"]').click();"

Fitting iframe inside a div

Based on the link provided by @better_use_mkstemp, here's a fiddle where nested iframe resizes to fill parent div: http://jsfiddle.net/orlenko/HNyJS/

Html:

<div id="content">
    <iframe src="http://www.microsoft.com" name="frame2" id="frame2" frameborder="0" marginwidth="0" marginheight="0" scrolling="auto" onload="" allowtransparency="false"></iframe>
</div>
<div id="block"></div>
<div id="header"></div>
<div id="footer"></div>

Relevant parts of CSS:

div#content {
    position: fixed;
    top: 80px;
    left: 40px;
    bottom: 25px;
    min-width: 200px;
    width: 40%;
    background: black;
}

div#content iframe {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100%;
    width: 100%;
}

How do I make the text box bigger in HTML/CSS?

Try this:

#signin input {
    background-color:#FFF;
    height: 1.5em;
    /* or */
    line-height: 1.5em;
}

How to convert a selection to lowercase or uppercase in Sublime Text

For Windows OS

For Uppercase CTRL + K + U

For Lowercase CTRL + K + L

How to perform a for-each loop over all the files under a specified path?

More compact version working with spaces and newlines in the file name:

find . -iname '*.txt' -exec sh -c 'echo "{}" ; ls -l "{}"' \;

Symbol for any number of any characters in regex?

You can use this regular expression (any whitespace or any non-whitespace) as many times as possible down to and including 0.

[\s\S]*

This expression will match as few as possible, but as many as necessary for the rest of the expression.

[\s\S]*?

For example, in this regex [\s\S]*?B will match aB in aBaaaaB. But in this regex [\s\S]*B will match aBaaaaB in aBaaaaB.

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model

Use the backslash before db on the header and you can use it then typically as you wrote it before.

Here is the example:

Use \DB;

Then inside your controller class you can use as you did before, like that ie :

$item = DB::table('items')->get();

Android "elevation" not showing a shadow

Also check if You don't change alpha on that view. I am investigating issue when i change alpha on some views, with elevation. They simply loose elevation when alpha is changed and changed back to 1f.

How can I start PostgreSQL server on Mac OS X?

Here is an easy and always forking solution (mac os):

(WARNING: IT WILL DELETE ALL YOUR DATABASES)

  1. Stop the postgres service:

    brew services stop postgres

  2. Delete all files in "postgres" directory:

    rm -rf /usr/local/var/postgres/*

  3. Initialize the new database system:

    initdb /usr/local/var/postgres -E utf8

  4. Start postgres:

    pg_ctl -D /usr/local/var/postgres -l server.log start

System.Net.WebException HTTP status code

this works only if WebResponse is a HttpWebResponse.

try
{
    ...
}
catch (System.Net.WebException exc)
{
    var webResponse = exc.Response as System.Net.HttpWebResponse;
    if (webResponse != null && 
        webResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
    {
        MessageBox.Show("401");
    }
    else
        throw;
}

Get screen width and height in Android

For kotlin user's

fun Activity.displayMetrics(): DisplayMetrics {
   val displayMetrics = DisplayMetrics()
   windowManager.defaultDisplay.getMetrics(displayMetrics)
   return displayMetrics
}

And in Activity you could use it like

     resources.displayMetrics.let { displayMetrics ->
        val height = displayMetrics.heightPixels
        val width = displayMetrics.widthPixels
    }

Or in fragment

    activity?.displayMetrics()?.run {
        val height = heightPixels
        val width = widthPixels
    }

linux/videodev.h : no such file or directory - OpenCV on ubuntu 11.04

v4l support has been dropped in recent kernel versions (including the one shipped with Ubuntu 11.04).

EDIT: Your question is connected to a recent message that was sent to the OpenCV users group, which has instructions to compile OpenCV 2.2 in Ubuntu 11.04. Your approach is not ideal.

Limiting double to 3 decimal places

You can use:

double example = 12.34567;
double output = ( (double) ( (int) (example * 1000.0) ) ) / 1000.0 ;

How do you run a js file using npm scripts?

You should use npm run-script build or npm build <project_folder>. More info here: https://docs.npmjs.com/cli/build.

Trigger an action after selection select2

As per my usage above v.4 this gonna work

$('#selectID').on("select2:select", function(e) { 
    //var value = e.params.data;  Using {id,text format}
});

And for less then v.4 this gonna work:

$('#selectID').on("change", function(e) { 
   //var value = e.params.data; Using {id,text} format
});

HTML list-style-type dash

Let me add my version too, mostly for me to find my own preferred solution again:

_x000D_
_x000D_
ul {_x000D_
  list-style-type: none;_x000D_
  /*use padding to move list item from left to right*/_x000D_
  padding-left: 1em;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
  content: "–";_x000D_
  position: absolute;_x000D_
  /*change margin to move dash around*/_x000D_
  margin-left: -1em;_x000D_
}
_x000D_
<!-- _x000D_
Just use the following CSS to turn your_x000D_
common disc lists into a list-style-type: 'dash' _x000D_
Give credit and enjoy!_x000D_
-->_x000D_
Some text_x000D_
<ul>_x000D_
  <li>One</li>_x000D_
  <li>Very</li>_x000D_
  <li>Simple Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</li>_x000D_
  <li>Approach!</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

https://codepen.io/burningTyger/pen/dNzgrQ

android listview item height

You need to use padding on the list item layout so space is added on the edges of the item (just increasing the font size won't do that).

<?xml version="1.0" encoding="utf-8"?>
<TextView android:id="@+id/text1"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    android:padding="8dp" />

Changing tab bar item image and text color iOS

Swift 5.3

let vc = UIViewController()
vc.tabBarItem.title = "sample"
vc.tabBarItem.image = UIImage(imageLiteralResourceName: "image.png").withRenderingMode(.alwaysOriginal)
vc.tabBarItem.selectedImage = UIImage(imageLiteralResourceName: "image.png").withRenderingMode(.alwaysOriginal)
        
// for text displayed below the tabBar item
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black], for: .selected)

How do I define and use an ENUM in Objective-C?

This is how Apple does it for classes like NSString:

In the header file:

enum {
    PlayerStateOff,
    PlayerStatePlaying,
    PlayerStatePaused
};

typedef NSInteger PlayerState;

Refer to Coding Guidelines at http://developer.apple.com/

Error: [ng:areq] from angular controller

I experienced this error once. The problem was I had defined angular.module() in two places with different arguments.

Eg:

var MyApp = angular.module('MyApp', []);

in other place,

var MyApp2 = angular.module('MyApp', ['ngAnimate']);

How do I pass a unique_ptr argument to a constructor or a function?

To the top voted answer. I prefer passing by rvalue reference.

I understand what's the problem about passing by rvalue reference may cause. But let's divide this problem to two sides:

  • for caller:

I must write code Base newBase(std::move(<lvalue>)) or Base newBase(<rvalue>).

  • for callee:

Library author should guarantee it will actually move the unique_ptr to initialize member if it want own the ownership.

That's all.

If you pass by rvalue reference, it will only invoke one "move" instruction, but if pass by value, it's two.

Yep, if library author is not expert about this, he may not move unique_ptr to initialize member, but it's the problem of author, not you. Whatever it pass by value or rvalue reference, your code is same!

If you are writing a library, now you know you should guarantee it, so just do it, passing by rvalue reference is a better choice than value. Client who use you library will just write same code.

Now, for your question. How do I pass a unique_ptr argument to a constructor or a function?

You know what's the best choice.

http://scottmeyers.blogspot.com/2014/07/should-move-only-types-ever-be-passed.html

UITableViewCell Selected Background Color on Multiple Selection

For Swift 3,4 and 5 you can do this in two ways.

1) class: UITableViewCell

override func awakeFromNib() {
    super.awakeFromNib()
    //Costumize cell

    selectionStyle = .none
}

or

2) tableView cellForRowAt

    cell.selectionStyle = .none

If you want to set selection color for specific cell, check this answer: https://stackoverflow.com/a/56166325/7987502

Android: remove left margin from actionbar's custom layout

If you are adding the Toolbar via XML, you can simply add XML attributes to remove content insets.

<android.support.v7.widget.Toolbar
    xmlns:app="schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/primaryColor"
    android:contentInsetLeft="0dp"
    android:contentInsetStart="0dp"
    app:contentInsetLeft="0dp"
    app:contentInsetStart="0dp"
    android:contentInsetRight="0dp"
    android:contentInsetEnd="0dp"
    app:contentInsetRight="0dp"
    app:contentInsetEnd="0dp" />

Marker content (infoWindow) Google Maps

Although this question has already been answered, I think this approach is better : http://jsfiddle.net/kjy112/3CvaD/ extract from this question on StackOverFlow google maps - open marker infowindow given the coordinates:

Each marker gets an "infowindow" entry :

function createMarker(lat, lon, html) {
    var newmarker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lon),
        map: map,
        title: html
    });

    newmarker['infowindow'] = new google.maps.InfoWindow({
            content: html
        });

    google.maps.event.addListener(newmarker, 'mouseover', function() {
        this['infowindow'].open(map, this);
    });
}

How to turn a String into a JavaScript function call?

If settings.functionName is already a function, you could do this:

settings.functionName(t.parentNode.id);

Otherwise this should also work if settings.functionName is just the name of the function:

if (typeof window[settings.functionName] == "function") {
    window[settings.functionName](t.parentNode.id);
}

How to add a .dll reference to a project in Visual Studio

You probably are looking for AddReference dialog accessible from Project Context Menu (right click..)

From there you can reference dll's, after which you can reference namespaces that you need in your code.

Compiler error: "initializer element is not a compile-time constant"

When you define a variable outside the scope of a function, that variable's value is actually written into your executable file. This means you can only use a constant value. Since you don't know everything about the runtime environment at compile time (which classes are available, what is their structure, etc.), you cannot create objective c objects until runtime, with the exception of constant strings, which are given a specific structure and guaranteed to stay that way. What you should do is initialize the variable to nil and use +initialize to create your image. initialize is a class method which will be called before any other method is called on your class.

Example:

NSImage *imageSegment = nil;
+ (void)initialize {
    if(!imageSegment)
        imageSegment = [[NSImage alloc] initWithContentsOfFile:@"/User/asd.jpg"];
}
- (id)init {
    self = [super init];
    if (self) {
        // Initialization code here.
    }

    return self;
}

get UTC timestamp in python with datetime

Simplest way:

>>> from datetime import datetime
>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0)
>>> dt.strftime("%s")
'1199163600'

Edit: @Daniel is correct, this would convert it to the machine's timezone. Here is a revised answer:

>>> from datetime import datetime, timezone
>>> epoch = datetime(1970, 1, 1, 0, 0, 0, 0, timezone.utc)
>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0, timezone.utc)
>>> int((dt-epoch).total_seconds())
'1199145600'

In fact, its not even necessary to specify timezone.utc, because the time difference is the same so long as both datetime have the same timezone (or no timezone).

>>> from datetime import datetime
>>> epoch = datetime(1970, 1, 1, 0, 0, 0, 0)
>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0)
>>> int((dt-epoch).total_seconds())
1199145600

Deleting Row in SQLite in Android

Works great!

public void deleteNewMelk(String melkCode) {
    getWritableDatabase().delete(your_table, your_column +"=?", new String[]{melkCode});
}

How to change the remote a branch is tracking?

With an up to date git (2.5.5) the command is the following :

git branch --set-upstream-to=origin/branch

This will update the remote tracked branch for your current local branch

How do implement a breadth first traversal?

Breadth first is a queue, depth first is a stack.

For breadth first, add all children to the queue, then pull the head and do a breadth first search on it, using the same queue.

For depth first, add all children to the stack, then pop and do a depth first on that node, using the same stack.

How to run 'sudo' command in windows

There is no sudo command in case of windows and also there is no need to put any $. For installing Angular CLI through node.js command prompt in windows, I just wrote npm install -g @angular/cli and then pressed Enter. It worked fine.

Counting repeated characters in a string in Python

s = 'today is sunday i would like to relax'
numberOfDuplicatedChar = len(s) - len(set(s))

#no duplicated element in set.

Interface vs Base class

Previous comments about using abstract classes for common implementation is definitely on the mark. One benefit I haven't seen mentioned yet is that the use of interfaces makes it much easier to implement mock objects for the purpose of unit testing. Defining IPet and PetBase as Jason Cohen described enables you to mock different data conditions easily, without the overhead of a physical database (until you decide it's time to test the real thing).

Disable keyboard on EditText

try: android:editable="false" or android:inputType="none"

LINUX: Link all files from one to another directory

GNU cp has an option to create symlinks instead of copying.

cp -rs /mnt/usr/lib /usr/

Note this is a GNU extension not found in POSIX cp.

how to declare global variable in SQL Server..?

My first question is which version of SQL Server are you using (i.e 2005, 2008, 2008 R2, 2012)?

Assuming you are using 2008 or later SQL uses scope for variable determination. I believe 2005 still had global variables that would use @@variablename instead of @variable name which would define the difference between global and local variables. Starting in 2008 I believe this was changed to a scope defined variable designation structure. For example to create a global variable the @variable has to be defined at the start of a procedure, function, view, etc. In 2008 and later @@defined system variables for system functions I do believe. I could explain further if you explained the version and also where the variable is being defined, and the error that you are getting.

iterating and filtering two lists using java 8

this can be achieved using below...

 List<String> unavailable = list1.stream()
                            .filter(e -> !list2.contains(e))
                            .collect(Collectors.toList());

JQuery - Call the jquery button click event based on name property

You can use normal CSS selectors to select an element by name using jquery. Like this:

Button Code
<button type="button" name="mybutton">Click Me!</button>

Selector & Event Bind Code
$("button[name='mybutton']").click(function() {});

Jaxb, Class has two properties of the same name

Many solutions have been given, and the internals are briefly touched by @Sriram and @ptomli as well. I just want to add a few references to the source code to help understand what is happening under the hood.

By default (i.e. no extra annotations used at all except @XmlRootElement on the root class), JABX tries to marshal things exposed via two ways:

  1. public fields
  2. getter methods that are named following the convention and have a corresponding setter method.

Notice that if a field is (or method returns) null, it will not be written into the output.

Now if @XmlElement is used, non-public things (could be fields or getter methods) can be marshalled as well.

But the two ways, i.e. fields and getter-methods, must not conflict with each other. Otherwise you get the exception.

How to execute an action before close metro app WinJS

If I am not mistaken, it will be onunload event.

"Occurs when the application is about to be unloaded." - MSDN

Is there a way to get colored text in GitHubflavored Markdown?

You cannot get green/red text, but you can get green/red highlighted text using the diff language template. Example:

```diff
+ this text is highlighted in green
- this text is highlighted in red
```

Importing a Maven project into Eclipse from Git

You should note that putting generated metadata under version control (let it be git or any other scm), is not a very good idea if there are more than one developer working on the codebase. Two developers may have a totally different project or classpath setup. Just as a heads up in case you intends to share the code at some time...

What is the advantage of using REST instead of non-REST HTTP?

I recommend taking a look at Ryan Tomayko's How I Explained REST to My Wife

Third party edit

Excerpt from the waybackmaschine link:

How about an example. You’re a teacher and want to manage students:

  • what classes they’re in,
  • what grades they’re getting,
  • emergency contacts,
  • information about the books you teach out of, etc.

If the systems are web-based, then there’s probably a URL for each of the nouns involved here: student, teacher, class, book, room, etc. ... If there were a machine readable representation for each URL, then it would be trivial to latch new tools onto the system because all of that information would be consumable in a standard way. ... you could build a country-wide system that was able to talk to each of the individual school systems to collect testing scores.

Each of the systems would get information from each other using a simple HTTP GET. If one system needs to add something to another system, it would use an HTTP POST. If a system wants to update something in another system, it uses an HTTP PUT. The only thing left to figure out is what the data should look like.

React - How to pass HTML tags in props?

<MyComponent text={<span>This is <strong>not</strong> working.</span>} />

and then in your component you can do prop checking like so:

import React from 'react';
export default class MyComponent extends React.Component {
  static get propTypes() {
    return {
      text: React.PropTypes.object, // if you always want react components
      text: React.PropTypes.any, // if you want both text or react components
    }
  }
}

Make sure you choose only one prop type.

c# - How to get sum of the values from List?

Use Sum()

 List<string> foo = new List<string>();
 foo.Add("1");
 foo.Add("2");
 foo.Add("3");
 foo.Add("4");

 Console.Write(foo.Sum(x => Convert.ToInt32(x)));

Prints:

10

Android design support library for API 28 (P) not working

if you want to solve this problem without migrating to AndroidX (I don't recommend it)

this manifest merger issue is related to one of your dependency using androidX.

you need to decrease this dependency's release version. for my case :

I was using google or firebase

api 'com.google.android.gms:play-services-base:17.1.0'

I have to decrease it 15.0.1 to use in support library.

How to set the background image of a html 5 canvas to .png image

You can draw the image on the canvas and let the user draw on top of that.

The drawImage() function will help you with that, see https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images

css - position div to bottom of containing div

Add position: relative to .outside. (https://developer.mozilla.org/en-US/docs/CSS/position)

Elements that are positioned relatively are still considered to be in the normal flow of elements in the document. In contrast, an element that is positioned absolutely is taken out of the flow and thus takes up no space when placing other elements. The absolutely positioned element is positioned relative to nearest positioned ancestor. If a positioned ancestor doesn't exist, the initial container is used.

The "initial container" would be <body>, but adding the above makes .outside positioned.

Check if image exists on server using JavaScript?

You may call this JS function to check if file exists on the Server:

function doesFileExist(urlToFile)
{
    var xhr = new XMLHttpRequest();
    xhr.open('HEAD', urlToFile, false);
    xhr.send();

    if (xhr.status == "404") {
        console.log("File doesn't exist");
        return false;
    } else {
        console.log("File exists");
        return true;
    }
}

Laravel 5.2 redirect back with success message

One way to do that is sending the message in the session like this:

Controller:

return redirect()->back()->with('success', 'IT WORKS!');

View:

@if (session()->has('success'))
    <h1>{{ session('success') }}</h1>
@endif

And other way to do that is just creating the session and put the text in the view directly:

Controller:

return redirect()->back()->with('success', true);

View:

@if (session()->has('success'))
    <h1>IT WORKS!</h1>
@endif

You can check the full documentation here: Redirecting With Flashed Session Data

I hope it is very helpful, regards.

onChange and onSelect in DropDownList

Simply & Easy : JavaScript code :

function JoinedOrNot(){
    var cat = document.getElementById("mySelect");
    if(cat.value == "yes"){
        document.getElementById("mySelect1").disabled = false;
    }else{
        document.getElementById("mySelect1").disabled = true;
    }
}

just add in this line [onChange="JoinedOrNot()"] : <select id="mySelect" onchange="JoinedOrNot()">

it's work fine ;)

"int cannot be dereferenced" in Java

try

id == list[pos].getItemNumber()

instead of

id.equals(list[pos].getItemNumber()

SCRIPT438: Object doesn't support property or method IE

My problem was having type="application/javascript" on the <script> tag for jQuery. IE8 does not like this! If your webpage is HTML5 you don't even need to declare the type, otherwise go with type="text/javascript" instead.