Programs & Examples On #Branding

Branding software usually means customizing its appearance (logos, layouts, colors, etc.) for a specific organization or theme.

How to remove youtube branding after embedding video in web page?

I tried this, but it is not possible to remove "Watch on YouTube" icon. Following solution of mine does not remove the icon itself but "blocks" the mouse hover so that watch on YouTube is not click-able. I added a div over icon, so no mouseover will be affected for that logo.

 <div class="holder">
     <div class="frame" id="player" style="height 350"></div>
     <div class="bar" id="bottom-layer">.</div>
 </div>

Where frame is my embedded player. include following to your css file

.holder{
position:relative;
width:640px;
height:350px;
}

.frame{
width: 100%;
height:100%;
}

.bar{
position:absolute;
bottom:0;
right:0;
width:100%;
height:40px;
}

This is not full solution but helps you if you are bothered with users' getting full youtube url.

Bootstrap 3 Navbar with Logo

Add the following to the .navbar-brand class

.navbar-brand
{
  padding: 0px; // this allows the image to occupy all the padding space of the navbar--brand
}

.navbar-brand > img
{
   height: 100%; // set height to occupy full height space on the navbar-brand
   width: auto; // width should be auto to allow img to scale accordingly
   max-height: 100%; // optional
   mrgin: 0 auto; // optional
}

Embed Youtube video inside an Android app

Refer to this answer: How can we play YouTube embeded code in an Android application using webview?

It uses WebViews and loads an iframe in it... and yes it works.

Getting an Embedded YouTube Video to Auto Play and Loop

Had same experience, however what did the magic for me is not to change embed to v.

So the code will look like this...

<iframe width="560" height="315" src="https://www.youtube.com/embed/cTYuscQu-Og?Version=3&loop=1&playlist=cTYuscQu-Og" frameborder="0" allowfullscreen></iframe>

Hope it helps...

How can I style an Android Switch?

You can define the drawables that are used for the background, and the switcher part like this:

<Switch
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:thumb="@drawable/switch_thumb"
    android:track="@drawable/switch_bg" />

Now you need to create a selector that defines the different states for the switcher drawable. Here the copies from the Android sources:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/switch_thumb_disabled_holo_light" />
    <item android:state_pressed="true"  android:drawable="@drawable/switch_thumb_pressed_holo_light" />
    <item android:state_checked="true"  android:drawable="@drawable/switch_thumb_activated_holo_light" />
    <item                               android:drawable="@drawable/switch_thumb_holo_light" />
</selector>

This defines the thumb drawable, the image that is moved over the background. There are four ninepatch images used for the slider:

The deactivated version (xhdpi version that Android is using)The deactivated version
The pressed slider: The pressed slider
The activated slider (on state):The activated slider
The default version (off state): enter image description here

There are also three different states for the background that are defined in the following selector:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/switch_bg_disabled_holo_dark" />
    <item android:state_focused="true"  android:drawable="@drawable/switch_bg_focused_holo_dark" />
    <item                               android:drawable="@drawable/switch_bg_holo_dark" />
</selector>

The deactivated version: The deactivated version
The focused version: The focused version
And the default version:the default version

To have a styled switch just create this two selectors, set them to your Switch View and then change the seven images to your desired style.

Uncaught ReferenceError: jQuery is not defined

For one, you don't seem to be including jQuery itself in the header but only a bunch of plugins. As for the '<' error, it's impossible to tell without seeing the generated HTML.

Standard Android Button with a different color

I like the color filter suggestion in previous answers from @conjugatedirection and @Tomasz; However, I found that the code provided so far wasn't as easily applied as I expected.

First, it wasn't mentioned where to apply and clear the color filter. It's possible that there are other good places to do this, but what came to mind for me was an OnTouchListener.

From my reading of the original question, the ideal solution would be one that does not involve any images. The accepted answer using custom_button.xml from @emmby is probably a better fit than color filters if that's your goal. In my case, I'm starting with a png image from a UI designer of what the button is supposed to look like. If I set the button background to this image, the default highlight feedback is lost completely. This code replaces that behavior with a programmatic darkening effect.

button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // 0x6D6D6D sets how much to darken - tweak as desired
                setColorFilter(v, 0x6D6D6D);
                break;
            // remove the filter when moving off the button
            // the same way a selector implementation would 
            case MotionEvent.ACTION_MOVE:
                Rect r = new Rect();
                v.getLocalVisibleRect(r);
                if (!r.contains((int) event.getX(), (int) event.getY())) {
                    setColorFilter(v, null);
                }
                break;
            case MotionEvent.ACTION_OUTSIDE:
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                setColorFilter(v, null);
                break;
        }
        return false;
    }

    private void setColorFilter(View v, Integer filter) {
        if (filter == null) v.getBackground().clearColorFilter();
        else {
            // To lighten instead of darken, try this:
            // LightingColorFilter lighten = new LightingColorFilter(0xFFFFFF, filter);
            LightingColorFilter darken = new LightingColorFilter(filter, 0x000000);
            v.getBackground().setColorFilter(darken);
        }
        // required on Android 2.3.7 for filter change to take effect (but not on 4.0.4)
        v.getBackground().invalidateSelf();
    }
});

I extracted this as a separate class for application to multiple buttons - shown as anonymous inner class just to get the idea.

ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies

Might sound obvious but do you definitely have AjaxControlToolkit.dll in your bin?

Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists

A little adding because I had to use different answers to get the actual solution (for me).

This did it for me:

  1. Open branch you are working on
  2. Open terminal (I use terminal in Git GUI)
  3. Typ in command: cd .git
  4. Typ in command: rm -f index.lock

Some may have to use -Force instead of -f. You can check the command lines of your terminal by executing a command in your terminal something like: git help.

There are No resources that can be added or removed from the server

The issue is it is missing Dynamic Web Module facet definition. Run the following at command line

mvn eclipse:eclipse -Dwtpversion=2.0

After build is success, refresh the project and you will be add the web project to server.

How do I combine 2 select statements into one?

select t1.* from 
(select * from TABLE Where CCC='D' AND DDD='X') as t1,
(select * from TABLE Where CCC<>'D' AND DDD='X') as t2

Another way to do this!

What possibilities can cause "Service Unavailable 503" error?

Primarily what that means is that there are too many concurrent requests and further that they exceed the default 1000 queued requests. That is there are 1000 or more queued requests to your website.

This could happen (assuming there are no faults in your app) if there are long running tasks and as a result the Request queue is backed up.

Depending on how the application pool has been set up you may see this kind of thing. Typically, the app pool's Process Model has an item called Maximum Worker Processes. By default this is 1. If you set it to more than 1 (typically up to a max of the number of cores on the hardware) you may not see this happen.

Just to note that unless the site is extremely busy you should not see this. If you do, it's really pointing to long running tasks

How do I use 3DES encryption/decryption in Java?

I had hard times figuring it out myself and this post helped me to find the right answer for my case. When working with financial messaging as ISO-8583 the 3DES requirements are quite specific, so for my especial case the "DESede/CBC/PKCS5Padding" combinations wasn't solving the problem. After some comparative testing of my results against some 3DES calculators designed for the financial world I found the the value "DESede/ECB/Nopadding" is more suited for the the specific task.

Here is a demo implementation of my TripleDes class (using the Bouncy Castle provider)



    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.security.NoSuchProviderException;
    import java.security.Security;
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;


    /**
     *
     * @author Jose Luis Montes de Oca
     */
    public class TripleDesCipher {
       private static String TRIPLE_DES_TRANSFORMATION = "DESede/ECB/Nopadding";
       private static String ALGORITHM = "DESede";
       private static String BOUNCY_CASTLE_PROVIDER = "BC";
       private Cipher encrypter;
       private Cipher decrypter;

       public TripleDesCipher(byte[] key) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
             InvalidKeyException {
          Security.addProvider(new BouncyCastleProvider());
          SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
          encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION, BOUNCY_CASTLE_PROVIDER);
          encrypter.init(Cipher.ENCRYPT_MODE, keySpec);
          decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION, BOUNCY_CASTLE_PROVIDER);
          decrypter.init(Cipher.DECRYPT_MODE, keySpec);
       }

       public byte[] encode(byte[] input) throws IllegalBlockSizeException, BadPaddingException {
          return encrypter.doFinal(input);
       }

       public byte[] decode(byte[] input) throws IllegalBlockSizeException, BadPaddingException {
          return decrypter.doFinal(input);
       }
    }

Struct with template variables in C++

Looks like @monkeyking is trying it to make it more obvious code as shown below

template <typename T> 
struct Array { 
  size_t x; 
  T *ary; 
};

typedef Array<int> iArray;
typedef Array<float> fArray;

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

This error has been happening randomly during my test runs over the last six months (still happens with Chrome 76 and Chromedriver 76) and only on Linux. On average one of every few hundred tests would fail, then the next test would run fine.

Unable to resolve the issue, in Python I wrapped the driver = webdriver.Chrome() in a try..except block in setUp() in my test case class that all my tests are derived from. If it hits the Webdriver exception it waits ten seconds and tries again.

It solved the issue I was having; not elegantly but it works.

from selenium import webdriver
from selenium.common.exceptions import WebDriverException

try:
    self.driver = webdriver.Chrome(chrome_options=chrome_options, desired_capabilities=capabilities)
except WebDriverException as e:
    print("\nChrome crashed on launch:")
    print(e)
    print("Trying again in 10 seconds..")
    sleep(10)
    self.driver = webdriver.Chrome(chrome_options=chrome_options, desired_capabilities=capabilities)
    print("Success!\n")
except Exception as e:
    raise Exception(e)

What is parsing in terms that a new programmer would understand?

Have them try to write a program that can evaluate arbitrary simple arithmetic expressions. This is a simple problem to understand but as you start getting deeper into it a lot of basic parsing starts to make sense.

How to add a vertical Separator?

Here is how I did it:

<TextBlock Margin="0,-2,0,0">|</TextBlock>

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

The documentation states several ways to do this.

If you want to replace the default ObjectMapper completely, define a @Bean of that type and mark it as @Primary.

Defining a @Bean of type Jackson2ObjectMapperBuilder will allow you to customize both default ObjectMapper and XmlMapper (used in MappingJackson2HttpMessageConverter and MappingJackson2XmlHttpMessageConverter respectively).

What are static factory methods?

  • have names, unlike constructors, which can clarify code.
  • do not need to create a new object upon each invocation - objects can be cached and reused, if necessary.
  • can return a subtype of their return type - in particular, can return an object whose implementation class is unknown to the caller. This is a very valuable and widely used feature in many frameworks which use interfaces as the return type of static factory methods.

fromhttp://www.javapractices.com/topic/TopicAction.do?Id=21

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

You can use "$http.jsonp"

OR

Below is the work around for chrome for local testing

You need to open your chrome with following command. (Press window+R)

Chrome.exe --allow-file-access-from-files

Note : Your chrome must not be open. When you run this command chrome will open automatically.

If you are entering this command in command prompt then select your chrome installation directory then use this command.

Below script code for open chrome in MAC with "--allow-file-access-from-files"

set chromePath to POSIX path of "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" 
set switch to " --allow-file-access-from-files"
do shell script (quoted form of chromePath) & switch & " > /dev/null 2>&1 &"

second options

You can just use open(1) to add the flags: open -a 'Google Chrome' --args --allow-file-access-from-files

Set object property using reflection

Use somethings like this :

public static class PropertyExtension{       

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

or

public static class PropertyExtension{       

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

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

no pg_hba.conf entry for host

Verify the postgres connection hostname/address in pgadmin and use the same in your connection parameter.

DBI connect('database=chaosLRdb;host="keep what is mentioned" ;port=5433','postgres',...)

Run Android studio emulator on AMD processor

Recent updates enabled computers with AMD processors to run Android Emulator and you don't need to install ARM images anymore. Taken from the Android Developers blog:

If you have an AMD processor in your computer you need the following setup requirements to be in place:

  • AMD Processor - Recommended: AMD® Ryzen™ processors
  • Android Studio 3.2 Beta or higher
  • Android Emulator v27.3.8+
  • x86 Android Virtual Device (AVD)
  • Windows 10 with April 2018 Update
  • Enable via Windows Features: "Windows Hypervisor Platform"

The important point is enabling Windows Hypervisor Platform and that's it! I strongly recommend reading the whole blog post:
https://android-developers.googleblog.com/2018/07/android-emulator-amd-processor-hyper-v.html

Split comma separated column data into additional columns

split_part() does what you want in one step:

SELECT split_part(col, ',', 1) AS col1
     , split_part(col, ',', 2) AS col2
     , split_part(col, ',', 3) AS col3
     , split_part(col, ',', 4) AS col4
FROM   tbl;

Add as many lines as you have items in col (the possible maximum). Columns exceeding data items will be empty strings ('').

replace all occurrences in a string

Use the global flag.

str.replace(/\n/g, '<br />');

Center fixed div with dynamic width (CSS)

<div id="container">
    <div id="some_kind_of_popup">
        center me
    </div>
</div>

You'd need to wrap it in a container. here's the css

#container{
    position: fixed;
    top: 100px;
    width: 100%;
    text-align: center;
}
#some_kind_of_popup{
    display:inline-block;
    width: 90%;
    max-width: 900px;  
    min-height: 300px;  
}

Loop through a date range with JavaScript

var start = new Date("2014-05-01"); //yyyy-mm-dd
var end = new Date("2014-05-05"); //yyyy-mm-dd

while(start <= end){

    var mm = ((start.getMonth()+1)>=10)?(start.getMonth()+1):'0'+(start.getMonth()+1);
    var dd = ((start.getDate())>=10)? (start.getDate()) : '0' + (start.getDate());
    var yyyy = start.getFullYear();
    var date = dd+"/"+mm+"/"+yyyy; //yyyy-mm-dd

    alert(date); 

    start = new Date(start.setDate(start.getDate() + 1)); //date increase by 1
}

'module' object is not callable - calling method in another file

The problem is in the import line. You are importing a module, not a class. Assuming your file is named other_file.py (unlike java, again, there is no such rule as "one class, one file"):

from other_file import findTheRange

if your file is named findTheRange too, following java's convenions, then you should write

from findTheRange import findTheRange

you can also import it just like you did with random:

import findTheRange
operator = findTheRange.findTheRange()

Some other comments:

a) @Daniel Roseman is right. You do not need classes here at all. Python encourages procedural programming (when it fits, of course)

b) You can build the list directly:

  randomList = [random.randint(0, 100) for i in range(5)]

c) You can call methods in the same way you do in java:

largestInList = operator.findLargest(randomList)
smallestInList = operator.findSmallest(randomList)

d) You can use built in function, and the huge python library:

largestInList = max(randomList)
smallestInList = min(randomList)

e) If you still want to use a class, and you don't need self, you can use @staticmethod:

class findTheRange():
    @staticmethod
    def findLargest(_list):
        #stuff...

How do you change Background for a Button MouseOver in WPF?

Just want to share my button style from my ResourceDictionary that i've been using. You can freely change the onHover background at the style triggers. "ColorAnimation To = *your desired BG(i.e #FFCEF7A0)". The button BG will also automatically revert to its original BG after the mouseOver state.You can even set how fast the transition.

Resource Dictionary

