Programs & Examples On #Cfstoredproc

Ajax request returns 200 OK, but an error event is fired instead of success

I have faced this issue with an updated jQuery library. If the service method is not returning anything it means that the return type is void.

Then in your Ajax call please mention dataType='text'.

It will resolve the problem.

Git fetch remote branch

You use 'git pull' to keep your branches separate. I will use the actual repository and branch names to help since 'lbranch' and 'rbranch' are tough to decipher.

Let's use:

  • myteam.unfuddle.com = the remote Git server
  • tlc = Unfuddle project account where the repository exists
  • daves_branch = remote branch name

    You, or any colleague, can run this to pull only your branch, no matter how many branches there are:

    git init
    git pull [email protected]:myteam/tlc daves_branch:refs/remotes/origin/daves_branch
    
  • Check if URL has certain string with PHP

    I think the easiest way is:

    if (strpos($_SERVER['REQUEST_URI'], "car") !== false){
    // car found
    }
    

    Create table with jQuery - append

    <table id="game_table" border="1">
    

    and Jquery

    var i;
    for (i = 0; ii < 10; i++) 
    {
    
            var tr = $("<tr></tr>")
            var ii;
            for (ii = 0; ii < 10; ii++) 
            {
            tr.append(`<th>Firstname</th>`)
            }
    
    $('#game_table').append(tr)
    }
    

    Android - How To Override the "Back" button so it doesn't Finish() my Activity?

    Looks like im very late but for those of you who need to switch to new screen and clear back button stack here is a very simple solution.

    startActivity(new Intent(this,your-new-screen.class));
    finishAffinity();
    

    The finishAffinity(); method clears back button stack.

    C: printf a float value

    printf("%9.6f", myFloat) specifies a format with 9 total characters: 2 digits before the dot, the dot itself, and six digits after the dot.

    Get the previous month's first and last day dates in c#

    If there's any chance that your datetimes aren't strict calendar dates, you should consider using enddate exclusion comparisons... This will prevent you from missing any requests created during the date of Jan 31.

    DateTime now = DateTime.Now;
    DateTime thisMonth = new DateTime(now.Year, now.Month, 1);
    DateTime lastMonth = thisMonth.AddMonths(-1);
    
    var RequestIds = rdc.request
      .Where(r => lastMonth <= r.dteCreated)
      .Where(r => r.dteCreated < thisMonth)
      .Select(r => r.intRequestId);
    

    Check input value length

    <input type='text' minlength=3 /><br />

    if browser supports html5,

    it will automatical be validate attributes(minlength) in tag

    but Safari(iOS) doesn't working

    How to position text over an image in css

    as Harry Joy points out, set the image as the div's background and then, if you only have one line of text you can set the line-height of the text to be the same as the div height and this will place your text in the center of the div.

    If you have more than one line you'll want to set the display to be table-cell and vertical-alignment to middle.

    How do you append rows to a table using jQuery?

    Add as first row or last row in a table

    To add as first row in table

    $(".table tbody").append("<tr><td>New row</td></tr>");
    

    To add as last row in table

    $(".table tbody").prepend("<tr><td>New row</td></tr>");
    

    Content is not allowed in Prolog SAXParserException

    to simply remove it, paste your xml file into notepad, you'll see the extra character before the first tag. Remove it & paste back into your file - bof

    Android - Dynamically Add Views into View

    Use the LayoutInflater to create a view based on your layout template, and then inject it into the view where you need it.

    LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = vi.inflate(R.layout.your_layout, null);
    
    // fill in any details dynamically here
    TextView textView = (TextView) v.findViewById(R.id.a_text_view);
    textView.setText("your text");
    
    // insert into main view
    ViewGroup insertPoint = (ViewGroup) findViewById(R.id.insert_point);
    insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
    

    You may have to adjust the index where you want to insert the view.

    Additionally, set the LayoutParams according to how you would like it to fit in the parent view. e.g. with FILL_PARENT, or MATCH_PARENT, etc.

    String comparison in bash. [[: not found

    If you know you're on bash, and still get this error, make sure you write the if with spaces.

    [[1==1]] # This outputs error
    
    [[ 1==1 ]] # OK
    

    Vertical Tabs with JQuery?

    Another options is Matteo Bicocchi's jQuery mb.extruder tabs plug-in: http://pupunzi.open-lab.com/mb-jquery-components/jquery-mb-extruder/

    Invalid use side-effecting operator Insert within a function

    There is an exception (I'm using SQL 2014) when you are only using Insert/Update/Delete on Declared-Tables. These Insert/Update/Delete statements cannot contain an OUTPUT statement. The other restriction is that you are not allowed to do a MERGE, even into a Declared-Table. I broke up my Merge statements, that didn't work, into Insert/Update/Delete statements that did work.

    The reason I didn't convert it to a stored-procedure is that the table-function was faster (even without the MERGE) than the stored-procedure. This is despite the stored-procedure allowing me to use Temp-Tables that have statistics. I needed the table-function to be very fast, since it is called 20-K times/day. This table function never updates the database.

    I also noticed that the NewId() and RAND() SQL functions are not allowed in a function.

    Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application

    As Simon mentioned, this is not possible in the new Facebook API. Pure technically speaking you can do it via browser automation.

    • this is against Facebook policy, so depending on the country where you live, this may not be legal
    • you'll have to use your credentials / ask user for credentials and possibly store them (storing passwords even symmetrically encrypted is not a good idea)
    • when Facebook changes their API, you'll have to update the browser automation code as well (if you can't force updates of your application, you should put browser automation piece out as a webservice)
    • this is bypassing the OAuth concept
    • on the other hand, my feeling is that I'm owning my data including the list of my friends and Facebook shouldn't restrict me from accessing those via the API

    Sample implementation using WatiN:

    class FacebookUser
    {
      public string Name { get; set; }
      public long Id { get; set; }
    }
    
    public IList<FacebookUser> GetFacebookFriends(string email, string password, int? maxTimeoutInMilliseconds)
    {
      var users = new List<FacebookUser>();
      Settings.Instance.MakeNewIeInstanceVisible = false;
      using (var browser = new IE("https://www.facebook.com"))
      {
        try
        {
          browser.TextField(Find.ByName("email")).Value = email;
          browser.TextField(Find.ByName("pass")).Value = password;
          browser.Form(Find.ById("login_form")).Submit();
          browser.WaitForComplete();
        }
        catch (ElementNotFoundException)
        {
          // We're already logged in
        }
        browser.GoTo("https://www.facebook.com/friends");
        var watch = new Stopwatch();
        watch.Start();
    
        Link previousLastLink = null;
        while (maxTimeoutInMilliseconds.HasValue && watch.Elapsed.TotalMilliseconds < maxTimeoutInMilliseconds.Value)
        {
          var lastLink = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
                           && l.GetAttributeValue("data-hovercard").Contains("user.php")
                           && l.Text != null
                         ).LastOrDefault();
    
          if (lastLink == null || previousLastLink == lastLink)
          {
            break;
          }
    
          var ieElement = lastLink.NativeElement as IEElement;
          if (ieElement != null)
          {
            var htmlElement = ieElement.AsHtmlElement;
            htmlElement.scrollIntoView();
            browser.WaitForComplete();
          }
    
          previousLastLink = lastLink;
        }
    
        var links = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
          && l.GetAttributeValue("data-hovercard").Contains("user.php")
          && l.Text != null
        ).ToList();
    
        var idRegex = new Regex("id=(?<id>([0-9]+))");
        foreach (var link in links)
        {
          string hovercard = link.GetAttributeValue("data-hovercard");
          var match = idRegex.Match(hovercard);
          long id = 0;
          if (match.Success)
          {
            id = long.Parse(match.Groups["id"].Value);
          }
          users.Add(new FacebookUser
          {
            Name = link.Text,
            Id = id
          });
        }
      }
      return users;
    }
    

    Prototype with implementation of this approach (using C#/WatiN) see https://github.com/svejdo1/ShadowApi. It is also allowing dynamic update of Facebook connector that is retrieving a list of your contacts.

    Where can I find the .apk file on my device, when I download any app and install?

    You can use a file browser with an backup function, for example the ES File Explorer Long tap a item and select create backup

    Create a mocked list by mockito

    OK, this is a bad thing to be doing. Don't mock a list; instead, mock the individual objects inside the list. See Mockito: mocking an arraylist that will be looped in a for loop for how to do this.

    Also, why are you using PowerMock? You don't seem to be doing anything that requires PowerMock.

    But the real cause of your problem is that you are using when on two different objects, before you complete the stubbing. When you call when, and provide the method call that you are trying to stub, then the very next thing you do in either Mockito OR PowerMock is to specify what happens when that method is called - that is, to do the thenReturn part. Each call to when must be followed by one and only one call to thenReturn, before you do any more calls to when. You made two calls to when without calling thenReturn - that's your error.

    Center a popup window on screen?

    This hybrid solution worked for me, both on single and dual screen setup

    function popupCenter (url, title, w, h) {
        // Fixes dual-screen position                              Most browsers      Firefox
        const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : window.screenX;
        const dualScreenTop = window.screenTop !== undefined ? window.screenTop : window.screenY;
        const left = (window.screen.width/2)-(w/2) + dualScreenLeft;
        const top = (window.screen.height/2)-(h/2) + dualScreenTop;
        return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
    }
    

    conflicting types for 'outchar'

    It's because you haven't declared outchar before you use it. That means that the compiler will assume it's a function returning an int and taking an undefined number of undefined arguments.

    You need to add a prototype pf the function before you use it:

    void outchar(char);  /* Prototype (declaration) of a function to be called */  int main(void) {     ... }  void outchar(char ch) {     ... } 

    Note the declaration of the main function differs from your code as well. It's actually a part of the official C specification, it must return an int and must take either a void argument or an int and a char** argument.

    How to remove leading and trailing zeros in a string? Python

    What about a basic

    your_string.strip("0")
    

    to remove both trailing and leading zeros ? If you're only interested in removing trailing zeros, use .rstrip instead (and .lstrip for only the leading ones).

    More info in the doc.

    You could use some list comprehension to get the sequences you want like so:

    trailing_removed = [s.rstrip("0") for s in listOfNum]
    leading_removed = [s.lstrip("0") for s in listOfNum]
    both_removed = [s.strip("0") for s in listOfNum]
    

    SQL Server Management Studio, how to get execution time down to milliseconds

    What you want to do is this:

    set statistics time on
    
    -- your query
    
    set statistics time off
    

    That will have the output looking something like this in your Messages window:

    SQL Server Execution Times: CPU time = 6 ms, elapsed time = 6 ms.

    Python popen command. Wait until the command is finished

    Let the command you are trying to pass be

    os.system('x')
    

    then you covert it to a statement

    t = os.system('x')
    

    now the python will be waiting for the output from the commandline so that it could be assigned to the variable t.

    Why are my CSS3 media queries not working on mobile devices?

    Today I had similar situation. Media query did not work. After a while I found that space after 'and' was missing. Proper media query should look like this:

    @media screen and (max-width: 1024px) {}
    

    How to get numeric position of alphabets in java?

    Convert each character to its ASCII code, subtract the ASCII code for "a" and add 1. I'm deliberately leaving the code as an exercise.

    This sounds like homework. If so, please tag it as such.

    Also, this won't deal with upper case letters, since you didn't state any requirement to handle them, but if you need to then just lowercase the string before you start.

    Oh, and this will only deal with the latin "a" through "z" characters without any accents, etc.

    C convert floating point to int

    my_var = (int)my_var;
    

    As simple as that. Basically you don't need it if the variable is int.

    mysqli_select_db() expects parameter 1 to be mysqli, string given

    Your arguments are in the wrong order. The connection comes first according to the docs

    <?php
    require("constants.php");
    
    // 1. Create a database connection
    $connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);
    
    if (!$connection) {
        error_log("Failed to connect to MySQL: " . mysqli_error($connection));
        die('Internal server error');
    }
    
    // 2. Select a database to use 
    $db_select = mysqli_select_db($connection, DB_NAME);
    if (!$db_select) {
        error_log("Database selection failed: " . mysqli_error($connection));
        die('Internal server error');
    }
    
    ?>
    

    AutoComplete TextBox Control

    Check out the AutoCompleteSource, AutoCompleteCustomSource and AutoCompleteMode properties.

    textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
    textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
    AutoCompleteStringCollection col = new AutoCompleteStringCollection();
    col.Add("Foo");
    col.Add("Bar");
    textBox1.AutoCompleteCustomSource = col;
    

    Note that the designer allows you to do that without writing any code...

    error opening trace file: No such file or directory (2)

    I think this is the problem

    A little background

    Traceview is a graphical viewer for execution logs that you create by using the Debug class to log tracing information in your code. Traceview can help you debug your application and profile its performance. Enabling it creates a .trace file in the sdcard root folder which can then be extracted by ADB and processed by traceview bat file for processing. It also can get added by the DDMS.

    It is a system used internally by the logger. In general unless you are using traceview to extract the trace file this error shouldnt bother you. You should look at error/logs directly related to your application

    How do I enable it:

    There are two ways to generate trace logs:

    1. Include the Debug class in your code and call its methods such as startMethodTracing() and stopMethodTracing(), to start and stop logging of trace information to disk. This option is very precise because you can specify exactly where to start and stop logging trace data in your code.

    2. Use the method profiling feature of DDMS to generate trace logs. This option is less precise because you do not modify code, but rather specify when to start and stop logging with DDMS. Although you have less control on exactly where logging starts and stops, this option is useful if you don't have access to the application's code, or if you do not need precise log timing.

    But the following restrictions exist for the above

    If you are using the Debug class, your application must have permission to write to external storage (WRITE_EXTERNAL_STORAGE).

    If you are using DDMS: Android 2.1 and earlier devices must have an SD card present and your application must have permission to write to the SD card. Android 2.2 and later devices do not need an SD card. The trace log files are streamed directly to your development machine.

    So in essence the traceFile access requires two things

    1.) Permission to write a trace log file i.e. WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE for good measure

    2.) An emulator with an SDCard attached with sufficient space. The doc doesnt say if this is only for DDMS but also for debug, so I am assuming this is also true for debugging via the application.

    What do I do with this error:

    Now the error is essentially a fall out of either not having the sdcard path to create a tracefile or not having permission to access it. This is an old thread, but the dev behind the bounty, check if are meeting the two prerequisites. You can then go search for the .trace file in the sdcard folder in your emulator. If it exists it shouldn't be giving you this problem, if it doesnt try creating it by adding the startMethodTracing to your app.
    I'm not sure why it automatically looks for this file when the logger kicks in. I think when an error/log event occurs , the logger internally tries to write to trace file and does not find it, in which case it throws the error.Having scoured through the docs, I don't find too many references to why this is automatically on. But in general this doesn't affect you directly, you should check direct application logs/errors. Also as an aside Android 2.2 and later devices do not need an SD card for DDMS trace logging. The trace log files are streamed directly to your development machine.

    Additional information on Traceview:

    Copying Trace Files to a Host Machine

    After your application has run and the system has created your trace files .trace on a device or emulator, you must copy those files to your development computer. You can use adb pull to copy the files. Here's an example that shows how to copy an example file, calc.trace, from the default location on the emulator to the /tmp directory on the emulator host machine:

    adb pull /sdcard/calc.trace /tmp Viewing Trace Files in Traceview To run Traceview and view the trace files, enter traceview . For example, to run Traceview on the example files copied in the previous section, use:

    traceview /tmp/calc Note: If you are trying to view the trace logs of an application that is built with ProGuard enabled (release mode build), some method and member names might be obfuscated. You can use the Proguard mapping.txt file to figure out the original unobfuscated names. For more information on this file, see the Proguard documentation.

    I think any other answer regarding positioning of oncreate statements or removing uses-sdk are not related, but this is Android and I could be wrong. Would be useful to redirect this question to an android engineer or post it as a bug

    More in the docs

    Configure Log4Net in web application

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

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

    <logger name="Mylog">
          <level value="All"></level>
          <appender-ref ref="RollingLogFileAppender" />
        </logger>
    
    
    
    private static readonly ILog Log = LogManager.GetLogger("Mylog");
    

    How do I escape the wildcard/asterisk character in bash?

    It may be worth getting into the habit of using printf rather then echo on the command line.

    In this example it doesn't give much benefit but it can be more useful with more complex output.

    FOO="BAR * BAR"
    printf %s "$FOO"
    

    How to split strings over multiple lines in Bash?

    However, if you have indented code, it doesn't work out so well:

        echo "continuation \
        lines"
    >continuation     lines
    

    Try with single quotes and concatenating the strings:

        echo 'continuation' \
        'lines'
    >continuation lines
    

    Note: the concatenation includes a whitespace.

    How can I use nohup to run process as a background process in linux?

    • Use screen: Start screen, start your script, press Ctrl+A, D. Reattach with screen -r.

    • Make a script that takes your "1" as a parameter, run nohup yourscript:

      #!/bin/bash
      (time bash executeScript $1 input fileOutput $> scrOutput) &> timeUse.txt
      

    Docker Compose wait for container X before starting Y

    Natively that is not possible, yet. See also this feature request.

    So far you need to do that in your containers CMD to wait until all required services are there.

    In the Dockerfiles CMD you could refer to your own start script that wraps starting up your container service. Before you start it, you wait for a depending one like:

    Dockerfile

    FROM python:2-onbuild
    RUN ["pip", "install", "pika"]
    ADD start.sh /start.sh
    CMD ["/start.sh"]
    

    start.sh

    #!/bin/bash
    while ! nc -z rabbitmq 5672; do sleep 3; done
    python rabbit.py
    

    Probably you need to install netcat in your Dockerfile as well. I do not know what is pre-installed on the python image.

    There are a few tools out there that provide easy to use waiting logic, for simple tcp port checks:

    For more complex waits:

    What is the difference between JavaScript and jQuery?

    jQuery is a multi-browser (cf. cross-browser) JavaScript library designed to simplify the client-side scripting of HTML. see http://en.wikipedia.org/wiki/JQuery

    kill -3 to get java thread dump

    With Java 8 in picture, jcmd is the preferred approach.

    jcmd <PID> Thread.print
    

    Following is the snippet from Oracle documentation :

    The release of JDK 8 introduced Java Mission Control, Java Flight Recorder, and jcmd utility for diagnosing problems with JVM and Java applications. It is suggested to use the latest utility, jcmd instead of the previous jstack utility for enhanced diagnostics and reduced performance overhead.

    However, shipping this with the application may be licensing implications which I am not sure.

    How to find the minimum value in an ArrayList, along with the index number? (Java)

    Here's what I do. I find the minimum first then after the minimum is found, it is removed from ArrayList.

    ArrayList<Integer> a = new ArrayList<>();
    a.add(3);
    a.add(6);
    a.add(2);
    a.add(5);
    
    while (a.size() > 0) {
        int min = 1000;
        for (int b:a) {
            if (b < min)
                min = b;
        }
        System.out.println("minimum: " + min);
        System.out.println("index of min: " + a.indexOf((Integer) min));
        a.remove((Integer) min);
    }
    

    How to change the plot line color from blue to black?

    If you get the object after creation (for instance after "seasonal_decompose"), you can always access and edit the properties of the plot; for instance, changing the color of the first subplot from blue to black:

    plt.axes[0].get_lines()[0].set_color('black')

    What exactly should be set in PYTHONPATH?

    Here is what I learned: PYTHONPATH is a directory to add to the Python import search path "sys.path", which is made up of current dir. CWD, PYTHONPATH, standard and shared library, and customer library. For example:

    % python3 -c "import sys;print(sys.path)"
    ['', 
    '/home/username/Documents/DjangoTutorial/mySite', 
    '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', 
    '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
    

    where the first path '' denotes the current dir., the 2nd path is via

    %export PYTHONPATH=/home/username/Documents/DjangoTutorial/mySite 
    

    which can be added to ~/.bashrc to make it permanent, and the rest are Python standard and dynamic shared library plus third-party library such as django.

    As said not to mess with PYTHONHOME, even setting it to '' or 'None' will cause python3 shell to stop working:

    % export PYTHONHOME=''
    % python3
    Fatal Python error: Py_Initialize: Unable to get the locale encoding
    ModuleNotFoundError: No module named 'encodings'
    
    Current thread 0x00007f18a44ff740 (most recent call first):
    Aborted (core dumped)
    

    Note that if you start a Python script, the CWD will be the script's directory. For example:

    username@bud:~/Documents/DjangoTutorial% python3 mySite/manage.py runserver
    ==== Printing sys.path ====
    /home/username/Documents/DjangoTutorial/mySite # CWD is where manage.py resides
    /usr/lib/python3.6
    /usr/lib/python3.6/lib-dynload
    /usr/local/lib/python3.6/dist-packages
    /usr/lib/python3/dist-packages
    

    You can also append a path to sys.path at run-time: Suppose you have a file Fibonacci.py in ~/Documents/Python directory:

    username@bud:~/Documents/DjangoTutorial% python3 
    >>> sys.path.append("/home/username/Documents")
    >>> print(sys.path)
    ['', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', 
    '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages', 
    '/home/username/Documents']
    >>> from Python import Fibonacci as fibo
    

    or via

    % PYTHONPATH=/home/username/Documents:$PYTHONPATH
    % python3
    >>> print(sys.path)
    ['', 
    '/home/username/Documents', '/home/username/Documents/DjangoTutorial/mySite', 
    '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', 
    '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
    >>> from Python import Fibonacci as fibo
    

    Convert JSON to Map

    java.lang.reflect.Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
    Gson gson = new Gson();
    Map<String, Object> categoryicons = gson.fromJson(json, mapType );
    

    How to make Twitter Bootstrap tooltips have multiple lines?

    If you are using Angular UI Bootstrap, you can use tooltip with html syntax: tooltip-html-unsafe

    e.g. update to angular 1.2.10 & angular-ui-bootstrap 0.11: http://jsfiddle.net/aX2vR/1/

    old one: http://jsfiddle.net/8LMwz/1/

    How to fix Invalid byte 1 of 1-byte UTF-8 sequence

    Those like me who understand character encoding principles, also read Joel's article which is funny as it contains wrong characters anyway and still can't figure out what the heck (spoiler alert, I'm Mac user) then your solution can be as simple as removing your local repo and clone it again.

    My code base did not change since the last time it was running OK so it made no sense to have UTF errors given the fact that our build system never complained about it....till I remembered that I accidentally unplugged my computer few days ago with IntelliJ Idea and the whole thing running (Java/Tomcat/Hibernate)

    My Mac did a brilliant job as pretending nothing happened and I carried on business as usual but the underlying file system was left corrupted somehow. Wasted the whole day trying to figure this one out. I hope it helps somebody.

    How to track untracked content?

    1. I removed the .git directories from those new directories (this can create submodule drama. Google it if interested.)
    2. I then ran git rm -rf --cached /the/new/directories
    3. Then I re-added the directories with a git add . from above

    Reference URL https://danielmiessler.com/blog/git-modified-untracked/#gs.W0C7X6U

    How to wait 5 seconds with jQuery?

    Built in javascript setTimeout.

    setTimeout(
      function() 
      {
        //do something special
      }, 5000);
    

    UPDATE: you want to wait since when the page has finished loading, so put that code inside your $(document).ready(...); script.

    UPDATE 2: jquery 1.4.0 introduced the .delay method. Check it out. Note that .delay only works with the jQuery effects queues.

    Gradle finds wrong JAVA_HOME even though it's correctly set

    Adding below lines in build.gradle solved my issue .

    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
    

    Inner join vs Where

    Using JOIN makes the code easier to read, since it's self-explanatory.

    There's no difference in speed(I have just tested it) and the execution plan is the same.

    How to transfer some data to another Fragment?

    Complete code of passing data using fragment to fragment

    Fragment fragment = new Fragment(); // replace your custom fragment class 
    Bundle bundle = new Bundle();
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                    bundle.putString("key","value"); // use as per your need
                    fragment.setArguments(bundle);
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.replace(viewID,fragment);
                    fragmentTransaction.commit();
    

    In custom fragment class

    Bundle mBundle = new Bundle();
    mBundle = getArguments();
    mBundle.getString(key);  // key must be same which was given in first fragment
    

    What does "int 0x80" mean in assembly code?

    int means interrupt, and the number 0x80 is the interrupt number. An interrupt transfers the program flow to whomever is handling that interrupt, which is interrupt 0x80 in this case. In Linux, 0x80 interrupt handler is the kernel, and is used to make system calls to the kernel by other programs.

    The kernel is notified about which system call the program wants to make, by examining the value in the register %eax (AT&T syntax, and EAX in Intel syntax). Each system call have different requirements about the use of the other registers. For example, a value of 1 in %eax means a system call of exit(), and the value in %ebx holds the value of the status code for exit().

    PHP convert string to hex and hex to string

    For any char with ord($char) < 16 you get a HEX back which is only 1 long. You forgot to add 0 padding.

    This should solve it:

    <?php
    function strToHex($string){
        $hex = '';
        for ($i=0; $i<strlen($string); $i++){
            $ord = ord($string[$i]);
            $hexCode = dechex($ord);
            $hex .= substr('0'.$hexCode, -2);
        }
        return strToUpper($hex);
    }
    function hexToStr($hex){
        $string='';
        for ($i=0; $i < strlen($hex)-1; $i+=2){
            $string .= chr(hexdec($hex[$i].$hex[$i+1]));
        }
        return $string;
    }
    
    
    // Tests
    header('Content-Type: text/plain');
    function test($expected, $actual, $success) {
        if($expected !== $actual) {
            echo "Expected: '$expected'\n";
            echo "Actual:   '$actual'\n";
            echo "\n";
            $success = false;
        }
        return $success;
    }
    
    $success = true;
    $success = test('00', strToHex(hexToStr('00')), $success);
    $success = test('FF', strToHex(hexToStr('FF')), $success);
    $success = test('000102FF', strToHex(hexToStr('000102FF')), $success);
    $success = test('???§P?§P ?§T?§?', hexToStr(strToHex('???§P?§P ?§T?§?')), $success);
    
    echo $success ? "Success" : "\nFailed";
    

    Creating a pandas DataFrame from columns of other DataFrames with similar indexes

    You can use concat:

    In [11]: pd.concat([df1['c'], df2['c']], axis=1, keys=['df1', 'df2'])
    Out[11]: 
                     df1       df2
    2014-01-01       NaN -0.978535
    2014-01-02 -0.106510 -0.519239
    2014-01-03 -0.846100 -0.313153
    2014-01-04 -0.014253 -1.040702
    2014-01-05  0.315156 -0.329967
    2014-01-06 -0.510577 -0.940901
    2014-01-07       NaN -0.024608
    2014-01-08       NaN -1.791899
    
    [8 rows x 2 columns]
    

    The axis argument determines the way the DataFrames are stacked:

    df1 = pd.DataFrame([1, 2, 3])
    df2 = pd.DataFrame(['a', 'b', 'c'])
    
    pd.concat([df1, df2], axis=0)
       0
    0  1
    1  2
    2  3
    0  a
    1  b
    2  c
    
    pd.concat([df1, df2], axis=1)
    
       0  0
    0  1  a
    1  2  b
    2  3  c
    

    How to start activity in another application?

    If both application have the same signature (meaning that both APPS are yours and signed with the same key), you can call your other app activity as follows:

    Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(CALC_PACKAGE_NAME);
    startActivity(LaunchIntent);
    

    Hope it helps.

    Html attributes for EditorFor() in ASP.NET MVC

    In my case I was trying to create an HTML5 number input editor template that could receive additional attributes. A neater approach would be to write your own HTML Helper, but since I already had my .ascx template, I went with this approach:

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
    <input id="<%= Regex.Replace(ViewData.TemplateInfo.GetFullHtmlFieldId(""), @"[\[\]]", "_") %>" name="<%= ViewData.TemplateInfo.HtmlFieldPrefix %>" type="number" value="<%= ViewData.TemplateInfo.FormattedModelValue %>"
    <% if (ViewData["attributes"] != null)
       {
           Dictionary<string, string> attributes = (Dictionary<string, string>)ViewData["attributes"];
           foreach (string attributeName in attributes.Keys){%>
            <%= String.Format(" {0}=\"{1}\"", attributeName, attributes[attributeName])%>
           <% }
       } %> />
    

    This ugly bit creates a number type input and looks for a ViewData Dictionary with the key "attributes". It will iterate through the dictionary adding its key/value pairs as attributes. The Regex in the ID attribute is unrelated and is there because when used in a collection, GetFullHtmlFieldId() returns an id containing square brackets [] which it would normally escape as underscores.

    This template is then called like this:

    Html.EditorFor(m => m.Quantity, "NumberField", new { attributes = new Dictionary<string, string>() { { "class", "txtQuantity" } } }
    

    Verbose, but it works. You could probably use reflection in the template to use property names as attribute names instead of using a dictionary.

    How do I get PHP errors to display?

    Create a file called php.ini in the folder where your PHP file resides.

    Inside php.ini add the following code (I am giving an simple error showing code):

    display_errors = on
    
    display_startup_errors = on
    

    Importing a GitHub project into Eclipse

    It can be done in two ways:

    1.Use clone Git

    2.You can set it up manually by rearranging folders given in it. make a two separate folder 'src' and 'res' and place appropriate classes and xml file given by library. and then import project from eclipse and make it as library, that's it.

    Hiding an Excel worksheet with VBA

    This can be done in a single line, as long as the worksheet is active:

    ActiveSheet.Visible = xlSheetHidden
    

    However, you may not want to do this, especially if you use any "select" operations or you use any more ActiveSheet operations.

    How can I do DNS lookups in Python, including referring to /etc/hosts?

    I found this way to expand a DNS RR hostname that expands into a list of IPs, into the list of member hostnames:

    #!/usr/bin/python
    
    def expand_dnsname(dnsname):
        from socket import getaddrinfo
        from dns import reversename, resolver
        namelist = [ ]
        # expand hostname into dict of ip addresses
        iplist = dict()
        for answer in getaddrinfo(dnsname, 80):
            ipa = str(answer[4][0])
            iplist[ipa] = 0
        # run through the list of IP addresses to get hostnames
        for ipaddr in sorted(iplist):
            rev_name = reversename.from_address(ipaddr)
            # run through all the hostnames returned, ignoring the dnsname
            for answer in resolver.query(rev_name, "PTR"):
                name = str(answer)
                if name != dnsname:
                    # add it to the list of answers
                    namelist.append(name)
                    break
        # if no other choice, return the dnsname
        if len(namelist) == 0:
            namelist.append(dnsname)
        # return the sorted namelist
        namelist = sorted(namelist)
        return namelist
    
    namelist = expand_dnsname('google.com.')
    for name in namelist:
        print name
    

    Which, when I run it, lists a few 1e100.net hostnames:

    php codeigniter count rows

    Try This :) I created my on model of count all results

    in library_model

    function count_all_results($column_name = array(),$where=array(), $table_name = array())
    {
            $this->db->select($column_name);
            // If Where is not NULL
            if(!empty($where) && count($where) > 0 )
            {
                $this->db->where($where);
            }
            // Return Count Column
            return $this->db->count_all_results($table_name[0]);//table_name array sub 0
    }
    

    Your Controller will look like this

    public function my_method()
    {
      $data = array(
         $countall = $this->model->your_method_model()
      );
       $this->load->view('page',$data);
    }
    

    Then Simple Call The Library Model In Your Model

    function your_method_model()
    {
            return $this->library_model->count_all_results(
                   ['id'],
                   ['where],
                   ['table name']
               );
    }
    

    Android Error [Attempt to invoke virtual method 'void android.app.ActionBar' on a null object reference]

    In my case I had the same error but my mistake was that I didn't declare my Toolbar.

    So, before I use getSupportActionBar I had to find my toolbar and set the actionBar

        appbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(appbar);
    
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_nav_menu);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    

    How do I create a MessageBox in C#?

    I got the same error 'System.Windows.Forms.MessageBox' is a 'type' but is used like a 'variable', even if using:

    MessageBox.Show("Hello, World!");
    

    I guess my initial attempts with invalid syntax caused some kind of bug and I ended up fixing it by adding a space between "MessageBox.Show" and the brackets ():

    MessageBox.Show ("Hello, World!");
    

    Now using the original syntax without the extra space works again:

    MessageBox.Show("Hello, World!");
    

    Edittext change border color with shape.xml

    selector is used for applying multiple alternate drawables for different status of the view, so in this case, there is no need for selector

    instead use shape

    <?xml version="1.0" encoding="utf-8"?>
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
        <solid android:color="#ffffff" />
        <stroke android:width="1dip" android:color="#ff9900" />
    </shape>
    

    Get size of folder or file

    public long folderSize (String directory)
        {
            File curDir = new File(directory);
            long length = 0;
            for(File f : curDir.listFiles())
            {
                if(f.isDirectory())
                {               
                     for ( File child : f.listFiles()) 
                     {
                         length = length + child.length();
                     }
    
                    System.out.println("Directory: " + f.getName() + " " + length + "kb");
                }
                else
                {
                    length = f.length();
                    System.out.println("File: " + f.getName() + " " + length + "kb");
                }
                length = 0;
            }
            return length;
        }
    

    Resolving ORA-4031 "unable to allocate x bytes of shared memory"

    The following are not needed as they they not fix the error:

    1. ps -ef|grep oracle
    2. Find the smon and kill the pid for it
    3. SQL> startup mount
    4. SQL> create pfile from spfile;

    Restarting the database will flush your pool and that solves a effect not the problem.

    Fixate your large_pool so it can not go lower then a certain point or add memory and set a higher max memory.

    boto3 client NoRegionError: You must specify a region error only sometimes

    you can also set environment variables in the script itself, rather than passing region_name parameter

    os.environ['AWS_DEFAULT_REGION'] = 'your_region_name'

    case sensitivity may matter.

    Why does foo = filter(...) return a <filter object>, not a list?

    filter expects to get a function and something that it can iterate over. The function should return True or False for each element in the iterable. In your particular example, what you're looking to do is something like the following:

    In [47]: def greetings(x):
       ....:     return x == "hello"
       ....:
    
    In [48]: filter(greetings, ["hello", "goodbye"])
    Out[48]: ['hello']
    

    Note that in Python 3, it may be necessary to use list(filter(greetings, ["hello", "goodbye"])) to get this same result.

    Convert date to UTC using moment.js

    This will be the answer:

    moment.utc(moment(localdate)).format()
    
    localdate = '2020-01-01 12:00:00'
    
    moment(localdate)
    //Moment<2020-01-01T12:00:00+08:00>
    
    moment.utc(moment(localdate)).format()
    //2020-01-01T04:00:00Z
    

    Javascript array value is undefined ... how do I test for that

    Check for

    if (predQuery[preId] === undefined)
    

    Use the strict equal to operator. See comparison operators

    Difference between npx and npm?

    npx is a npm package runner (x probably stands for eXecute). The typical use is to download and run a package temporarily or for trials.

    create-react-app is an npm package that is expected to be run only once in a project's lifecycle. Hence, it is preferred to use npx to install and run it in a single step.

    As mentioned in the man page https://www.npmjs.com/package/npx, npx can run commands in the PATH or from node_modules/.bin by default.

    Note: With some digging, we can find that create-react-app points to a Javascript file (possibly to /usr/lib/node_modules/create-react-app/index.js on Linux systems) that is executed within the node environment. This is simply a global tool that does some checks. The actual setup is done by react-scripts, whose latest version is installed in the project. Refer https://github.com/facebook/create-react-app for more info.

    How to initialize a List<T> to a given size (as opposed to capacity)?

    A bit late but first solution you proposed seems far cleaner to me : you dont allocate memory twice. Even List constrcutor needs to loop through array in order to copy it; it doesn't even know by advance there is only null elements inside.

    1. - allocate N - loop N Cost: 1 * allocate(N) + N * loop_iteration

    2. - allocate N - allocate N + loop () Cost : 2 * allocate(N) + N * loop_iteration

    However List's allocation an loops might be faster since List is a built-in class, but C# is jit-compiled sooo...

    get specific row from spark dataframe

    This Works for me in PySpark

    df.select("column").collect()[0][0]
    

    GridView - Show headers on empty data source

    Add this property to your grid-view : ShowHeaderWhenEmpty="True" it might help just check

    Java 8 lambda get and remove element from list

    To Remove element from the list

    objectA.removeIf(x -> conditions);
    

    eg:

    objectA.removeIf(x -> blockedWorkerIds.contains(x));
    
    List<String> str1 = new ArrayList<String>();
    str1.add("A");
    str1.add("B");
    str1.add("C");
    str1.add("D");
    
    List<String> str2 = new ArrayList<String>();
    str2.add("D");
    str2.add("E");
    
    str1.removeIf(x -> str2.contains(x)); 
    
    str1.forEach(System.out::println);
    

    OUTPUT: A B C

    How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

    ENABLEDELAYEDEXPANSION is a parameter passed to the SETLOCAL command (look at setlocal /?)

    Its effect lives for the duration of the script, or an ENDLOCAL:

    When the end of a batch script is reached, an implied ENDLOCAL is executed for any outstanding SETLOCAL commands issued by that batch script.

    In particular, this means that if you use SETLOCAL ENABLEDELAYEDEXPANSION in a script, any environment variable changes are lost at the end of it unless you take special measures.

    Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

    try this :

    public class FileStore
     {
       [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
       public Guid Id { get; set; }
       public string Name { get; set; }
       public string Path { get; set; }
     }
    

    You can check this SO post.

    How do I POST XML data to a webservice with Postman?

    Send XML requests with the raw data type, then set the Content-Type to text/xml.


    1. After creating a request, use the dropdown to change the request type to POST.

      Set request type to POST

    2. Open the Body tab and check the data type for raw.

      Setting data type to raw

    3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

      Selecting content-type text/xml

    4. Enter your raw XML data into the input field below

      Example of XML request in Postman

    5. Click Send to submit your XML Request to the specified server.

      Clicking the Send button

    How to hide TabPage from TabControl

    No, this doesn't exist. You have to remove the tab and re-add it when you want it. Or use a different (3rd-party) tab control.

    Count with IF condition in MySQL query

    Replace this line:

    count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id, 0)) AS comments
    

    With this one:

    coalesce(sum(ccc_news_comments.id = 'approved'), 0) comments
    

    Remove a file from the list that will be committed

    if you did a git add and you haven't pushed anything yet, you just have to do this to unstage it from your commit.

    git reset HEAD <file>

    How to replace sql field value

    To avoid update names that contain .com like [email protected] to [email protected], you can do this:

    UPDATE Yourtable
    SET Email = LEFT(@Email, LEN(@Email) - 4) + REPLACE(RIGHT(@Email, 4), '.com', '.org')
    

    How do I change the font size and color in an Excel Drop Down List?

    I created a custom view that is at 100%. Use the dropdowns then click to view page layout to go back to a smaller view.

    Cannot find name 'require' after upgrading to Angular4

    The problem (as outlined in typescript getting error TS2304: cannot find name ' require') is that the type definitions for node are not installed.

    With a projected genned with @angular/cli 1.x, the specific steps should be:

    Step 1:

    Install @types/node with either of the following:

    - npm install --save @types/node
    - yarn add @types/node -D
    

    Step 2: Edit your src/tsconfig.app.json file and add the following in place of the empty "types": [], which should already be there:

    ...
    "types": [ "node" ],
    "typeRoots": [ "../node_modules/@types" ]
    ...
    

    If I've missed anything, jot a comment and I'll edit my answer.

    multiple conditions for JavaScript .includes() method

    That should work even if one, and only one of the conditions is true :

    var str = "bonjour le monde vive le javascript";
    var arr = ['bonjour','europe', 'c++'];
    
    function contains(target, pattern){
        var value = 0;
        pattern.forEach(function(word){
          value = value + target.includes(word);
        });
        return (value === 1)
    }
    
    console.log(contains(str, arr));
    

    How can I run MongoDB as a Windows service?

    1) echo logpath=F:\mongodb\log\mongo.log > F:\mongodb\mongod.cfg
    
    2) dbpath=F:\mongodb\data\db [add this to the next line in mongod.cfg]
    
    C:\>F:\mongodb\bin\mongod.exe –config F:\mongodb\mongod.cfg –install
    

    Reference

    How do I fix MSB3073 error in my post-build event?

    This is too late but posting my experience for people looking at it later:-

    In MS VS 2010 I had the same issue. It got resolved by putting quotes to post build copy command args which contained spaces!

    In Project Properties --> Configuration Properties --> Build Events --> Post-Build Event --> Command Line change:

    copy $(ProjectDir)a\b\c $(OutputPath)

    to

    copy "$(ProjectDir)a\b\c" "$(OutputPath)"

    SQLite - getting number of rows in a database

    Not sure if I understand your question, but max(id) won't give you the number of lines at all. For example if you have only one line with id = 13 (let's say you deleted the previous lines), you'll have max(id) = 13 but the number of rows is 1. The correct (and fastest) solution is to use count(). BTW if you wonder why there's a star, it's because you can count lines based on a criteria.

    MySQL vs MongoDB 1000 reads

    Source: https://github.com/webcaetano/mongo-mysql

    10 rows

    mysql insert: 1702ms
    mysql select: 11ms
    
    mongo insert: 47ms
    mongo select: 12ms
    

    100 rows

    mysql insert: 8171ms
    mysql select: 10ms
    
    mongo insert: 167ms
    mongo select: 60ms
    

    1000 rows

    mysql insert: 94813ms (1.58 minutes)
    mysql select: 13ms
    
    mongo insert: 1013ms
    mongo select: 677ms
    

    10.000 rows

    mysql insert: 924695ms (15.41 minutes)
    mysql select: 144ms
    
    mongo insert: 9956ms (9.95 seconds)
    mongo select: 4539ms (4.539 seconds)
    

    HTTP GET request in JavaScript?

    I'm not familiar with Mac OS Dashcode Widgets, but if they let you use JavaScript libraries and support XMLHttpRequests, I'd use jQuery and do something like this:

    var page_content;
    $.get( "somepage.php", function(data){
        page_content = data;
    });
    

    find files by extension, *.html under a folder in nodejs

    I just noticed, you are using sync fs methods, that might block you application, here is a promise-based async way using async and q, you can execute it with START=/myfolder FILTER=".jpg" node myfile.js, assuming you put the following code in a file called myfile.js:

    Q = require("q")
    async = require("async")
    path = require("path")
    fs = require("fs")
    
    function findFiles(startPath, filter, files){
        var deferred;
        deferred = Q.defer(); //main deferred
    
        //read directory
        Q.nfcall(fs.readdir, startPath).then(function(list) {
            var ideferred = Q.defer(); //inner deferred for resolve of async each
            //async crawling through dir
            async.each(list, function(item, done) {
    
                //stat current item in dirlist
                return Q.nfcall(fs.stat, path.join(startPath, item))
                    .then(function(stat) {
                        //check if item is a directory
                        if (stat.isDirectory()) {
                            //recursive!! find files in subdirectory
                            return findFiles(path.join(startPath, item), filter, files)
                                .catch(function(error){
                                    console.log("could not read path: " + error.toString());
                                })
                                .finally(function() {
                                    //resolve async job after promise of subprocess of finding files has been resolved
                                    return done();
                                 });
                        //check if item is a file, that matches the filter and add it to files array
                        } else if (item.indexOf(filter) >= 0) {
                            files.push(path.join(startPath, item));
                            return done();
                        //file is no directory and does not match the filefilter -> don't do anything
                        } else {
                            return done();
                        }
                    })
                    .catch(function(error){
                        ideferred.reject("Could not stat: " + error.toString());
                    });
            }, function() {
                return ideferred.resolve(); //async each has finished, so resolve inner deferred
            });
            return ideferred.promise;
        }).then(function() {
            //here you could do anything with the files of this recursion step (otherwise you would only need ONE deferred)
            return deferred.resolve(files); //resolve main deferred
        }).catch(function(error) {
            deferred.reject("Could not read dir: " + error.toString());
            return
        });
        return deferred.promise;
    }
    
    
    findFiles(process.env.START, process.env.FILTER, [])
        .then(function(files){
            console.log(files);
        })
        .catch(function(error){
            console.log("Problem finding files: " + error);
    })
    

    pandas: multiple conditions while indexing data frame - unexpected behavior

    You can also use query(), i.e.:

    df_filtered = df.query('a == 4 & b != 2')
    

    What's the easy way to auto create non existing dir in ansible

    copy module creates the directory if it's not there. In this case it created the resolved.conf.d directory

    - name: put fallback_dns.conf in place                                                                 
      copy:                                                                                                
        src: fallback_dns.conf                                                                             
        dest: /etc/systemd/resolved.conf.d/                                                                
        mode: '0644'                                                                                       
        owner: root                                                                                        
        group: root                                                                                        
      become: true                                                                                         
      tags: testing
    

    How to iterate over a JSONObject?

    First put this somewhere:

    private <T> Iterable<T> iteratorToIterable(final Iterator<T> iterator) {
        return new Iterable<T>() {
            @Override
            public Iterator<T> iterator() {
                return iterator;
            }
        };
    }
    

    Or if you have access to Java8, just this:

    private <T> Iterable<T> iteratorToIterable(Iterator<T> iterator) {
        return () -> iterator;
    }
    

    Then simply iterate over the object's keys and values:

    for (String key : iteratorToIterable(object.keys())) {
        JSONObject entry = object.getJSONObject(key);
        // ...
    

    Could not autowire field in spring. why?

    I had exactly the same problem try to put the two classes in the same package and add line in the pom.xml

    <dependency> 
                <groupId> org.springframework.boot </groupId> 
                <artifactId> spring-boot-starter-web </artifactId> 
                <version> 1.2.0.RELEASE </version> 
    </dependency>
    

    C++11 reverse range-based for-loop

    If not using C++14, then I find below the simplest solution.

    #define METHOD(NAME, ...) auto NAME __VA_ARGS__ -> decltype(m_T.r##NAME) { return m_T.r##NAME; }
    template<typename T>
    struct Reverse
    {
      T& m_T;
    
      METHOD(begin());
      METHOD(end());
      METHOD(begin(), const);
      METHOD(end(), const);
    };
    #undef METHOD
    
    template<typename T>
    Reverse<T> MakeReverse (T& t) { return Reverse<T>{t}; }
    

    Demo.
    It doesn't work for the containers/data-types (like array), which doesn't have begin/rbegin, end/rend functions.

    Django - limiting query results

    As an addition and observation to the other useful answers, it's worth noticing that actually doing [:10] as slicing will return the first 10 elements of the list, not the last 10...

    To get the last 10 you should do [-10:] instead (see here). This will help you avoid using order_by('-id') with the - to reverse the elements.

    ImportError: No module named 'google'

    Use this both installation and then go ahead with your python code

    pip install google-cloud    
    pip install google-cloud-vision
    

    Is there any way I can define a variable in LaTeX?

    add the following to you preamble:

    \newcommand{\newCommandName}{text to insert}
    

    Then you can just use \newCommandName{} in the text

    For more info on \newcommand, see e.g. wikibooks

    Example:

    \documentclass{article}
    \newcommand\x{30}
    \begin{document}
    \x
    \end{document}
    

    Output:

    30
    

    Execute Immediate within a stored procedure keeps giving insufficient priviliges error

    You should use this example with AUTHID CURRENT_USER :

    CREATE OR REPLACE PROCEDURE Create_sequence_for_tab (VAR_TAB_NAME IN VARCHAR2)
       AUTHID CURRENT_USER
    IS
       SEQ_NAME       VARCHAR2 (100);
       FINAL_QUERY    VARCHAR2 (100);
       COUNT_NUMBER   NUMBER := 0;
       cur_id         NUMBER;
    BEGIN
       SEQ_NAME := 'SEQ_' || VAR_TAB_NAME;
    
       SELECT COUNT (*)
         INTO COUNT_NUMBER
         FROM USER_SEQUENCES
        WHERE SEQUENCE_NAME = SEQ_NAME;
    
       DBMS_OUTPUT.PUT_LINE (SEQ_NAME || '>' || COUNT_NUMBER);
    
       IF COUNT_NUMBER = 0
       THEN
          --DBMS_OUTPUT.PUT_LINE('DROP SEQUENCE ' || SEQ_NAME);
          -- EXECUTE IMMEDIATE 'DROP SEQUENCE ' || SEQ_NAME;
          -- ELSE
          SELECT 'CREATE SEQUENCE COMPTABILITE.' || SEQ_NAME || ' START WITH ' || ROUND (DBMS_RANDOM.VALUE (100000000000, 999999999999), 0) || ' INCREMENT BY 1'
            INTO FINAL_QUERY
            FROM DUAL;
    
          DBMS_OUTPUT.PUT_LINE (FINAL_QUERY);
          cur_id := DBMS_SQL.OPEN_CURSOR;
          DBMS_SQL.parse (cur_id, FINAL_QUERY, DBMS_SQL.v7);
          DBMS_SQL.CLOSE_CURSOR (cur_id);
       -- EXECUTE IMMEDIATE FINAL_QUERY;
    
       END IF;
    
       COMMIT;
    END;
    /
    

    How can I right-align text in a DataGridView column?

    this.dataGridView1.Columns["CustomerName"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; 
    

    Converting String to Double in Android

    You seem to assign Double object into native double value field. Does that really compile?

    Double.valueOf() creates a Double object so .doubleValue() should not be necessary.

    If you want native double field, you need to define the field as double and then use .doubleValue()

    Retrieving the COM class factory for component failed

    I had the same error when I deployed my app. I've got solution from this site: Component with CLSID XXX failed due to the following error: 80070005 Access is denied

    Here is this solution:

    1. In DCOMCNFG, right click on the My Computer and select properties.

    2. Choose the COM Securities tab.

    3. In Access Permissions, click Edit Defaults and add Network Service to it and give it Allow local access permission. Do the same for < Machine_name >\Users.

    4. In Launch and Activation Permissions, click Edit Defaults and add Network Service to it and give it Local launch and Local Activation permission. Do the same for < Machine_name >\Users.

    *I used forms authentication.

    Dynamically change bootstrap progress bar value when checkboxes checked

    Bootstrap 4 progress bar

    <div class="progress">
    <div class="progress-bar" role="progressbar" style="" aria-valuenow="" aria-valuemin="0" aria-valuemax="100"></div>
    </div>
    

    Javascript

    change progress bar on next/previous page actions

    var count = Number(document.getElementById('count').innerHTML); //set this on page load in a hidden field after an ajax call
    var total = document.getElementById('total').innerHTML; //set this on initial page load
    var pcg = Math.floor(count/total*100);        
    document.getElementsByClassName('progress-bar').item(0).setAttribute('aria-valuenow',pcg);
    document.getElementsByClassName('progress-bar').item(0).setAttribute('style','width:'+Number(pcg)+'%');
    

    MongoDB vs Firebase

    Firebase provides some good features like real time change reflection , easy integration of authentication mechanism , and lots of other built-in features for rapid web development. Firebase, really makes Web development so simple that never exists. Firebase database is a fork of MongoDB.

    What's the advantage of using Firebase over MongoDB?

    You can take advantage of all built-in features of Firebase over MongoDB.

    How can I convert a .py to .exe for Python?

    I can't tell you what's best, but a tool I have used with success in the past was cx_Freeze. They recently updated (on Jan. 7, '17) to version 5.0.1 and it supports Python 3.6.

    Here's the pypi https://pypi.python.org/pypi/cx_Freeze

    The documentation shows that there is more than one way to do it, depending on your needs. http://cx-freeze.readthedocs.io/en/latest/overview.html

    I have not tried it out yet, so I'm going to point to a post where the simple way of doing it was discussed. Some things may or may not have changed though.

    How do I use cx_freeze?

    C# Encoding a text string with line breaks

    Try \n\n , it will work! :)

    public async Task AjudaAsync(IDialogContext context, LuisResult result){
    await context.PostAsync("How can I help you? \n\n 1.To Schedule \n\n 2.Consult");
    context.Wait(MessageReceived);
    }
    

    How to disable Google Chrome auto update?

    The simplest method on Windows 10 with recent versions of Chrome as of early 2020. No registry hack, Powershell or GPO required :

    1. Open the Computer Management app with elevated rights: type it in the taskbar search, then click Run as administrator on the menu
    2. Go to Service and Applications -> Services
    3. Find Google Update Service (gupdate) and Google Update Service (gupdatem)
    4. For both services, right-click, select Properties and set Startup type: to Disabled.

    Tested and working on Google Chrome v 80, Win 10 / 1909 / 18363.592, as of March 2020.

    Cancel split window in Vim

    The command :hide will hide the currently focused window. I think this is the functionality you are looking for.

    In order to navigate between windows type Ctrl+w followed by a navigation key (h,j,k,l, or arrow keys)

    For more information run :help window and :help hide in vim.

    How to have the formatter wrap code with IntelliJ?

    You can create a macro for Ctrl +Shift + S (for example) that do all this things:

    Edit > Macros > Start Macro Recording (the recording will start). Click where you need.

    For example:

    Code > Reformat Code
    Code > Auto-Indent Lines
    Code > Optimize Imports
    Code > Rearrange Code
    File > Save All
    ... (all that you want)
    

    Then, click on red button in bottom-right of the IDE to stop the Macro recording.

    Set a macro name.

    Go to File > Settings > Macros > YOUR MACRO NAME.

    Right Click > Add Keyboard Shortcut, and type Ctrl + Shift + S.

    Sequelize, convert entity to plain object

    For nested JSON plain text

    db.model.findAll({
      raw : true ,
      nest : true
    })
    

    Get the current file name in gulp.src()

    Here is another simple way.

    var es, log, logFile;
    
    es = require('event-stream');
    
    log = require('gulp-util').log;
    
    logFile = function(es) {
      return es.map(function(file, cb) {
        log(file.path);
        return cb();
      });
    };
    
    gulp.task("do", function() {
     return gulp.src('./examples/*.html')
       .pipe(logFile(es))
       .pipe(gulp.dest('./build'));
    });
    

    How to set a variable inside a loop for /F

    There are two methods to setting and using variables within for loops and parentheses scope.

    1. setlocal enabledelayedexpansion see setlocal /? for help. This only works on XP/2000 or newer versions of Windows. then use !variable! instead of %variable% inside the loop...

    2. Create a batch function using batch goto labels :Label.

      Example:

      for /F "tokens=*" %%a in ('type %FileName%') do call :Foo %%a
      goto End
      
      :Foo
      set z=%1
      echo %z%
      echo %1
      goto :eof
      
      :End
      

      Batch functions are very useful mechanism.

    programmatically add column & rows to WPF Datagrid

    If you already have the databinding in place John Myczek answer is complete.
    If not you have at least 2 options I know of if you want to specify the source of your data. (However I am not sure whether or not this is in line with most guidelines, like MVVM)

    option 1: like JohnB said. But I think you should use your own defined collection instead of a weakly typed DataTable (no offense, but you can't tell from the code what each column represents)

    xaml.cs

    DataContext = myCollection;
    
    //myCollection is a `ICollection<YourType>` preferably
    `ObservableCollection<YourType>
    
     - option 2) Declare the name of the Datagrid in xaml
    
            <WpfToolkit:DataGrid Name=dataGrid}>
    

    in xaml.cs

    CollectionView myCollectionView = 
          (CollectionView)CollectionViewSource.GetDefaultView(yourCollection);
    dataGrid.ItemsSource = myCollectionView;
    

    If your type has a property FirstName defined, you can then do what John Myczek pointed out.

    DataGridTextColumn textColumn = new DataGridTextColumn(); 
    dataColumn.Header = "First Name"; 
    dataColumn.Binding = new Binding("FirstName"); 
    dataGrid.Columns.Add(textColumn); 
    

    This obviously doesn't work if you don't know properties you will need to show in your dataGrid, but if that is the case you will have more problems to deal with, and I believe that's out of scope here.

    Does Hibernate create tables in the database automatically

    add following property in your hibernate.cfg.xml file

    <property name="hibernate.hbm2ddl.auto">update</property>

    BTW, in your Entity class, you must define your @Id filed like this:

    @Id
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "increment")
    @Column(name = "id")
    private long id;
    

    if you use the following definition, it maybe not work:

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;
    

    Converting a string to an integer on Android

    You can also do it one line:

    int hello = Integer.parseInt(((Button)findViewById(R.id.button1)).getText().toString().replaceAll("[\\D]", ""));
    

    Reading from order of execution

    1. grab the view using findViewById(R.id.button1)
    2. use ((Button)______) to cast the View as a Button
    3. Call .GetText() to get the text entry from Button
    4. Call .toString() to convert the Character Varying to a String
    5. Call .ReplaceAll() with "[\\D]" to replace all Non Digit Characters with "" (nothing)
    6. Call Integer.parseInt() grab and return an integer out of the Digit-only string.

    how to add key value pair in the JSON object already declared

    Hi I add key and value to each object

    _x000D_
    _x000D_
    let persons = [_x000D_
      {_x000D_
        name : "John Doe Sr",_x000D_
        age: 30_x000D_
      },{_x000D_
        name: "John Doe Jr",_x000D_
        age : 5_x000D_
      }_x000D_
    ]_x000D_
    _x000D_
    function addKeyValue(obj, key, data){_x000D_
      obj[key] = data;_x000D_
    }_x000D_
     _x000D_
    _x000D_
    let newinfo = persons.map(function(person) {_x000D_
      return addKeyValue(person, 'newKey', 'newValue');_x000D_
    });_x000D_
    _x000D_
    console.log(persons);
    _x000D_
    _x000D_
    _x000D_

    How to remove first and last character of a string?

    You can always use substring:

    String loginToken = getName().toString();
    loginToken = loginToken.substring(1, loginToken.length() - 1);
    

    Get and Set a Single Cookie with Node.js HTTP Server

    If you don't care what's in the cookie and you just want to use it, try this clean approach using request (a popular node module):

    var request = require('request');
    var j = request.jar();
    var request = request.defaults({jar:j});
    request('http://www.google.com', function () {
      request('http://images.google.com', function (error, response, body){
         // this request will will have the cookie which first request received
         // do stuff
      });
    });
    

    How to sum all the values in a dictionary?

    sum(d.values()) - "d" -> Your dictionary Variable

    "Can't find Project or Library" for standard VBA functions

    I had the same problem. This worked for me:

    • In VB go to Tools » References
    • Uncheck the library "Crystal Analysis Common Controls 1.0". Or any library.
    • Just leave these 5 references:
      1. Visual Basic For Applications (This is the library that defines the VBA language.)
      2. Microsoft Excel Object Library (This defines all of the elements of Excel.)
      3. OLE Automation (This specifies the types for linking and embedding documents and for automation of other applications and the "plumbing" of the COM system that Excel uses to communicate with the outside world.)
      4. Microsoft Office (This defines things that are common to all Office programs such as Command Bars and Command Bar controls.)
      5. Microsoft Forms 2.0 This is required if you are using a User Form. This library defines things like the user form and the controls that you can place on a form.
    • Then Save.

    How do I get the directory of the PowerShell script I execute?

    PowerShell 3 has the $PSScriptRoot automatic variable:

    Contains the directory from which a script is being run.

    In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.

    Don't be fooled by the poor wording. PSScriptRoot is the directory of the current file.

    In PowerShell 2, you can calculate the value of $PSScriptRoot yourself:

    # PowerShell v2
    $PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
    

    How to programmatically set the SSLContext of a JAX-WS client?

    I had problems trusting a self signed certificate when setting up the trust manager. I used the SSLContexts builder of the apache httpclient to create a custom SSLSocketFactory

    SSLContext sslcontext = SSLContexts.custom()
            .loadKeyMaterial(keyStoreFile, "keystorePassword.toCharArray(), keyPassword.toCharArray())
            .loadTrustMaterial(trustStoreFile, "password".toCharArray(), new TrustSelfSignedStrategy())
            .build();
    SSLSocketFactory customSslFactory = sslcontext.getSocketFactory()
    bindingProvider.getRequestContext().put(JAXWSProperties.SSL_SOCKET_FACTORY, customSslFactory);
    

    and passing in the new TrustSelfSignedStrategy() as an argument in the loadTrustMaterial method.

    How do I search for an object by its ObjectId in the mongo console?

    To use Objectid method you don't need to import it. It is already on the mongodb object.

    _x000D_
    _x000D_
    var ObjectId = new db.ObjectId('58c85d1b7932a14c7a0a320d');_x000D_
    db.yourCollection.findOne({ _id: ObjectId }, function (err, info) {_x000D_
       console.log(info)_x000D_
    });_x000D_
                   
    _x000D_
    _x000D_
    _x000D_

    What's the difference between deadlock and livelock?

    Taken from http://en.wikipedia.org/wiki/Deadlock:

    In concurrent computing, a deadlock is a state in which each member of a group of actions, is waiting for some other member to release a lock

    A livelock is similar to a deadlock, except that the states of the processes involved in the livelock constantly change with regard to one another, none progressing. Livelock is a special case of resource starvation; the general definition only states that a specific process is not progressing.

    A real-world example of livelock occurs when two people meet in a narrow corridor, and each tries to be polite by moving aside to let the other pass, but they end up swaying from side to side without making any progress because they both repeatedly move the same way at the same time.

    Livelock is a risk with some algorithms that detect and recover from deadlock. If more than one process takes action, the deadlock detection algorithm can be repeatedly triggered. This can be avoided by ensuring that only one process (chosen randomly or by priority) takes action.

    When should we implement Serializable interface?

    1. Implement the Serializable interface when you want to be able to convert an instance of a class into a series of bytes or when you think that a Serializable object might reference an instance of your class.

    2. Serializable classes are useful when you want to persist instances of them or send them over a wire.

    3. Instances of Serializable classes can be easily transmitted. Serialization does have some security consequences, however. Read Joshua Bloch's Effective Java.

    postgresql port confusion 5433 or 5432?

    Quick answer on OSX, set your environment variables.

    >export PGHOST=localhost
    
    >export PGPORT=5432
    

    Or whatever you need.

    How do I execute cmd commands through a batch file?

    This fixes some issues with Blorgbeard's answer (but is untested):

    @echo off
    cd /d "c:\Program files\IIS Express"
    start "" iisexpress /path:"C:\FormsAdmin.Site" /port:8088 /clr:v2.0
    timeout 10
    start http://localhost:8088/default.aspx
    pause
    

    JavaScript DOM remove element

    In most browsers, there's a slightly more succinct way of removing an element from the DOM than calling .removeChild(element) on its parent, which is to just call element.remove(). In due course, this will probably become the standard and idiomatic way of removing an element from the DOM.

    The .remove() method was added to the DOM Living Standard in 2011 (commit), and has since been implemented by Chrome, Firefox, Safari, Opera, and Edge. It was not supported in any version of Internet Explorer.

    If you want to support older browsers, you'll need to shim it. This turns out to be a little irritating, both because nobody seems to have made a all-purpose DOM shim that contains these methods, and because we're not just adding the method to a single prototype; it's a method of ChildNode, which is just an interface defined by the spec and isn't accessible to JavaScript, so we can't add anything to its prototype. So we need to find all the prototypes that inherit from ChildNode and are actually defined in the browser, and add .remove to them.

    Here's the shim I came up with, which I've confirmed works in IE 8.

    (function () {
        var typesToPatch = ['DocumentType', 'Element', 'CharacterData'],
            remove = function () {
                // The check here seems pointless, since we're not adding this
                // method to the prototypes of any any elements that CAN be the
                // root of the DOM. However, it's required by spec (see point 1 of
                // https://dom.spec.whatwg.org/#dom-childnode-remove) and would
                // theoretically make a difference if somebody .apply()ed this
                // method to the DOM's root node, so let's roll with it.
                if (this.parentNode != null) {
                    this.parentNode.removeChild(this);
                }
            };
    
        for (var i=0; i<typesToPatch.length; i++) {
            var type = typesToPatch[i];
            if (window[type] && !window[type].prototype.remove) {
                window[type].prototype.remove = remove;
            }
        }
    })();
    

    This won't work in IE 7 or lower, since extending DOM prototypes isn't possible before IE 8. I figure, though, that on the verge of 2015 most people needn't care about such things.

    Once you've included them shim, you'll be able to remove a DOM element element from the DOM by simply calling

    element.remove();
    

    Converting a string to a date in DB2

    Okay, seems like a bit of a hack. I have got it to work using a substring, so that only the part of the string with the date (not the time) gets passed into the DATE function...

    DATE(substr(SETTLEMENTDATE.VALUE,7,4)||'-'|| substr(SETTLEMENTDATE.VALUE,4,2)||'-'|| substr(SETTLEMENTDATE.VALUE,1,2))
    

    I will still accept any answers that are better than this one!

    How do I enable C++11 in gcc?

    H2CO3 is right, you can use a makefile with the CXXFLAGS set with -std=c++11 A makefile is a simple text file with instructions about how to compile your program. Create a new file named Makefile (with a capital M). To automatically compile your code just type the make command in a terminal. You may have to install make.

    Here's a simple one :

    CXX=clang++
    CXXFLAGS=-g -std=c++11 -Wall -pedantic
    BIN=prog
    
    SRC=$(wildcard *.cpp)
    OBJ=$(SRC:%.cpp=%.o)
    
    all: $(OBJ)
        $(CXX) -o $(BIN) $^
    
    %.o: %.c
        $(CXX) $@ -c $<
    
    clean:
        rm -f *.o
        rm $(BIN)
    

    It assumes that all the .cpp files are in the same directory as the makefile. But you can easily tweak your makefile to support a src, include and build directories.

    Edit : I modified the default c++ compiler, my version of g++ isn't up-to-date. With clang++ this makefile works fine.

    How to disable phone number linking in Mobile Safari?

    I had an ABN (Australian Business Number) that iPad Safari insisted on turning into a phone number link. None of the suggestions helped. My solution was to put img tags between the numbers.

    ABN 98<img class="PreventSafariFromTurningIntoLink" /> 009<img /> 675<img /> 709
    

    The class exists only to document what the img tags are for.

    Works on iPad 1 (4.3.1) and iPad 2 (4.3.3).

    What does --net=host option in Docker command really do?

    After the docker installation you have 3 networks by default:

    docker network ls
    NETWORK ID          NAME                DRIVER              SCOPE
    f3be8b1ef7ce        bridge              bridge              local
    fbff927877c1        host                host                local
    023bb5940080        none                null                local
    

    I'm trying to keep this simple. So if you start a container by default it will be created inside the bridge (docker0) network.

    $ docker run -d jenkins
    1498e581cdba        jenkins             "/bin/tini -- /usr..."   3 minutes ago       Up 3 minutes        8080/tcp, 50000/tcp   friendly_bell
    

    In the dockerfile of jenkins the ports 8080 and 50000 are exposed. Those ports are opened for the container on its bridge network. So everything inside that bridge network can access the container on port 8080 and 50000. Everything in the bridge network is in the private range of "Subnet": "172.17.0.0/16", If you want to access them from the outside you have to map the ports with -p 8080:8080. This will map the port of your container to the port of your real server (the host network). So accessing your server on 8080 will route to your bridgenetwork on port 8080.

    Now you also have your host network. Which does not containerize the containers networking. So if you start a container in the host network it will look like this (it's the first one):

    CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                 NAMES
    1efd834949b2        jenkins             "/bin/tini -- /usr..."   6 minutes ago       Up 6 minutes                              eloquent_panini
    1498e581cdba        jenkins             "/bin/tini -- /usr..."   10 minutes ago      Up 10 minutes       8080/tcp, 50000/tcp   friendly_bell
    

    The difference is with the ports. Your container is now inside your host network. So if you open port 8080 on your host you will acces the container immediately.

    $ sudo iptables -I INPUT 5 -p tcp -m tcp --dport 8080 -j ACCEPT
    

    I've opened port 8080 in my firewall and when I'm now accesing my server on port 8080 I'm accessing my jenkins. I think this blog is also useful to understand it better.

    What are -moz- and -webkit-?

    These are the vendor-prefixed properties offered by the relevant rendering engines (-webkit for Chrome, Safari; -moz for Firefox, -o for Opera, -ms for Internet Explorer). Typically they're used to implement new, or proprietary CSS features, prior to final clarification/definition by the W3.

    This allows properties to be set specific to each individual browser/rendering engine in order for inconsistencies between implementations to be safely accounted for. The prefixes will, over time, be removed (at least in theory) as the unprefixed, the final version, of the property is implemented in that browser.

    To that end it's usually considered good practice to specify the vendor-prefixed version first and then the non-prefixed version, in order that the non-prefixed property will override the vendor-prefixed property-settings once it's implemented; for example:

    .elementClass {
        -moz-border-radius: 2em;
        -ms-border-radius: 2em;
        -o-border-radius: 2em;
        -webkit-border-radius: 2em;
        border-radius: 2em;
    }
    

    Specifically, to address the CSS in your question, the lines you quote:

    -webkit-column-count: 3;
    -webkit-column-gap: 10px;
    -webkit-column-fill: auto;
    -moz-column-count: 3;
    -moz-column-gap: 10px;
    -moz-column-fill: auto;
    

    Specify the column-count, column-gap and column-fill properties for Webkit browsers and Firefox.

    References:

    Changing the default title of confirm() in JavaScript?

    This is not possible, as you say, from a security stand point. The only way you could simulate it, is by creating a modeless dialog window.

    There are many third-party javascript-plugins that you could use to fake this effect so you do not have to write all that code.

    Calling another method java GUI

    I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

    public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

    test attribute in JSTL <c:if> tag

    All that the test attribute looks for to determine if something is true is the string "true" (case in-sensitive). For example, the following code will print "Hello world!"

    <c:if test="true">Hello world!</c:if>
    

    The code within the <%= %> returns a boolean, so it will either print the string "true" or "false", which is exactly what the <c:if> tag looks for.

    Can jQuery provide the tag name?

    you can try:
    jQuery(this).get(0).tagName;
    or
    jQuery(this).get(0).nodeName;
    

    note: replace this with your selector (h1, h3 or ...)

    How to automatically generate N "distinct" colors?

    This is trivial in MATLAB (there is an hsv command):

    cmap = hsv(number_of_colors)
    

    splitting a number into the integer and decimal parts

    This variant allows getting desired precision:

    >>> a = 1234.5678
    >>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e0)
    (1234, 0.0)
    >>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e1)
    (1234, 0.5)
    >>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e15)
    (1234, 0.5678)
    

    How do I create my own URL protocol? (e.g. so://...)

    Here's a list of the registered URI schemes. Each one has an RFC - a document defining it, which is almost a standard. The RFC tells the developers of new applications (such as browsers, ftp clients, etc.) what they need to support. If you need a new base-level protocol, you can use an unregistered one. The other answers tell you how. Please keep in mind you can do lots of things with the existing protocols, thus gaining their existing implementations.

    Simple (I think) Horizontal Line in WPF?

    To draw Horizontal 
    ************************    
    <Rectangle  HorizontalAlignment="Stretch"  VerticalAlignment="Center" Fill="DarkCyan" Height="4"/>
    
    To draw vertical 
    *******************
     <Rectangle  HorizontalAlignment="Stretch" VerticalAlignment="Center" Fill="DarkCyan" Height="4" Width="Auto" >
            <Rectangle.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform Angle="90"/>
                    <TranslateTransform/>
                </TransformGroup>
            </Rectangle.RenderTransform>
        </Rectangle>
    

    Pygame mouse clicking detection

    The pygame documentation for mouse events is here. You can either use the pygame.mouse.get_pressed method in collaboration with the pygame.mouse.get_pos (if needed). But please use the mouse click event via a main event loop. The reason why the event loop is better is due to "short clicks". You may not notice these on normal machines, but computers that use tap-clicks on trackpads have excessively small click periods. Using the mouse events will prevent this.

    EDIT: To perform pixel perfect collisions use pygame.sprite.collide_rect() found on their docs for sprites.

    How to play .wav files with java

    A class that will play a WAV file, blocking until the sound has finished playing:

    class Sound implements Playable {
    
        private final Path wavPath;
        private final CyclicBarrier barrier = new CyclicBarrier(2);
    
        Sound(final Path wavPath) {
    
            this.wavPath = wavPath;
        }
    
        @Override
        public void play() throws LineUnavailableException, IOException, UnsupportedAudioFileException {
    
            try (final AudioInputStream audioIn = AudioSystem.getAudioInputStream(wavPath.toFile());
                 final Clip clip = AudioSystem.getClip()) {
    
                listenForEndOf(clip);
                clip.open(audioIn);
                clip.start();
                waitForSoundEnd();
            }
        }
    
        private void listenForEndOf(final Clip clip) {
    
            clip.addLineListener(event -> {
                if (event.getType() == LineEvent.Type.STOP) waitOnBarrier();
            });
        }
    
        private void waitOnBarrier() {
    
            try {
    
                barrier.await();
            } catch (final InterruptedException ignored) {
            } catch (final BrokenBarrierException e) {
    
                throw new RuntimeException(e);
            }
        }
    
        private void waitForSoundEnd() {
    
            waitOnBarrier();
        }
    }
    

    How to select rows where column value IS NOT NULL using CodeIgniter's ActiveRecord?

    One way to check either column is null or not is

    $this->db->where('archived => TRUE);
    $q = $this->db->get('projects');
    

    in php if column has data, it can be represent as True otherwise False To use multiple comparison in where command and to check if column data is not null do it like

    here is the complete example how I am filter columns in where clause (Codeignitor). The last one show Not NULL Compression

    $where = array('somebit' => '1', 'status' => 'Published', 'archived ' => TRUE );
    $this->db->where($where);
    

    Java heap terminology: young, old and permanent generations?

    The Java virtual machine is organized into three generations: a young generation, an old generation, and a permanent generation. Most objects are initially allocated in the young generation. The old generation contains objects that have survived some number of young generation collections, as well as some large objects that may be allocated directly in the old generation. The permanent generation holds objects that the JVM finds convenient to have the garbage collector manage, such as objects describing classes and methods, as well as the classes and methods themselves.

    How can I add a class attribute to an HTML element generated by MVC's HTML Helpers?

    Current best practice in CSS development is to create more general selectors with modifiers that can be applied as widely as possible throughout the web site. I would try to avoid defining separate styles for individual page elements.

    If the purpose of the CSS class on the <form/> element is to control the style of elements within the form, you could add the class attribute the existing <fieldset/> element which encapsulates any form by default in web pages generated by ASP.NET MVC. A CSS class on the form is rarely necessary.

    Formatting Phone Numbers in PHP

    Another option - easily updated to receive a format from configuration.

    $numbers = explode("\n", '(111) 222-3333
    ((111) 222-3333
    1112223333
    111 222-3333
    111-222-3333
    (111)2223333
    +11234567890
        1-8002353551
        123-456-7890   -Hello!
    +1 - 1234567890
    ');
    foreach( $numbers AS $number ){
      echo comMember_format::phoneNumber($number) . '<br>';
    }
    
    // ************************************************************************
    // Format Phone Number
    public function phoneNumber( $number ){
      $txt = preg_replace('/[\s\-|\.|\(|\)]/','',$number);
      $format = '[$1?$1 :][$2?($2):x][$3: ]$4[$5: ]$6[$7? $7:]';
      if( preg_match('/^(.*)(\d{3})([^\d]*)(\d{3})([^\d]*)(\d{4})([^\d]{0,1}.*)$/', $txt, $matches) ){
        $result = $format;
        foreach( $matches AS $k => $v ){
          $str = preg_match('/\[\$'.$k.'\?(.*?)\:(.*?)\]|\[\$'.$k.'\:(.*?)\]|(\$'.$k.'){1}/', $format, $filterMatch);
          if( $filterMatch ){
            $result = str_replace( $filterMatch[0], (!isset($filterMatch[3]) ? (strlen($v) ? str_replace( '$'.$k, $v, $filterMatch[1] ) : $filterMatch[2]) : (strlen($v) ? $v : (isset($filterMatch[4]) ? '' : (isset($filterMatch[3]) ? $filterMatch[3] : '')))), $result );
          }
        }
        return $result;
      }
      return $number;
    }
    

    How to define servlet filter order of execution using annotations in WAR

    1. Make the servlet filter implement the spring Ordered interface.
    2. Declare the servlet filter bean manually in configuration class.
        import org.springframework.core.Ordered;
        
        public class MyFilter implements Filter, Ordered {
    
            @Override
            public void init(FilterConfig filterConfig) {
                // do something
            }
    
            @Override
            public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
                // do something
            }
    
            @Override
            public void destroy() {
                // do something
            }
    
            @Override
            public int getOrder() {
                return -100;
            }
        }
    
    
        import org.springframework.context.annotation.ComponentScan;
        import org.springframework.context.annotation.Configuration;
    
        @Configuration
        @ComponentScan
        public class MyAutoConfiguration {
    
            @Bean
            public MyFilter myFilter() {
                return new MyFilter();
            }
        }
    

    Having a UITextField in a UITableViewCell

    I had been avoiding this by calling a method to run [cell.contentView bringSubviewToFront:textField] every time my cells appeared, but then I discovered this relatively simple technique:

    cell.accessoryView = textField;
    

    Doesn't seem to have the same background-overpasting issue, and it aligns itself on its own (somewhat). Also, the textLabel auto-truncates to avoid overflowing into (or under) it, which is handy.

    How to use HTML to print header and footer on every printed page of a document?

    I found one solution. The basic idea is to make a table and in thead section place the data of header in tr and by css force to show that tr only in print not in screen then your normal header should be force to show only in screen not in print. 100% working on many pages print. sample code is here

    <style> 
        @media screen {
            .only_print{
                display:none;
            }
        }
        @media print {
            .no-print {
                display: none !important;
            }
        }
        TABLE{border-collapse: collapse;}
        TH, TD {border:1px solid grey;}
    </style>
    <div class="no-print">  <!-- This is header for screen and will not be printed -->
        <div>COMPANY NAME FOR SCREEN</div>
        <div>DESCRIPTION FOR SCREEN</div>
    </div>
    
    <table>
        <thead>
            <tr class="only_print"> <!-- This is header for print and will not be shown on screen -->
                <td colspan="100" style="border: 0px;">
                    <div>COMPANY NAME FOR PRINT</div>
                    <div>DESCRIPTION FOR PRINT</div>
                </td>
            </tr>
            <!-- From here Actual Data of table start -->
            <tr>
                <th>Column 1</th>
                <th>Column 2</th>
                <th>Column 3</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1-1</td>
                <td>1-2</td>
                <td>1-3</td>
            </tr>
            <tr>
                <td>2-1</td>
                <td>2-2</td>
                <td>2-3</td>
            </tr>
        </tbody>
    </table>
    

    package javax.mail and javax.mail.internet do not exist

    For anyone still looking to use the aforementioned IMAP library but need to use gradle, simply add this line to your modules gradle file (not the main gradle file)

    compile group: 'javax.mail', name: 'mail', version: '1.4.1'
    

    The links to download the .jar file were dead for me, so had to go with an alternate route.

    Hope this helps :)

    What does "restore purchases" in In-App purchases mean?

    You typically restore purchases with this code:

    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
    

    It will reinvoke -paymentQueue:updatedTransactions on the observer(s) for the purchased items. This is useful for users who reinstall the app after deletion or install it on a different device.

    Not all types of In-App purchases can be restored.

    How to Install Sublime Text 3 using Homebrew

    To install Sublime Text 3 run:

    brew install --cask sublime-text
    

    reference: https://formulae.brew.sh/cask/sublime-text

    mongodb/mongoose findMany - find all documents with IDs listed in array

    Both node.js and MongoChef force me to convert to ObjectId. This is what I use to grab a list of users from the DB and fetch a few properties. Mind the type conversion on line 8.

    // this will complement the list with userName and userPhotoUrl based on userId field in each item
    augmentUserInfo = function(list, callback){
            var userIds = [];
            var users = [];         // shortcut to find them faster afterwards
            for (l in list) {       // first build the search array
                var o = list[l];
                if (o.userId) {
                    userIds.push( new mongoose.Types.ObjectId( o.userId ) );           // for the Mongo query
                    users[o.userId] = o;                                // to find the user quickly afterwards
                }
            }
            db.collection("users").find( {_id: {$in: userIds}} ).each(function(err, user) {
                if (err) callback( err, list);
                else {
                    if (user && user._id) {
                        users[user._id].userName = user.fName;
                        users[user._id].userPhotoUrl = user.userPhotoUrl;
                    } else {                        // end of list
                        callback( null, list );
                    }
                }
            });
        }
    

    Why does printf not flush after the call unless a newline is in the format string?

    It's probably like that because of efficiency and because if you have multiple programs writing to a single TTY, this way you don't get characters on a line interlaced. So if program A and B are outputting, you'll usually get:

    program A output
    program B output
    program B output
    program A output
    program B output
    

    This stinks, but it's better than

    proprogrgraam m AB  ououtputputt
    prproogrgram amB A  ououtputtput
    program B output
    

    Note that it isn't even guaranteed to flush on a newline, so you should flush explicitly if flushing matters to you.

    How to switch to another domain and get-aduser

    best solution TNX to Drew Chapin and all of you too:

    I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server argument.

    $dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
    
    Get-ADUser -Server $dc.HostName[0] `
        -Filter { EmailAddress -Like "*Smith_Karla*" } `
        -Properties EmailAddress
    

    my script:

    $dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
     Get-ADUser -Server $dc.HostName[0] ` -Filter { EmailAddress -Like "*Smith_Karla*" } `  -Properties EmailAddress | Export-CSV "C:\Scripts\Email.csv
    

    Spring 3 MVC resources and tag <mvc:resources />

    It works for me:

    <mvc:resources mapping="/static/**" location="/static/"/>
    <mvc:default-servlet-handler />
    <mvc:annotation-driven />
    

    Difference between -XX:+UseParallelGC and -XX:+UseParNewGC

    Parallel GC

    • XX:+UseParallelGC Use parallel garbage collection for scavenges. (Introduced in 1.4.1)
    • XX:+UseParallelOldGC Use parallel garbage collection for the full collections. Enabling this option automatically sets -XX:+UseParallelGC. (Introduced in 5.0 update 6.)

    UseParNewGC

    UseParNewGC A parallel version of the young generation copying collector is used with the concurrent collector (i.e. if -XX:+ UseConcMarkSweepGC is used on the command line then the flag UseParNewGC is also set to true if it is not otherwise explicitly set on the command line).

    Perhaps the easiest way to understand was combinations of garbage collection algorithms made by Alexey Ragozin

    _x000D_
    _x000D_
    <table border="1" style="width:100%">_x000D_
      <tr>_x000D_
        <td align="center">Young collector</td>_x000D_
        <td align="center">Old collector</td>_x000D_
        <td align="center">JVM option</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Serial (DefNew)</td>_x000D_
        <td>Serial Mark-Sweep-Compact</td>_x000D_
        <td>-XX:+UseSerialGC</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Parallel scavenge (PSYoungGen)</td>_x000D_
        <td>Serial Mark-Sweep-Compact (PSOldGen)</td>_x000D_
        <td>-XX:+UseParallelGC</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Parallel scavenge (PSYoungGen)</td>_x000D_
        <td>Parallel Mark-Sweep-Compact (ParOldGen)</td>_x000D_
        <td>-XX:+UseParallelOldGC</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Serial (DefNew)</td>_x000D_
        <td>Concurrent Mark Sweep</td>_x000D_
        <td>_x000D_
          <p>-XX:+UseConcMarkSweepGC</p>_x000D_
          <p>-XX:-UseParNewGC</p>_x000D_
        </td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Parallel (ParNew)</td>_x000D_
        <td>Concurrent Mark Sweep</td>_x000D_
        <td>_x000D_
          <p>-XX:+UseConcMarkSweepGC</p>_x000D_
          <p>-XX:+UseParNewGC</p>_x000D_
        </td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td colspan="2">G1</td>_x000D_
        <td>-XX:+UseG1GC</td>_x000D_
      </tr>_x000D_
    </table>
    _x000D_
    _x000D_
    _x000D_

    Conclusion:

    1. Apply -XX:+UseParallelGC when you require parallel collection method over YOUNG generation ONLY, (but still) use serial-mark-sweep method as OLD generation collection
    2. Apply -XX:+UseParallelOldGC when you require parallel collection method over YOUNG generation (automatically sets -XX:+UseParallelGC) AND OLD generation collection
    3. Apply -XX:+UseParNewGC & -XX:+UseConcMarkSweepGC when you require parallel collection method over YOUNG generation AND require CMS method as your collection over OLD generation memory
    4. You can't apply -XX:+UseParallelGC or -XX:+UseParallelOldGC with -XX:+UseConcMarkSweepGC simultaneously, that's why your require -XX:+UseParNewGC to be paired with CMS otherwise use -XX:+UseSerialGC explicitly OR -XX:-UseParNewGC if you wish to use serial method against young generation

    Searching for Text within Oracle Stored Procedures

    I allways use UPPER(text) like UPPER('%blah%')

    How can I generate an INSERT script for an existing SQL Server table that includes all stored rows?

    Just to share, I've developed my own script to do it. Feel free to use it. It generates "SELECT" statements that you can then run on the tables to generate the "INSERT" statements.

    select distinct 'SELECT ''INSERT INTO ' + schema_name(ta.schema_id) + '.' + so.name + ' (' + substring(o.list, 1, len(o.list)-1) + ') VALUES ('
    + substring(val.list, 1, len(val.list)-1) + ');''  FROM ' + schema_name(ta.schema_id) + '.' + so.name + ';'
    from    sys.objects so
    join sys.tables ta on ta.object_id=so.object_id
    cross apply
    (SELECT '  ' +column_name + ', '
     from information_schema.columns c
     join syscolumns co on co.name=c.COLUMN_NAME and object_name(co.id)=so.name and OBJECT_NAME(co.id)=c.TABLE_NAME and co.id=so.object_id and c.TABLE_SCHEMA=SCHEMA_NAME(so.schema_id)
     where table_name = so.name
     order by ordinal_position
    FOR XML PATH('')) o (list)
    cross apply
    (SELECT '''+' +case
             when data_type = 'uniqueidentifier' THEN 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''' END '
             WHEN data_type = 'timestamp' then '''''''''+CONVERT(NVARCHAR(MAX),CONVERT(BINARY(8),[' + COLUMN_NAME + ']),1)+'''''''''
             WHEN data_type = 'nvarchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
             WHEN data_type = 'varchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
             WHEN data_type = 'char' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
             WHEN data_type = 'nchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
             when DATA_TYPE='datetime' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],121)+'''''''' END '
             when DATA_TYPE='datetime2' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],121)+'''''''' END '
             when DATA_TYPE='geography' and column_name<>'Shape' then 'ST_GeomFromText(''POINT('+column_name+'.Lat '+column_name+'.Long)'') '
             when DATA_TYPE='geography' and column_name='Shape' then '''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''''
             when DATA_TYPE='bit' then '''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''''
             when DATA_TYPE='xml' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE(CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + ']),'''''''','''''''''''')+'''''''' END '
             WHEN DATA_TYPE='image' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),CONVERT(VARBINARY(MAX),[' + COLUMN_NAME + ']),1)+'''''''' END '
             WHEN DATA_TYPE='varbinary' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],1)+'''''''' END '
             WHEN DATA_TYPE='binary' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],1)+'''''''' END '
             when DATA_TYPE='time' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''' END '
             ELSE 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE CONVERT(NVARCHAR(MAX),['+column_name+']) END' end
       + '+'', '
     from information_schema.columns c
     join syscolumns co on co.name=c.COLUMN_NAME and object_name(co.id)=so.name and OBJECT_NAME(co.id)=c.TABLE_NAME and co.id=so.object_id and c.TABLE_SCHEMA=SCHEMA_NAME(so.schema_id)
     where table_name = so.name
     order by ordinal_position
    FOR XML PATH('')) val (list)
    where   so.type = 'U'
    

    Youtube autoplay not working on mobile devices with embedded HTML5 player

    There is a way to make youtube autoplay, and complete playlists play through. Get Adblock browser for Android, and then go to the youtube website, and and configure it for the desktop version of the page, close Adblock browser out, and then reopen, and you will have the desktop version, where autoplay will work.

    Using the desktop version will also mean that AdBlock will work. The mobile version invokes the standalone YouTube player, which is why you want the desktop version of the page, so that autoplay will work, and so ad blocking will work.

    Get spinner selected items text?

    TextView textView = (TextView) spinActSubTask.getSelectedView().findViewById(R.id.tvProduct);
    
    String subItem = textView.getText().toString();
    

    Add the loading screen in starting of the android application

    If the application is not doing anything in that 10 seconds, this will form a bad design only to make the user wait for 10 seconds doing nothing.

    If there is something going on in that, or if you wish to implement 10 seconds delay splash screen,Here is the Code :

    ProgressDialog pd;
    pd = ProgressDialog.show(this,"Please Wait...", "Loading Application..", false, true);
    pd.setCanceledOnTouchOutside(false);
    Thread t = new Thread()
    { 
          @Override
          public void run()
          {
                    try
                    {
                        sleep(10000)  //Delay of 10 seconds
                    } 
            catch (Exception e) {}
            handler.sendEmptyMessage(0);
            }
    } ;
    t.start();
    
    //Handles the thread result of the Backup being executed.
    private Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) 
        {
            pd.dismiss();
            //Start the Next Activity here...
    
        }
    };
    

    What is lazy loading in Hibernate?

    Lazy setting decides whether to load child objects while loading the Parent Object.You need to do this setting respective hibernate mapping file of the parent class.Lazy = true (means not to load child)By default the lazy loading of the child objects is true.

    Way to read first few lines for pandas dataframe

    I think you can use the nrows parameter. From the docs:

    nrows : int, default None
    
        Number of rows of file to read. Useful for reading pieces of large files
    

    which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):

    In [1]: import pandas as pd
    
    In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
    CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
    Wall time: 0.00 s
    
    In [3]: len(z)
    Out[3]: 20
    
    In [4]: time z = pd.read_csv("P00000001-ALL.csv")
    CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
    Wall time: 30.23 s
    

    .prop() vs .attr()

    All is in the doc:

    The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

    So use prop!

    Get User Selected Range

    Selection is its own object within VBA. It functions much like a Range object.

    Selection and Range do not share all the same properties and methods, though, so for ease of use it might make sense just to create a range and set it equal to the Selection, then you can deal with it programmatically like any other range.

    Dim myRange as Range
    Set myRange = Selection
    

    For further reading, check out the MSDN article.

    Read JSON data in a shell script

    tl;dr

    $ cat /tmp/so.json | underscore select '.Messages .Body' 
    ["172.16.1.42|/home/480/1234/5-12-2013/1234.toSort"]
    

    Javascript CLI tools

    You can use Javascript CLI tools like

    Example

    Select all name children of a addons:

    underscore select ".addons > .name"
    

    The underscore-cli provide others real world examples as well as the json:select() doc.

    Removing elements from an array in C

    What solution you need depends on whether you want your array to retain its order, or not.

    Generally, you never only have the array pointer, you also have a variable holding its current logical size, as well as a variable holding its allocated size. I'm also assuming that the removeIndex is within the bounds of the array. With that given, the removal is simple:

    Order irrelevant

    array[removeIndex] = array[--logicalSize];
    

    That's it. You simply copy the last array element over the element that is to be removed, decrementing the logicalSize of the array in the process.

    If removeIndex == logicalSize-1, i.e. the last element is to be removed, this degrades into a self-assignment of that last element, but that is not a problem.

    Retaining order

    memmove(array + removeIndex, array + removeIndex + 1, (--logicalSize - removeIndex)*sizeof(*array));
    

    A bit more complex, because now we need to call memmove() to perform the shifting of elements, but still a one-liner. Again, this also updates the logicalSize of the array in the process.

    Android Studio - Importing external Library/Jar

    In Android Studio (mine is 2.3.1) go to File - Project Structure:

    enter image description here

    gradle build fails on lint task

    if abortOnError false will not resolve your problem, you can try this.

    lintOptions {
        checkReleaseBuilds false
    }
    

    Check if a string is palindrome

    I'm no c++ guy, but you should be able to get the gist from this.

    public static string Reverse(string s) {
        if (s == null || s.Length < 2) {
            return s;
        }
    
        int length = s.Length;
        int loop = (length >> 1) + 1;
        int j;
        char[] chars = new char[length];
        for (int i = 0; i < loop; i++) {
            j = length - i - 1;
            chars[i] = s[j];
            chars[j] = s[i];
        }
        return new string(chars);
    }
    

    How can I mock the JavaScript window object using Jest?

    I found an easy way to do it: delete and replace

    describe('Test case', () => {
      const { open } = window;
    
      beforeAll(() => {
        // Delete the existing
        delete window.open;
        // Replace with the custom value
        window.open = jest.fn();
        // Works for `location` too, eg:
        // window.location = { origin: 'http://localhost:3100' };
      });
    
      afterAll(() => {
        // Restore original
        window.open = open;
      });
    
      it('correct url is called', () => {
        statementService.openStatementsReport(111);
        expect(window.open).toBeCalled(); // Happy happy, joy joy
      });
    });
    

    How to undo 'git reset'?

    1.Use git reflog to get all references update.

    2.git reset <id_of_commit_to_which_you_want_restore>

    Pressing Ctrl + A in Selenium WebDriver

    WebDriver driver = new FirefoxDriver();
    
    Actions action = new Actions(driver); 
    
    action.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();
    

    This method removes the extra call ( String.ValueOf() ) to convert unicode to string.

    Choosing a jQuery datagrid plugin?

    A good plugin that I have used before is DataTables.

    What's a "static method" in C#?

    When you add a "static" keyword to a method, it means that underlying implementation gives the same result for any instance of the class. Needless to say, result varies with change in the value of parameters

    How do I hide the PHP explode delimiter from submitted form results?

    <select name="FakeName" id="Fake-ID" aria-required="true" required>  <?php $options=nl2br(file_get_contents("employees.txt")); $options=explode("<br />",$options);  foreach ($options as $item_array) { echo "<option value='".$item_array"'>".$item_array"</option>";  } ?> </select> 

    How to finish Activity when starting other activity in Android?

    startActivity(new Intent(context, ListofProducts.class)
        .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK));
    

    tr:hover not working

    Also, it matters in which order the tags in your CSS file are styled. Make sure that your tr:nth-child and tr:hover td are described before table's td and th. Like so:

    #tblServers {
      font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
      border-collapse: collapse;
      width: 100%;
    }
    
    #tblServers tr:nth-child(even){background-color: #f2f2f2;}
    
    #tblServers tr:hover td{background-color: #c1c4c8;}
    
    #tblServers td, #tblServers th {
      border: 1px solid #ddd;
      padding: 8px;
    }
    
    #tblServers th {
      padding-top: 12px;
      padding-bottom: 12px;
      text-align: left;
      background-color: #4a536e;
      color: white;
    }
    

    Best way to repeat a character in C#

    What about this:

    string tabs = new String('\t', n);
    

    Where n is the number of times you want to repeat the string.

    Or better:

    static string Tabs(int n)
    {
        return new String('\t', n);
    }
    

    Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

    I have tried above all issue but was not working for me What I tried is

    First of all, I want to go with manual code signing process, I am not doing via automatic code signing

    • I specify team name enter image description here
    • Then change deployment target enter image description here
    • Clean and build

    You will good to go now

    split string in two on given index and return both parts

    function splitText(value, index) {
      if (value.length < index) {return value;} 
      return [value.substring(0, index)].concat(splitText(value.substring(index), index));
    }
    console.log(splitText('this is a testing peace of text',10));
    // ["this is a ", "testing pe", "ace of tex", "t"] 
    

    For those who want to split a text into array using the index.

    Is there a Google Chrome-only CSS hack?

    Try to use the new '@supports' feature, here is one good hack that you might like:

    * UPDATE!!! * Microsoft Edge and Safari 9 both added support for the @supports feature in Fall 2015, Firefox also -- so here is my updated version for you:

    /* Chrome 29+ (Only) */
    
    @supports (-webkit-appearance:none) and (not (overflow:-webkit-marquee))
    and (not (-ms-ime-align:auto)) and (not (-moz-appearance:none)) { 
       .selector { color:red; } 
    }
    

    More info on this here (the reverse... Safari but not Chrome): [ is there a css hack for safari only NOT chrome? ]

    The previous CSS Hack [before Edge and Safari 9 or newer Firefox versions]:

    /* Chrome 28+ (now also Microsoft Edge, Firefox, and Safari 9+) */
    
    @supports (-webkit-appearance:none) { .selector { color:red; } }
    

    This worked for (only) chrome, version 28 and newer.

    (The above chrome 28+ hack was not one of my creations. I found this on the web and since it was so good I sent it to BrowserHacks.com recently, there are others coming.)

    August 17th, 2014 update: As I mentioned, I have been working on reaching more versions of chrome (and many other browsers), and here is one I crafted that handles chrome 35 and newer.

    /* Chrome 35+ */
    
    _::content, _:future, .selector:not(*:root) { color:red; }
    

    In the comments below it was mentioned by @BoltClock about future, past, not... etc... We can in fact use them to go a little farther back in Chrome history.

    So then this is one that also works but not 'Chrome-only' which is why I did not put it here. You still have to separate it by a Safari-only hack to complete the process. I have created css hacks to do this however, not to worry. Here are a few of them, starting with the simplest:

    /* Chrome 26+, Safari 6.1+ */
    
    _:past, .selector:not(*:root) { color:red; }
    

    Or instead, this one which goes back to Chrome 22 and newer, but Safari as well...

    /* Chrome 22+, Safari 6.1+ */
    
    @media screen and (-webkit-min-device-pixel-ratio:0)
    and (min-resolution:.001dpcm),
    screen and(-webkit-min-device-pixel-ratio:0)
    {
        .selector { color:red; } 
    }
    

    The block of Chrome versions 22-28 (more complicated but works nicely) are also possible to target via a combination I worked out:

    /* Chrome 22-28 (Only!) */
    
    @media screen and(-webkit-min-device-pixel-ratio:0)
    {
        .selector  {-chrome-:only(;
    
           color:red; 
    
        );}
    }
    

    Now follow up with this next couple I also created that targets Safari 6.1+ (only) in order to still separate Chrome and Safari. Updated to include Safari 8

    /* Safari 6.1-7.0 */
    
    @media screen and (-webkit-min-device-pixel-ratio:0) and (min-color-index:0)
    {
        .selector {(;  color:blue;  );} 
    }
    
    
    /* Safari 7.1+ */
    
    _::-webkit-full-page-media, _:future, :root .selector { color:blue; } 
    

    So if you put one of the Chrome+Safari hacks above, and then the Safari 6.1-7 and 8 hacks in your styles sequentially, you will have Chrome items in red, and Safari items in blue.

    How to filter Android logcat by application?

    This is probably the simplest solution.

    On top of a solution from Tom Mulcahy, you can further simplify it like below:

    alias logcat="adb logcat | grep `adb shell ps | egrep '\bcom.your.package.name\b' | cut -c10-15`"
    

    Usage is easy as normal alias. Just type the command in your shell:

    logcat
    

    The alias setup makes it handy. And the regex makes it robust for multi-process apps, assuming you care about the main process only.

    Of coz you can set more aliases for each process as you please. Or use hegazy's solution. :)

    In addition, if you want to set logging levels, it is

    alias logcat-w="adb logcat *:W | grep `adb shell ps | egrep '\bcom.your.package.name\b' | cut -c10-15`"
    

    How to append strings using sprintf?

    For safety (buffer overflow) I recommend to use snprintf()

    const int MAX_BUF = 1000;
    char* Buffer = malloc(MAX_BUF);
    
    int length = 0;
    length += snprintf(Buffer+length, MAX_BUF-length, "Hello World");
    length += snprintf(Buffer+length, MAX_BUF-length, "Good Morning");
    length += snprintf(Buffer+length, MAX_BUF-length, "Good Afternoon");
    

    How is malloc() implemented internally?

    The sbrksystem call moves the "border" of the data segment. This means it moves a border of an area in which a program may read/write data (letting it grow or shrink, although AFAIK no malloc really gives memory segments back to the kernel with that method). Aside from that, there's also mmap which is used to map files into memory but is also used to allocate memory (if you need to allocate shared memory, mmap is how you do it).

    So you have two methods of getting more memory from the kernel: sbrk and mmap. There are various strategies on how to organize the memory that you've got from the kernel.

    One naive way is to partition it into zones, often called "buckets", which are dedicated to certain structure sizes. For example, a malloc implementation could create buckets for 16, 64, 256 and 1024 byte structures. If you ask malloc to give you memory of a given size it rounds that number up to the next bucket size and then gives you an element from that bucket. If you need a bigger area malloc could use mmap to allocate directly with the kernel. If the bucket of a certain size is empty malloc could use sbrk to get more space for a new bucket.

    There are various malloc designs and there is propably no one true way of implementing malloc as you need to make a compromise between speed, overhead and avoiding fragmentation/space effectiveness. For example, if a bucket runs out of elements an implementation might get an element from a bigger bucket, split it up and add it to the bucket that ran out of elements. This would be quite space efficient but would not be possible with every design. If you just get another bucket via sbrk/mmap that might be faster and even easier, but not as space efficient. Also, the design must of course take into account that "free" needs to make space available to malloc again somehow. You don't just hand out memory without reusing it.

    If you're interested, the OpenSER/Kamailio SIP proxy has two malloc implementations (they need their own because they make heavy use of shared memory and the system malloc doesn't support shared memory). See: https://github.com/OpenSIPS/opensips/tree/master/mem

    Then you could also have a look at the GNU libc malloc implementation, but that one is very complicated, IIRC.

    Append an int to a std::string

    You are casting ClientID to char* causing the function to assume its a null terinated char array, which it is not.

    from cplusplus.com :

    string& append ( const char * s ); Appends a copy of the string formed by the null-terminated character sequence (C string) pointed by s. The length of this character sequence is determined by the first ocurrence of a null character (as determined by traits.length(s)).

    Keyboard shortcut for Jump to Previous View Location (Navigate back/forward) in IntelliJ IDEA

    Press Ctrl + Alt + S then choose Keymap and finally find the keyboard shortcut by type back word in search bar at the top right corner.

    Angular 2 - View not updating after model changes

    It might be that the code in your service somehow breaks out of Angular's zone. This breaks change detection. This should work:

    import {Component, OnInit, NgZone} from 'angular2/core';
    
    export class RecentDetectionComponent implements OnInit {
    
        recentDetections: Array<RecentDetection>;
    
        constructor(private zone:NgZone, // <== added
            private recentDetectionService: RecentDetectionService) {
            this.recentDetections = new Array<RecentDetection>();
        }
    
        getRecentDetections(): void {
            this.recentDetectionService.getJsonFromApi()
                .subscribe(recent => { 
                     this.zone.run(() => { // <== added
                         this.recentDetections = recent;
                         console.log(this.recentDetections[0].macAddress) 
                     });
            });
        }
    
        ngOnInit() {
            this.getRecentDetections();
            let timer = Observable.timer(2000, 5000);
            timer.subscribe(() => this.getRecentDetections());
        }
    }
    

    For other ways to invoke change detection see Triggering change detection manually in Angular

    Alternative ways to invoke change detection are

    ChangeDetectorRef.detectChanges()
    

    to immediately run change detection for the current component and its children

    ChangeDetectorRef.markForCheck()
    

    to include the current component the next time Angular runs change detection

    ApplicationRef.tick()
    

    to run change detection for the whole application

    Cross-Origin Request Headers(CORS) with PHP headers

    If you want to create a CORS service from PHP, you can use this code as the first step in your file that handles the requests:

    // Allow from any origin
    if(isset($_SERVER["HTTP_ORIGIN"]))
    {
        // You can decide if the origin in $_SERVER['HTTP_ORIGIN'] is something you want to allow, or as we do here, just allow all
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    }
    else
    {
        //No HTTP_ORIGIN set, so we allow any. You can disallow if needed here
        header("Access-Control-Allow-Origin: *");
    }
    
    header("Access-Control-Allow-Credentials: true");
    header("Access-Control-Max-Age: 600");    // cache for 10 minutes
    
    if($_SERVER["REQUEST_METHOD"] == "OPTIONS")
    {
        if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_METHOD"]))
            header("Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT"); //Make sure you remove those you do not want to support
    
        if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"]))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    
        //Just exit with 200 OK with the above headers for OPTIONS method
        exit(0);
    }
    //From here, handle the request as it is ok
    

    How to screenshot website in JavaScript client-side / how Google did it? (no need to access HDD)

    I needed to snapshot a div on the page (for a webapp I wrote) that is protected by JWT's and makes very heavy use of Angular.

    I had no luck with any of the above methods.

    I ended up taking the outerHTML of the div I needed, cleaning it up a little (*) and then sending it to the server where I run wkhtmltopdf against it.

    This is working very well for me.

    (*) various input devices in my pages didn't render as checked or have their text values when viewed in the pdf... So I run a little bit of jQuery on the html before I send it up for rendering. ex: for text input items -- I copy their .val()'s into 'value' attributes, which then can be seen by wkhtmlpdf

    How to set ssh timeout?

    Well, you could use nohup to run whatever you are running on 'non-blocking mode'. So you can just keep checking if whatever it was supposed to run, ran, otherwise exit.

    nohup ./my-script-that-may-take-long-to-finish.sh &
    ./check-if-previous-script-ran-or-exit.sh
    
    
    echo "Script ended on Feb 15, 2011, 9:20AM" > /tmp/done.txt
    

    So in the second one you just check if the file exists.

    Iterate all files in a directory using a 'for' loop

    Here's my go with comments in the code.

    I'm just brushing up by biatch skills so forgive any blatant errors.

    I tried to write an all in one solution as best I can with a little modification where the user requires it.

    Some important notes: Just change the variable recursive to FALSE if you only want the root directories files and folders processed. Otherwise, it goes through all folders and files.

    C&C most welcome...

    @echo off
    title %~nx0
    chcp 65001 >NUL
    set "dir=c:\users\%username%\desktop"
    ::
    :: Recursive Loop routine - First Written by Ste on - 2020.01.24 - Rev 1
    ::
    setlocal EnableDelayedExpansion
    rem THIS IS A RECURSIVE SOLUTION [ALBEIT IF YOU CHANGE THE RECURSIVE TO FALSE, NO]
    rem By removing the /s switch from the first loop if you want to loop through
    rem the base folder only.
    set recursive=TRUE
    if %recursive% equ TRUE ( set recursive=/s ) else ( set recursive= )
    endlocal & set recursive=%recursive%
    cd /d %dir%
    echo Directory %cd%
    for %%F in ("*") do (echo    ? %%F)                                 %= Loop through the current directory. =%
    for /f "delims==" %%D in ('dir "%dir%" /ad /b %recursive%') do (    %= Loop through the sub-directories only if the recursive variable is TRUE. =%
      echo Directory %%D
      echo %recursive% | find "/s" >NUL 2>NUL && (
        pushd %%D
        cd /d %%D
        for /f "delims==" %%F in ('dir "*" /b') do (                      %= Then loop through each pushd' folder and work on the files and folders =%
          echo %%~aF | find /v "d" >NUL 2>NUL && (                        %= This will weed out the directories by checking their attributes for the lack of 'd' with the /v switch therefore you can now work on the files only. =%
          rem You can do stuff to your files here.
          rem Below are some examples of the info you can get by expanding the %%F variable.
          rem Uncomment one at a time to see the results.
          echo    ? %%~F           &rem expands %%F removing any surrounding quotes (")
          rem echo    ? %%~dF          &rem expands %%F to a drive letter only
          rem echo    ? %%~fF          &rem expands %%F to a fully qualified path name
          rem echo    ? %%~pF          &rem expands %%A to a path only
          rem echo    ? %%~nF          &rem expands %%F to a file name only
          rem echo    ? %%~xF          &rem expands %%F to a file extension only
          rem echo    ? %%~sF          &rem expanded path contains short names only
          rem echo    ? %%~aF          &rem expands %%F to file attributes of file
          rem echo    ? %%~tF          &rem expands %%F to date/time of file
          rem echo    ? %%~zF          &rem expands %%F to size of file
          rem echo    ? %%~dpF         &rem expands %%F to a drive letter and path only
          rem echo    ? %%~nxF         &rem expands %%F to a file name and extension only
          rem echo    ? %%~fsF         &rem expands %%F to a full path name with short names only
          rem echo    ? %%~dp$dir:F    &rem searches the directories listed in the 'dir' environment variable and expands %%F to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string
          rem echo    ? %%~ftzaF       &rem expands %%F to a DIR like output line
          )
          )
        popd
        )
      )
    echo/ & pause & cls
    

    TypeError: 'dict' object is not callable

    strikes  = [number_map[int(x)] for x in input_str.split()]
    

    Use square brackets to explore dictionaries.

    Truncating long strings with CSS: feasible yet?

    OK, Firefox 7 implemented text-overflow: ellipsis as well as text-overflow: "string". Final release is planned for 2011-09-27.

    Maven does not find JUnit tests to run

    junitArtifactName might also be the case if the JUnit in use isn't the standard (junit:junit) but for instance...

    <dependency>
        <groupId>org.eclipse.orbit</groupId>
        <artifactId>org.junit</artifactId>
        <version>4.11.0</version>
        <type>bundle</type>
        <scope>test</scope>
    </dependency>
    

    remove kernel on jupyter notebook

    If you are doing this for virtualenv, the kernels in inactive environments might not be shown with jupyter kernelspec list, as suggested above. You can delete it from directory:

    ~/.local/share/jupyter/kernels/
    

    Best way to pretty print a hash

    For large nested hashes this script could be helpful for you. It prints a nested hash in a nice python/like syntax with only indents to make it easy to copy.

    module PrettyHash
      # Usage: PrettyHash.call(nested_hash)
      # Prints the nested hash in the easy to look on format
      # Returns the amount of all values in the nested hash
    
      def self.call(hash, level: 0, indent: 2)
        unique_values_count = 0
        hash.each do |k, v|
          (level * indent).times { print ' ' }
          print "#{k}:"
          if v.is_a?(Hash)
            puts
            unique_values_count += call(v, level: level + 1, indent: indent)
          else
            puts " #{v}"
            unique_values_count += 1
          end
        end
        unique_values_count
      end
    end
    

    Example usage:

      h = {a: { b: { c: :d }, e: :f }, g: :i }
      PrettyHash.call(h)
    
    a:
      b:
        c: d
      e: f
    g: i
    => 3
    

    The returned value is the count (3) of all the end-level values of the nested hash.

    How do I set the selected item in a comboBox to match my string using C#?

    Supposing test1, test2, test3 belong to comboBox1 collection following statement will work.

    comboBox1.SelectedIndex = 0; 
    

    Dilemma: when to use Fragments vs Activities:

    I use Fragments for better user experience. For example if you have a Button and you want to run let's say a webservice when you click it, I attach a Fragment to the parent Activity.

    if (id == R.id.forecast) {
    
        ForecastFragment forecastFragment = new ForecastFragment();
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.main_content, forecastFragment);
        ft.addToBackStack("backstack");
        forecastFragment.setArguments(b);
        ft.commit();
    }
    

    In that way the user won't have to move in another activity.

    And secondly I prefer Fragments because you can handle them easily during rotation.