<Style x:Key="Flat_Button" TargetType="{x:Type Button}">
    <Setter Property="Width" Value="100"/>
    <Setter Property="Height" Value="50"/>
    <Setter Property="Margin" Value="2"/>
    <Setter Property="FontFamily" Value="Arial Narrow"/>
    <Setter Property="FontSize" Value="12px"/>
    <Setter Property="FontWeight" Value="Bold"/>
    <Setter Property="Cursor" Value="Hand"/>
    <Setter Property="Foreground">
        <Setter.Value>
            <SolidColorBrush Opacity="1" Color="White"/>
        </Setter.Value>
    </Setter>
    <Setter Property="Background" >
        <Setter.Value>
            <SolidColorBrush Opacity="1" Color="#28C2FF" />
        </Setter.Value>
    </Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">

                <Border x:Name="border"
                         SnapsToDevicePixels="True"
                         BorderThickness="1"
                         Padding="4,2"
                         BorderBrush="Gray"
                         CornerRadius="3"
                         Background="{TemplateBinding Background}">
                    <Grid>
                        <ContentPresenter 
                        Margin="2"
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center"
                        RecognizesAccessKey="True" />

                    </Grid>
                </Border>

            </ControlTemplate>
        </Setter.Value>
    </Setter>

    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="true">
            <Trigger.EnterActions>
                <BeginStoryboard>
                    <Storyboard>
                        <ColorAnimation To="#D2F898"
                                        Storyboard.TargetProperty="(Control.Background).(SolidColorBrush.Color)" 
                                        FillBehavior="HoldEnd" Duration="0:0:0.25" AutoReverse="False" RepeatBehavior="1x"/>
                    </Storyboard>
                </BeginStoryboard>
            </Trigger.EnterActions>

            <Trigger.ExitActions>
                <BeginStoryboard>
                    <Storyboard>
                        <ColorAnimation
                                            Storyboard.TargetProperty="(Control.Background).(SolidColorBrush.Color)" 
                                            FillBehavior="HoldEnd" Duration="0:0:0.25" AutoReverse="False" RepeatBehavior="1x"/>
                    </Storyboard>
                </BeginStoryboard>
            </Trigger.ExitActions>

        </Trigger>


    </Style.Triggers>
</Style>

all you have to do is call the style.

Example Implementation

<Button Style="{StaticResource Flat_Button}" Height="Auto"Width="Auto">  
     <StackPanel>
     <TextBlock Text="SAVE" FontFamily="Arial" FontSize="10.667"/>
     </StackPanel>
</Button>

Get the generated SQL statement from a SqlCommand object?

I needed a similar command to string transformer to allow for more verbose logging, so I wrote this one. It will produce the text needed to re-execute the command in a new session including output parameters and structured parameters. It is lightly tested, but caveat emptor.

Example:

SqlCommand cmd = new SqlCommand("GetEntity", con);
cmd.Parameters.AddWithValue("@foobar", 1);
cmd.Parameters.Add(new SqlParameter(){
    ParameterName = "@outParam",
    Direction = ParameterDirection.Output,
    SqlDbType = System.Data.SqlDbType.Int
});
cmd.Parameters.Add(new SqlParameter(){
    Direction = ParameterDirection.ReturnValue
});
cmd.CommandType = CommandType.StoredProcedure;

Will produce:

-- BEGIN COMMAND
DECLARE @foobar INT = 1;
DECLARE @outParam INT = NULL;
DECLARE @returnValue INT;
-- END PARAMS
EXEC @returnValue = GetEntity @foobar = @foobar, @outParam = @outParam OUTPUT
-- RESULTS
SELECT 1 as Executed, @returnValue as ReturnValue, @outParam as [@outParam];
-- END COMMAND

Implementation:

public class SqlCommandDumper
{
    public static string GetCommandText(SqlCommand sqc)
    {
        StringBuilder sbCommandText = new StringBuilder();

        sbCommandText.AppendLine("-- BEGIN COMMAND");

        // params
        for (int i = 0; i < sqc.Parameters.Count; i++)
            logParameterToSqlBatch(sqc.Parameters[i], sbCommandText);
        sbCommandText.AppendLine("-- END PARAMS");

        // command
        if (sqc.CommandType == CommandType.StoredProcedure)
        {
            sbCommandText.Append("EXEC ");

            bool hasReturnValue = false;
            for (int i = 0; i < sqc.Parameters.Count; i++)
            {
                if (sqc.Parameters[i].Direction == ParameterDirection.ReturnValue)
                    hasReturnValue = true;
            }
            if (hasReturnValue)
            {
                sbCommandText.Append("@returnValue = ");
            }

            sbCommandText.Append(sqc.CommandText);

            bool hasPrev = false;
            for (int i = 0; i < sqc.Parameters.Count; i++)
            {
                var cParam = sqc.Parameters[i];
                if (cParam.Direction != ParameterDirection.ReturnValue)
                {
                    if (hasPrev)
                        sbCommandText.Append(", ");

                    sbCommandText.Append(cParam.ParameterName);
                    sbCommandText.Append(" = ");
                    sbCommandText.Append(cParam.ParameterName);

                    if (cParam.Direction.HasFlag(ParameterDirection.Output))
                        sbCommandText.Append(" OUTPUT");

                    hasPrev = true;
                }
            }
        }
        else
        {
            sbCommandText.AppendLine(sqc.CommandText);
        }

        sbCommandText.AppendLine("-- RESULTS");
        sbCommandText.Append("SELECT 1 as Executed");
        for (int i = 0; i < sqc.Parameters.Count; i++)
        {
            var cParam = sqc.Parameters[i];

            if (cParam.Direction == ParameterDirection.ReturnValue)
            {
                sbCommandText.Append(", @returnValue as ReturnValue");
            }
            else if (cParam.Direction.HasFlag(ParameterDirection.Output))
            {
                sbCommandText.Append(", ");
                sbCommandText.Append(cParam.ParameterName);
                sbCommandText.Append(" as [");
                sbCommandText.Append(cParam.ParameterName);
                sbCommandText.Append(']');
            }
        }
        sbCommandText.AppendLine(";");

        sbCommandText.AppendLine("-- END COMMAND");
        return sbCommandText.ToString();
    }

    private static void logParameterToSqlBatch(SqlParameter param, StringBuilder sbCommandText)
    {
        sbCommandText.Append("DECLARE ");
        if (param.Direction == ParameterDirection.ReturnValue)
        {
            sbCommandText.AppendLine("@returnValue INT;");
        }
        else
        {
            sbCommandText.Append(param.ParameterName);

            sbCommandText.Append(' ');
            if (param.SqlDbType != SqlDbType.Structured)
            {
                logParameterType(param, sbCommandText);
                sbCommandText.Append(" = ");
                logQuotedParameterValue(param.Value, sbCommandText);

                sbCommandText.AppendLine(";");
            }
            else
            {
                logStructuredParameter(param, sbCommandText);
            }
        }
    }

    private static void logStructuredParameter(SqlParameter param, StringBuilder sbCommandText)
    {
        sbCommandText.AppendLine(" {List Type};");
        var dataTable = (DataTable)param.Value;

        for (int rowNo = 0; rowNo < dataTable.Rows.Count; rowNo++)
        {
            sbCommandText.Append("INSERT INTO ");
            sbCommandText.Append(param.ParameterName);
            sbCommandText.Append(" VALUES (");

            bool hasPrev = false;
            for (int colNo = 0; colNo < dataTable.Columns.Count; colNo++)
            {
                if (hasPrev)
                {
                    sbCommandText.Append(", ");
                }
                logQuotedParameterValue(dataTable.Rows[rowNo].ItemArray[colNo], sbCommandText);
                hasPrev = true;
            }
            sbCommandText.AppendLine(");");
        }
    }

    const string DATETIME_FORMAT_ROUNDTRIP = "o";
    private static void logQuotedParameterValue(object value, StringBuilder sbCommandText)
    {
        try
        {
            if (value == null)
            {
                sbCommandText.Append("NULL");
            }
            else
            {
                value = unboxNullable(value);

                if (value is string
                    || value is char
                    || value is char[]
                    || value is System.Xml.Linq.XElement
                    || value is System.Xml.Linq.XDocument)
                {
                    sbCommandText.Append("N'");
                    sbCommandText.Append(value.ToString().Replace("'", "''"));
                    sbCommandText.Append('\'');
                }
                else if (value is bool)
                {
                    // True -> 1, False -> 0
                    sbCommandText.Append(Convert.ToInt32(value));
                }
                else if (value is sbyte
                    || value is byte
                    || value is short
                    || value is ushort
                    || value is int
                    || value is uint
                    || value is long
                    || value is ulong
                    || value is float
                    || value is double
                    || value is decimal)
                {
                    sbCommandText.Append(value.ToString());
                }
                else if (value is DateTime)
                {
                    // SQL Server only supports ISO8601 with 3 digit precision on datetime,
                    // datetime2 (>= SQL Server 2008) parses the .net format, and will 
                    // implicitly cast down to datetime.
                    // Alternatively, use the format string "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK"
                    // to match SQL server parsing
                    sbCommandText.Append("CAST('");
                    sbCommandText.Append(((DateTime)value).ToString(DATETIME_FORMAT_ROUNDTRIP));
                    sbCommandText.Append("' as datetime2)");
                }
                else if (value is DateTimeOffset)
                {
                    sbCommandText.Append('\'');
                    sbCommandText.Append(((DateTimeOffset)value).ToString(DATETIME_FORMAT_ROUNDTRIP));
                    sbCommandText.Append('\'');
                }
                else if (value is Guid)
                {
                    sbCommandText.Append('\'');
                    sbCommandText.Append(((Guid)value).ToString());
                    sbCommandText.Append('\'');
                }
                else if (value is byte[])
                {
                    var data = (byte[])value;
                    if (data.Length == 0)
                    {
                        sbCommandText.Append("NULL");
                    }
                    else
                    {
                        sbCommandText.Append("0x");
                        for (int i = 0; i < data.Length; i++)
                        {
                            sbCommandText.Append(data[i].ToString("h2"));
                        }
                    }
                }
                else
                {
                    sbCommandText.Append("/* UNKNOWN DATATYPE: ");
                    sbCommandText.Append(value.GetType().ToString());
                    sbCommandText.Append(" *" + "/ N'");
                    sbCommandText.Append(value.ToString());
                    sbCommandText.Append('\'');
                }
            }
        }

        catch (Exception ex)
        {
            sbCommandText.AppendLine("/* Exception occurred while converting parameter: ");
            sbCommandText.AppendLine(ex.ToString());
            sbCommandText.AppendLine("*/");
        }
    }

    private static object unboxNullable(object value)
    {
        var typeOriginal = value.GetType();
        if (typeOriginal.IsGenericType
            && typeOriginal.GetGenericTypeDefinition() == typeof(Nullable<>))
        {
            // generic value, unboxing needed
            return typeOriginal.InvokeMember("GetValueOrDefault",
                System.Reflection.BindingFlags.Public |
                System.Reflection.BindingFlags.Instance |
                System.Reflection.BindingFlags.InvokeMethod,
                null, value, null);
        }
        else
        {
            return value;
        }
    }

    private static void logParameterType(SqlParameter param, StringBuilder sbCommandText)
    {
        switch (param.SqlDbType)
        {
            // variable length
            case SqlDbType.Char:
            case SqlDbType.NChar:
            case SqlDbType.Binary:
                {
                    sbCommandText.Append(param.SqlDbType.ToString().ToUpper());
                    sbCommandText.Append('(');
                    sbCommandText.Append(param.Size);
                    sbCommandText.Append(')');
                }
                break;
            case SqlDbType.VarChar:
            case SqlDbType.NVarChar:
            case SqlDbType.VarBinary:
                {
                    sbCommandText.Append(param.SqlDbType.ToString().ToUpper());
                    sbCommandText.Append("(MAX /* Specified as ");
                    sbCommandText.Append(param.Size);
                    sbCommandText.Append(" */)");
                }
                break;
            // fixed length
            case SqlDbType.Text:
            case SqlDbType.NText:
            case SqlDbType.Bit:
            case SqlDbType.TinyInt:
            case SqlDbType.SmallInt:
            case SqlDbType.Int:
            case SqlDbType.BigInt:
            case SqlDbType.SmallMoney:
            case SqlDbType.Money:
            case SqlDbType.Decimal:
            case SqlDbType.Real:
            case SqlDbType.Float:
            case SqlDbType.Date:
            case SqlDbType.DateTime:
            case SqlDbType.DateTime2:
            case SqlDbType.DateTimeOffset:
            case SqlDbType.UniqueIdentifier:
            case SqlDbType.Image:
                {
                    sbCommandText.Append(param.SqlDbType.ToString().ToUpper());
                }
                break;
            // Unknown
            case SqlDbType.Timestamp:
            default:
                {
                    sbCommandText.Append("/* UNKNOWN DATATYPE: ");
                    sbCommandText.Append(param.SqlDbType.ToString().ToUpper());
                    sbCommandText.Append(" *" + "/ ");
                    sbCommandText.Append(param.SqlDbType.ToString().ToUpper());
                }
                break;
        }
    }
}

Refresh an asp.net page on button click

That on code behind redirect to the same page.

Response.Redirect(Request.RawUrl);

"echo -n" prints "-n"

enable -n echo
echo -n "Some string..."

getContext is not a function

Your value:

this.element = $(id);

is a jQuery object, not a pure Canvas element.

To turn it back so you can call getContext(), call this.element.get(0), or better yet store the real element and not the jQuery object:

function canvasLayer(location, id) {

    this.width = $(window).width();
    this.height = $(window).height();
    this.element = document.createElement('canvas');

    $(this.element)
       .attr('id', id)
       .text('unsupported browser')
       .attr('width', this.width)       // for pixels
       .attr('height', this.height)
       .width(this.width)               // for CSS scaling
       .height(this.height)
       .appendTo(location);

    this.context = this.element.getContext("2d");
}

See running code at http://jsfiddle.net/alnitak/zbaMh/, ideally using the Chrome Javascript Console so you can see the resulting object in the debug output.

Passing just a type as a parameter in C#

You can do this, just wrap it in typeof()

foo.GetColumnValues(typeof(int))

public void GetColumnValues(Type type)
{
    //logic
}

Replace transparency in PNG images with white background

this creates an image just placing the 1st with transparency on top of the 2nd

composite -gravity center ImgWithTransp.png BackgroundSameSizeOfImg.png ResultImg.png

originally found the tip on this post

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

Why not use the jQuery Event API?

http://learn.jquery.com/events/event-extensions/

I've used this simple event with success. It's clean, namespaceable and flexible enough to improve upon.

var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent);
var eventType = isMobile ? "touchstart" : "click";

jQuery.event.special.touchclick = {
  bindType: eventType,
  delegateType: eventType
};

PHP Parse error: syntax error, unexpected end of file in a CodeIgniter View

Usually the problem is not closing brackets (}) or missing semicolon (;)

Storing SHA1 hash values in MySQL

If you need an index on the sha1 column, I suggest CHAR(40) for performance reasons. In my case the sha1 column is an email confirmation token, so on the landing page the query enters only with the token. In this case CHAR(40) with INDEX, in my opinion, is the best choice :)

If you want to adopt this method, remember to leave $raw_output = false.

Reload child component when variables on parent component changes. Angular2

You can use @input with ngOnChanges, to see the changes when it happened.

reference: https://angular.io/api/core/OnChanges

(or)

If you want to pass data between multiple component or routes then go with Rxjs way.

Service.ts

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class MessageService {
  private subject = new Subject<any>();

  sendMessage(message: string) {
    this.subject.next({ text: message });
  }

  clearMessages() {
    this.subject.next();
  }

  getMessage(): Observable<any> {
    return this.subject.asObservable();
  }
}

Component.ts

import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';

import { MessageService } from './_services/index';

@Component({
  selector: 'app',
  templateUrl: 'app.component.html'
})

export class AppComponent implements OnDestroy {
  messages: any[] = [];
  subscription: Subscription;

  constructor(private messageService: MessageService) {
    // subscribe to home component messages
    this.subscription = this.messageService.getMessage().subscribe(message => {
      if (message) {
        this.messages.push(message);
      } else {
        // clear messages when empty message received
        this.messages = [];
      }
    });
  }

  ngOnDestroy() {
    // unsubscribe to ensure no memory leaks
    this.subscription.unsubscribe();
  }
}

Reference: http://jasonwatmore.com/post/2019/02/07/angular-7-communicating-between-components-with-observable-subject

Make virtualenv inherit specific packages from your global site-packages

You can use virtualenv --clear. which won't install any packages, then install the ones you want.

How to fix syntax error, unexpected T_IF error in php?

PHP parser errors take some getting used to; if it complains about an unexpected 'something' at line X, look at line X-1 first. In this case it will not tell you that you forgot a semi-colon at the end of the previous line , instead it will complain about the if that comes next.

You'll get used to it :)

How do I create a SQL table under a different schema?

When I create a table using SSMS 2008, I see 3 panes:

  • The column designer
  • Column properties
  • The table properties

In the table properties pane, there is a field: Schema which allows you to select the schema.

Why is access to the path denied?

I was facing this error because

Sometimes when I Combine the path with File Name and FileName = ""

It become Path Directory not a file which is a problem as mentioned above

so you must check for FileName like this

if(itemUri!="")
        File.Delete(Path.Combine(RemoteDirectoryPath, itemUri));

Resize a picture to fit a JLabel

Outline

Here are the steps to follow.

  • Read the picture as a BufferedImage.
  • Resize the BufferedImage to another BufferedImage that's the size of the JLabel.
  • Create an ImageIcon from the resized BufferedImage.

You do not have to set the preferred size of the JLabel. Once you've scaled the image to the size you want, the JLabel will take the size of the ImageIcon.

Read the picture as a BufferedImage

BufferedImage img = null;
try {
    img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
    e.printStackTrace();
}

Resize the BufferedImage

Image dimg = img.getScaledInstance(label.getWidth(), label.getHeight(),
        Image.SCALE_SMOOTH);

Make sure that the label width and height are the same proportions as the original image width and height. In other words, if the picture is 600 x 900 pixels, scale to 100 X 150. Otherwise, your picture will be distorted.

Create an ImageIcon

ImageIcon imageIcon = new ImageIcon(dimg);

How to set character limit on the_content() and the_excerpt() in wordpress

This also balances HTML tags so that they won't be left open and doesn't break words.

add_filter("the_content", "break_text");
function break_text($text){
    $length = 500;
    if(strlen($text)<$length+10) return $text;//don't cut if too short

    $break_pos = strpos($text, ' ', $length);//find next space after desired length
    $visible = substr($text, 0, $break_pos);
    return balanceTags($visible) . " […]";
} 

Saving timestamp in mysql table using php

Better is use datatype varchar(15).

Get properties of a class

There is another answer here that also fits the authors request: 'compile-time' way to get all property names defined interface

If you use the plugin ts-transformer-keys and an Interface to your class you can get all the keys for the class.

But if you're using Angular or React then in some scenarios there is additional configuration necessary (webpack and typescript) to get it working: https://github.com/kimamula/ts-transformer-keys/issues/4

Best approach to real time http streaming to HTML5 video client

One way to live-stream a RTSP-based webcam to a HTML5 client (involves re-encoding, so expect quality loss and needs some CPU-power):

  • Set up an icecast server (could be on the same machine you web server is on or on the machine that receives the RTSP-stream from the cam)
  • On the machine receiving the stream from the camera, don't use FFMPEG but gstreamer. It is able to receive and decode the RTSP-stream, re-encode it and stream it to the icecast server. Example pipeline (only video, no audio):

    gst-launch-1.0 rtspsrc location=rtsp://192.168.1.234:554 user-id=admin user-pw=123456 ! rtph264depay ! avdec_h264 ! vp8enc threads=2 deadline=10000 ! webmmux streamable=true ! shout2send password=pass ip=<IP_OF_ICECAST_SERVER> port=12000 mount=cam.webm
    

=> You can then use the <video> tag with the URL of the icecast-stream (http://127.0.0.1:12000/cam.webm) and it will work in every browser and device that supports webm

Equals(=) vs. LIKE

This is a copy/paste of another answer of mine for question SQL 'like' vs '=' performance:

A personal example using mysql 5.5: I had an inner join between 2 tables, one of 3 million rows and one of 10 thousand rows.

When using a like on an index as below(no wildcards), it took about 30 seconds:

where login like '12345678'

using 'explain' I get:

enter image description here

When using an '=' on the same query, it took about 0.1 seconds:

where login ='12345678'

Using 'explain' I get:

enter image description here

As you can see, the like completely cancelled the index seek, so query took 300 times more time.

jQuery delete all table rows except first


$("#p-items").find( 'tr.row-items' ).remove();

findAll() in yii

Just to add some alternate, you could do like this also:

$id =101;
$criteria = new CDbCriteria();
$criteria->condition = "email_id =:email_id";
$criteria->params = array(':email_id' => $id);
$comments = EmailArchive::model()->findAll($criteria);

Passing HTML input value as a JavaScript Function Parameter

   <form action="" onsubmit="additon()" name="form1" id="form1">
      a: <input type="number" name="a" id="a"><br>
      b: <input type="number" name="b" id="b"><br>
      <input type="submit" value="Submit" name="submit">
   </form>
  <script>
      function additon() 
      {
           var a = document.getElementById('a').value;
           var b = document.getElementById('b').value;
           var sum = parseInt(a) + parseInt(b);
           return sum;
      }
  </script>

Loading and parsing a JSON file with multiple JSON objects

You have a JSON Lines format text file. You need to parse your file line by line:

import json

data = []
with open('file') as f:
    for line in f:
        data.append(json.loads(line))

Each line contains valid JSON, but as a whole, it is not a valid JSON value as there is no top-level list or object definition.

Note that because the file contains JSON per line, you are saved the headaches of trying to parse it all in one go or to figure out a streaming JSON parser. You can now opt to process each line separately before moving on to the next, saving memory in the process. You probably don't want to append each result to one list and then process everything if your file is really big.

If you have a file containing individual JSON objects with delimiters in-between, use How do I use the 'json' module to read in one JSON object at a time? to parse out individual objects using a buffered method.

Spell Checker for Python

The best way for spell checking in python is by: SymSpell, Bk-Tree or Peter Novig's method.

The fastest one is SymSpell.

This is Method1: Reference link pyspellchecker

This library is based on Peter Norvig's implementation.

pip install pyspellchecker

from spellchecker import SpellChecker

spell = SpellChecker()

# find those words that may be misspelled
misspelled = spell.unknown(['something', 'is', 'hapenning', 'here'])

for word in misspelled:
    # Get the one `most likely` answer
    print(spell.correction(word))

    # Get a list of `likely` options
    print(spell.candidates(word))

Method2: SymSpell Python

pip install -U symspellpy

Get Category name from Post ID

here you go get_the_category( $post->ID ); will return the array of categories of that post you need to loop through the array

$category_detail=get_the_category('4');//$post->ID
foreach($category_detail as $cd){
echo $cd->cat_name;
}

get_the_category

How do I concatenate text in a query in sql server?

Another option is the CONCAT command:

SELECT CONCAT(MyTable.TextColumn, 'Text') FROM MyTable

Preventing twitter bootstrap carousel from auto sliding on page load

Or if you're using Bootstrap 3.0 you can stop the cycling with data-interval="false" for instance

<div id="carousel-example-generic" class="carousel slide" data-interval="false">

Other helpful carousel data attributes are here -> http://getbootstrap.com/javascript/#carousel-usage

How do I show a message in the foreach loop?

You are looking to see if a single value is in an array. Use in_array.

However note that case is important, as are any leading or trailing spaces. Use var_dump to find out the length of the strings too, and see if they fit.

WebDriver: check if an element exists?

String link = driver.findElement(By.linkText(linkText)).getAttribute("href")

This will give you the link the element is pointing to.

Intent from Fragment to Activity

Remove this

android:onClick="goToAttract"

Then

View rootView = inflater.inflate(R.layout.fragment_home, container, false);
Button b = (Button)rootView.findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
     public void onClick(View v)
     {
        Intent intent = new Intent(getActivity(), MainActivityList.class);
        startActivity(intent);

     } 

});
return rootView;

The error says you need to public void goToAttract(View v) in Activity class

Could not find method goToAttract(View) in the activity class

Reason pls check the answer by PareshMayani @

Android app crashing (fragment and xml onclick)

Edit:

Caused by: java.lang.OutOfMemoryError

I guess you have a image that is too big to fit in and it needs to be scaled down. Hence the OutOfMemoryError.

Why catch and rethrow an exception in C#?

Most of answers talking about scenario catch-log-rethrow.

Instead of writing it in your code consider to use AOP, in particular Postsharp.Diagnostic.Toolkit with OnExceptionOptions IncludeParameterValue and IncludeThisArgument

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

The way I solved this issue was quite simple, I checked my chrome version and I had an older chromedriver in my PATH variable, so I downloaded the chromedriver version that matched my browser and replaced the old one in the PATH, so when the webdriver module looked for a chromedriver in my PATH, it would find the matching version

how to display data values on Chart.js

This animation option works for 2.1.3 on a bar chart.

Slightly modified @Ross answer

animation: {
duration: 0,
onComplete: function () {
    // render the value of the chart above the bar
    var ctx = this.chart.ctx;
    ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
    ctx.fillStyle = this.chart.config.options.defaultFontColor;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'bottom';
    this.data.datasets.forEach(function (dataset) {
        for (var i = 0; i < dataset.data.length; i++) {
            var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
            ctx.fillText(dataset.data[i], model.x, model.y - 5);
        }
    });
}}

"elseif" syntax in JavaScript

Actually, technically when indented properly, it would be:

if (condition) {
    ...
} else {
    if (condition) {
        ...
    } else {
        ...
    }
}

There is no else if, strictly speaking.

(Update: Of course, as pointed out, the above is not considered good style.)

android.view.InflateException: Binary XML file: Error inflating class fragment

FWIW: I was getting "Android.Views.InflateException Message=Binary XML file line #1: Binary XML file line #1: Error inflating class android.view.TextureView"

I am new to android form design. In trying to put a border on some buttons I found an SO post that inspired me to create buttonborder.xml that looks like:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="@android:color/transparent" />
<stroke android:width="1dp" android:color="@android:color/white"/>

Then for each button I added

android:background="@drawable/buttonborder"

However, in my enthusiasm I also added it to a TextureView - which was my problem. When I removed the line from the TextureView, things worked.

How to Allow Remote Access to PostgreSQL database

A fast shortcut for restarting service on Windows:

1) Press Windows Key + R

2) Type "services.msc"

enter image description here

3) Order by name

4) Find "PostgreSQL" service and restart it.

enter image description here

JavaScript array to CSV

for a simple csv one map() and a join() are enough:

var csv = test_array.map(function(d){
    return d.join();
}).join('\n');

/* Results in 
name1,2,3
name2,4,5
name3,6,7
name4,8,9
name5,10,11

This method also allows you to specify column separator other than a comma in the inner join. for example a tab: d.join('\t')

On the other hand if you want to do it properly and enclose strings in quotes "", then you can use some JSON magic:

var csv = test_array.map(function(d){
   return JSON.stringify(d);
})
.join('\n') 
.replace(/(^\[)|(\]$)/mg, ''); // remove opening [ and closing ] brackets from each line 

/* would produce
"name1",2,3
"name2",4,5
"name3",6,7
"name4",8,9
"name5",10,11

if you have array of objects like :

var data = [
  {"title": "Book title 1", "author": "Name1 Surname1"},
  {"title": "Book title 2", "author": "Name2 Surname2"},
  {"title": "Book title 3", "author": "Name3 Surname3"},
  {"title": "Book title 4", "author": "Name4 Surname4"}
];

// use
var csv = data.map(function(d){
    return JSON.stringify(Object.values(d));
})
.join('\n') 
.replace(/(^\[)|(\]$)/mg, '');

MongoDB: Is it possible to make a case-insensitive query?

TL;DR

Correct way to do this in mongo

Do not Use RegExp

Go natural And use mongodb's inbuilt indexing , search

Step 1 :

db.articles.insert(
   [
     { _id: 1, subject: "coffee", author: "xyz", views: 50 },
     { _id: 2, subject: "Coffee Shopping", author: "efg", views: 5 },
     { _id: 3, subject: "Baking a cake", author: "abc", views: 90  },
     { _id: 4, subject: "baking", author: "xyz", views: 100 },
     { _id: 5, subject: "Café Con Leche", author: "abc", views: 200 },
     { _id: 6, subject: "???????", author: "jkl", views: 80 },
     { _id: 7, subject: "coffee and cream", author: "efg", views: 10 },
     { _id: 8, subject: "Cafe con Leche", author: "xyz", views: 10 }
   ]
)
 

Step 2 :

Need to create index on whichever TEXT field you want to search , without indexing query will be extremely slow

db.articles.createIndex( { subject: "text" } )

step 3 :

db.articles.find( { $text: { $search: "coffee",$caseSensitive :true } } )  //FOR SENSITIVITY
db.articles.find( { $text: { $search: "coffee",$caseSensitive :false } } ) //FOR INSENSITIVITY


 

Generate war file from tomcat webapp folder

Create the war file in a different directory to where the content is otherwise the jar command might try to zip up the file it is creating.

#!/bin/bash

set -euo pipefail

war=app.war
src=contents

# Clean last war build
if [ -e ${war} ]; then
    echo "Removing old war ${war}"
    rm -rf ${war}
fi

# Build war
if [ -d ${src} ]; then
    echo "Found source at ${src}"
    cd ${src}
    jar -cvf ../${war} *
    cd ..
fi

# Show war details
ls -la ${war}

Calling a javascript function recursively

Using Named Function Expressions:

You can give a function expression a name that is actually private and is only visible from inside of the function ifself:

var factorial = function myself (n) {
    if (n <= 1) {
        return 1;
    }
    return n * myself(n-1);
}
typeof myself === 'undefined'

Here myself is visible only inside of the function itself.

You can use this private name to call the function recursively.

See 13. Function Definition of the ECMAScript 5 spec:

The Identifier in a FunctionExpression can be referenced from inside the FunctionExpression's FunctionBody to allow the function to call itself recursively. However, unlike in a FunctionDeclaration, the Identifier in a FunctionExpression cannot be referenced from and does not affect the scope enclosing the FunctionExpression.

Please note that Internet Explorer up to version 8 doesn't behave correctly as the name is actually visible in the enclosing variable environment, and it references a duplicate of the actual function (see patrick dw's comment below).

Using arguments.callee:

Alternatively you could use arguments.callee to refer to the current function:

var factorial = function (n) {
    if (n <= 1) {
        return 1;
    }
    return n * arguments.callee(n-1);
}

The 5th edition of ECMAScript forbids use of arguments.callee() in strict mode, however:

(From MDN): In normal code arguments.callee refers to the enclosing function. This use case is weak: simply name the enclosing function! Moreover, arguments.callee substantially hinders optimizations like inlining functions, because it must be made possible to provide a reference to the un-inlined function if arguments.callee is accessed. arguments.callee for strict mode functions is a non-deletable property which throws when set or retrieved.

How to output to the console in C++/Windows

If you have a none-console Windows application, you can create a console with the AllocConsole function. Once created, you can write to it using the normal std::cout methods.

JAX-RS — How to return JSON and HTTP status code together?

There are several use cases for setting HTTP status codes in a REST web service, and at least one was not sufficiently documented in the existing answers (i.e. when you are using auto-magical JSON/XML serialization using JAXB, and you want to return an object to be serialized, but also a status code different than the default 200).

So let me try and enumerate the different use cases and the solutions for each one:

1. Error code (500, 404,...)

The most common use case when you want to return a status code different than 200 OK is when an error occurs.

For example:

  • an entity is requested but it doesn't exist (404)
  • the request is semantically incorrect (400)
  • the user is not authorized (401)
  • there is a problem with the database connection (500)
  • etc..

a) Throw an exception

In that case, I think that the cleanest way to handle the problem is to throw an exception. This exception will be handled by an ExceptionMapper, that will translate the exception into a response with the appropriate error code.

You can use the default ExceptionMapper that comes pre-configured with Jersey (and I guess it's the same with other implementations) and throw any of the existing sub-classes of javax.ws.rs.WebApplicationException. These are pre-defined exception types that are pre-mapped to different error codes, for example:

  • BadRequestException (400)
  • InternalServerErrorException (500)
  • NotFoundException (404)

Etc. You can find the list here: API

Alternatively, you can define your own custom exceptions and ExceptionMapper classes, and add these mappers to Jersey by the mean of the @Provider annotation (source of this example):

public class MyApplicationException extends Exception implements Serializable
{
    private static final long serialVersionUID = 1L;
    public MyApplicationException() {
        super();
    }
    public MyApplicationException(String msg)   {
        super(msg);
    }
    public MyApplicationException(String msg, Exception e)  {
        super(msg, e);
    }
}

Provider :

    @Provider
    public class MyApplicationExceptionHandler implements ExceptionMapper<MyApplicationException> 
    {
        @Override
        public Response toResponse(MyApplicationException exception) 
        {
            return Response.status(Status.BAD_REQUEST).entity(exception.getMessage()).build();  
        }
    }

Note: you can also write ExceptionMappers for existing exception types that you use.

b) Use the Response builder

Another way to set a status code is to use a Response builder to build a response with the intended code.

In that case, your method's return type must be javax.ws.rs.core.Response. This is described in various other responses such as hisdrewness' accepted answer and looks like this :

@GET
@Path("myresource({id}")
public Response retrieveSomething(@PathParam("id") String id) {
    ...
    Entity entity = service.getById(uuid);
    if(entity == null) {
        return Response.status(Response.Status.NOT_FOUND).entity("Resource not found for ID: " + uuid).build();
    }
    ...
}

2. Success, but not 200

Another case when you want to set the return status is when the operation was successful, but you want to return a success code different than 200, along with the content that you return in the body.

A frequent use case is when you create a new entity (POST request) and want to return info about this new entity or maybe the entity itself, together with a 201 Created status code.

One approach is to use the response object just like described above and set the body of the request yourself. However, by doing this you loose the ability to use the automatic serialization to XML or JSON provided by JAXB.

This is the original method returning an entity object that will be serialized to JSON by JAXB:

@Path("/")
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public User addUser(User user){
    User newuser = ... do something like DB insert ...
    return newuser;
}

This will return a JSON representation of the newly created user, but the return status will be 200, not 201.

Now the problem is if I want to use the Response builder to set the return code, I have to return a Response object in my method. How do I still return the User object to be serialized?

a) Set the code on the servlet response

One approach to solve this is to obtain a servlet request object and set the response code manually ourselves, like demonstrated in Garett Wilson's answer :

@Path("/")
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public User addUser(User user, @Context final HttpServletResponse response){

    User newUser = ...

    //set HTTP code to "201 Created"
    response.setStatus(HttpServletResponse.SC_CREATED);
    try {
        response.flushBuffer();
    }catch(Exception e){}

    return newUser;
}

The method still returns an entity object and the status code will be 201.

Note that to make it work, I had to flush the response. This is an unpleasant resurgence of low-level Servlet API code in our nice JAX_RS resource, and much worse, it causes the headers to be unmodifiable after this because they were already sent on the wire.

b) Use the response object with the entity

The best solution, in that case, is to use the Response object and set the entity to be serialized on this response object. It would be nice to make the Response object generic to indicate the type of the payload entity in that case, but is not the currently the case.

@Path("/")
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response addUser(User user){

    User newUser = ...

    return Response.created(hateoas.buildLinkUri(newUser, "entity")).entity(restResponse).build();
}

In that case, we use the created method of the Response builder class in order to set the status code to 201. We pass the entity object (user) to the response via the entity() method.

The result is that the HTTP code is 401 as we wanted, and the body of the response is the exact same JSON as we had before when we just returned the User object. It also adds a location header.

The Response class has a number of builder method for different statuses (stati ?) such as :

Response.accepted() Response.ok() Response.noContent() Response.notAcceptable()

NB: the hateoas object is a helper class that I developed to help generate resources URIs. You will need to come up with your own mechanism here ;)

That's about it.

I hope this lengthy response helps somebody :)

How to reset form body in bootstrap modal box?

The below solution solved my problem and also kept the default values

$('body').on('hidden.bs.modal', '.modal', function () { 
  $(this).find('input[type="text"],input[type="email"],textarea,select').each(function() { 
    if (this.defaultValue != '' || this.value != this.defaultValue) {
         this.value = this.defaultValue; 
    } else { this.value = ''; }
  }); 
}); 

IndexError: tuple index out of range ----- Python

A tuple consists of a number of values separated by commas. like

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345

tuple are index based (and also immutable) in Python.

Here in this case x = rows[1][1] + " " + rows[1][2] have only two index 0, 1 available but you are trying to access the 3rd index.

java: Class.isInstance vs Class.isAssignableFrom

Both answers are in the ballpark but neither is a complete answer.

MyClass.class.isInstance(obj) is for checking an instance. It returns true when the parameter obj is non-null and can be cast to MyClass without raising a ClassCastException. In other words, obj is an instance of MyClass or its subclasses.

MyClass.class.isAssignableFrom(Other.class) will return true if MyClass is the same as, or a superclass or superinterface of, Other. Other can be a class or an interface. It answers true if Other can be converted to a MyClass.

A little code to demonstrate:

public class NewMain
{
    public static void main(String[] args)
    {
        NewMain nm = new NewMain();
        nm.doit();
    }

    class A { }

    class B extends A { }

    public void doit()
    {
        A myA = new A();
        B myB = new B();
        A[] aArr = new A[0];
        B[] bArr = new B[0];

        System.out.println("b instanceof a: " + (myB instanceof A)); // true
        System.out.println("b isInstance a: " + A.class.isInstance(myB)); //true
        System.out.println("a isInstance b: " + B.class.isInstance(myA)); //false
        System.out.println("b isAssignableFrom a: " + A.class.isAssignableFrom(B.class)); //true
        System.out.println("a isAssignableFrom b: " + B.class.isAssignableFrom(A.class)); //false
        System.out.println("bArr isInstance A: " + A.class.isInstance(bArr)); //false
        System.out.println("bArr isInstance aArr: " + aArr.getClass().isInstance(bArr)); //true
        System.out.println("bArr isAssignableFrom aArr: " + aArr.getClass().isAssignableFrom(bArr.getClass())); //true
    }
}

Sending HTML email using Python

Actually, yagmail took a bit different approach.

It will by default send HTML, with automatic fallback for incapable email-readers. It is not the 17th century anymore.

Of course, it can be overridden, but here goes:

import yagmail
yag = yagmail.SMTP("[email protected]", "mypassword")

html_msg = """<p>Hi!<br>
              How are you?<br>
              Here is the <a href="http://www.python.org">link</a> you wanted.</p>"""

yag.send("[email protected]", "the subject", html_msg)

For installation instructions and many more great features, have a look at the github.

Angular JS break ForEach

onSelectionChanged(event) {
    let selectdata = event['api']['immutableService']['gridOptionsWrapper']['gridOptions']['rowData'];
    let selected_flag = 0;

    selectdata.forEach(data => {
      if (data.selected == true) {
        selected_flag = 1;
      }
    });

    if (selected_flag == 1) {
      this.showForms = true;
    } else {
      this.showForms = false;
    }
}

How to: Install Plugin in Android Studio

As far as installing a custom plugin there is a good walkthrough on GitHub for the rest2mobile library that could be used for any plugin.

Basically the steps are as follows:

  1. Run Android Studio.
  2. From the menu bar, select Android Studio > Preferences.
  3. Under IDE Settings, click Plugins and then click Install plugin from disk.
  4. Navigate to the folder where you downloaded the plugin and double-click it.
  5. Restart Android Studio.

How to get substring in C

If you just want to print the substrings ...

char s[] = "THESTRINGHASNOSPACES";
size_t i, slen = strlen(s);
for (i = 0; i < slen; i += 4) {
  printf("%.4s\n", s + i);
}

assign headers based on existing row in dataframe in R

The key here is to unlist the row first.

colnames(DF) <- as.character(unlist(DF[1,]))
DF = DF[-1, ]

How do I determine whether my calculation of pi is accurate?

You could try computing sin(pi/2) (or cos(pi/2) for that matter) using the (fairly) quickly converging power series for sin and cos. (Even better: use various doubling formulas to compute nearer x=0 for faster convergence.)

BTW, better than using series for tan(x) is, with computing say cos(x) as a black box (e.g. you could use taylor series as above) is to do root finding via Newton. There certainly are better algorithms out there, but if you don't want to verify tons of digits this should suffice (and it's not that tricky to implement, and you only need a bit of calculus to understand why it works.)

How to filter an array from all elements of another array

A more flexible filtering array from another array which contain object properties

_x000D_
_x000D_
function filterFn(array, diffArray, prop, propDiff) {_x000D_
    diffArray = !propDiff ? diffArray : diffArray.map(d => d[propDiff])_x000D_
    this.fn = f => diffArray.indexOf(f) === -1_x000D_
    if (prop) {_x000D_
         return array.map(r => r[prop]).filter(this.fn)_x000D_
    } else {_x000D_
         return array.filter(this.fn)_x000D_
    }_x000D_
}_x000D_
_x000D_
//You can use it like this;_x000D_
_x000D_
var arr = [];_x000D_
_x000D_
for (var i = 0; i < 10; i++) {_x000D_
    var obj = {}_x000D_
    obj.index = i_x000D_
    obj.value = Math.pow(2, i)_x000D_
    arr.push(obj)_x000D_
}_x000D_
_x000D_
var arr2 = [1, 2, 3, 4, 5]_x000D_
_x000D_
var sec = [{t:2}, {t:99}, {t:256}, {t:4096}]_x000D_
_x000D_
var log = console.log.bind(console)_x000D_
_x000D_
var filtered = filterFn(arr, sec, 'value', 't')_x000D_
_x000D_
var filtered2 = filterFn(arr2, sec, null, 't')_x000D_
_x000D_
log(filtered, filtered2)
_x000D_
_x000D_
_x000D_

How to respond to clicks on a checkbox in an AngularJS directive?

Liviu's answer was extremely helpful for me. Hope this is not bad form but i made a fiddle that may help someone else out in the future.

Two important pieces that are needed are:

    $scope.entities = [{
    "title": "foo",
    "id": 1
}, {
    "title": "bar",
    "id": 2
}, {
    "title": "baz",
    "id": 3
}];
$scope.selected = [];

View/edit ID3 data for MP3 files

TagLib Sharp is pretty popular.

As a side note, if you wanted to take a quick and dirty peek at doing it yourself.. here is a C# snippet I found to read an mp3's tag info.

class MusicID3Tag

{

    public byte[] TAGID = new byte[3];      //  3
    public byte[] Title = new byte[30];     //  30
    public byte[] Artist = new byte[30];    //  30 
    public byte[] Album = new byte[30];     //  30 
    public byte[] Year = new byte[4];       //  4 
    public byte[] Comment = new byte[30];   //  30 
    public byte[] Genre = new byte[1];      //  1

}

string filePath = @"C:\Documents and Settings\All Users\Documents\My Music\Sample Music\041105.mp3";

        using (FileStream fs = File.OpenRead(filePath))
        {
            if (fs.Length >= 128)
            {
                MusicID3Tag tag = new MusicID3Tag();
                fs.Seek(-128, SeekOrigin.End);
                fs.Read(tag.TAGID, 0, tag.TAGID.Length);
                fs.Read(tag.Title, 0, tag.Title.Length);
                fs.Read(tag.Artist, 0, tag.Artist.Length);
                fs.Read(tag.Album, 0, tag.Album.Length);
                fs.Read(tag.Year, 0, tag.Year.Length);
                fs.Read(tag.Comment, 0, tag.Comment.Length);
                fs.Read(tag.Genre, 0, tag.Genre.Length);
                string theTAGID = Encoding.Default.GetString(tag.TAGID);

                if (theTAGID.Equals("TAG"))
                {
                    string Title = Encoding.Default.GetString(tag.Title);
                    string Artist = Encoding.Default.GetString(tag.Artist);
                    string Album = Encoding.Default.GetString(tag.Album);
                    string Year = Encoding.Default.GetString(tag.Year);
                    string Comment = Encoding.Default.GetString(tag.Comment);
                    string Genre = Encoding.Default.GetString(tag.Genre);

                    Console.WriteLine(Title);
                    Console.WriteLine(Artist);
                    Console.WriteLine(Album);
                    Console.WriteLine(Year);
                    Console.WriteLine(Comment);
                    Console.WriteLine(Genre);
                    Console.WriteLine();
                }
            }
        }

Oracle insert from select into table with more columns

just select '0' as the value for the desired column

Inserting a Python datetime.datetime object into MySQL

You are most likely getting the TypeError because you need quotes around the datecolumn value.

Try:

now = datetime.datetime(2009, 5, 5)

cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s, '%s')",
               ("name", 4, now))

With regards to the format, I had success with the above command (which includes the milliseconds) and with:

now.strftime('%Y-%m-%d %H:%M:%S')

Hope this helps.

How to disable Compatibility View in IE

Adding a tag to your page will not control the UI in the Internet Control Panel (the dialog that appears when you selection Tools -> Options). If you're looking at your homepage which could be google.com, msn.com, about:blank or example.com, the Internet Control Panel has no way of knowing what the contents of your page may be, and it will not download it in the background.

Have a look at this document on MSDN which discussed compatibility mode and how to turn it off for your site.

Convert string to int if string is a number

Use IsNumeric. It returns true if it's a number or false otherwise.

Public Sub NumTest()
    On Error GoTo MyErrorHandler

    Dim myVar As Variant
    myVar = 11.2 'Or whatever

    Dim finalNumber As Integer
    If IsNumeric(myVar) Then
        finalNumber = CInt(myVar)
    Else
        finalNumber = 0
    End If

    Exit Sub

MyErrorHandler:
    MsgBox "NumTest" & vbCrLf & vbCrLf & "Err = " & Err.Number & _
        vbCrLf & "Description: " & Err.Description
End Sub

What is the difference between Spring, Struts, Hibernate, JavaServer Faces, Tapestry?

Generally...

Hibernate is used for handling database operations. There is a rich set of database utility functionality, which reduces your number of lines of code. Especially you have to read @Annotation of hibernate. It is an ORM framework and persistence layer.

Spring provides a rich set of the Injection based working mechanism. Currently, Spring is well-known. You have to also read about Spring AOP. There is a bridge between Struts and Hibernate. Mainly Spring provides this kind of utility.

Struts2 provides action based programming. There are a rich set of Struts tags. Struts prove action based programming so you have to maintain all the relevant control of your view.

In Addition, Tapestry is a different framework for Java. In which you have to handle only .tml (template file). You have to create two main files for any class. One is JAVA class and another one is its template. Both names are same. Tapestry automatically calls related classes.

Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]

Another cause of "TCP ACKed Unseen" is the number of packets that may get dropped in a capture. If I run an unfiltered capture for all traffic on a busy interface, I will sometimes see a large number of 'dropped' packets after stopping tshark.

On the last capture I did when I saw this, I had 2893204 packets captured, but once I hit Ctrl-C, I got a 87581 packets dropped message. Thats a 3% loss, so when wireshark opens the capture, its likely to be missing packets and report "unseen" packets.

As I mentioned, I captured a really busy interface with no capture filter, so tshark had to sort all packets, when I use a capture filter to remove some of the noise, I no longer get the error.

Forward declaration of a typedef in C++

Because to declare a type, its size needs to be known. You can forward declare a pointer to the type, or typedef a pointer to the type.

If you really want to, you can use the pimpl idiom to keep the includes down. But if you want to use a type, rather than a pointer, the compiler has to know its size.

Edit: j_random_hacker adds an important qualification to this answer, basically that the size needs to be know to use the type, but a forward declaration can be made if we only need to know the type exists, in order to create pointers or references to the type. Since the OP didn't show code, but complained it wouldn't compile, I assumed (probably correctly) that the OP was trying to use the type, not just refer to it.

how to use "AND", "OR" for RewriteCond on Apache?

After many struggles and to achive a general, flexible and more readable solution, in my case I ended up saving the ORs results into ENV variables and doing the ANDs of those variables.

# RESULT_ONE = A OR B
RewriteRule ^ - [E=RESULT_ONE:False]
RewriteCond ...A... [OR]
RewriteCond ...B...
RewriteRule ^ - [E=RESULT_ONE:True]

# RESULT_TWO = C OR D
RewriteRule ^ - [E=RESULT_TWO:False]
RewriteCond ...C... [OR]
RewriteCond ...D...
RewriteRule ^ - [E=RESULT_TWO:True]

# if ( RESULT_ONE AND RESULT_TWO ) then ( RewriteRule ...something... )
RewriteCond %{ENV:RESULT_ONE} =True
RewriteCond %{ENV:RESULT_TWO} =True
RewriteRule ...something...

Requirements:

Hide Utility Class Constructor : Utility classes should not have a public or default constructor

If this class is only a utility class, you should make the class final and define a private constructor:

public final class FilePathHelper {

   private FilePathHelper() {
      //not called
   }
}

This prevents the default parameter-less constructor from being used elsewhere in your code. Additionally, you can make the class final, so that it can't be extended in subclasses, which is a best practice for utility classes. Since you declared only a private constructor, other classes wouldn't be able to extend it anyway, but it is still a best practice to mark the class as final.

Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?

I had the same issue. I think it was a deadlock issue with SQL. You can just force close the SQL process from Task Manager. If that didn't fix it, just restart your computer. You don't need to drop the table and reload the data.

The most accurate way to check JS object's type?

The best solution is toString (as stated above):

function getRealObjectType(obj: {}): string {
    return Object.prototype.toString.call(obj).match(/\[\w+ (\w+)\]/)[1].toLowerCase();
}

enter image description here

FAIR WARNING: toString considers NaN a number so you must manually safeguard later with Number.isNaN(value).

The other solution suggested, using Object.getPrototypeOf fails with null and undefined

Using constructor

How can I search sub-folders using glob.glob module?

The glob2 package supports wild cards and is reasonably fast

code = '''
import glob2
glob2.glob("files/*/**")
'''
timeit.timeit(code, number=1)

On my laptop it takes approximately 2 seconds to match >60,000 file paths.

How to add a "confirm delete" option in ASP.Net Gridview?

Although many of these answers will work, this shows a straightforward example when using CommandField in GridView using the OnClientClick property.

ASPX:

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound"... >
<Columns>
<!-- Data columns here -->
        <asp:CommandField ButtonType="Button" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="150" />
</Columns>
</asp:GridView>

ASPX.CS:

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex)
    {
        (e.Row.Cells[2].Controls[2] as Button).OnClientClick = "return confirm('Do you want to delete this row?');";
    }
}

How to use a wildcard in the classpath to add multiple jars?

From: http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html

Class path entries can contain the basename wildcard character *, which is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR. For example, the class path entry foo/* specifies all JAR files in the directory named foo. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory.

This should work in Java6, not sure about Java5

(If it seems it does not work as expected, try putting quotes. eg: "foo/*")

Declaring multiple variables in JavaScript

Although both are valid, using the second discourages inexperienced developers from placing var statements all over the place and causing hoisting issues. If there is only one var per function, at the top of the function, then it is easier to debug the code as a whole. This can mean that the lines where the variables are declared are not as explicit as some may like.

I feel that trade-off is worth it, if it means weaning a developer off of dropping 'var' anywhere they feel like.

People may complain about JSLint, I do as well, but a lot of it is geared not toward fixing issues with the language, but in correcting bad habits of the coders and therefore preventing problems in the code they write. Therefore:

"In languages with block scope, it is usually recommended that variables be declared at the site of first use. But because JavaScript does not have block scope, it is wiser to declare all of a function's variables at the top of the function. It is recommended that a single var statement be used per function." - http://www.jslint.com/lint.html#scope

MySQL Sum() multiple columns

Another way of doing this is by generating the select query. Play with this fiddle.

SELECT CONCAT('SELECT ', group_concat(`COLUMN_NAME` SEPARATOR '+'), ' FROM scorecard') 
FROM  `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_SCHEMA` = (select database()) 
AND   `TABLE_NAME`   = 'scorecard'
AND   `COLUMN_NAME` LIKE 'mark%';

The query above will generate another query that will do the selecting for you.

  1. Run the above query.
  2. Get the result and run that resulting query.

Sample result:

SELECT mark1+mark2+mark3 FROM scorecard

You won't have to manually add all the columns anymore.

How do I check if a SQL Server text column is empty?

I wanted to have a predefined text("No Labs Available") to be displayed if the value was null or empty and my friend helped me with this:

StrengthInfo = CASE WHEN ((SELECT COUNT(UnitsOrdered) FROM [Data_Sub_orders].[dbo].[Snappy_Orders_Sub] WHERE IdPatient = @PatientId and IdDrugService = 226)> 0)
                            THEN cast((S.UnitsOrdered) as varchar(50))
                    ELSE 'No Labs Available'
                    END

Google maps Places API V3 autocomplete - select first option on enter

@benregn @amirnissim I think the selection error comes from:

var suggestion_selected = $(".pac-item.pac-selected").length > 0;

The class pac-selected should be pac-item-selected, which explains why !suggestion_selected always evaluate to true, causing the incorrect location to be selected when the enter key is pressed after using 'keyup' or 'keydown' to highlight the desired location.

'LIKE ('%this%' OR '%that%') and something=else' not working

Break out the LIKE clauses into 2 separate statements, i.e.:

(fieldname1 LIKE '%this%' or fieldname1 LIKE '%that%' ) and something=else

HQL ERROR: Path expected for join

You need to name the entity that holds the association to User. For example,

... INNER JOIN ug.user u ...

That's the "path" the error message is complaining about -- path from UserGroup to User entity.

Hibernate relies on declarative JOINs, for which the join condition is declared in the mapping metadata. This is why it is impossible to construct the native SQL query without having the path.

fstream won't create a file

This will do:

#include <fstream>
#include <iostream>
using std::fstream;

int main(int argc, char *argv[]) {
    fstream file;
    file.open("test.txt",std::ios::out);
    file << fflush;
    file.close();
}

How to get N rows starting from row M from sorted table in T-SQL

Find id for row N Then get the top M rows that have an id greater than or equal to that

declare @N as int
set @N = 2
declare @M as int
set @M = 3

declare @Nid as int

set @Nid = max(id)
from
  (select top @N *
from MyTable
order by id)

select top @M *
from MyTable
where id >= @Nid
order by id

Something like that ... but I've made some assumptions here (e.g. you want to order by id)

Android: install .apk programmatically

I solved the problem. I made mistake in setData(Uri) and setType(String).

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

That is correct now, my auto-update is working. Thanks for help. =)

Edit 20.7.2016:

After a long time, I had to use this way of updating again in another project. I encountered a number of problems with old solution. A lot of things have changed in that time, so I had to do this with a different approach. Here is the code:

    //get destination to update file and set Uri
    //TODO: First I wanted to store my update .apk file on internal storage for my app but apparently android does not allow you to open and install
    //aplication with existing package from there. So for me, alternative solution is Download directory in external storage. If there is better
    //solution, please inform us in comment
    String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
    String fileName = "AppName.apk";
    destination += fileName;
    final Uri uri = Uri.parse("file://" + destination);

    //Delete update file if exists
    File file = new File(destination);
    if (file.exists())
    //file.delete() - test this, I think sometimes it doesnt work
        file.delete();

    //get url of app on server
    String url = Main.this.getString(R.string.update_app_url);

    //set downloadmanager
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    request.setDescription(Main.this.getString(R.string.notification_description));
    request.setTitle(Main.this.getString(R.string.app_name));

    //set destination
    request.setDestinationUri(uri);

    // get download service and enqueue file
    final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    final long downloadId = manager.enqueue(request);

    //set BroadcastReceiver to install app when .apk is downloaded
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        public void onReceive(Context ctxt, Intent intent) {
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            install.setDataAndType(uri,
                    manager.getMimeTypeForDownloadedFile(downloadId));
            startActivity(install);

            unregisterReceiver(this);
            finish();
        }
    };
    //register receiver for when .apk download is compete
    registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

How do I redirect with JavaScript?

window.location.replace('http://sidanmor.com');

It's better than using window.location.href = 'http://sidanmor.com';

Using replace() is better because it does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.

If you want to simulate someone clicking on a link, use window.location.href

If you want to simulate an HTTP redirect, use window.location.replace

For example:

// similar behavior as an HTTP redirect
window.location.replace("http://sidanmor.com");

// similar behavior as clicking on a link
window.location.href = "http://sidanmor.com";

Taken from here: How to redirect to another page in jQuery?

websocket closing connection automatically

I believe this is a Jetty issue. I have not seen any browsers close WebSocket connections due to inactivity nor have I encountered other WebSocket servers that timeout WebSocket connections.

Jetty is (was) primarily focused on building HTTP based application servlets. In that context, HTTP connections need to be cleaned up pretty aggressively and HTTP was not designed for long-lived connections so having a short default timeout is reasonable.

I've not seen the precise problem you described (closing even with activity) but I do see WebSocket connections closed after 30 second of inactivity. It's possible that in older versions of Jetty or in the current version for some other reason, the timer is not reset by WebSocket activity. I get around this by using the setMaxIdleTime method on my BlockingChannelConnector object to set the timeout value to Integer MAX_VALUE.

How to dynamically add rows to a table in ASP.NET?

public partial class result : System.Web.UI.Page
{
    static DataTable table1 = new DataTable("Shashank");
    static DataSet set = new DataSet("office");


    protected void Page_Load(object sender, EventArgs e)
    {
        lblEmployeeNumber.Text = HttpContext.Current.Request.Form["txtEmployeeNumber"];
        lblFirstName.Text = Request.Form["txtFirstName"];
        lblLastName.Text = Request.Form["txtLastName"];
        lblTitle.Text = Request.Form["txtTitle"];

        Int32 Rcount = Convert.ToInt32(table1.Rows.Count);

        if (Rcount == 0)
        {

            table1.Columns.Add("ID");
            table1.Columns.Add("FName");
            table1.Columns.Add("LName");
            table1.Columns.Add("Title");
            table1.Rows.Add(lblEmployeeNumber.Text, lblFirstName.Text, lblLastName.Text, lblTitle.Text);
            set.Tables.Add(table1);
        }
        else
        {
            if (lblEmployeeNumber.Text != "")
            {
                DataRow dr = table1.NewRow();
                dr["ID"] = lblEmployeeNumber.Text;
                dr["FName"] = lblFirstName.Text;
                dr["LName"] = lblLastName.Text;
                dr["Title"] = lblTitle.Text;
                table1.Rows.Add(dr);
            }
        }

        gvrEmp.DataSource = set;
        gvrEmp.DataBind();

    }
}

How to get the screen width and height in iOS?

NSLog(@"%.0f", [[UIScreen mainScreen] bounds].size.width);
NSLog(@"%.0f", [[UIScreen mainScreen] bounds].size.height);

How should I print types like off_t and size_t?

I saw this post at least twice, because the accepted answer is hard to remeber for me(I rarely use z or j flags and they are seems not platform independant).

The standard never says clearly the exact data length of size_t, so I suggest you should first check the length size_t on your platform then select one of them:

if sizeof(size_t) == 4 use PRIu32
if sizeof(size_t) == 8 use PRIu64

And I suggest using stdint types instead of raw data types for consistancy.

How can I enable Assembly binding logging?

When I had the same problem I fixed it by deleting the existing key.snk in that project and adding a new key.

Downloading and unzipping a .zip file without writing to disk

Adding on to the other answers using requests:

 # download from web

 import requests
 url = 'http://mlg.ucd.ie/files/datasets/bbc.zip'
 content = requests.get(url)

 # unzip the content
 from io import BytesIO
 from zipfile import ZipFile
 f = ZipFile(BytesIO(content.content))
 print(f.namelist())

 # outputs ['bbc.classes', 'bbc.docs', 'bbc.mtx', 'bbc.terms']

Use help(f) to get more functions details for e.g. extractall() which extracts the contents in zip file which later can be used with with open.

In Excel how to get the left 5 characters of each cell in a specified column and put them into a new column

I find, if the data is imported, you may need to use the trim command on top of it, to get your details. =LEFT(TRIM(B2),8) In my case, I was using it to find a IP range. 10.3.44.44 with mask 255.255.255.0, so response is: 10.3.44 Kind of handy.

Replace string in text file using PHP

Does this work:

$msgid = $_GET['msgid'];

$oldMessage = '';

$deletedFormat = '';

//read the entire string
$str=file_get_contents('msghistory.txt');

//replace something in the file string - this is a VERY simple example
$str=str_replace($oldMessage, $deletedFormat,$str);

//write the entire string
file_put_contents('msghistory.txt', $str);

Listen to changes within a DIV and act accordingly

Try this

$('#D25,#E37,#E31,#F37,#E16,#E40,#F16,#F40,#E41,#F41').bind('DOMNodeInserted DOMNodeRemoved',function(){
          // your code;
       });

Do not use this. This may crash the page.

$('mydiv').bind("DOMSubtreeModified",function(){
  alert('changed');
});

Java: Convert a String (representing an IP) to InetAddress

From the documentation of InetAddress.getByName(String host):

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

So you can use it.

Where to download Microsoft Visual c++ 2003 redistributable

Storm's answer is not correct. No hard feelings Storm, and apologies to the OP as I'm a bit late to the party here (wish I could have helped sooner, but I didn't run into the problem until today, or this stack overflow answer until I was figuring out a solution.)

The Visual C++ 2003 runtime was not available as a seperate download because it was included with the .NET 1.1 runtime.

If you install the .NET 1.1 runtime you will get msvcr71.dll installed, and in addition added to C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322.

The .NET 1.1 runtime is available here: http://www.microsoft.com/downloads/en/details.aspx?familyid=262d25e3-f589-4842-8157-034d1e7cf3a3&displaylang=en (23.1 MB)

If you are looking for a file that ends with a "P" such as msvcp71.dll, this indicates that your file was compiled against a C++ runtime (as opposed to a C runtime), in some situations I noticed these files were only installed when I installed the full SDK. If you need one of these files, you may need to install the full .NET 1.1 SDK as well, which is available here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=9b3a2ca6-3647-4070-9f41-a333c6b9181d (106.2 MB)

After installing the SDK I now have both msvcr71.dll and msvcp71.dll in my System32 folder, and the application I'm trying to run (boomerang c++ decompiler) works fine without any missing DLL errors.

Also on a side note: be VERY aware of the difference between a Hotfix Update and a Regular Update. As noted in the linked KB932298 download (linked below by Storm): "Please be aware this Hotfix has not gone through full Microsoft product regression testing nor has it been tested in combination with other Hotfixes."

Hotfixes are NOT meant for general users, but rather users who are facing a very specific problem. As described in the article only install that Hotfix if you are have having specific daylight savings time issues with the rules that changed in 2007. -- Likely this was a pre-release for customers who "just couldn't wait" for the official update (probably for some business critical application) -- for regular users Windows Update should be all you need.

Thanks, and I hope this helps others who run into this issue!

Image, saved to sdcard, doesn't appear in Android's Gallery app

This will aslo solve your problem if your image in gallery are not showing instead they might showing a 404 type bitmap in midle. please add a the tags that are in my code with your image because there must some meta data in order to show image in gallery.

      String resultPath = getExternalFilesDir(Environment.DIRECTORY_PICTURES)+ 
      getString(R.string.directory) + System.currentTimeMillis() + ".jpg";

       new File(resultPath).getParentFile().mkdir();

        try {
            OutputStream fileOutputStream = new FileOutputStream(resultPath);
            savedBitmap.compress(CompressFormat.JPEG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        savedBitmap.recycle();

        File file = new File(resultPath);
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, "Photo");
        values.put(MediaStore.Images.Media.DESCRIPTION, "Edited");
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis ());
        values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
        values.put(MediaStore.Images.ImageColumns.BUCKET_ID, file.toString().toLowerCase(Locale.US).hashCode());
        values.put(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, file.getName().toLowerCase(Locale.US));
        values.put("_data", resultPath);

        ContentResolver cr = getContentResolver();
        cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);




        return  resultPath;

How to use CSS to surround a number with a circle?

Late to the party, but here is a bootstrap-only solution that has worked for me. I'm using Bootstrap 4:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<body>_x000D_
<div class="row mt-4">_x000D_
<div class="col-md-12">_x000D_
<span class="bg-dark text-white rounded-circle px-3 py-1 mx-2 h3">1</span>_x000D_
<span class="bg-dark text-white rounded-circle px-3 py-1 mx-2 h3">2</span>_x000D_
<span class="bg-dark text-white rounded-circle px-3 py-1 mx-2 h3">3</span>_x000D_
</div>_x000D_
</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

You basically add bg-dark text-white rounded-circle px-3 py-1 mx-2 h3 classes to your <span> (or whatever) element and you're done.

Note that you might need to adjust margin and padding classes if your content has more than one digits.

How to get height of Keyboard?

Swift 5

override func viewDidLoad() {
    //  Registering for keyboard notification.
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
}


/*  UIKeyboardWillShowNotification. */
    @objc internal func keyboardWillShow(_ notification : Notification?) -> Void {
        
        var _kbSize:CGSize!
        
        if let info = notification?.userInfo {

            let frameEndUserInfoKey = UIResponder.keyboardFrameEndUserInfoKey
            
            //  Getting UIKeyboardSize.
            if let kbFrame = info[frameEndUserInfoKey] as? CGRect {
                
                let screenSize = UIScreen.main.bounds
                
                //Calculating actual keyboard displayed size, keyboard frame may be different when hardware keyboard is attached (Bug ID: #469) (Bug ID: #381)
                let intersectRect = kbFrame.intersection(screenSize)
                
                if intersectRect.isNull {
                    _kbSize = CGSize(width: screenSize.size.width, height: 0)
                } else {
                    _kbSize = intersectRect.size
                }
                print("Your Keyboard Size \(_kbSize)")
            }
        }
    }

Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?

This is an old post but maybe this could help people to complete the CORS problem. To complete the basic authorization problem you should avoid authorization for OPTIONS requests in your server. This is an Apache configuration example. Just add something like this in your VirtualHost or Location.

<LimitExcept OPTIONS>
    AuthType Basic
    AuthName <AUTH_NAME>
    Require valid-user
    AuthUserFile <FILE_PATH>
</LimitExcept>

Copy or rsync command

It's not really a question of what's more efficient.

The commands 'rsync', and 'cp' are not equivalent and achieve different goals.

1- rsync can preserve the time of creation of existing files. (using -a option)
2- rsync will run multiprocess and transfer using either local sockets or network sockets. (i.e. fork itself into multiple processes)
3- The multiprocessing, and threading will increase your throughput when copying large number of small files, and even with multiple larger files.

So bottom line is rsync is for large data, and cp is for smaller local copying. (MB to small GB range). When you start getting into multiple GB or in the TB range, go with rsync. And of course network copies, rsync all the way.

Why can't I shrink a transaction log file, even after backup?

This answer has been lifted from here and is posted here in case the other thread gets deleted:

The fact that you have non-distributed LSN in the log is the problem. I have seen this once before not sure why we dont unmark the transaction as replicated. We will investigate this internally. You can execute the following command to unmark the transaction as replicated

EXEC sp_repldone @xactid = NULL, @xact_segno = NULL, @numtrans = 0, @time = 0, @reset = 1

At this point you should be able to truncate the log.

JavaScript/jQuery to download file via POST with JSON data

It is been a while since this question was asked but I had the same challenge and want to share my solution. It uses elements from the other answers but I wasn't able to find it in its entirety. It doesn't use a form or an iframe but it does require a post/get request pair. Instead of saving the file between the requests, it saves the post data. It seems to be both simple and effective.

client

var apples = new Array(); 
// construct data - replace with your own
$.ajax({
   type: "POST",
   url: '/Home/Download',
   data: JSON.stringify(apples),
   contentType: "application/json",
   dataType: "text",

   success: function (data) {
      var url = '/Home/Download?id=' + data;
      window.location = url;
   });
});

server

[HttpPost]
// called first
public ActionResult Download(Apple[] apples)
{
   string json = new JavaScriptSerializer().Serialize(apples);
   string id = Guid.NewGuid().ToString();
   string path = Server.MapPath(string.Format("~/temp/{0}.json", id));
   System.IO.File.WriteAllText(path, json);

   return Content(id);
}

// called next
public ActionResult Download(string id)
{
   string path = Server.MapPath(string.Format("~/temp/{0}.json", id));
   string json = System.IO.File.ReadAllText(path);
   System.IO.File.Delete(path);
   Apple[] apples = new JavaScriptSerializer().Deserialize<Apple[]>(json);

   // work with apples to build your file in memory
   byte[] file = createPdf(apples); 

   Response.AddHeader("Content-Disposition", "attachment; filename=juicy.pdf");
   return File(file, "application/pdf");
}

How to create custom exceptions in Java?

To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception. For example:

public class FooException extends Exception {
  public FooException() { super(); }
  public FooException(String message) { super(message); }
  public FooException(String message, Throwable cause) { super(message, cause); }
  public FooException(Throwable cause) { super(cause); }
}

Methods that can potentially throw or propagate this exception must declare it:

public void calculate(int i) throws FooException, IOException;

... and code calling this method must either handle or propagate this exception (or both):

try {
  int i = 5;
  myObject.calculate(5);
} catch(FooException ex) {
  // Print error and terminate application.
  ex.printStackTrace();
  System.exit(1);
} catch(IOException ex) {
  // Rethrow as FooException.
  throw new FooException(ex);
}

You'll notice in the above example that IOException is caught and rethrown as FooException. This is a common technique used to encapsulate exceptions (typically when implementing an API).

Sometimes there will be situations where you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException (which itself is a subclass of java.lang.Exception):

public class FooRuntimeException extends RuntimeException {
  ...
}

Methods can throw or propagate FooRuntimeException exception without declaring it; e.g.

public void calculate(int i) {
  if (i < 0) {
    throw new FooRuntimeException("i < 0: " + i);
  }
}

Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.

The java.lang.Throwable class is the root of all errors and exceptions that can be thrown within Java. java.lang.Exception and java.lang.Error are both subclasses of Throwable. Anything that subclasses Throwable may be thrown or caught. However, it is typically bad practice to catch or throw Error as this is used to denote errors internal to the JVM that cannot usually be "handled" by the programmer (e.g. OutOfMemoryError). Likewise you should avoid catching Throwable, which could result in you catching Errors in addition to Exceptions.

Extracting double-digit months and days from a Python date

Look at the types of those properties:

In [1]: import datetime

In [2]: d = datetime.date.today()

In [3]: type(d.month)
Out[3]: <type 'int'>

In [4]: type(d.day)
Out[4]: <type 'int'>

Both are integers. So there is no automatic way to do what you want. So in the narrow sense, the answer to your question is no.

If you want leading zeroes, you'll have to format them one way or another. For that you have several options:

In [5]: '{:02d}'.format(d.month)
Out[5]: '03'

In [6]: '%02d' % d.month
Out[6]: '03'

In [7]: d.strftime('%m')
Out[7]: '03'

In [8]: f'{d.month:02d}'
Out[8]: '03'

Get the filename of a fileupload in a document through JavaScript

Try document.getElementById("FileUpload1").value this value should have a path for a file to be uploaded, just strip all dirs from that value and you will have file name.

What are good message queue options for nodejs?

Shameless plug: I'm working on Bokeh: a simple, scalable and blazing-fast task queue built on ZeroMQ. It supports pluggable data stores for persisting tasks, currently in-memory, Redis and Riak are supported. Check it out.

What does ellipsize mean in android?

Set this property to edit text. Elipsize is working with disable edit text

android:lines="1"
android:scrollHorizontally="true"
android:ellipsize="end"
android:singleLine="true"
android:editable="false"

or setKeyListener(null);

Exception thrown inside catch block - will it be caught again?

It won't be caught by the second catch block. Each Exception is caught only when inside a try block. You can nest tries though (not that it's a good idea generally):

try {
    doSomething();
} catch (IOException) {
   try {
       doSomething();
   } catch (IOException e) {
       throw new ApplicationException("Failed twice at doSomething" +
       e.toString());
   }          
} catch (Exception e) {
}

How to change UINavigationBar background color from the AppDelegate

You can easily do this with Xcode 6.3.1. Select your NavigationBar in the Document outline. Select the Attributes Inspector. Uncheck Translucent. Set Bar Tint to your desired color. Done!

Difference between "on-heap" and "off-heap"

from http://code.google.com/p/fast-serialization/wiki/QuickStartHeapOff

What is Heap-Offloading ?

Usually all non-temporary objects you allocate are managed by java's garbage collector. Although the VM does a decent job doing garbage collection, at a certain point the VM has to do a so called 'Full GC'. A full GC involves scanning the complete allocated Heap, which means GC pauses/slowdowns are proportional to an applications heap size. So don't trust any person telling you 'Memory is Cheap'. In java memory consumtion hurts performance. Additionally you may get notable pauses using heap sizes > 1 Gb. This can be nasty if you have any near-real-time stuff going on, in a cluster or grid a java process might get unresponsive and get dropped from the cluster.

However todays server applications (frequently built on top of bloaty frameworks ;-) ) easily require heaps far beyond 4Gb.

One solution to these memory requirements, is to 'offload' parts of the objects to the non-java heap (directly allocated from the OS). Fortunately java.nio provides classes to directly allocate/read and write 'unmanaged' chunks of memory (even memory mapped files).

So one can allocate large amounts of 'unmanaged' memory and use this to save objects there. In order to save arbitrary objects into unmanaged memory, the most viable solution is the use of Serialization. This means the application serializes objects into the offheap memory, later on the object can be read using deserialization.

The heap size managed by the java VM can be kept small, so GC pauses are in the millis, everybody is happy, job done.

It is clear, that the performance of such an off heap buffer depends mostly on the performance of the serialization implementation. Good news: for some reason FST-serialization is pretty fast :-).

Sample usage scenarios:

  • Session cache in a server application. Use a memory mapped file to store gigabytes of (inactive) user sessions. Once the user logs into your application, you can quickly access user-related data without having to deal with a database.
  • Caching of computational results (queries, html pages, ..) (only applicable if computation is slower than deserializing the result object ofc).
  • very simple and fast persistance using memory mapped files

Edit: For some scenarios one might choose more sophisticated Garbage Collection algorithms such as ConcurrentMarkAndSweep or G1 to support larger heaps (but this also has its limits beyond 16GB heaps). There is also a commercial JVM with improved 'pauseless' GC (Azul) available.

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

This is a bug in the IDE; I've seen it since VS 2003. THe solution is simple though.

Save your files. Completely exit the IDE (make sure the process stops, task mgr.)

Reopen the solution, dirty the markup, save. Fixed.

Docker build gives "unable to prepare context: context must be a directory: /Users/tempUser/git/docker/Dockerfile"

You can also run docker build with -f option

docker build -t ubuntu-test:latest -f Dockerfile.custom .

HTML/CSS - Adding an Icon to a button

<a href="#" class="btnTest">Test</a>


.btnTest{
   background:url('images/icon.png') no-repeat left center;
   padding-left:20px;
}    

How to set environment variable or system property in spring tests?

You can initialize the System property in a static initializer:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
public class TestWarSpringContext {

    static {
        System.setProperty("myproperty", "foo");
    }

}

The static initializer code will be executed before the spring application context is initialized.

Live-stream video from one android phone to another over WiFi

I did work on something like this once, but sending a video and playing it in real time is a really complex thing. I suggest you work with PNG's only. In my implementation What i did was capture PNGs using the host camera and then sending them over the network to the client, Which will display the image as soon as received and request the next image from the host. Since you are on wifi that communication will be fast enough to get around 8-10 images per-second(approximation only, i worked on Bluetooth). So this will look like a continuous video but with much less effort. For communication you may use UDP sockets(Faster and less complex) or DLNA (Not sure how that works).

How do I fix "for loop initial declaration used outside C99 mode" GCC error?

For Qt-creator: just add next lines to *.pro file...

QMAKE_CFLAGS_DEBUG = \
    -std=gnu99

QMAKE_CFLAGS_RELEASE = \
    -std=gnu99

How to concatenate text from multiple rows into a single text string in SQL server?

With a recursive query you can do it:

-- Create example table
CREATE TABLE tmptable (NAME VARCHAR(30)) ;

-- Insert example data
INSERT INTO tmptable VALUES('PETER');
INSERT INTO tmptable VALUES('PAUL');
INSERT INTO tmptable VALUES('MARY');

-- Recurse query
with tblwithrank as (
select * , row_number() over(order by name) rang , count(*) over() NbRow
from tmptable
),
tmpRecursive as (
select *, cast(name as varchar(2000)) as AllName from tblwithrank  where rang=1
union all
select f0.*,  cast(f0.name + ',' + f1.AllName as varchar(2000)) as AllName 
from tblwithrank f0 inner join tmpRecursive f1 on f0.rang=f1.rang +1 
)
select AllName from tmpRecursive
where rang=NbRow

SQLAlchemy equivalent to SQL "LIKE" statement

try this code

output = dbsession.query(<model_class>).filter(<model_calss>.email.ilike('%' + < email > + '%'))

How is the default max Java heap size determined?

Finally!

As of Java 8u191 you now have the options:

-XX:InitialRAMPercentage
-XX:MaxRAMPercentage
-XX:MinRAMPercentage

that can be used to size the heap as a percentage of the usable physical RAM. (which is same as the RAM installed less what the kernel uses).

See Release Notes for Java8 u191 for more information. Note that the options are mentioned under a Docker heading but in fact they apply whether you are in Docker environment or in a traditional environment.

The default value for MaxRAMPercentage is 25%. This is extremely conservative.

My own rule: If your host is more or less dedicated to running the given java application, then you can without problems increase dramatically. If you are on Linux, only running standard daemons and have installed RAM from somewhere around 1 Gb and up then I wouldn't hesitate to use 75% for the JVM's heap. Again, remember that this is 75% of the RAM available, not the RAM installed. What is left is the other user land processes that may be running on the host and the other types of memory that the JVM needs (eg for stack). All together, this will typically fit nicely in the 25% that is left. Obviously, with even more installed RAM the 75% is a safer and safer bet. (I wish the JDK folks had implemented an option where you could specify a ladder)

Setting the MaxRAMPercentage option look like this:

java -XX:MaxRAMPercentage=75.0  ....

Note that these percentage values are of 'double' type and therefore you must specify them with a decimal dot. You get a somewhat odd error if you use "75" instead of "75.0".

How to make a phone call in android and come back to my activity when the call is done?

This is solution from my point of view:

ok.setOnClickListener(this);
@Override
public void onClick(View view) {
    if(view == ok){
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + num));
        activity.startActivity(intent);

    }

Of course in Activity (class) definition you have to implement View.OnClickListener .

Server cannot set status after HTTP headers have been sent IIS7.5

I remember the part from this exception : "Cannot modify header information - headers already sent by" occurring in PHP. It occurred when the headers were already sent in the redirection phase and any other output was generated e.g.:

echo "hello"; header("Location:http://stackoverflow.com");

Pardon me and do correct me if I am wrong but I am still learning MS Technologies and I was trying to help.

Returning http status code from Web Api controller

If you need to return an IHttpActionResult and want to return the error code plus a message, use:

return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotModified, "Error message here"));

iterate through a map in javascript

I'd use standard javascript:

for (var m in myMap){
    for (var i=0;i<myMap[m].length;i++){
    ... do something with myMap[m][i] ...
    }
} 

Note the different ways of treating objects and arrays.

How to delete large data of table in SQL without log?

This variation of M.Ali's is working fine for me. It deletes some, clears the log and repeats. I'm watching the log grow, drop and start over.

DECLARE @Deleted_Rows INT;
SET @Deleted_Rows = 1;
WHILE (@Deleted_Rows > 0)
  BEGIN
   -- Delete some small number of rows at a time
    delete top (100000) from InstallLog where DateTime between '2014-12-01' and '2015-02-01'
    SET @Deleted_Rows = @@ROWCOUNT;
    dbcc shrinkfile (MobiControlDB_log,0,truncateonly);
END

CKEditor, Image Upload (filebrowserUploadUrl)

The URL should point to your own custom filebrowser url you might have.

I have already done this in one of my projects, and I have posted a tutorial on this topic on my blog

http://www.mixedwaves.com/2010/02/integrating-fckeditor-filemanager-in-ckeditor/

The tutorial gives a step by step instructions about how to integrate the inbuilt FileBrowser of FCKEditor in CKEditor, if you don't want to make our own. Its pretty simple.

How to align entire html body to the center?

<style>
        body{
            max-width: 1180px;
            width: 98%;
            margin: 0px auto;
            text-align: left;
        }
</style>

Just apply this style before applying any CSS. You can change width as per your need.

Remove all spaces from a string in SQL Server

I would use a REPLACE

select REPLACE (' Hello , How Are You ?', ' ', '' )

REPLACE

What is mod_php?

It means that you have to have PHP installed as a module in Apache, instead of starting it as a CGI script.

How to add custom method to Spring Data JPA

Im using the following code in order to access generated find methods from my custom implementation. Getting the implementation through the bean factory prevents circular bean creation problems.

public class MyRepositoryImpl implements MyRepositoryExtensions, BeanFactoryAware {

    private BrandRepository myRepository;

    public MyBean findOne(int first, int second) {
        return myRepository.findOne(new Id(first, second));
    }

    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        myRepository = beanFactory.getBean(MyRepository.class);
    }
}

Working with time DURATION, not time of day

With custom format of a cell you can insert a type like this: d "days", h:mm:ss, which will give you a result like 16 days, 13:56:15 in an excel-cell.

If you would like to show the duration in hours you use the following type [h]:mm:ss, which will lead to something like 397:56:15. Control check: 16 =(397 hours -13 hours)/24

enter image description here

Python circular importing?

I think the answer by jpmc26, while by no means wrong, comes down too heavily on circular imports. They can work just fine, if you set them up correctly.

The easiest way to do so is to use import my_module syntax, rather than from my_module import some_object. The former will almost always work, even if my_module included imports us back. The latter only works if my_object is already defined in my_module, which in a circular import may not be the case.

To be specific to your case: Try changing entities/post.py to do import physics and then refer to physics.PostBody rather than just PostBody directly. Similarly, change physics.py to do import entities.post and then use entities.post.Post rather than just Post.

MySQL: Quick breakdown of the types of joins

I have 2 tables like this:

> SELECT * FROM table_a;
+------+------+
| id   | name |
+------+------+
|    1 | row1 |
|    2 | row2 |
+------+------+

> SELECT * FROM table_b;
+------+------+------+
| id   | name | aid  |
+------+------+------+
|    3 | row3 |    1 |
|    4 | row4 |    1 |
|    5 | row5 | NULL |
+------+------+------+

INNER JOIN cares about both tables

INNER JOIN cares about both tables, so you only get a row if both tables have one. If there is more than one matching pair, you get multiple rows.

> SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | id   | name | aid  |
+------+------+------+------+------+
|    1 | row1 |    3 | row3 | 1    |
|    1 | row1 |    4 | row4 | 1    |
+------+------+------+------+------+

It makes no difference to INNER JOIN if you reverse the order, because it cares about both tables:

> SELECT * FROM table_b b INNER JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | aid  | id   | name |
+------+------+------+------+------+
|    3 | row3 | 1    |    1 | row1 |
|    4 | row4 | 1    |    1 | row1 |
+------+------+------+------+------+

You get the same rows, but the columns are in a different order because we mentioned the tables in a different order.

LEFT JOIN only cares about the first table

LEFT JOIN cares about the first table you give it, and doesn't care much about the second, so you always get the rows from the first table, even if there is no corresponding row in the second:

> SELECT * FROM table_a a LEFT JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | id   | name | aid  |
+------+------+------+------+------+
|    1 | row1 |    3 | row3 | 1    |
|    1 | row1 |    4 | row4 | 1    |
|    2 | row2 | NULL | NULL | NULL |
+------+------+------+------+------+

Above you can see all rows of table_a even though some of them do not match with anything in table b, but not all rows of table_b - only ones that match something in table_a.

If we reverse the order of the tables, LEFT JOIN behaves differently:

> SELECT * FROM table_b b LEFT JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | aid  | id   | name |
+------+------+------+------+------+
|    3 | row3 | 1    |    1 | row1 |
|    4 | row4 | 1    |    1 | row1 |
|    5 | row5 | NULL | NULL | NULL |
+------+------+------+------+------+

Now we get all rows of table_b, but only matching rows of table_a.

RIGHT JOIN only cares about the second table

a RIGHT JOIN b gets you exactly the same rows as b LEFT JOIN a. The only difference is the default order of the columns.

> SELECT * FROM table_a a RIGHT JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | id   | name | aid  |
+------+------+------+------+------+
|    1 | row1 |    3 | row3 | 1    |
|    1 | row1 |    4 | row4 | 1    |
| NULL | NULL |    5 | row5 | NULL |
+------+------+------+------+------+

This is the same rows as table_b LEFT JOIN table_a, which we saw in the LEFT JOIN section.

Similarly:

> SELECT * FROM table_b b RIGHT JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | aid  | id   | name |
+------+------+------+------+------+
|    3 | row3 | 1    |    1 | row1 |
|    4 | row4 | 1    |    1 | row1 |
| NULL | NULL | NULL |    2 | row2 |
+------+------+------+------+------+

Is the same rows as table_a LEFT JOIN table_b.

No join at all gives you copies of everything

If you write your tables with no JOIN clause at all, just separated by commas, you get every row of the first table written next to every row of the second table, in every possible combination:

> SELECT * FROM table_b b, table_a;
+------+------+------+------+------+
| id   | name | aid  | id   | name |
+------+------+------+------+------+
|    3 | row3 | 1    |    1 | row1 |
|    3 | row3 | 1    |    2 | row2 |
|    4 | row4 | 1    |    1 | row1 |
|    4 | row4 | 1    |    2 | row2 |
|    5 | row5 | NULL |    1 | row1 |
|    5 | row5 | NULL |    2 | row2 |
+------+------+------+------+------+

(This is from my blog post Examples of SQL join types)

change figure size and figure format in matplotlib

The first part (setting the output size explictly) isn't too hard:

import matplotlib.pyplot as plt
list1 = [3,4,5,6,9,12]
list2 = [8,12,14,15,17,20]
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
ax.plot(list1, list2)
fig.savefig('fig1.png', dpi = 300)
fig.close()

But after a quick google search on matplotlib + tiff, I'm not convinced that matplotlib can make tiff plots. There is some mention of the GDK backend being able to do it.

One option would be to convert the output with a tool like imagemagick's convert.

(Another option is to wait around here until a real matplotlib expert shows up and proves me wrong ;-)

react native get TextInput value

User in the init of class:

constructor() {
    super()
    this.state = {
        email: ''
    }
}

Then in some function:

handleSome = () => { console.log(this.state.email) };

And in the input:

<TextInput onChangeText={(email) => this.setState({email})}/>

Textarea that can do syntax highlighting on the fly?

I would recommend EditArea for live editing of a syntax hightlighted textarea.

(XML) The markup in the document following the root element must be well-formed. Start location: 6:2

In XML there can be only one root element - you have two - heading and song.

If you restructure to something like:

<?xml version="1.0" encoding="UTF-8"?>
<song> 
 <heading>
 The Twelve Days of Christmas
 </heading>
 ....
</song>

The error about well-formed XML on the root level should disappear (though there may be other issues).

Failed to build gem native extension (installing Compass)

On yosemite, all you must do is install the command line tools. then it works.

Even if other gems installed fine. You must run xcode-select --install for gem install compass to work.

Good luck.

Disabling same-origin policy in Safari

Unfortunately, there is no equivalent for Safari and the argument --disable-web-security doesn't work with Safari.

If you have access to the server side application, you can modify the https response headers to allow access. Mainly the Access-Control-Allow-Origin header. Modifying it will allow Safari to access the resource. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Access-Control-Allow-Origin for more information on the response headers that will help.

How to capitalize first letter of each word, like a 2-word city?

function convertCase(str) {
  var lower = String(str).toLowerCase();
  return lower.replace(/(^| )(\w)/g, function(x) {
    return x.toUpperCase();
  });
}

How do I remove the space between inline/inline-block elements?

I'm not pretty sure if you want to make two blue spans without a gap or want to handle other white-space, but if you want to remove the gap:

span {
    display: inline-block;
    width: 100px;
    background: blue;
    font-size: 30px;
    color: white;
    text-align: center;

    float: left;
}

And done.

Webdriver Screenshot

Have a look on the below python script to take snap of FB homepage by using selenium package of Chrome web driver.

Script:

import selenium

from selenium import webdriver

import time

from time import sleep

chrome_browser = webdriver.Chrome()

chrome_browser.get('https://www.facebook.com/') # Enter to FB login page

sleep(5)

chrome_browser.save_screenshot('C:/Users/user/Desktop/demo.png') # To take FB homepage snap

chrome_browser.close() # To Close the driver connection

chrome_browser.quit() # To Close the browser

what is the unsigned datatype?

unsigned really is a shorthand for unsigned int, and so defined in standard C.

Overcoming "Display forbidden by X-Frame-Options"

UPDATE 2019: You can bypass X-Frame-Options in an <iframe> using just client-side JavaScript and my X-Frame-Bypass Web Component. Here is a demo: Hacker News in an X-Frame-Bypass. (Tested in Chrome & Firefox.)

Logging framework incompatibility

You are mixing the 1.5.6 version of the jcl bridge with the 1.6.0 version of the slf4j-api; this won't work because of a few changes in 1.6.0. Use the same versions for both, i.e. 1.6.1 (the latest). I use the jcl-over-slf4j bridge all the time and it works fine.

Laravel 5 - redirect to HTTPS

In Laravel 5.1, I used: File: app\Providers\AppServiceProvider.php

public function boot()
{
    if ($this->isSecure()) {
        \URL::forceSchema('https');
    }
}

public function isSecure()
{
    $isSecure = false;
    if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
        $isSecure = true;
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
        $isSecure = true;
    }

    return $isSecure;
}

NOTE: use forceSchema, NOT forceScheme

Better way to sort array in descending order

For in-place sorting in descending order:

int[] numbers = { 1, 2, 3 };
Array.Sort(numbers, (a, b) => b.CompareTo(a));

For out-of-place sorting (no changes to input array):

int[] numbers = { 1, 2, 3 };
var sortedNumbers = numbers.OrderByDescending(x => x).ToArray();

AttributeError: 'dict' object has no attribute 'predictors'

The dict.items iterates over the key-value pairs of a dictionary. Therefore for key, value in dictionary.items() will loop over each pair. This is documented information and you can check it out in the official web page, or even easier, open a python console and type help(dict.items). And now, just as an example:

>>> d = {'hello': 34, 'world': 2999}
>>> for key, value in d.items():
...   print key, value
...
world 2999
hello 34

The AttributeError is an exception thrown when an object does not have the attribute you tried to access. The class dict does not have any predictors attribute (now you know where to check it :) ), and therefore it complains when you try to access it. As easy as that.

JavaScript closure inside loops – simple practical example

Ok. I read through all of the answers. Even though there is a good explanation here - I just could not get this to work. So I went looking on the internet. The person at https://dzone.com/articles/why-does-javascript-loop-only-use-last-value had an answer which is not presented here. So I thought I'd post a short example. This made a lot more sense to me.

The long and short of it is that the LET command is nice but is only now being used. HOWEVER, the LET command is really just a TRY-CATCH combo. This works all the way back to IE3 (I believe). Using the TRY-CATCH combo - life is simple and good. Probably why the EMCScript people decided to use it. It also does not need a setTimeout() function. So no time is lost. Basically, you need one TRY-CATCH combo per FOR loop. Here is an example:

    for( var i in myArray ){
       try{ throw i }
       catch(ii){
// Do whatever it is you want to do with ii
          }
       }

If you have more than one FOR loop, you just put a TRY-CATCH combo for each one. Also, personally, I always use the double letter of whatever FOR variable I am using. So "ii" for "i" and so on. I am using this technique in a routine to send mouseover commands to a different routine.

IE 8: background-size fix

I use the filter solution above, for ie8. However.. In order to solve the freezing links problem , do also the following:

background: no-repeat center center fixed\0/; /* IE8 HACK */

This has solved the frozen links problem for me.

How to remove leading whitespace from each line in a file

For what it's worth, if you are editing this file, you can probably highlight all the lines and use your un-tab button.

  • In Vim, use Shift + V to highlight the lines, then press <<
  • If you're on a Mac, then you can use Atom, Sublime Text, etc., then highlight with your mouse and then press Shift + Tab

I am not sure if there is some requirement that this must be done from the command line. If so, then :thumbs-up: to the accepted answer! =)

Bootstrap push div content to new line

If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.

This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="grid">_x000D_
  <div class="row">_x000D_
    <div class="col-sm-3">Under me should be a DIV</div>_x000D_
    <div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
    <div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

mysql query: SELECT DISTINCT column1, GROUP BY column2

You can just add the DISTINCT(ip), but it has to come at the start of the query. Be sure to escape PHP variables that go into the SQL string.

SELECT DISTINCT(ip), name, COUNT(name) nameCnt, 
time, price, SUM(price) priceSum
FROM tablename 
WHERE time >= $yesterday AND time <$today 
GROUP BY ip, name

Access parent DataContext from DataTemplate

You can use RelativeSource to find the parent element, like this -

Binding="{Binding Path=DataContext.CurveSpeedMustBeSpecified, 
RelativeSource={RelativeSource AncestorType={x:Type local:YourParentElementType}}}"

See this SO question for more details about RelativeSource.

php implode (101) with quotes

I think this is what you are trying to do

$array = array('lastname', 'email', 'phone');
echo "'" . implode("','", explode(',', $array)) . "'";

PostgreSQL "DESCRIBE TABLE"

This variation of the query (as explained in other answers) worked for me.

SELECT
 COLUMN_NAME
FROM
 information_schema.COLUMNS
WHERE
 TABLE_NAME = 'city';

It's described here in details: http://www.postgresqltutorial.com/postgresql-describe-table/

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

You can create the required headers in a filter too.

@WebFilter(urlPatterns="/rest/*")
public class AllowAccessFilter implements Filter {
    @Override
    public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain) throws IOException, ServletException {
        System.out.println("in AllowAccessFilter.doFilter");
        HttpServletRequest request = (HttpServletRequest)sRequest;
        HttpServletResponse response = (HttpServletResponse)sResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type"); 
        chain.doFilter(request, response);
    }
    ...
}

Pythonic way to combine FOR loop and IF statement

I personally think this is the prettiest version:

a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]
for x in filter(lambda w: w in a, xyz):
  print x

Edit

if you are very keen on avoiding to use lambda you can use partial function application and use the operator module (that provides functions of most operators).

https://docs.python.org/2/library/operator.html#module-operator

from operator import contains
from functools import partial
print(list(filter(partial(contains, a), xyz)))

Vim: faster way to select blocks of text in visual mode

It could come in handy to know:

In order to select the same ammount of lines for example use 1v You should have done some modification to be able to use 1v, blockwise or linewise.

Today I saw this amazing tip from here:

 :5mark < | 10mark > | normal gvV
 :5mark < | 10mark > | normal gv

You can also reset the visual block boundaries doing so:

m< .......... sets the visual mode start point
m> .......... sets the visual mode end point

Pass a JavaScript function as parameter

You can use a JSON as well to store and send JS functions.

Check the following:

var myJSON = 
{
    "myFunc1" : function (){
        alert("a");
    }, 
    "myFunc2" : function (functionParameter){
        functionParameter();
    }
}



function main(){
    myJSON.myFunc2(myJSON.myFunc1);
}

This will print 'a'.

The following has the same effect with the above:

var myFunc1 = function (){
    alert('a');
}

var myFunc2 = function (functionParameter){
    functionParameter();
}

function main(){
    myFunc2(myFunc1);
}

Which is also has the same effect with the following:

function myFunc1(){
    alert('a');
}


function myFunc2 (functionParameter){
    functionParameter();
}

function main(){
    myFunc2(myFunc1);
}

And a object paradigm using Class as object prototype:

function Class(){
    this.myFunc1 =  function(msg){
        alert(msg);
    }

    this.myFunc2 = function(callBackParameter){
        callBackParameter('message');
    }
}


function main(){    
    var myClass = new Class();  
    myClass.myFunc2(myClass.myFunc1);
}

Pad with leading zeros

The concept of leading zero is meaningless for an int, which is what you have. It is only meaningful, when printed out or otherwise rendered as a string.

Console.WriteLine("{0:0000000}", FileRecordCount);

Forgot to end the double quotes!

favicon.png vs favicon.ico - why should I use PNG instead of ICO?

Avoid PNG in any case if you want reliable IE6 compatibility.

How to convert the ^M linebreak to 'normal' linebreak in a file opened in vim?

sed s/^M//g file1.txt > file2.txt

where ^M is typed by simultaneously pressing the 3 keys, ctrl + v + m

Proper way to concatenate variable strings

Since strings are lists of characters in Python, we can concatenate strings the same way we concatenate lists (with the + sign):

{{ var1 + '-' + var2 + '-' + var3 }}

If you want to pipe the resulting string to some filter, make sure you enclose the bits in parentheses:

e.g. To concatenate our 3 vars, and get a sha512 hash:

{{ (var1 + var2 + var3) | hash('sha512') }}

Note: this works on Ansible 2.3. I haven't tested it on earlier versions.

How do I get client IP address in ASP.NET CORE?

try this.

var host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                 ipAddress = ip.ToString();
            }
        }

syntax for creating a dictionary into another dictionary in python

You can declare a dictionary inside a dictionary by nesting the {} containers:

d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

And then you can access the elements using the [] syntax:

print d['dict1']           # {'foo': 1, 'bar': 2}
print d['dict1']['foo']    # 1
print d['dict2']['quux']   # 4

Given the above, if you want to add another dictionary to the dictionary, it can be done like so:

d['dict3'] = {'spam': 5, 'ham': 6}

or if you prefer to add items to the internal dictionary one by one:

d['dict4'] = {}
d['dict4']['king'] = 7
d['dict4']['queen'] = 8

Sys is undefined

When I experienced the errors

  • Sys is undefined
  • ASP.NET Ajax client-side framework failed to load

in IE when using ASP.NET Ajax controls in .NET 2.0, I needed to add the following to the web.config file within the <system.web> tags:

<httpHandlers>
  <remove verb="*" path="*.asmx"/>
  <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  <add verb="GET" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler" validate="false"/>
</httpHandlers>

Only Add Unique Item To List

Just like the accepted answer says a HashSet doesn't have an order. If order is important you can continue to use a List and check if it contains the item before you add it.

if (_remoteDevices.Contains(rDevice))
    _remoteDevices.Add(rDevice);

Performing List.Contains() on a custom class/object requires implementing IEquatable<T> on the custom class or overriding the Equals. It's a good idea to also implement GetHashCode in the class as well. This is per the documentation at https://msdn.microsoft.com/en-us/library/ms224763.aspx

public class RemoteDevice: IEquatable<RemoteDevice>
{
    private readonly int id;
    public RemoteDevice(int uuid)
    {
        id = id
    }
    public int GetId
    {
        get { return id; }
    }

    // ...

    public bool Equals(RemoteDevice other)
    {
        if (this.GetId == other.GetId)
            return true;
        else
            return false;
    }
    public override int GetHashCode()
    {
        return id;
    }
}

How can I send an HTTP POST request to a server from Excel using VBA?

I did this before using the MSXML library and then using the XMLHttpRequest object, see here.

How can I compare two strings in java and define which of them is smaller than the other alphabetically?

If you would like to ignore case you could use the following:

String s = "yip";
String best = "yodel";
int compare = s.compareToIgnoreCase(best);
if(compare < 0){
    //-1, --> s is less than best. ( s comes alphabetically first)
}
else if(compare > 0 ){
// best comes alphabetically first.
}
else{
    // strings are equal.
}

Is there a CSS selector for text nodes?

Text nodes cannot have margins or any other style applied to them, so anything you need style applied to must be in an element. If you want some of the text inside of your element to be styled differently, wrap it in a span or div, for example.

Simple java program of pyramid

A better pyramid can be printed this way:

The Pattern is
     $     
    $$$    
   $$$$$   
  $$$$$$$  
 $$$$$$$$$ 
$$$$$$$$$$$
public static void main(String agrs[]) {
    System.out.println("The Pattern is");
    int size = 11; //use only odd numbers here
    for (int i = 1; i <= size; i=i+2) {
        int spaceCount = (size - i)/2;
        for(int j = 0; j< size; j++) {
            if(j < spaceCount || j >= (size - spaceCount)) {
                System.out.print(" ");
            } else {
                System.out.print("$");
            }
        }
        System.out.println();
    }
}

Smooth scroll to div id jQuery

Here's what I use:

<!-- jquery smooth scroll to id's -->   
<script>
$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 500);
        return false;
      }
    }
  });
});
</script>

The beauty with this one is you can use an unlimited number of hash-links and corresponding ids without having to execute a new script for each.

If you’re using WordPress, insert the code in your theme’s footer.php file right before the closing body tag </body>.

If you have no access to the theme files, you can embed the code right inside the post/page editor (you must be editing the post in Text mode) or on a Text widget that will load up on all pages.

If you’re using any other CMS or just HTML, you can insert the code in a section that loads up on all pages right before the closing body tag </body>.

If you need more details on this, check out my quick post here: jQuery smooth scroll to id

Hope that helps, and let me know if you have questions about it.

Java Currency Number format

  public static String formatPrice(double value) {
        DecimalFormat formatter;
        if (value<=99999)
          formatter = new DecimalFormat("###,###,##0.00");
        else
            formatter = new DecimalFormat("#,##,##,###.00");

        return formatter.format(value);
    }

Does C# have a String Tokenizer like Java's?

If you are using C# 3.5 you could write an extension method to System.String that does the splitting you need. You then can then use syntax:

string.SplitByMyTokens();

More info and a useful example from MS here http://msdn.microsoft.com/en-us/library/bb383977.aspx

If Browser is Internet Explorer: run an alternative script instead

var browserName=navigator.appName; if (browserName=="Microsoft Internet Explorer") { document.write("Your html for IE") }

Understanding Python super() with __init__() methods

Super has no side effects

Base = ChildB

Base()

works as expected

Base = ChildA

Base()

gets into infinite recursion.

How to check if a variable is an integer or a string?

In my opinion you have two options:

  • Just try to convert it to an int, but catch the exception:

    try:
        value = int(value)
    except ValueError:
        pass  # it was a string, not an int.
    

    This is the Ask Forgiveness approach.

  • Explicitly test if there are only digits in the string:

    value.isdigit()
    

    str.isdigit() returns True only if all characters in the string are digits (0-9).

    The unicode / Python 3 str type equivalent is unicode.isdecimal() / str.isdecimal(); only Unicode decimals can be converted to integers, as not all digits have an actual integer value (U+00B2 SUPERSCRIPT 2 is a digit, but not a decimal, for example).

    This is often called the Ask Permission approach, or Look Before You Leap.

The latter will not detect all valid int() values, as whitespace and + and - are also allowed in int() values. The first form will happily accept ' +10 ' as a number, the latter won't.

If your expect that the user normally will input an integer, use the first form. It is easier (and faster) to ask for forgiveness rather than for permission in that case.

grep for special characters in Unix

Tell grep to treat your input as fixed string using -F option.

grep -F '*^%Q&$*&^@$&*!^@$*&^&^*&^&' application.log

Option -n is required to get the line number,

grep -Fn '*^%Q&$*&^@$&*!^@$*&^&^*&^&' application.log

Xcode 'CodeSign error: code signing is required'

Most common cause, considering that all certificates are installed properly is not specifying the Code Signing Identity in the Active Target settings along with the Project settings. Change these from to iPhone Developer (Xcode will select the right profile depending on App ID match).

  • In Xcode , change from Simulator to Device (in the dropdown at the top of the Xcode window), so that your target for application deployment will be the Device.

  • The default ID which is a wild card ID is like a catch all iD, when associated in Code Signing (if you are using sample files to build, they will most obviously not have com.coolapps.appfile imports, in which case without the 'Team Provisioning profile', your build would fail. So you would want to set this in your

  • Xcode->Project ->Edit Project Settings->Build (tab)->Code Signing Identity (header) ->Any iOS (change from Any iOS Simulator)->(select 'iPhone Developer' as value and it will default to the wildcard development provisioning profile (Team Provisioning Profile: * )

and also (VERY IMPORTANT)

  • Xcode->Project ->Edit Active Target ->Build (tab)->Code Signing Identity (header) ->Any iOS (change from Any iOS Simulator)->(select 'iPhone Developer' as value and it will default to the wildcard development provisioning profile (Team Provisioning Profile: * )

Complete steps for a beginner at: http://codevelle.wordpress.com/2010/12/21/moving-from-ios-simulator-to-the-ios-device-smoothly-without-code-sign-error/

Get Value of Radio button group

Your quotes only need to surround the value part of the attribute-equals selector, [attr='val'], like this:

$('a#check_var').click(function() {
  alert($("input:radio[name='r']:checked").val()+ ' '+
        $("input:radio[name='s']:checked").val());
});?

You can see the working version here.

Change visibility of ASP.NET label with JavaScript

You need to be wary of XSS when doing stuff like this:

document.getElementById('<%= Label1.ClientID %>').style.display

The chances are that no-one will be able to tamper with the ClientID of Label1 in this instance, but just to be on the safe side you might want pass it's value through one of the AntiXss library's methods:

document.getElementById('<%= AntiXss.JavaScriptEncode(Label1.ClientID) %>').style.display