Programs & Examples On #Seed

Seed is a JavaScript interpreter and a library of the GNOME project.

Java random numbers using a seed

If you're giving the same seed, that's normal. That's an important feature allowing tests.

Check this to understand pseudo random generation and seeds:

Pseudorandom number generator

A pseudorandom number generator (PRNG), also known as a deterministic random bit generator DRBG, is an algorithm for generating a sequence of numbers that approximates the properties of random numbers. The sequence is not truly random in that it is completely determined by a relatively small set of initial values, called the PRNG's state, which includes a truly random seed.

If you want to have different sequences (the usual case when not tuning or debugging the algorithm), you should call the zero argument constructor which uses the nanoTime to try to get a different seed every time. This Random instance should of course be kept outside of your method.

Your code should probably be like this:

private Random generator = new Random();
double randomGenerator() {
    return generator.nextDouble()*0.5;
}

Seedable JavaScript random number generator

If you want to be able to specify the seed, you just need to replace the calls to getSeconds() and getMinutes(). You could pass in an int and use half of it mod 60 for the seconds value and the other half modulo 60 to give you the other part.

That being said, this method looks like garbage. Doing proper random number generation is very hard. The obvious problem with this is that the random number seed is based on seconds and minutes. To guess the seed and recreate your stream of random numbers only requires trying 3600 different second and minute combinations. It also means that there are only 3600 different possible seeds. This is correctable, but I'd be suspicious of this RNG from the start.

If you want to use a better RNG, try the Mersenne Twister. It is a well tested and fairly robust RNG with a huge orbit and excellent performance.

EDIT: I really should be correct and refer to this as a Pseudo Random Number Generator or PRNG.

"Anyone who uses arithmetic methods to produce random numbers is in a state of sin."
                                                                                                                                                          --- John von Neumann

What is the best way to seed a database in Rails?

Rails has a built in way to seed data as explained here.

Another way would be to use a gem for more advanced or easy seeding such as: seedbank.

The main advantage of this gem and the reason I use it is that it has advanced capabilities such as data loading dependencies and per environment seed data.

Adding an up to date answer as this answer was first on google.

Showing Thumbnail for link in WhatsApp || og:image meta-tag doesn't work

Only these 3 tags seem to be required (og:title, twitter:description, rel="icon"):

<meta property="og:title" content="San Roque 2014 Pollos" />

<meta name="twitter:description" property="og:description" itemprop="description" content="Programa de fiestas" />

<link rel="icon" type="image/png" href="https://images.weserv.nl/?url=http://pollosweb.wesped.es/programa_pollos/play.png&w=192&height=192" sizes="192x192" />

Experimenting / playing

The easiest way to experiment for me was with CodeSandbox following these steps:

  • Create a Vanilla app with https://codesandbox.io/s/
  • Modify your meta tags accordingly in the index.html file
  • Save the file (ctrl+s) which would fork the app and generate its own unique url
  • Paste that url in WhatsApp to see the preview (you don't even need to send a message)
  • Make changes to the meta tags
  • Modify the url - add a single character at the end of the url. This discards the "previous cached preview"

Quotes required

Just be sure to ALWAYS have quotes and closing quotes because WhatsApp is sensitive to that. Your above example does not have a closing quote for your og:description.

How to commit changes to a new branch

git checkout -b your-new-branch

git add <files>

git commit -m <message>

First, checkout your new branch. Then add all the files you want to commit to staging. Lastly, commit all the files you just added. You might want to do a git push origin your-new-branch afterward so your changes show up on the remote.

How can I use regex to get all the characters after a specific character, e.g. comma (",")

This matches a word from any length:

var phrase = "an important number comes after this: 123456";
var word = "this: ";
var number = phrase.substr(phrase.indexOf(word) + word.length);
// number = 123456

SSH Key - Still asking for password and passphrase

Adding to the above answers. Had to do one more step on Windows for git to be able to use ssh-agent.

Had to run the following command in powershell to update the environment variable:

PS> [Environment]::SetEnvironmentVariable("GIT_SSH", "$((Get-Command ssh).Source)", [System.EnvironmentVariableTarget]::User)

Restart VSCode, Powershell or whatever terminal you are using to activate the env variable.

Complete instructions can be found [here] (https://snowdrift.tech/cli/ssh/git/tutorials/2019/01/31/using-ssh-agent-git-windows.html).

"int cannot be dereferenced" in Java

Assuming getItemNumber() returns an int, replace

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

with

if (id == list[pos].getItemNumber())

Hbase quickly count number of rows

Go to Hbase home directory and run this command,

./bin/hbase org.apache.hadoop.hbase.mapreduce.RowCounter 'namespace:tablename'

This will launch a mapreduce job and the output will show the number of records existing in the hbase table.

Save the console.log in Chrome to a file

A lot of good answers but why not just use JSON.stringify(your_variable) ? Then take the contents via copy and paste (remove outer quotes). I posted this same answer also at: How to save the output of a console.log(object) to a file?

What are the differences between struct and class in C++?

**UPDATE: ** Please ignore this reply. I did not consider the possibility that for the struct, the value was uninitialized but just happened to be 0. There is not an initialization difference between struct and class.


I am seeing another different between structs and classes having to do with default initialization.

struct Foo {
    int a;
};

class Bar {
    int a;
};

class Tester {
    Foo m_Foo = Foo();
    Bar m_Bar = Bar();

public:
    Tester() {}
};

int main() {
    auto myTester = Tester();
}

Run that code and examine myTester. You'll find that for m_Foo, the struct, m_Foo.a has been initialized to 0, but for m_Bar, the class, m_Bar.a is uninitialized. So there does appear to be a difference in what the default constructor does for struct vs. class. I'm seeing this with Visual Studio.

How to use JavaScript regex over multiple lines?

DON'T use (.|[\r\n]) instead of . for multiline matching.

DO use [\s\S] instead of . for multiline matching

Also, avoid greediness where not needed by using *? or +? quantifier instead of * or +. This can have a huge performance impact.

See the benchmark I have made: http://jsperf.com/javascript-multiline-regexp-workarounds

Using [^]: fastest
Using [\s\S]: 0.83% slower
Using (.|\r|\n): 96% slower
Using (.|[\r\n]): 96% slower

NB: You can also use [^] but it is deprecated in the below comment.

JPA and Hibernate - Criteria vs. JPQL or HQL

  • HQL is to perform both select and non-select operations on the data, but Criteria is only for selecting the data, we cannot perform non-select operations using criteria
  • HQL is suitable for executing Static Queries, where as Criteria is suitable for executing Dynamic Queries
  • HQL doesn’t support pagination concept, but we can achieve pagination with Criteria
  • Criteria used to take more time to execute then HQL
  • With Criteria we are safe with SQL Injection because of its dynamic query generation but in HQL as your queries are either fixed or parametrized, there is no safe from SQL Injection.

source

How to store arbitrary data for some HTML tags

If you are using jQuery already then you should leverage the "data" method which is the recommended method for storing arbitrary data on a dom element with jQuery.

To store something:

$('#myElId').data('nameYourData', { foo: 'bar' });

To retrieve data:

var myData = $('#myElId').data('nameYourData');

That is all that there is to it but take a look at the jQuery documentation for more info/examples.

What is the difference between HTTP and REST?

REST is a specific way of approaching the design of big systems (like the web).

It's a set of 'rules' (or 'constraints').

HTTP is a protocol that tries to obey those rules.

Tomcat is not running even though JAVA_HOME path is correct

To run Tomcat8 you need to have JRE_HOME defined in Env Variable.

JAVA_HOME alone will not do even if correctly set.

JRE_HOME = C:\Program Files\Java\jdk1.8.0_77\jre

You should select the JRE that is inside SDK, i.e. one with your JDK(SDK) installation. In other words your JAVA_HOME + \jre

When compiling JDK is needed to support JSP, to compile Servlets which are generated from *.jsp files. Otherwise to run JRE is needed. So when you develop you need JAVA_HOME and when you deploy you need JRE_HOME.

How to set Spring profile from system variable?

I normally configure the applicationContext using Annotation based configuration rather than XML based configuration. Anyway, I believe both of them have the same priority.

*Answering your question, system variable has higher priority *


Getting profile based beans from applicationContext

  • Use @Profile on a Bean

@Component
@Profile("dev")
public class DatasourceConfigForDev

Now, the profile is dev

Note : if the Profile is given as @Profile("!dev") then the profile will exclude dev and be for all others.

  • Use profiles attribute in XML

<beans profile="dev">
    <bean id="DatasourceConfigForDev" class="org.skoolguy.profiles.DatasourceConfigForDev"/>
</beans>

Set the value for profile:

  • Programmatically via WebApplicationInitializer interface

    In web applications, WebApplicationInitializer can be used to configure the ServletContext programmatically
@Configuration
public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
            servletContext.setInitParameter("spring.profiles.active", "dev");
    }
}
  • Programmatically via ConfigurableEnvironment

    You can also set profiles directly on the environment:
    @Autowired
    private ConfigurableEnvironment env;

    // ...

    env.setActiveProfiles("dev");
  • Context Parameter in web.xml

    profiles can be activated in the web.xml of the web application as well, using a context parameter:
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/app-config.xml</param-value>
    </context-param>
    <context-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>dev</param-value>
    </context-param>
  • JVM System Parameter

    The profile names passed as the parameter will be activated during application start-up:

    -Dspring.profiles.active=dev
    

    In IDEs, you can set the environment variables and values to use when an application runs. The following is the Run Configuration in Eclipse:

Eclipse Run Configuration - screenshot is unavailable

  • Environment Variable

    to set via command line : export spring_profiles_active=dev

Any bean that does not specify a profile belongs to “default” profile.


The priority order is :

  1. Context parameter in web.xml
  2. WebApplicationInitializer
  3. JVM System parameter
  4. Environment variable

How to hide the bar at the top of "youtube" even when mouse hovers over it?

The answer to this question in 2020 is IT DOESN'T WORK AT ALL NOW.

How to get next/previous record in MySQL?

Try this example.

create table student(id int, name varchar(30), age int);

insert into student values
(1 ,'Ranga', 27),
(2 ,'Reddy', 26),
(3 ,'Vasu',  50),
(5 ,'Manoj', 10),
(6 ,'Raja',  52),
(7 ,'Vinod', 27);

SELECT name,
       (SELECT name FROM student s1
        WHERE s1.id < s.id
        ORDER BY id DESC LIMIT 1) as previous_name,
       (SELECT name FROM student s2
        WHERE s2.id > s.id
        ORDER BY id ASC LIMIT 1) as next_name
FROM student s
    WHERE id = 7; 

Note: If value is not found then it will return null.

In the above example, Previous value will be Raja and Next value will be null because there is no next value.

How to launch Windows Scheduler by command-line?

I'm also running XP SP2, and this works perfectly (from the command line...):

start control schedtasks

POST: sending a post request in a url itself

Based on what you provided, it is pretty simple for what you need to do and you even have a number of ways to go about doing it. You'll need something that'll let you post a body with your request. Almost any programming language can do this as well as command line tools like cURL.

One you have your tool decided, you'll need to create your JSON body and submit it to the server.

An example using cURL would be (all in one line, minus the \ at the end of the first line):

curl -v -H "Content-Type: application/json" -X POST \
     -d '{"name":"your name","phonenumber":"111-111"}' http://www.abc.com/details

The above command will create a request that should look like the following:

POST /details HTTP/1.1
Host: www.abc.com
Content-Type: application/json
Content-Length: 44

{"name":"your name","phonenumber":"111-111"}

On select change, get data attribute value

this works for me

<select class="form-control" id="foo">
    <option value="first" data-id="1">first</option>
    <option value="second" data-id="2">second</option>
</select>

and the script

$('#foo').on("change",function(){
    var dataid = $("#foo option:selected").attr('data-id');
    alert(dataid)
});

Setting property 'source' to 'org.eclipse.jst.jee.server:JSFTut' did not find a matching property

In regards to setting the logging.properties value

org.apache.tomcat.util.digester.Digester.level = SEVERE

... if you're running an embedded tomcat server in eclipse, the logging.properties file used by default is the JDK default at %JAVA_HOME%/jre/lib/logging.properties

If you want to use a different logging.properties file (e.g. in the tomcat server's conf directory), this needs to be set via the java.util.logging.config.file system property. e.g. to use the logging properties defined in the file c:\java\apache-tomcat-7.0.54\conf\eclipse-logging.properties, add this to the VM argument list:

-Djava.util.logging.config.file="c:\java\apache-tomcat-7.0.54\conf\eclipse-logging.properties"

(double-click on the server icon, click 'Open launch configuration', select the Arguments tab, then enter this in the 'VM arguments' text box)

You might also find it useful to add the VM argument

-Djava.util.logging.SimpleFormatter.format="%1$tc %4$s %3$s %5$s%n"

as well, which will then include the source logger name in the output, which should make it easier to determine which logger to throttle in the logging.properties file (as per http://docs.oracle.com/javase/7/docs/api/java/util/logging/SimpleFormatter.html )

Which loop is faster, while or for?

In C#, the For loop is slightly faster.

For loop average about 2.95 to 3.02 ms.

The While loop averaged about 3.05 to 3.37 ms.

Quick little console app to prove:

 class Program
    {
        static void Main(string[] args)
        {
            int max = 1000000000;
            Stopwatch stopWatch = new Stopwatch();

            if (args.Length == 1 && args[0].ToString() == "While")
            {
                Console.WriteLine("While Loop: ");
                stopWatch.Start();
                WhileLoop(max);
                stopWatch.Stop();
                DisplayElapsedTime(stopWatch.Elapsed);
            }
            else
            {
                Console.WriteLine("For Loop: ");
                stopWatch.Start();
                ForLoop(max);
                stopWatch.Stop();
                DisplayElapsedTime(stopWatch.Elapsed);
            }
        }

        private static void WhileLoop(int max)
        {
            int i = 0;
            while (i <= max)
            {
                //Console.WriteLine(i);
                i++;
            };
        }

        private static void ForLoop(int max)
        {
            for (int i = 0; i <= max; i++)
            {
                //Console.WriteLine(i);
            }
        }

        private static void DisplayElapsedTime(TimeSpan ts)
        {
            // Format and display the TimeSpan value.
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                ts.Hours, ts.Minutes, ts.Seconds,
                ts.Milliseconds / 10);
            Console.WriteLine(elapsedTime, "RunTime");
        }
    }

Capturing browser logs with Selenium WebDriver using Java

Starting with Firefox 65 an about:config flag exists now so console API calls like console.log() land in the output stream and thus the log file (see (https://github.com/mozilla/geckodriver/issues/284#issuecomment-458305621).

profile = new FirefoxProfile();
profile.setPreference("devtools.console.stdout.content", true);

JSON array get length

Check you have the line:

 import org.json.JSONArray;

at the top of your source code

Calling a function of a module by using its name (a string)

Try this. While this still uses eval, it only uses it to summon the function from the current context. Then, you have the real function to use as you wish.

The main benefit for me from this is that you will get any eval-related errors at the point of summoning the function. Then you will get only the function-related errors when you call.

def say_hello(name):
    print 'Hello {}!'.format(name)

# get the function by name
method_name = 'say_hello'
method = eval(method_name)

# call it like a regular function later
args = ['friend']
kwargs = {}
method(*args, **kwargs)

Any easy way to use icons from resources?

Forms maintain separate resource files (SomeForm.Designer.resx) added via the designer. To use icons embedded in another resource file requires codes. (this.Icone = Project.Resources.SomeIcon;)

Instantiate and Present a viewController in Swift

akashivskyy's answer works just fine! But, in case you have some trouble returning from the presented view controller, this alternative can be helpful. It worked for me!

Swift:

let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("someViewController") as! UIViewController
// Alternative way to present the new view controller
self.navigationController?.showViewController(vc, sender: nil)

Obj-C:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MyStoryboardName" bundle:nil];
UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"someViewController"];
[self.navigationController showViewController:vc sender:nil];

Pandas (python): How to add column to dataframe for index?

How about:

df['new_col'] = range(1, len(df) + 1)

Alternatively if you want the index to be the ranks and store the original index as a column:

df = df.reset_index()

How to strip comma in Python string

Use replace method of strings not strip:

s = s.replace(',','')

An example:

>>> s = 'Foo, bar'
>>> s.replace(',',' ')
'Foo  bar'
>>> s.replace(',','')
'Foo bar'
>>> s.strip(',') # clears the ','s at the start and end of the string which there are none
'Foo, bar'
>>> s.strip(',') == s
True

How to enable assembly bind failure logging (Fusion) in .NET

Instead of using a ugly log file, you can also activate Fusion log via ETW/xperf by turning on the DotnetRuntime Private provider (Microsoft-Windows-DotNETRuntimePrivate) with GUID 763FD754-7086-4DFE-95EB-C01A46FAF4CA and the FusionKeyword keyword (0x4) on.

@echo off
echo Press a key when ready to start...
pause
echo .
echo ...Capturing...
echo .

"C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\xperf.exe" -on PROC_THREAD+LOADER+PROFILE -stackwalk Profile -buffersize 1024 -MaxFile 2048 -FileMode Circular -f Kernel.etl
"C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\xperf.exe" -start ClrSession -on Microsoft-Windows-DotNETRuntime:0x8118:0x5:'stack'+763FD754-7086-4DFE-95EB-C01A46FAF4CA:0x4:0x5 -f clr.etl -buffersize 1024

echo Press a key when you want to stop...
pause
pause
echo .
echo ...Stopping...
echo .

"C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\xperf.exe" -start ClrRundownSession -on Microsoft-Windows-DotNETRuntime:0x8118:0x5:'stack'+Microsoft-Windows-DotNETRuntimeRundown:0x118:0x5:'stack' -f clr_DCend.etl -buffersize 1024 

timeout /t 15

set XPERF_CreateNGenPdbs=1

"C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\xperf.exe" -stop ClrSession ClrRundownSession 
"C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\xperf.exe" -stop
"C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\xperf.exe" -merge kernel.etl clr.etl clr_DCend.etl Result.etl -compress
del kernel.etl
del clr.etl
del clr_DCend.etl

When you now open the ETL file in PerfView and look under the Events table, you can find the Fusion data:

Fusion events in PerfView

Making a Simple Ajax call to controller in asp.net mvc

View;

 $.ajax({
        type: 'GET',
        cache: false,
        url: '/Login/Method',
        dataType: 'json',
        data: {  },
        error: function () {
        },
        success: function (result) {
            alert("success")
        }
    });

Controller Method;

 public JsonResult Method()
 {
   return Json(new JsonResult()
      {
         Data = "Result"
      }, JsonRequestBehavior.AllowGet);
 }

How do I pass command-line arguments to a WinForms application?

The best way to work with args for your winforms app is to use

string[] args = Environment.GetCommandLineArgs();

You can probably couple this with the use of an enum to solidify the use of the array througout your code base.

"And you can use this anywhere in your application, you aren’t just restricted to using it in the main() method like in a console application."

Found at:HERE

Convert timestamp long to normal date format

Let me propose this solution for you. So in your managed bean, do this

public String convertTime(long time){
    Date date = new Date(time);
    Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
    return format.format(date);
}

so in your JSF page, you can do this (assuming foo is the object that contain your time)

<h:dataTable value="#{myBean.convertTime(myBean.foo.time)}" />

If you have multiple pages that want to utilize this method, you can put this in an abstract class and have your managed bean extend this abstract class.

EDIT: Return time with TimeZone

unfortunately, I think SimpleDateFormat will always format the time in local time, so we can't use SimpleDateFormat anymore. So to display time in different TimeZone, we can do this

public String convertTimeWithTimeZome(long time){
    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(TimeZone.getTimeZone("UTC"));
    cal.setTimeInMillis(time);
    return (cal.get(Calendar.YEAR) + " " + (cal.get(Calendar.MONTH) + 1) + " " 
            + cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":"
            + cal.get(Calendar.MINUTE));

}

A better solution is to utilize JodaTime. In my opinion, this API is much better than Calendar (lighter weight, faster and provide more functionality). Plus Calendar.Month of January is 0, that force developer to add 1 to the result, and you have to format the time yourself. Using JodaTime, you can fix all of that. Correct me if I am wrong, but I think JodaTime is incorporated in JDK7

How can I display two div in one line via css inline property

You don't need to use display:inline to achieve this:

.inline { 
    border: 1px solid red;
    margin:10px;
    float:left;/*Add float left*/
    margin :10px;
}

You can use float-left.

Using float:left is best way to place multiple div elements in one line. Why? Because inline-block does have some problem when is viewed in IE older versions.

fiddle

Can Mockito stub a method without regard to the argument?

Another option is to rely on good old fashion equals method. As long as the argument in the when mock equals the argument in the code being tested, then Mockito will match the mock.

Here is an example.

public class MyPojo {

    public MyPojo( String someField ) {
        this.someField = someField;
    }

    private String someField;

    @Override
    public boolean equals( Object o ) {
        if ( this == o ) return true;
        if ( o == null || getClass() != o.getClass() ) return false;
        MyPojo myPojo = ( MyPojo ) o;
        return someField.equals( myPojo.someField );
    }

}

then, assuming you know what the value for someField will be, you can mock it like this.

when(fooDao.getBar(new MyPojo(expectedSomeField))).thenReturn(myFoo);

pros: This is more explicit then any matchers. As a reviewer of code, I keep an eye open for any in the code junior developers write, as it glances over their code's logic to generate the appropriate object being passed.

con: Sometimes the field being passed to the object is a random ID. For this case you cannot easily construct the expected argument object in your mock code.

Another possible approach is to use Mockito's Answer object that can be used with the when method. Answer lets you intercept the actual call and inspect the input argument and return a mock object. In the example below I am using any to catch any request to the method being mocked. But then in the Answer lambda, I can further inspect the Bazo argument... maybe to verify that a proper ID was passed to it. I prefer this over any by itself so that at least some inspection is done on the argument.

    Bar mockBar = //generate mock Bar.

    when(fooDao.getBar(any(Bazo.class))
    .thenAnswer(  ( InvocationOnMock invocationOnMock) -> {
        Bazo actualBazo = invocationOnMock.getArgument( 0 );

        //inspect the actualBazo here and thrw exception if it does not meet your testing requirements.
        return mockBar;
    } );

So to sum it all up, I like relying on equals (where the expected argument and actual argument should be equal to each other) and if equals is not possible (due to not being able to predict the actual argument's state), I'll resort to Answer to inspect the argument.

How can I strip first and last double quotes?

Starting in Python 3.9, you can use removeprefix and removesuffix:

'"" " " ""\\1" " "" ""'.removeprefix('"').removesuffix('"')
# '" " " ""\\1" " "" "'

OOP vs Functional Programming vs Procedural

I think that they are often not "versus", but you can combine them. I also think that oftentimes, the words you mention are just buzzwords. There are few people who actually know what "object-oriented" means, even if they are the fiercest evangelists of it.

Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error

If you run into this problem with Visual Studio 2019 (VS2019), you can download the build tools from https://visualstudio.microsoft.com/downloads/. And, under Tools for Visual Studio 2019 and download Build Tools for Visual Studios 2019.

How to make the overflow CSS property work with hidden as value

In addition to provided answers:

it seems like parent element (the one with overflow:hidden) must not be display:inline. Changing to display:inline-block worked for me.

_x000D_
_x000D_
.outer {_x000D_
  position: relative;_x000D_
  border: 1px dotted black;_x000D_
  padding: 5px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
.inner {_x000D_
  position: absolute;_x000D_
  left: 50%;_x000D_
  margin-left: -20px;_x000D_
  top: 70%;_x000D_
  width: 40px;_x000D_
  height: 80px;_x000D_
  background: yellow;_x000D_
}
_x000D_
<span class="outer">_x000D_
  Some text_x000D_
  <span class="inner"></span>_x000D_
</span>_x000D_
<span class="outer" style="display:inline-block;">_x000D_
  Some text_x000D_
  <span class="inner"></span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

How to sort a NSArray alphabetically?

Use below code for sorting in alphabetical order:

    NSArray *unsortedStrings = @[@"Verdana", @"MS San Serif", @"Times New Roman",@"Chalkduster",@"Impact"];

    NSArray *sortedStrings =
    [unsortedStrings sortedArrayUsingSelector:@selector(compare:)];

    NSLog(@"Unsorted Array : %@",unsortedStrings);        
    NSLog(@"Sorted Array : %@",sortedStrings);

Below is console log :

2015-04-02 16:17:50.614 ToDoList[2133:100512] Unsorted Array : (
    Verdana,
    "MS San Serif",
    "Times New Roman",
    Chalkduster,
    Impact
)

2015-04-02 16:17:50.615 ToDoList[2133:100512] Sorted Array : (
    Chalkduster,
    Impact,
    "MS San Serif",
    "Times New Roman",
    Verdana
)

How to get the element clicked (for the whole document)?

Here's a solution that uses a jQuery selector so you can easily target tags of any class, ID, type etc.

jQuery('div').on('click', function(){
    var node = jQuery(this).get(0);
    var range = document.createRange();
    range.selectNodeContents( node );
    window.getSelection().removeAllRanges();
    window.getSelection().addRange( range );
});

excel formula to subtract number of days from a date

Assuming the original date is in cell A1:

=DATE(YEAR(A1), MONTH(A1), DAY(A1)-180)

Merge two rows in SQL

if one row has value in field1 column and other rows have null value then this Query might work.

SELECT
  FK,
  MAX(Field1) as Field1,
  MAX(Field2) as Field2
FROM 
(
select FK,ISNULL(Field1,'') as Field1,ISNULL(Field2,'') as Field2 from table1
)
tbl
GROUP BY FK

How can I specify a local gem in my Gemfile?

You can reference gems with source:

source: 'https://source.com', git repository (:github => 'git/url') and with local path

:path => '.../path/gem_name'.

You can learn more about [Gemfiles and how to use them] (https://kolosek.com/rails-bundle-install-and-gemfile) in this article.

Multiple maven repositories in one gradle file

In short you have to do like this

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "https://maven.fabric.io/public" }
}

Detail:

You need to specify each maven URL in its own curly braces. Here is what I got working with skeleton dependencies for the web services project I’m going to build up:

apply plugin: 'java'

sourceCompatibility = 1.7
version = '1.0'

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "http://maven.restlet.org" }
  mavenCentral()
}

dependencies {
  compile group:'org.restlet.jee', name:'org.restlet', version:'2.1.1'
  compile group:'org.restlet.jee', name:'org.restlet.ext.servlet',version.1.1'
  compile group:'org.springframework', name:'spring-web', version:'3.2.1.RELEASE'
  compile group:'org.slf4j', name:'slf4j-api', version:'1.7.2'
  compile group:'ch.qos.logback', name:'logback-core', version:'1.0.9'
  testCompile group:'junit', name:'junit', version:'4.11'
}

Blog

Search a string in a file and delete it from this file by Shell Script

Try the vim-way:

ex -s +"g/foo/d" -cwq file.txt

Iterate over a Javascript associative array in sorted order

<script type="text/javascript">
    var a = {
        b:1,
        z:1,
        a:1
    }; // your JS Object
    var keys = [];
    for (key in a) {
        keys.push(key);
    }
    keys.sort();
    var i = 0;
    var keyslen = keys.length;
    var str = '';
    //SORTED KEY ITERATION
    while (i < keyslen) {
        str += keys[i] + '=>' + a[keys[i]] + '\n';
        ++i;
    }
    alert(str);
    /*RESULT:
    a=>1
    b=>1
    z=>1
    */
</script>

How do I get first element rather than using [0] in jQuery?

You can try like this:
yourArray.shift()

Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

Using REQUIRES_NEW is only relevant when the method is invoked from a transactional context; when the method is invoked from a non-transactional context, it will behave exactly as REQUIRED - it will create a new transaction.

That does not mean that there will only be one single transaction for all your clients - each client will start from a non-transactional context, and as soon as the the request processing will hit a @Transactional, it will create a new transaction.

So, with that in mind, if using REQUIRES_NEW makes sense for the semantics of that operation - than I wouldn't worry about performance - this would textbook premature optimization - I would rather stress correctness and data integrity and worry about performance once performance metrics have been collected, and not before.

On rollback - using REQUIRES_NEW will force the start of a new transaction, and so an exception will rollback that transaction. If there is also another transaction that was executing as well - that will or will not be rolled back depending on if the exception bubbles up the stack or is caught - your choice, based on the specifics of the operations. Also, for a more in-depth discussion on transactional strategies and rollback, I would recommend: «Transaction strategies: Understanding transaction pitfalls», Mark Richards.

How can I delete multiple lines in vi?

d5d "cuts" five lines

I usually just throw the number in the middle like:

d7l = delete 7 letters

How can I convert a comma-separated string to an array?

Watch out if you are aiming at integers, like 1,2,3,4,5. If you intend to use the elements of your array as integers and not as strings after splitting the string, consider converting them into such.

var str = "1,2,3,4,5,6";
var temp = new Array();
// This will return an array with strings "1", "2", etc.
temp = str.split(",");

Adding a loop like this,

for (a in temp ) {
    temp[a] = parseInt(temp[a], 10); // Explicitly include base as per Álvaro's comment
}

will return an array containing integers, and not strings.

No WebApplicationContext found: no ContextLoaderListener registered?

You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

You need to understand the difference between Web application context and root application context .

In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.

The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .

Read the spring reference here for spring mvc .

Load an image from a url into a PictureBox

yourPictureBox.ImageLocation = "http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG"

How can I obfuscate (protect) JavaScript?

Dean Edward's Packer is an excellent obfuscator, though it primarily obfuscates the code, not any string elements you may have within your code.

See: Online Javascript Compression Tool and select Packer (Dean Edwards) from the dropdown

Get epoch for a specific date using Javascript

You can create a Date object, and call getTime on it:

new Date(2010, 6, 26).getTime() / 1000

'cannot open git-upload-pack' error in Eclipse when cloning or pushing git repository

I had my proxy settings set up in Eclipse and wasn't connected via ssh, which was causing the error.

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

I found a possible solution, but... I don't know if it's a good solution.

@Entity
public class Role extends Identifiable {

    @ManyToMany(cascade ={CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinTable(name="Role_Permission",
            joinColumns=@JoinColumn(name="Role_id"),
            inverseJoinColumns=@JoinColumn(name="Permission_id")
        )
    public List<Permission> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<Permission> permissions) {
        this.permissions = permissions;
    }
}

@Entity
public class Permission extends Identifiable {

    @ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinTable(name="Role_Permission",
            joinColumns=@JoinColumn(name="Permission_id"),
            inverseJoinColumns=@JoinColumn(name="Role_id")
        )
    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

I have tried this and it works. When you delete Role, also the relations are deleted (but not the Permission entities) and when you delete Permission, the relations with Role are deleted too (but not the Role instance). But we are mapping a unidirectional relation two times and both entities are the owner of the relation. Could this cause some problems to Hibernate? Which type of problems?

Thanks!

The code above is from another post related.

ascending/descending in LINQ - can one change the order via parameter?

You can easily create your own extension method on IEnumerable or IQueryable:

public static IOrderedEnumerable<TSource> OrderByWithDirection<TSource,TKey>
    (this IEnumerable<TSource> source,
     Func<TSource, TKey> keySelector,
     bool descending)
{
    return descending ? source.OrderByDescending(keySelector)
                      : source.OrderBy(keySelector);
}

public static IOrderedQueryable<TSource> OrderByWithDirection<TSource,TKey>
    (this IQueryable<TSource> source,
     Expression<Func<TSource, TKey>> keySelector,
     bool descending)
{
    return descending ? source.OrderByDescending(keySelector)
                      : source.OrderBy(keySelector);
}

Yes, you lose the ability to use a query expression here - but frankly I don't think you're actually benefiting from a query expression anyway in this case. Query expressions are great for complex things, but if you're only doing a single operation it's simpler to just put that one operation:

var query = dataList.OrderByWithDirection(x => x.Property, direction);

Changing Underline color

Update from author:
This answer is outdated since text-decoration-color is now supported by most modern browsers.


:pseudo + em

In order to accurately replicate the size, stroke width, and positioning of the native text-decoration:underline without introducing extra HTML markup, you should use a pseudo-element with em units. This allows for accurate scaling of the element and native behavior without additional markup.

CSS

`a {
  text-decoration: none;
  display: inline-table;
}

a:after {
  content: "";
  border-bottom: 0.1em solid #f00;
  display: table-caption;
  caption-side: bottom;
  position: relative;
  margin-top:-0.15em;
}`

By using display:table-caption and caption-side on the pseudo-element and display inline-table, we can force the browser to vertically-align both line and link accurately, even when scaled.

In this instance, we use inline-table instead of inline-block to force the pseudo to display without the need to specify height or negative values.

Examples

JSFIDDLE: https://jsfiddle.net/pohuski/8yfpjuod/8/
CODEPEN: http://codepen.io/pohuski/pen/vEzxPj | (example with scaling)

Successfully Tested On:
Internet Explorer: 8, 9, 10, 11
Firefox: 41, 40, 39, 38, 37, 36
Chrome: 45, 44, 43, 42
Safari: 8, 7, 6.2
Mobile Safari: 9.0, 8.0
Android Browser: 4.4, 2.3
Dolphin Mobile: 8, 11.4

Setting button text via javascript

Use textContent instead of value to set the button text.

Typically the value attribute is used to associate a value with the button when it's submitted as form data.

Note that while it's possible to set the button text with innerHTML, using textContext should be preferred because it's more performant and it can prevent cross-site scripting attacks as its value is not parsed as HTML.

JS:

var b = document.createElement('button');
b.setAttribute('content', 'test content');
b.setAttribute('class', 'btn');  
b.textContent = 'test value';

var wrapper = document.getElementById("divWrapper");
wrapper.appendChild(b);

Produces this in the DOM:

<div id="divWrapper">
    <button content="test content" class="btn">test value</button>
</div>

Demo: https://jsfiddle.net/13ucp6ob/

Undo scaffolding in Rails

When we generate scaffold, following files will be created:

Command: rails generate scaffold Game

Files created:

>       invoke  active_record
>       create    db/migrate/20160905064128_create_games.rb
>       create    app/models/game.rb
>       invoke    test_unit
>       create      test/models/game_test.rb
>       create      test/fixtures/games.yml
>       invoke  resource_route
>        route    resources :games
>       invoke  inherited_resources_controller
>       create    app/controllers/games_controller.rb
>       invoke    erb
>       create      app/views/games
>       create      app/views/games/index.html.erb
>       create      app/views/games/edit.html.erb
>       create      app/views/games/show.html.erb
>       create      app/views/games/new.html.erb
>       create      app/views/games/_form.html.erb
>       invoke    test_unit
>       create      test/controllers/games_controller_test.rb
>       invoke    helper
>       create      app/helpers/games_helper.rb
>       invoke      test_unit
>       create        test/helpers/games_helper_test.rb
>       invoke    jbuilder
>       create      app/views/games/index.json.jbuilder
>       create      app/views/games/show.json.jbuilder
>       invoke  assets
>       invoke    coffee
>       create      app/assets/javascripts/games.js.coffee
>       invoke    scss
>       create      app/assets/stylesheets/games.css.scss
>       invoke  scss
>       create    app/assets/stylesheets/scaffolds.css.scss

If we have run the migration after this then we have to rollback the migration first as the deletion of scaffold will remove the migration file too and we will not able to revert that migration.

Incase we have run the migration:

rake db:rollback

and after this we can safely remove the scaffold by this commad.

rails d scaffold Game

This command will remove all the files created by the scaffold in your project.

How to re-render flatlist?

For me, the trick was extraData and drilling down into the item component one more time

state = {
  uniqueValue: 0
}

<FlatList
  keyExtractor={(item, index) => item + index}
  data={this.props.photos}
  renderItem={this.renderItem}
  ItemSeparatorComponent={this.renderSeparator}
/>

renderItem = (item) => {
  if(item.item.selected) {
    return ( <Button onPress={this.itemPressed.bind(this, item)}>Selected</Button> );
  }
  return ( <Button onPress={this.itemPressed.bind(this, item)}>Not selected</Button>);
}

itemPressed (item) {
  this.props.photos.map((img, i) => {
    if(i === item.index) {
      if(img['selected') {
        delete img.selected;
      } else {
        img['selected'] = true;
      }
      this.setState({ uniqueValue: this.state.uniqueValue +1 });
    }
  }
}

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

The JDK has switched locations of java.exe between 1.6 and 1.7!!!

In my case I found that the JAVA_HOME for the JDK had to add the \jre on the end. The mvn bat file is looking for java.exe and it looks for it in JAVA_HOME\bin. Its not there for JDK 1.7; it is in JAVA_HOME\jre\bin. In JDK 1.6 such it IS in JAVA_HOME\bin.

Hope this helps somebody.

Asynchronous method call in Python?

You can implement a decorator to make your functions asynchronous, though that's a bit tricky. The multiprocessing module is full of little quirks and seemingly arbitrary restrictions – all the more reason to encapsulate it behind a friendly interface, though.

from inspect import getmodule
from multiprocessing import Pool


def async(decorated):
    r'''Wraps a top-level function around an asynchronous dispatcher.

        when the decorated function is called, a task is submitted to a
        process pool, and a future object is returned, providing access to an
        eventual return value.

        The future object has a blocking get() method to access the task
        result: it will return immediately if the job is already done, or block
        until it completes.

        This decorator won't work on methods, due to limitations in Python's
        pickling machinery (in principle methods could be made pickleable, but
        good luck on that).
    '''
    # Keeps the original function visible from the module global namespace,
    # under a name consistent to its __name__ attribute. This is necessary for
    # the multiprocessing pickling machinery to work properly.
    module = getmodule(decorated)
    decorated.__name__ += '_original'
    setattr(module, decorated.__name__, decorated)

    def send(*args, **opts):
        return async.pool.apply_async(decorated, args, opts)

    return send

The code below illustrates usage of the decorator:

@async
def printsum(uid, values):
    summed = 0
    for value in values:
        summed += value

    print("Worker %i: sum value is %i" % (uid, summed))

    return (uid, summed)


if __name__ == '__main__':
    from random import sample

    # The process pool must be created inside __main__.
    async.pool = Pool(4)

    p = range(0, 1000)
    results = []
    for i in range(4):
        result = printsum(i, sample(p, 100))
        results.append(result)

    for result in results:
        print("Worker %i: sum value is %i" % result.get())

In a real-world case I would ellaborate a bit more on the decorator, providing some way to turn it off for debugging (while keeping the future interface in place), or maybe a facility for dealing with exceptions; but I think this demonstrates the principle well enough.

How to convert string to binary?

In Python version 3.6 and above you can use f-string to format result.

str = "hello world"
print(" ".join(f"{ord(i):08b}" for i in str))

01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100
  • The left side of the colon, ord(i), is the actual object whose value will be formatted and inserted into the output. Using ord() gives you the base-10 code point for a single str character.

  • The right hand side of the colon is the format specifier. 08 means width 8, 0 padded, and the b functions as a sign to output the resulting number in base 2 (binary).

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

You are repeating the y,m,d.

Instead of

gmdate('yyyy-mm-dd hh:mm:ss \G\M\T', time());  

You should use it like

gmdate('Y-m-d h:m:s \G\M\T', time());

How to delete cookies on an ASP.NET website

It is 2018 now, so in ASP.NET Core, there is a straight forward built in function. To delete a cookie try this code:

if(Request.Cookies["aa"] != null)
{
    Response.Cookies.Delete("aa");
}
return View();

OwinStartup not firing

I found the following article to be very helpful:

https://weblog.west-wind.com/posts/2015/Apr/29/Adding-minimal-OWIN-Identity-Authentication-to-an-Existing-ASPNET-MVC-Application#MinimalCodeSummary

In my case, I had to set the following before Owin authentication would work instead of windows authentication:

<system.web>   
    <authentication mode="None" />   
<system.web>

Does PHP have threading?

There is the rather obscure, and soon to be deprecated, feature called ticks. The only thing I have ever used it for, is to allow a script to capture SIGKILL (Ctrl+C) and close down gracefully.

Copy a file list as text from Windows Explorer

In Windows 7 and later, this will do the trick for you

  • Select the file/files.
  • Hold the shift key and then right-click on the selected file/files.
  • You will see Copy as Path. Click that.
  • Open a Notepad file and paste and you will be good to go.

The menu item Copy as Path is not available in Windows XP.

How to draw text using only OpenGL methods?

enter image description here

Use glutStrokeCharacter(GLUT_STROKE_ROMAN, myCharString).

An example: A STAR WARS SCROLLER.

#include <windows.h>
#include <string.h>
#include <GL\glut.h>
#include <iostream.h>
#include <fstream.h>

GLfloat UpwardsScrollVelocity = -10.0;
float view=20.0;

char quote[6][80];
int numberOfQuotes=0,i;

//*********************************************
//*  glutIdleFunc(timeTick);                  *
//*********************************************

void timeTick(void)
{
    if (UpwardsScrollVelocity< -600)
        view-=0.000011;
    if(view < 0) {view=20; UpwardsScrollVelocity = -10.0;}
    //  exit(0);
    UpwardsScrollVelocity -= 0.015;
  glutPostRedisplay();

}


//*********************************************
//* printToConsoleWindow()                *
//*********************************************

void printToConsoleWindow()
{
    int l,lenghOfQuote, i;

    for(  l=0;l<numberOfQuotes;l++)
    {
        lenghOfQuote = (int)strlen(quote[l]);

        for (i = 0; i < lenghOfQuote; i++)
        {
          //cout<<quote[l][i];
        }
          //out<<endl;
    }

}

//*********************************************
//* RenderToDisplay()                       *
//*********************************************

void RenderToDisplay()
{
    int l,lenghOfQuote, i;

    glTranslatef(0.0, -100, UpwardsScrollVelocity);
    glRotatef(-20, 1.0, 0.0, 0.0);
    glScalef(0.1, 0.1, 0.1);



    for(  l=0;l<numberOfQuotes;l++)
    {
        lenghOfQuote = (int)strlen(quote[l]);
        glPushMatrix();
        glTranslatef(-(lenghOfQuote*37), -(l*200), 0.0);
        for (i = 0; i < lenghOfQuote; i++)
        {
            glColor3f((UpwardsScrollVelocity/10)+300+(l*10),(UpwardsScrollVelocity/10)+300+(l*10),0.0);
            glutStrokeCharacter(GLUT_STROKE_ROMAN, quote[l][i]);
        }
        glPopMatrix();
    }

}
//*********************************************
//* glutDisplayFunc(myDisplayFunction);       *
//*********************************************

void myDisplayFunction(void)
{
  glClear(GL_COLOR_BUFFER_BIT);
  glLoadIdentity();
  gluLookAt(0.0, 30.0, 100.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
  RenderToDisplay();
  glutSwapBuffers();
}
//*********************************************
//* glutReshapeFunc(reshape);               *
//*********************************************

void reshape(int w, int h)
{
  glViewport(0, 0, w, h);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluPerspective(60, 1.0, 1.0, 3200);
  glMatrixMode(GL_MODELVIEW);
}

//*********************************************
//* int main()                                *
//*********************************************


int main()
{
    strcpy(quote[0],"Luke, I am your father!.");
    strcpy(quote[1],"Obi-Wan has taught you well. ");
    strcpy(quote[2],"The force is strong with this one. ");
    strcpy(quote[3],"Alert all commands. Calculate every possible destination along their last known trajectory. ");
    strcpy(quote[4],"The force is with you, young Skywalker, but you are not a Jedi yet.");
    numberOfQuotes=5;

    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(800, 400);
    glutCreateWindow("StarWars scroller");
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glLineWidth(3);

    glutDisplayFunc(myDisplayFunction);
    glutReshapeFunc(reshape);
    glutIdleFunc(timeTick);
    glutMainLoop();

    return 0;
}

Removing items from a list

Besides all the excellent solutions offered here I would like to offer a different solution.

I'm not sure if you're free to add dependencies, but if you can, you could add the https://code.google.com/p/guava-libraries/ as a dependency. This library adds support for many basic functional operations to Java and can make working with collections a lot easier and more readable.

In the code I replaced the type of the List by T, since I don't know what your list is typed to.

This problem can with guava be solved like this:

List<T> filteredList = new Arraylist<>(filter(list, not(XXX_EQUAL_TO_AAA)));

And somewhere else you then define XXX_EQUAL_TO_AAA as:

public static final Predicate<T> XXX_EQUAL_TO_AAA = new Predicate<T>() {
    @Override
    public boolean apply(T input) {
        return input.getXXX().equalsIgnoreCase("AAA");
    }
}

However, this is probably overkill in your situation. It's just something that becomes increasingly powerful the more you work with collections.

Ohw, also, you need these static imports:

import static com.google.common.base.Predicates.not;
import static com.google.common.collect.Collections2.filter;

Check if a variable is between two numbers with Java

<<= is like +=, but for a left shift. x <<= 1 means x = x << 1. That's why 90 >>= angle doesn't parse. And, like others have said, Java doesn't have an elegant syntax for checking if a number is an an interval, so you have to do it the long way. It also can't do if (x == 0 || 1), and you're stuck writing it out the long way.

Setting the zoom level for a MKMapView

Swift:

Map.setRegion(MKCoordinateRegion(center: locValue, latitudinalMeters: 200, longitudinalMeters: 200), animated: true)

locValue is your coordinate.

PHP: Split a string in to an array foreach char

Since str_split() function is not multibyte safe, an easy solution to split UTF-8 encoded string is to use preg_split() with u (PCRE_UTF8) modifier.

preg_split( '//u', $str, null, PREG_SPLIT_NO_EMPTY )

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

I programmatically provide required input files to GNUPlot executable and invoke it using system() function. It is suitable to my situation since I only want to visualize my data during research. But if you want the plotting functionality integrated into your executable file, maybe this is not for you :)

dyld: Library not loaded ... Reason: Image not found

If you use cmake, add DYLIB_INSTALL_NAME_BASE "@rpath" to target properties:

set_target_properties(target_dyLib PROPERTIES
        # # for FRAMEWORK begin
        # FRAMEWORK TRUE
        # FRAMEWORK_VERSION C
        # MACOSX_FRAMEWORK_IDENTIFIER com.cmake.targetname
        # MACOSX_FRAMEWORK_INFO_PLIST ./Info.plist
        # PUBLIC_HEADER targetname.h
        # # for FRAMEWORK end
        IPHONEOS_DEPLOYMENT_TARGET "8.0"
        DYLIB_INSTALL_NAME_BASE "@rpath" # this is the key point
        XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "iPhone Developer"
        DEVELOPMENT_TEAM "${DEVELOPMENT_TEAM}"
    )

or in Xcode dynamic library project Target -> Build Setting set Dynamic Library Install Name Base to @rpath

How can I simulate an array variable in MySQL?

Rather than Saving data as a array or in one row only you should be making diffrent rows for every value received. This will make it much simpler to understand rather than putting all together.

How to check if a process id (PID) exists

By pid:

pgrep [pid] >/dev/null

By name:

pgrep -u [user] -x [name] >/dev/null

"-x" means "exact match".

Pointer to class data member "::*"

Another application are intrusive lists. The element type can tell the list what its next/prev pointers are. So the list does not use hard-coded names but can still use existing pointers:

// say this is some existing structure. And we want to use
// a list. We can tell it that the next pointer
// is apple::next.
struct apple {
    int data;
    apple * next;
};

// simple example of a minimal intrusive list. Could specify the
// member pointer as template argument too, if we wanted:
// template<typename E, E *E::*next_ptr>
template<typename E>
struct List {
    List(E *E::*next_ptr):head(0), next_ptr(next_ptr) { }

    void add(E &e) {
        // access its next pointer by the member pointer
        e.*next_ptr = head;
        head = &e;
    }

    E * head;
    E *E::*next_ptr;
};

int main() {
    List<apple> lst(&apple::next);

    apple a;
    lst.add(a);
}

What is the difference between UNION and UNION ALL?

Both UNION and UNION ALL concatenate the result of two different SQLs. They differ in the way they handle duplicates.

  • UNION performs a DISTINCT on the result set, eliminating any duplicate rows.

  • UNION ALL does not remove duplicates, and it therefore faster than UNION.

Note: While using this commands all selected columns need to be of the same data type.

Example: If we have two tables, 1) Employee and 2) Customer

  1. Employee table data:

enter image description here

  1. Customer table data:

enter image description here

  1. UNION Example (It removes all duplicate records):

enter image description here

  1. UNION ALL Example (It just concatenate records, not eliminate duplicates, so it is faster than UNION):

enter image description here

Exit from app when click button in android phonegap?

navigator.app.exitApp();

add this line where you want you exit the application.

How to base64 encode image in linux bash / shell

Base 64 for html:

file="DSC_0251.JPG"
type=$(identify -format "%m" "$file" | tr '[A-Z]' '[a-z]')
echo "data:image/$type;base64,$(base64 -w 0 "$file")"

Compare integer in bash, unary operator expected

Your piece of script works just great. Are you sure you are not assigning anything else before the if to "i"?

A common mistake is also not to leave a space after and before the square brackets.

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

I had the same problem in my code. I was concatenating a string to create a string. Below is the part of code.

int scannerId = 1;
std:strring testValue;
strInXml = std::string(std::string("<inArgs>" \
                        "<scannerID>" + scannerId) + std::string("</scannerID>" \
                        "<cmdArgs>" \
                        "<arg-string>" + testValue) + "</arg-string>" \
                        "<arg-bool>FALSE</arg-bool>" \
                        "<arg-bool>FALSE</arg-bool>" \
                        "</cmdArgs>"\
                        "</inArgs>");

JTable won't show column headers

As said in previous answers the 'normal' way is to add it to a JScrollPane, but sometimes you don't want it to scroll (don't ask me when:)). Then you can add the TableHeader yourself. Like this:

JPanel tablePanel = new JPanel(new BorderLayout());
JTable table = new JTable();
tablePanel.add(table, BorderLayout.CENTER);
tablePanel.add(table.getTableHeader(), BorderLayout.NORTH);

How to read numbers separated by space using scanf

I think by default values read by scanf with space/enter. Well you can provide space between '%d' if you are printing integers. Also same for other cases.

scanf("%d %d %d", &var1, &var2, &var3);

Similarly if you want to read comma separated values use :

scanf("%d,%d,%d", &var1, &var2, &var3);

java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy

It is simple use below codes.

final Date todayDate = new Date();

System.out.println(todayDate);

System.out.println(new SimpleDateFormat("MM-dd-yyyy").format(todayDate));

System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(todayDate));

System.out.println(todayDate);

How to urlencode a querystring in Python?

For use in scripts/programs which need to support both python 2 and 3, the six module provides quote and urlencode functions:

>>> from six.moves.urllib.parse import urlencode, quote
>>> data = {'some': 'query', 'for': 'encoding'}
>>> urlencode(data)
'some=query&for=encoding'
>>> url = '/some/url/with spaces and %;!<>&'
>>> quote(url)
'/some/url/with%20spaces%20and%20%25%3B%21%3C%3E%26'

How do I set the default value for an optional argument in Javascript?

You can also do this with ArgueJS:

function (){
  arguments = __({nodebox: undefined, str: [String: "hai"]})

  // and now on, you can access your arguments by
  //   arguments.nodebox and arguments.str
}

jQuery - Getting form values for ajax POST

var data={
 userName: $('#userName').val(),
 email: $('#email').val(),
 //add other properties similarly
}

and

$.ajax({
        type: "POST",
        url: "http://rt.ja.com/includes/register.php?submit=1",
        data: data

        success: function(html)
        {   
            //alert(html);
            $('#userError').html(html);
            $("#userError").html(userChar);
            $("#userError").html(userTaken);
        }
    });

You dont have to bother about anything else. jquery will handle the serialization etc. also you can append the submit query string parameter submit=1 into the data json object.

Extract month and year from a zoo::yearmon object

The lubridate package is amazing for this kind of thing:

> require(lubridate)
> month(date1)
[1] 3
> year(date1)
[1] 2012

How can I use jQuery to make an input readonly?

You can do this by simply marking it disabled or enabled. You can use this code to do this:

//for disable
$('#fieldName').prop('disabled', true);

//for enable 
$('#fieldName').prop('disabled', false);

or

$('#fieldName').prop('readonly', true);

$('#fieldName').prop('readonly', false);

--- Its better to use prop instead of attr.

How to directly execute SQL query in C#?

To execute your command directly from within C#, you would use the SqlCommand class.

Quick sample code using paramaterized SQL (to avoid injection attacks) might look like this:

string queryString = "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday  FROM  [dbo].[TPatientRaw] WHERE tPatSName = @tPatSName";
string connectionString = "Server=.\PDATA_SQLEXPRESS;Database=;User Id=sa;Password=2BeChanged!;";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(queryString, connection);
    command.Parameters.AddWithValue("@tPatSName", "Your-Parm-Value");
    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    try
    {
        while (reader.Read())
        {
            Console.WriteLine(String.Format("{0}, {1}",
            reader["tPatCulIntPatIDPk"], reader["tPatSFirstname"]));// etc
        }
    }
    finally
    {
        // Always call Close when done reading.
        reader.Close();
    }
}

Remove Select arrow on IE

I would suggest mine solution that you can find in this GitHub repo. This works also for IE8 and IE9 with a custom arrow that comes from an icon font.

Examples of Custom Cross Browser Drop-down in action: check them with all your browsers to see the cross-browser feature.

Anyway, let's start with the modern browsers and then we will see the solution for the older ones.

Drop-down Arrow for Chrome, Firefox, Opera, Internet Explorer 10+

For these browser, it is easy to set the same background image for the drop-down in order to have the same arrow.

To do so, you have to reset the browser's default style for the select tag and set new background rules (like suggested before).

select {
    /* you should keep these firsts rules in place to maintain cross-browser behaviour */
    -webkit-appearance: none;
    -moz-appearance: none;
    -o-appearance: none;
    appearance: none;
    background-image: url('<custom_arrow_image_url_here>');
    background-position: 98% center;
    background-repeat: no-repeat;
    outline: none;
    ...
}

The appearance rules are set to none to reset browsers default ones, if you want to have the same aspect for each arrow, you should keep them in place.

The background rules in the examples are set with SVG inline images that represent different arrows. They are positioned 98% from left to keep some margin to the right border (you can easily modify the position as you wish).

In order to maintain the correct cross-browser behavior, the only other rule that have to be left in place is the outline. This rule resets the default border that appears (in some browsers) when the element is clicked. All the others rules can be easily modified if needed.

Drop-down Arrow for Internet Explorer 8 (IE8) and Internet Explorer 9 (IE9) using Icon Font

This is the harder part... Or maybe not.

There is no standard rule to hide the default arrows for these browsers (like the select::-ms-expand for IE10+). The solution is to hide the part of the drop-down that contains the default arrow and insert an arrow icon font (or a SVG, if you prefer) similar to the SVG that is used in the other browsers (see the select CSS rule for more details about the inline SVG used).

The very first step is to set a class that can recognize the browser: this is the reason why I have used the conditional IE IFs at the beginning of the code. These IFs are used to attach specific classes to the html tag to recognize the older IE browser.

After that, every select in the HTML have to be wrapped by a div (or whatever tag that can wraps an element). At this wrapper just add the class that contains the icon font.

<div class="selectTagWrapper prefix-icon-arrow-down-fill">
    ...
</div>

In easy words, this wrapper is used to simulate the select tag.

To act like a drop-down, the wrapper must have a border, because we hide the one that comes from the select.

Notice that we cannot use the select border because we have to hide the default arrow lengthening it 25% more than the wrapper. Consequently its right border should not be visible because we hide this 25% more by the overflow: hidden rule applied to the select itself.

The custom arrow icon-font is placed in the pseudo class :before where the rule content contains the reference for the arrow (in this case it is a right parenthesis).

We also place this arrow in an absolute position to center it as much as possible (if you use different icon fonts, remember to adjust them opportunely by changing top and left values and the font size).

.ie8 .prefix-icon-arrow-down-fill:before,
.ie9 .prefix-icon-arrow-down-fill:before {
    content: ")";
    position: absolute;
    top: 43%;
    left: 93%;
    font-size: 6px;
    ...
}

You can easily create and substitute the background arrow or the icon font arrow, with every one that you want simply changing it in the background-image rule or making a new icon font file by yourself.

Difference between uint32 and uint32_t

uint32_t is defined in the standard, in

18.4.1 Header <cstdint> synopsis [cstdint.syn]

namespace std {
//...
typedef unsigned integer type uint32_t; // optional
//...
}

uint32 is not, it's a shortcut provided by some compilers (probably as typedef uint32_t uint32) for ease of use.

A reference to the dll could not be added

I just ran into that issue and after all the explanations about fixing it with command prompt I found that if you add it directly to the project you can then simply include the library on each page that it's needed

Hibernate-sequence doesn't exist

I was getting the same error "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mylocaldb.hibernate_sequence' doesn't exist".

Using spring mvc 4.3.7 and hibernate version 5.2.9, application is made using spring java based configuration. Now I have to add the hibernate.id.new_generator_mappings property mentioned by @Eva Mariam in my code like this:

@Autowired
    @Bean(name = "sessionFactory")
    public SessionFactory getSessionFactory(DataSource dataSource) {

        LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
        sessionBuilder.addProperties(getHibernateProperties());
        sessionBuilder.addAnnotatedClasses(User.class);

        return sessionBuilder.buildSessionFactory();
    }

    private Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        properties.put("hibernate.id.new_generator_mappings","false");
        return properties;
    }

And it worked like charm.

Display an array in a readable/hierarchical format

print_r() is mostly for debugging. If you want to print it in that format, loop through the array, and print the elements out.

foreach($data as $d){
  foreach($d as $v){
    echo $v."\n";
  }
}

How do you clear the focus in javascript?

You can call window.focus();

but moving or losing the focus is bound to interfere with anyone using the tab key to get around the page.

you could listen for keycode 13, and forego the effect if the tab key is pressed.

Creating a Plot Window of a Particular Size

A convenient function for saving plots is ggsave(), which can automatically guess the device type based on the file extension, and smooths over differences between devices. You save with a certain size and units like this:

ggsave("mtcars.png", width = 20, height = 20, units = "cm")

In R markdown, figure size can be specified by chunk:

```{r, fig.width=6, fig.height=4}  
plot(1:5)
```

jQuery exclude elements with certain class in selector

To add some info that helped me today, a jQuery object/this can also be passed in to the .not() selector.

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $(".navitem").click(function(){_x000D_
        $(".navitem").removeClass("active");_x000D_
        $(".navitem").not($(this)).addClass("active");_x000D_
    });_x000D_
});
_x000D_
.navitem_x000D_
{_x000D_
    width: 100px;_x000D_
    background: red;_x000D_
    color: white;_x000D_
    display: inline-block;_x000D_
    position: relative;_x000D_
    text-align: center;_x000D_
}_x000D_
.navitem.active_x000D_
{_x000D_
    background:green;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="navitem">Home</div>_x000D_
<div class="navitem">About</div>_x000D_
<div class="navitem">Pricing</div>
_x000D_
_x000D_
_x000D_

The above example can be simplified, but wanted to show the usage of this in the not() selector.

How to rearrange Pandas column sequence?

Feel free to disregard this solution as subtracting a list from an Index does not preserve the order of the original Index, if that's important.

In [61]: df.reindex(columns=pd.Index(['x', 'y']).append(df.columns - ['x', 'y']))
Out[61]: 
    x  y  a  b
0   3 -1  1  2
1   6 -2  2  4
2   9 -3  3  6
3  12 -4  4  8

What does the term "Tuple" Mean in Relational Databases?

Most of the answers here are on the right track. However, a row is not a tuple. Tuples* are unordered sets of known values with names. Thus, the following tuples are the same thing (I'm using an imaginary tuple syntax since a relational tuple is largely a theoretical construct):

(x=1, y=2, z=3)
(z=3, y=2, x=1)
(y=2, z=3, x=1)

...assuming of course that x, y, and z are all integers. Also note that there is no such thing as a "duplicate" tuple. Thus, not only are the above equal, they're the same thing. Lastly, tuples can only contain known values (thus, no nulls).

A row** is an ordered set of known or unknown values with names (although they may be omitted). Therefore, the following comparisons return false in SQL:

(1, 2, 3) = (3, 2, 1)
(3, 1, 2) = (2, 1, 3)

Note that there are ways to "fake it" though. For example, consider this INSERT statement:

INSERT INTO point VALUES (1, 2, 3)

Assuming that x is first, y is second, and z is third, this query may be rewritten like this:

INSERT INTO point (x, y, z) VALUES (1, 2, 3)

Or this:

INSERT INTO point (y, z, x) VALUES (2, 3, 1)

...but all we're really doing is changing the ordering rather than removing it.

And also note that there may be unknown values as well. Thus, you may have rows with unknown values:

(1, 2, NULL) = (1, 2, NULL)

...but note that this comparison will always yield UNKNOWN. After all, how can you know whether two unknown values are equal?

And lastly, rows may be duplicated. In other words, (1, 2) and (1, 2) may compare to be equal, but that doesn't necessarily mean that they're the same thing.

If this is a subject that interests you, I'd highly recommend reading SQL and Relational Theory: How to Write Accurate SQL Code by CJ Date.

* Note that I'm talking about tuples as they exist in the relational model, which is a bit different from mathematics in general.

**And just in case you're wondering, just about everything in SQL is a row or table. Therefore, (1, 2) is a row, while VALUES (1, 2) is a table (with one row).

UPDATE: I've expanded a little bit on this answer in a blog post here.

When is "java.io.IOException:Connection reset by peer" thrown?

I think this should be java.net.SocketException as its definition is stated for a TCP error.

/**
 * Thrown to indicate that there is an error in the underlying 
 * protocol, such as a TCP error. 
 *
 * @author  Jonathan Payne
 * @version %I%, %G%
 * @since   JDK1.0
 */
public 
class SocketException extends IOException {

jQuery animate scroll

There is a jquery plugin for this. It scrolls document to a specific element, so that it would be perfectly in the middle of viewport. It also supports animation easings so that the scroll effect would look super smooth. Check out AnimatedScroll.js.

how to set active class to nav menu from twitter bootstrap

You can use this JavaScript\jQuery code:

// Sets active link in Bootstrap menu
// Add this code in a central place used\shared by all pages
// like your _Layout.cshtml in ASP.NET MVC for example
$('a[href="' + this.location.pathname + '"]').parents('li,ul').addClass('active');

It'll set the <a>'s parent <li> and the <li>'s parent <ul> as active.

A simple solution that works!


Original source:

Bootstrap add active class to li

JPA: How to get entity based on field value other than ID?

Basically, you should add a specific unique field. I usually use xxxUri fields.

class User {

    @Id
    // automatically generated
    private Long id;

    // globally unique id
    @Column(name = "SCN", nullable = false, unique = true)
    private String scn;
}

And you business method will do like this.

public User findUserByScn(@NotNull final String scn) {
    CriteriaBuilder builder = manager.getCriteriaBuilder();
    CriteriaQuery<User> criteria = builder.createQuery(User.class);
    Root<User> from = criteria.from(User.class);
    criteria.select(from);
    criteria.where(builder.equal(from.get(User_.scn), scn));
    TypedQuery<User> typed = manager.createQuery(criteria);
    try {
        return typed.getSingleResult();
    } catch (final NoResultException nre) {
        return null;
    }
}

MAC addresses in JavaScript

The quick and simple answer is No.

Javascript is quite a high level language and does not have access to this sort of information.

Excel Validation Drop Down list using VBA

This worked on my test file (note the index in VBA starts from zero):

Sub DV_Test()
    Dim ValidationList(5) As Variant, i As Integer

    For i = 0 To UBound(ValidationList)
        ValidationList(i) = i + 1
    Next

    With Range("A1").Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
            Operator:=xlEqual, Formula1:=Join(ValidationList, ",")
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
End Sub

I used xlEqual because that's what I think you are trying to get people to select one of the list.

Could not reserve enough space for object heap

Anyway, here is how to fix it: Go to Start->Control Panel->System->Advanced(tab)->Environment Variables->System Variables->New: Variable name: _JAVA_OPTIONS Variable value: -Xmx512M

OR

Change the ant call as shown as below.

   <exec
        **<arg value="-J-Xmx512m" />**
    </exec>

It worked for me.

AngularJS : How do I switch views from a controller function?

Firstly you have to create state in app.js as below

.state('login', {
      url: '/',
      templateUrl: 'views/login.html',
      controller: 'LoginCtrl'
    })

and use below code in controller

 $location.path('login'); 

Hope this will help you

How to compare two dates to find time difference in SQL Server 2005, date manipulation

Declare the Start and End date DECLARE @SDATE AS DATETIME

TART_DATE  AS DATETIME
DECLARE @END_-- Set Start and End date
SET @START_DATE = GETDATE()
SET @END_DATE    = DATEADD(SECOND, 3910, GETDATE())

-- Get the Result in HH:MI:SS:MMM(24H) format SELECT CONVERT(VARCHAR(12), DATEADD(MS, DATEDIFF(MS, @START_DATE, @END_DATE), 0), 114) AS TimeDiff

What are the alternatives now that the Google web search API has been deprecated?

Yes, Google Custom Search has now replaced the old Search API, but you can still use Google Custom Search to search the entire web, although the steps are not obvious from the Custom Search setup.

To create a Google Custom Search engine that searches the entire web:

  1. From the Google Custom Search homepage ( http://www.google.com/cse/ ), click Create a Custom Search Engine.
  2. Type a name and description for your search engine.
  3. Under Define your search engine, in the Sites to Search box, enter at least one valid URL (For now, just put www.anyurl.com to get past this screen. More on this later ).
  4. Select the CSE edition you want and accept the Terms of Service, then click Next. Select the layout option you want, and then click Next.
  5. Click any of the links under the Next steps section to navigate to your Control panel.
  6. In the left-hand menu, under Control Panel, click Basics.
  7. In the Search Preferences section, select Search the entire web but emphasize included sites.
  8. Click Save Changes.
  9. In the left-hand menu, under Control Panel, click Sites.
  10. Delete the site you entered during the initial setup process.

Now your custom search engine will search the entire web.

Pricing

  • Google Custom Search gives you 100 queries per day for free.
  • After that you pay $5 per 1000 queries.
  • There is a maximum of 10,000 queries per day.

Source: https://developers.google.com/custom-search/json-api/v1/overview#Pricing


  • The search quality is much lower than normal Google search (no synonyms, "intelligence" etc.)
  • It seems that Google is even planning to shut down this service completely.

How to detect DataGridView CheckBox event change?

In the event CellContentClick you can use this strategy:

private void myDataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{    
    if (e.ColumnIndex == 2)//set your checkbox column index instead of 2
    {   //When you check
        if (Convert.ToBoolean(myDataGrid.Rows[e.RowIndex].Cells[2].EditedFormattedValue) == true)
        {
            //EXAMPLE OF OTHER CODE
            myDataGrid.Rows[e.RowIndex].Cells[5].Value = DateTime.Now.ToShortDateString();

            //SET BY CODE THE CHECK BOX
            myDataGrid.Rows[e.RowIndex].Cells[2].Value = 1;
        }
        else //When you decheck
        {
            myDataGrid.Rows[e.RowIndex].Cells[5].Value = String.Empty;

            //SET BY CODE THE CHECK BOX
            myDataGrid.Rows[e.RowIndex].Cells[2].Value = 0;
        }
    }
}

how to clear JTable

You must remove the data from the TableModel used for the table.

If using the DefaultTableModel, just set the row count to zero. This will delete the rows and fire the TableModelEvent to update the GUI.

JTable table;
…
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);

If you are using other TableModel, please check the documentation.

Change the location of the ~ directory in a Windows install of Git Bash

I don't understand, why you don't want to set the $HOME environment variable since that solves exactly what you're asking for.

cd ~ doesn't mean change to the root directory, but change to the user's home directory, which is set by the $HOME environment variable.

Quick'n'dirty solution

Edit C:\Program Files (x86)\Git\etc\profile and set $HOME variable to whatever you want (add it if it's not there). A good place could be for example right after a condition commented by # Set up USER's home directory. It must be in the MinGW format, for example:

HOME=/c/my/custom/home

Save it, open Git Bash and execute cd ~. You should be in a directory /c/my/custom/home now.

Everything that accesses the user's profile should go into this directory instead of your Windows' profile on a network drive.

Note: C:\Program Files (x86)\Git\etc\profile is shared by all users, so if the machine is used by multiple users, it's a good idea to set the $HOME dynamically:

HOME=/c/Users/$USERNAME

Cleaner solution

Set the environment variable HOME in Windows to whatever directory you want. In this case, you have to set it in Windows path format (with backslashes, e.g. c:\my\custom\home), Git Bash will load it and convert it to its format.

If you want to change the home directory for all users on your machine, set it as a system environment variable, where you can use for example %USERNAME% variable so every user will have his own home directory, for example:

HOME=c:\custom\home\%USERNAME%

If you want to change the home directory just for yourself, set it as a user environment variable, so other users won't be affected. In this case, you can simply hard-code the whole path:

HOME=c:\my\custom\home

Count number of records returned by group by

You can do both in one query using the OVER clause on another COUNT

select
    count(*) RecordsPerGroup,
    COUNT(*) OVER () AS TotalRecords
from temptable
group by column_1, column_2, column_3, column_4

How to return a class object by reference in C++?

I will show you some examples:

First example, do not return local scope object, for example:

const string &dontDoThis(const string &s)
{
    string local = s;
    return local;
}

You can't return local by reference, because local is destroyed at the end of the body of dontDoThis.

Second example, you can return by reference:

const string &shorterString(const string &s1, const string &s2)
{
    return (s1.size() < s2.size()) ? s1 : s2;
}

Here, you can return by reference both s1 and s2 because they were defined before shorterString was called.

Third example:

char &get_val(string &str, string::size_type ix)
{
    return str[ix];
}

usage code as below:

string s("123456");
cout << s << endl;
char &ch = get_val(s, 0); 
ch = 'A';
cout << s << endl; // A23456

get_val can return elements of s by reference because s still exists after the call.

Fourth example

class Student
{
public:
    string m_name;
    int age;    

    string &getName();
};

string &Student::getName()
{
    // you can return by reference
    return m_name;
}

string& Test(Student &student)
{
    // we can return `m_name` by reference here because `student` still exists after the call
    return stu.m_name;
}

usage example:

Student student;
student.m_name = 'jack';
string name = student.getName();
// or
string name2 = Test(student);

Fifth example:

class String
{
private:
    char *str_;

public:
    String &operator=(const String &str);
};

String &String::operator=(const String &str)
{
    if (this == &str)
    {
        return *this;
    }
    delete [] str_;
    int length = strlen(str.str_);
    str_ = new char[length + 1];
    strcpy(str_, str.str_);
    return *this;
}

You could then use the operator= above like this:

String a;
String b;
String c = b = a;

angular 2 ngIf and CSS transition/animation

    trigger('slideIn', [
      state('*', style({ 'overflow-y': 'hidden' })),
      state('void', style({ 'overflow-y': 'hidden' })),
      transition('* => void', [
        style({ height: '*' }),
        animate(250, style({ height: 0 }))
      ]),
      transition('void => *', [
        style({ height: '0' }),
        animate(250, style({ height: '*' }))
      ])
    ])

$ is not a function - jQuery error

There are quite lots of answer based on situation.

1) Try to replace '$' with "jQuery"

2) Check that code you are executed are always below the main jquery script.

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){

});
</script>

3) Pass $ into the function and add "jQuery" as a main function like below.

<script type="text/javascript">
jQuery(document).ready(function($){

});
</script>

Add more than one parameter in Twig path

Consider making your route:

_files_manage:
    pattern: /files/management/{project}/{user}
    defaults: { _controller: AcmeTestBundle:File:manage }

since they are required fields. It will make your url's prettier, and be a bit easier to manage.

Your Controller would then look like

 public function projectAction($project, $user)

Fatal error: iostream: No such file or directory in compiling C program using GCC

Neither <iostream> nor <iostream.h> are standard C header files. Your code is meant to be C++, where <iostream> is a valid header. Use g++ (and a .cpp file extension) for C++ code.

Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream> and using namespace std;, and replace cout << endl; with putchar('\n');... I advise compiling using C99 (eg. gcc -std=c99)

Getting assembly name

You could try this code which uses the System.Reflection.AssemblyTitleAttribute.Title property:

((AssemblyTitleAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyTitleAttribute), false)).Title;

HTTP 1.0 vs 1.1

A key compatibility issue is support for persistent connections. I recently worked on a server that "supported" HTTP/1.1, yet failed to close the connection when a client sent an HTTP/1.0 request. When writing a server that supports HTTP/1.1, be sure it also works well with HTTP/1.0-only clients.

How to close IPython Notebook properly?

Environment


My OS is Ubuntu 16.04 and jupyter is 4.3.0.

Method


First, i logged out jupyter at its homepage on browser(the logout button is at top-right)

Second, type in Ctrl + C in your terminal and it shows:

[I 15:59:48.407 NotebookApp]interrupted Serving notebooks from local directory: /home/Username 0 active kernels

The Jupyter Notebook is running at: http://localhost:8888/?token=a572c743dfb73eee28538f9a181bf4d9ad412b19fbb96c82

Shutdown this notebook server (y/[n])?

Last step, type in y within 5 sec, and if it shows:

[C 15:59:50.407 NotebookApp] Shutdown confirmed
[I 15:59:50.408 NotebookApp] Shutting down kernels

Congrats! You close your jupyter successfully.

Android notification is not showing

I had the same issue with my Android app. I was trying out notifications and found that notifications were showing on my Android emulator which ran a Android 7.0 (Nougat) system, whereas it wasn't running on my phone which had Android 8.1 (Oreo).

After reading the documentation, I found that Android had a feature called notification channel, without which notifications won't show up on Oreo devices. Below is the link to official Android documentation on notification channels.

Android ListView with onClick items

You should definitely extend you ArrayListAdapter and implement this in your getView() method. The second parameter (a View) should be inflated if it's value is null, take advantage of it and set it an onClickListener() just after inflating.

Suposing it's called your second getView()'s parameter is called convertView:

convertView.setOnClickListener(new View.OnClickListener() {
  public void onClick(final View v) {
    if (isSamsung) {
      final Intent intent = new Intent(this, SamsungInfo.class);
      startActivity(intent);
    }
    else if (...) {
      ...
    }
  }
}

If you want some info on how to extend ArrayListAdapter, I recommend this link.

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

This error occurs when the client URL and server URL don't match, including the port number. In this case you need to enable your service for CORS which is cross origin resource sharing.

If you are hosting a Spring REST service then you can find it in the blog post CORS support in Spring Framework.

If you are hosting a service using a Node.js server then

  1. Stop the Node.js server.
  2. npm install cors --save
  3. Add following lines to your server.js

    var cors = require('cors')
    
    app.use(cors()) // Use this after the variable declaration
    

How can I check if a user is logged-in in php?

See this script for registering. It is simple and very easy to understand.

<?php
    define('DB_HOST', 'Your Host[Could be localhost or also a website]');
    define('DB_NAME', 'database name');
    define('DB_USERNAME', 'Username[In many cases root, but some sites offer a MySQL page where the username might be different]');
    define('DB_PASSWORD', 'whatever you keep[if username is root then 99% of the password is blank]');

    $link = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);

    if (!$link) {
        die('Could not connect line 9');
    }

    $DB_SELECT = mysql_select_db(DB_NAME, $link);

    if (!$DB_SELECT) {
        die('Could not connect line 15');
    }

    $valueone = $_POST['name'];
    $valuetwo = $_POST['last_name'];
    $valuethree = $_POST['email'];
    $valuefour = $_POST['password'];
    $valuefive = $_POST['age'];

    $sqlone = "INSERT INTO user (name, last_name, email, password, age) VALUES ('$valueone','$valuetwo','$valuethree','$valuefour','$valuefive')";

    if (!mysql_query($sqlone)) {
        die('Could not connect name line 33');
    }

    mysql_close();
?>

Make sure you make all the database stuff using phpMyAdmin. It's a very easy tool to work with. You can find it here: phpMyAdmin

(Excel) Conditional Formatting based on Adjacent Cell Value

I don't know if maybe it's a difference in Excel version but this question is 6 years old and the accepted answer didn't help me so this is what I figured out:

Under Conditional Formatting > Manage Rules:

  1. Make a new rule with "Use a formula to determine which cells to format"
  2. Make your rule, but put a dollar sign only in front of the letter: $A2<$B2
  3. Under "Applies to", Manually select the second column (It would not work for me if I changed the value in the box, it just kept snapping back to what was already there), so it looks like $B$2:$B$100 (assuming you have 100 rows)

This worked for me in Excel 2016.

Use querystring variables in MVC controller

Here is what I came up with. I was having major problems with this and believe I am in MVC 6 now but this may be helpful to someone even myself in the future..

//The issue was that Reqest.Form Request.Querystring and Request not working in MVC the solution is to use Context.Request.Form and also making sure the form has been submitted otherwise null reference or context issue bug will show up.

     if(Context.Request.ContentLength != null)
     {
         String StartDate = Context.Request.Form["StartMonth"].ToString();
         String EndMonth = Context.Request.Form["EndMonth"].ToString();
        // Vendor

     }

Search for string within text column in MySQL

SELECT * FROM items WHERE `items.xml` LIKE '%123456%'

The % operator in LIKE means "anything can be here".

batch file - counting number of files in folder and storing in a variable

I'm going to assume you do not want to count hidden or system files.

There are many ways to do this. All of the methods that I will show involve some form of the FOR command. There are many variations of the FOR command that look almost the same, but they behave very differently. It can be confusing for a beginner.

You can get help by typing HELP FOR or FOR /? from the command line. But that help is a bit cryptic if you are not used to reading it.

1) The DIR command lists the number of files in the directory. You can pipe the results of DIR to FIND to get the relevant line and then use FOR /F to parse the desired value from the line. The problem with this technique is the string you search for has to change depending on the language used by the operating system.

@echo off
for /f %%A in ('dir ^| find "File(s)"') do set cnt=%%A
echo File count = %cnt%

2) You can use DIR /B /A-D-H-S to list the non-hidden/non-system files without other info, pipe the result to FIND to count the number of files, and use FOR /F to read the result.

@echo off
for /f %%A in ('dir /a-d-s-h /b ^| find /v /c ""') do set cnt=%%A
echo File count = %cnt%

3) You can use a simple FOR to enumerate all the files and SET /A to increment a counter for each file found.

@echo off
set cnt=0
for %%A in (*) do set /a cnt+=1
echo File count = %cnt%

Rollback to an old Git commit in a public repo

git read-tree -um @ $commit_to_revert_to

will do it. It's "git checkout" but without updating HEAD.

You can achieve the same effect with

git checkout $commit_to_revert_to
git reset --soft @{1}

if you prefer stringing convenience commands together.

These leave you with your worktree and index in the desired state, you can just git commit to finish.

Excel tab sheet names vs. Visual Basic sheet names

In the Excel object model a Worksheet has 2 different name properties:

Worksheet.Name
Worksheet.CodeName

the Name property is read/write and contains the name that appears on the sheet tab. It is user and VBA changeable

the CodeName property is read-only

You can reference a particular sheet as Worksheets("Fred").Range("A1") where Fred is the .Name property or as Sheet1.Range("A1") where Sheet1 is the codename of the worksheet.

What is the best way to repeatedly execute a function every x seconds?

You might want to consider Twisted which is a Python networking library that implements the Reactor Pattern.

from twisted.internet import task, reactor

timeout = 60.0 # Sixty seconds

def doWork():
    #do work here
    pass

l = task.LoopingCall(doWork)
l.start(timeout) # call every sixty seconds

reactor.run()

While "while True: sleep(60)" will probably work Twisted probably already implements many of the features that you will eventually need (daemonization, logging or exception handling as pointed out by bobince) and will probably be a more robust solution

Detect if the app was launched/opened from a push notification

For swift:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    PFPush.handlePush(userInfo)

    if application.applicationState == UIApplicationState.Inactive || application.applicationState == UIApplicationState.Background {
        //opened from a push notification when the app was in the background

    }

}

What is the difference between WCF and WPF?

Windows communication Fundation(WCF) is used for connecting different applications and passing the data's between them using endpoints.

Windows Presentation Foundation is used for designing rich internet applications in the format of xaml.

What is the point of "final class" in Java?

Yes, sometimes you may want this though, either for security or speed reasons. It's done also in C++. It may not be that applicable for programs, but moreso for frameworks. http://www.glenmccl.com/perfj_025.htm

Getting Hour and Minute in PHP

function get_time($time) {
    $duration = $time / 1000;
    $hours = floor($duration / 3600);
    $minutes = floor(($duration / 60) % 60);
    $seconds = $duration % 60;
    if ($hours != 0)
        echo "$hours:$minutes:$seconds";
    else
        echo "$minutes:$seconds";
}

get_time('1119241');

TypeError: unsupported operand type(s) for /: 'str' and 'str'

I would have written:

percent = 100
while True:
     try:
        pyc = int(input('enter pyc :'))
        tpy = int(input('enter tpy:'))
        percent = (pyc / tpy) * percent
        break
     except ZeroDivisionError as detail:
        print 'Handling run-time error:', detail

Change UITextField and UITextView Cursor / Caret Color

For people searching the equivalent in SwiftUI for Textfield this is accentColor:

TextField("Label", text: $self.textToBind).accentColor(Color.red)

@viewChild not working - cannot read property nativeElement of undefined

Sometimes, this error occurs when you're trying to target an element that is wrapped in a condition, for example: <div *ngIf="canShow"> <p #target>Targeted Element</p></div>

In this code, if canShow is false on render, Angular won't be able to get that element as it won't be rendered, hence the error that comes up.

One of the solutions is to use a display: hidden on the element instead of the *ngIf so the element gets rendered but is hidden until your condition is fulfilled.

Read More over at Github

Ignore cells on Excel line graph

  1. In the value or values you want to separate, enter the =NA() formula. This will appear that the value is skipped but the preceding and following data points will be joined by the series line.
  2. Enter the data you want to skip in the same location as the original (row or column) but add it as a new series. Add the new series to your chart.
  3. Format the new data point to match the original series format (color, shape, etc.). It will appear as though the data point was just skipped in the original series but will still show on your chart if you want to label it or add a callout.

How do I remove trailing whitespace using a regular expression?

You can simply use it like this:

_x000D_
_x000D_
var regex = /( )/g;
_x000D_
_x000D_
_x000D_

Sample: click here

JTable How to refresh table model after insert delete or update the data.

The faster way for your case is:

    jTable.repaint(); // Repaint all the component (all Cells).

The optimized way when one or few cell change:

    ((AbstractTableModel) jTable.getModel()).fireTableCellUpdated(x, 0); // Repaint one cell.

What is the meaning of ToString("X2")?

It formats the string as two uppercase hexadecimal characters.

In more depth, the argument "X2" is a "format string" that tells the ToString() method how it should format the string. In this case, "X2" indicates the string should be formatted in Hexadecimal.

byte.ToString() without any arguments returns the number in its natural decimal representation, with no padding.

Microsoft documents the standard numeric format strings which generally work with all primitive numeric types' ToString() methods. This same pattern is used for other types as well: for example, standard date/time format strings can be used with DateTime.ToString().

ASP.NET Web Site or ASP.NET Web Application?

WebSite : It generates app_code folder automatically and if you publish it on the server and after that if you do some changes in any particular file or page than you don't have to do compile all files.

Web Application It generates solutions file automatically which website doesn't generate and if you change in one file than you have to compile full project to reflects its changes.

How to create a Jar file in Netbeans

Create a Java archive (.jar) file using NetBeans as follows:

  1. Right-click on the Project name
  2. Select Properties
  3. Click Packaging
  4. Check Build JAR after Compiling
  5. Check Compress JAR File
  6. Click OK to accept changes
  7. Right-click on a Project name
  8. Select Build or Clean and Build

Clean and Build will first delete build artifacts (such as .class files), whereas Build will retain any existing .class files, creating new versions necessary. To elucidate, imagine a project with two classes, A and B.

When built the first time, the IDE creates A.class and B.class. Now you delete B.java but don't clear out B.class. Executing Build should leave B.class in the build directory, and bundle it into the JAR. Selecting Clean and Build will delete B.class. Since B.java was deleted, no longer will B.class be bundled.

The JAR file is built. To view it inside NetBeans:

  1. Click the Files tab
  2. Expand Project name >> dist

Ensure files aren't being excluded when building the JAR file.

type checking in javascript

Try this code:

 alert(typeof(1) == "number");

I have Python on my Ubuntu system, but gcc can't find Python.h

I ran into the same issue while trying to build a very old copy of omniORB on a CentOS 7 machine. Resolved the issue by installing the python development libraries:

# yum install python-devel

This installed the Python.h into:

/usr/include/python2.7/Python.h

Calling onclick on a radiobutton list using javascript

How are you generating the radio button list? If you're just using HTML:

<input type="radio" onclick="alert('hello');"/>

If you're generating these via something like ASP.NET, you can add that as an attribute to each element in the list. You can run this after you populate your list, or inline it if you build up your list one-by-one:

foreach(ListItem RadioButton in RadioButtons){
    RadioButton.Attributes.Add("onclick", "alert('hello');");
}

More info: http://www.w3schools.com/jsref/event_onclick.asp

Removing all non-numeric characters from string in Python

Just to add another option to the mix, there are several useful constants within the string module. While more useful in other cases, they can be used here.

>>> from string import digits
>>> ''.join(c for c in "abc123def456" if c in digits)
'123456'

There are several constants in the module, including:

  • ascii_letters (abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ)
  • hexdigits (0123456789abcdefABCDEF)

If you are using these constants heavily, it can be worthwhile to covert them to a frozenset. That enables O(1) lookups, rather than O(n), where n is the length of the constant for the original strings.

>>> digits = frozenset(digits)
>>> ''.join(c for c in "abc123def456" if c in digits)
'123456'

How to get the current user in ASP.NET MVC

I use:

Membership.GetUser().UserName

I am not sure this will work in ASP.NET MVC, but it's worth a shot :)

Testing if a list of integer is odd or even

Just use the modulus

loop through the list and run the following on each item

if(num % 2 == 0)
{
  //is even
}
else
{
  //is odd
}

Alternatively if you want to know if all are even you can do something like this:

bool allAreEven = lst.All(x => x % 2 == 0);

Rename package in Android Studio

Create a new package in the java directory and move your project into that package. Like your current project id is com.testapp.user and you want to change it xyz.testapp.user. Then create a package in src/java directory named xyz and move your child package testapp.user into xyz. It works for me. Finally, update build.gradle and manifest project id.

How to parse a query string into a NameValueCollection in .NET

let search = window.location.search;

console.log(search);

let qString = search.substring(1);

while(qString.indexOf("+") !== -1)

   qString  = qString.replace("+", "");

let qArray = qString.split("&");

let values = [];

for(let i = 0; i < qArray.length; i++){
   let pos = qArray[i].search("=");
   let keyVal = qArray[i].substring(0, pos);
   let dataVal = qArray[i].substring(pos + 1);
   dataVal = decodeURIComponent(dataVal);
   values[keyVal] = dataVal;
}

Trying to retrieve first 5 characters from string in bash error?

echo 'mystring' |cut -c1-5 is an alternative solution to ur problem.

more on unix cut program

Jquery select this + class

Use $(this).find(), or pass this in context, using jQuery context with selector.

Using $(this).find()

$(".class").click(function(){
     $(this).find(".subclass").css("visibility","visible");
});

Using this in context, $( selector, context ), it will internally call find function, so better to use find on first place.

$(".class").click(function(){
     $(".subclass", this).css("visibility","visible");
});

How to avoid pressing Enter with getchar() for reading a single character only?

On a linux system, you can modify terminal behaviour using the stty command. By default, the terminal will buffer all information until Enter is pressed, before even sending it to the C program.

A quick, dirty, and not-particularly-portable example to change the behaviour from within the program itself:

#include<stdio.h>
#include<stdlib.h>

int main(void){
  int c;
  /* use system call to make terminal send all keystrokes directly to stdin */
  system ("/bin/stty raw");
  while((c=getchar())!= '.') {
    /* type a period to break out of the loop, since CTRL-D won't work raw */
    putchar(c);
  }
  /* use system call to set terminal behaviour to more normal behaviour */
  system ("/bin/stty cooked");
  return 0;
}

Please note that this isn't really optimal, since it just sort of assumes that stty cooked is the behaviour you want when the program exits, rather than checking what the original terminal settings were. Also, since all special processing is skipped in raw mode, many key sequences (such as CTRL-C or CTRL-D) won't actually work as you expect them to without explicitly processing them in the program.

You can man stty for more control over the terminal behaviour, depending exactly on what you want to achieve.

Displaying better error message than "No JSON object could be decoded"

Trailing_commas is recognized as a non-standard JSON format, which is recognized as the correct format under the RFC 8259/RFC 7159 standard (you can verify it here JSON Formatter/Validator), but there will be warnings. However, it is being parsed Sometimes, Trailing_commas will be abnormal

Hibernate Criteria Join with 3 Tables

The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:

Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();

This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.

How to load external scripts dynamically in Angular?

a sample can be

script-loader.service.ts file

import {Injectable} from '@angular/core';
import * as $ from 'jquery';

declare let document: any;

interface Script {
  src: string;
  loaded: boolean;
}

@Injectable()
export class ScriptLoaderService {
public _scripts: Script[] = [];

/**
* @deprecated
* @param tag
* @param {string} scripts
* @returns {Promise<any[]>}
*/
load(tag, ...scripts: string[]) {
scripts.forEach((src: string) => {
  if (!this._scripts[src]) {
    this._scripts[src] = {src: src, loaded: false};
  }
});

let promises: any[] = [];
scripts.forEach((src) => promises.push(this.loadScript(tag, src)));

return Promise.all(promises);
}

 /**
 * Lazy load list of scripts
 * @param tag
 * @param scripts
 * @param loadOnce
 * @returns {Promise<any[]>}
 */
loadScripts(tag, scripts, loadOnce?: boolean) {
loadOnce = loadOnce || false;

scripts.forEach((script: string) => {
  if (!this._scripts[script]) {
    this._scripts[script] = {src: script, loaded: false};
  }
});

let promises: any[] = [];
scripts.forEach(
    (script) => promises.push(this.loadScript(tag, script, loadOnce)));

return Promise.all(promises);
}

/**
 * Lazy load a single script
 * @param tag
 * @param {string} src
 * @param loadOnce
 * @returns {Promise<any>}
 */
loadScript(tag, src: string, loadOnce?: boolean) {
loadOnce = loadOnce || false;

if (!this._scripts[src]) {
  this._scripts[src] = {src: src, loaded: false};
}

return new Promise((resolve, reject) => {
  // resolve if already loaded
  if (this._scripts[src].loaded && loadOnce) {
    resolve({src: src, loaded: true});
  }
  else {
    // load script tag
    let scriptTag = $('<script/>').
        attr('type', 'text/javascript').
        attr('src', this._scripts[src].src);

    $(tag).append(scriptTag);

    this._scripts[src] = {src: src, loaded: true};
    resolve({src: src, loaded: true});
  }
 });
 }
 }

and usage

first inject

  constructor(
  private _script: ScriptLoaderService) {
  }

then

ngAfterViewInit()  {
this._script.loadScripts('app-wizard-wizard-3',
['assets/demo/default/custom/crud/wizard/wizard.js']);

}

or

    this._script.loadScripts('body', [
  'assets/vendors/base/vendors.bundle.js',
  'assets/demo/default/base/scripts.bundle.js'], true).then(() => {
  Helpers.setLoading(false);
  this.handleFormSwitch();
  this.handleSignInFormSubmit();
  this.handleSignUpFormSubmit();
  this.handleForgetPasswordFormSubmit();
});

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;

import java.util.concurrent.TimeUnit;

@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Fork(value = 1)
@Measurement(iterations = 5, time = 1)
public class StringFirstCharBenchmark {

    private String source;

    @Setup
    public void init() {
        source = "MALE";
    }

    @Benchmark
    public String substring() {
        return source.substring(0, 1);
    }

    @Benchmark
    public String indexOf() {
        return String.valueOf(source.indexOf(0));
    }
}

Results:

+----------------------------------------------------------------------+
| Benchmark                           Mode  Cnt   Score   Error  Units |
+----------------------------------------------------------------------+
| StringFirstCharBenchmark.indexOf    avgt    5  23.777 ? 5.788  ns/op |
| StringFirstCharBenchmark.substring  avgt    5  11.305 ? 1.411  ns/op |
+----------------------------------------------------------------------+

ActiveMQ or RabbitMQ or ZeroMQ or

There is a comparison of the features and performance of RabbitMQ ActiveMQ and QPID given at
http://bhavin.directi.com/rabbitmq-vs-apache-activemq-vs-apache-qpid/

Personally I have tried all the above three. RabbitMQ is the best performance wise according to me, but it does not have failover and recovery options. ActiveMQ has the most features, but is slower.

Update : HornetQ is also an option you can look into, it is JMS Complaint, a better option than ActiveMQ if you are looking for a JMS based solution.

Could not find method android() for arguments

My issue was inside of my app.gradle. I ran into this issue when I moved

apply plugin: "com.android.application"

from the top line to below a line with

apply from:

I switched the plugin back to the top and violá

My exact error was

Could not find method android() for arguments [dotenv_wke4apph61tdae6bfodqe7sj$_run_closure1@5d9d91a5] on project ':app' of type org.gradle.api.Project.

The top of my app.gradle now looks like this

project.ext.envConfigFiles = [
        debug: ".env",
        release: ".env",
        anothercustombuild: ".env",
]


apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
apply plugin: "com.android.application"

How to ensure that there is a delay before a service is started in systemd?

This answer on super user I think is a better answer. From https://superuser.com/a/573761/67952

"But since you asked for a way without using Before and After, you can use:

Type=idle

which as man systemd.service explains

Behavior of idle is very similar to simple; however, actual execution of the service program is delayed until all active jobs are dispatched. This may be used to avoid interleaving of output of shell services with the status output on the console. Note that this type is useful only to improve console output, it is not useful as a general unit ordering tool, and the effect of this service type is subject to a 5s time-out, after which the service program is invoked anyway. "

https with WCF error: "Could not find base address that matches scheme https"

I think you are trying to configure your service in a similar way to the following config. There is more information here: Specify a Service with Two Endpoints Using Different Binding Values. Also, other than for development, it's probably not a good idea to have both HTTP & HTTPS endpoints to the same service. It kinda defeats the purpose of HTTPS. Hope this helps!

<service type="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null">
    <endpoint
        address="http://computer:8080/Hello"
        contract="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
        binding="basicHttpBinding"
        bindingConfiguration="shortTimeout"
    </endpoint>
    <endpoint
        address="http://computer:8080/Hello"
        contract="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
        binding="basicHttpBinding"
        bindingConfiguration="Secure"
     </endpoint>
</service>
<bindings>
    <basicHttpBinding 
        name="shortTimeout"
        timeout="00:00:00:01" 
     />
     <basicHttpBinding 
        name="Secure">
        <Security mode="Transport" />
     </basicHttpBinding>
</bindings>

custom facebook share button

Given that we are in a php code context and the variable $url contains the link the user wants to share, you can try this to use a custom image :

<a class="facebook-share-button" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($url); ?>" target="_blank"><img src="/img/facebook-share-button.png" /></a>

or this for just plain text :

<a class="facebook-share-button" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($url); ?>" target="_blank">share</a>

You can also style the link purely with css.

The html code :

<a class="facebook-share-button" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($url); ?>" target="_blank"></a>

The css code :

.facebook-share-button {
    background-image: url("/img/facebook-share-button.png");
    display: inline-block;
    height: 32px;
    width: 32px;
}

.facebook-share-button:active,
.facebook-share-button:focus,
.facebook-share-button:hover {
    background-image: url("/img/facebook-share-button-hover.png");
}

Adding a custom header to HTTP request using angular.js

my suggestion will be add a function call settings like this inside the function check the header which is appropriate for it. I am sure it will definitely work. it is perfectly working for me.

function getSettings(requestData) {
    return {
        url: requestData.url,
        dataType: requestData.dataType || "json",
        data: requestData.data || {},
        headers: requestData.headers || {
            "accept": "application/json; charset=utf-8",
            'Authorization': 'Bearer ' + requestData.token
        },
        async: requestData.async || "false",
        cache: requestData.cache || "false",
        success: requestData.success || {},
        error: requestData.error || {},
        complete: requestData.complete || {},
        fail: requestData.fail || {}
    };
}

then call your data like this

    var requestData = {
        url: 'API end point',
        data: Your Request Data,
        token: Your Token
    };

    var settings = getSettings(requestData);
    settings.method = "POST"; //("Your request type")
    return $http(settings);

Already defined in .obj - no double inclusions

You probably don't want to do this:

#include "client.cpp"

A *.cpp file will have been compiled by the compiler as part of your build. By including it in other files, it will be compiled again (and again!) in every file in which you include it.

Now here's the thing: You are guarding it with #ifndef SOCKET_CLIENT_CLASS, however, each file that has #include "client.cpp" is built independently and as such will find SOCKET_CLIENT_CLASS not yet defined. Therefore it's contents will be included, not #ifdef'd out.

If it contains any definitions at all (rather than just declarations) then these definitions will be repeated in every file where it's included.

How to deal with SQL column names that look like SQL keywords?

While you are doing it - alias it as something else (or better yet, use a view or an SP and deprecate the old direct access method).

SELECT [from] AS TransferFrom -- Or something else more suitable
FROM TableName

How do I detect what .NET Framework versions and service packs are installed?

The registry is the official way to detect if a specific version of the Framework is installed.

enter image description here

Which registry keys are needed change depending on the Framework version you are looking for:

Framework Version  Registry Key
------------------------------------------------------------------------------------------
1.0                HKLM\Software\Microsoft\.NETFramework\Policy\v1.0\3705 
1.1                HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322\Install 
2.0                HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Install 
3.0                HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\Setup\InstallSuccess 
3.5                HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Install 
4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Client\Install
4.0 Full Profile   HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full\Install

Generally you are looking for:

"Install"=dword:00000001

except for .NET 1.0, where the value is a string (REG_SZ) rather than a number (REG_DWORD).

Determining the service pack level follows a similar pattern:

Framework Version  Registry Key
------------------------------------------------------------------------------------------
1.0                HKLM\Software\Microsoft\Active Setup\Installed Components\{78705f0d-e8db-4b2d-8193-982bdda15ecd}\Version 
1.0[1]             HKLM\Software\Microsoft\Active Setup\Installed Components\{FDC11A6F-17D1-48f9-9EA3-9051954BAA24}\Version 
1.1                HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322\SP 
2.0                HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\SP 
3.0                HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\SP 
3.5                HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\SP 
4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Client\Servicing
4.0 Full Profile   HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full\Servicing

[1] Windows Media Center or Windows XP Tablet Edition

As you can see, determining the SP level for .NET 1.0 changes if you are running on Windows Media Center or Windows XP Tablet Edition. Again, .NET 1.0 uses a string value while all of the others use a DWORD.

For .NET 1.0 the string value at either of these keys has a format of #,#,####,#. The last # is the Service Pack level.

While I didn't explicitly ask for this, if you want to know the exact version number of the Framework you would use these registry keys:

Framework Version  Registry Key
------------------------------------------------------------------------------------------
1.0                HKLM\Software\Microsoft\Active Setup\Installed Components\{78705f0d-e8db-4b2d-8193-982bdda15ecd}\Version 
1.0[1]             HKLM\Software\Microsoft\Active Setup\Installed Components\{FDC11A6F-17D1-48f9-9EA3-9051954BAA24}\Version 
1.1                HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322 
2.0[2]             HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Version 
2.0[3]             HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Increment
3.0                HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\Version 
3.5                HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Version 
4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Version 
4.0 Full Profile   HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Version 

[1] Windows Media Center or Windows XP Tablet Edition
[2] .NET 2.0 SP1
[3] .NET 2.0 Original Release (RTM)

Again, .NET 1.0 uses a string value while all of the others use a DWORD.

Additional Notes

  • for .NET 1.0 the string value at either of these keys has a format of #,#,####,#. The #,#,#### portion of the string is the Framework version.

  • for .NET 1.1, we use the name of the registry key itself, which represents the version number.

  • Finally, if you look at dependencies, .NET 3.0 adds additional functionality to .NET 2.0 so both .NET 2.0 and .NET 3.0 must both evaulate as being installed to correctly say that .NET 3.0 is installed. Likewise, .NET 3.5 adds additional functionality to .NET 2.0 and .NET 3.0, so .NET 2.0, .NET 3.0, and .NET 3. should all evaluate to being installed to correctly say that .NET 3.5 is installed.

  • .NET 4.0 installs a new version of the CLR (CLR version 4.0) which can run side-by-side with CLR 2.0.

Update for .NET 4.5

There won't be a v4.5 key in the registry if .NET 4.5 is installed. Instead you have to check if the HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full key contains a value called Release. If this value is present, .NET 4.5 is installed, otherwise it is not. More details can be found here and here.

Types in Objective-C on iOS

Update for the new 64bit arch

Ranges:
CHAR_MIN:   -128
CHAR_MAX:   127
SHRT_MIN:   -32768
SHRT_MAX:   32767
INT_MIN:    -2147483648
INT_MAX:    2147483647
LONG_MIN:   -9223372036854775808
LONG_MAX:   9223372036854775807
ULONG_MAX:  18446744073709551615
LLONG_MIN:  -9223372036854775808
LLONG_MAX:  9223372036854775807
ULLONG_MAX: 18446744073709551615

FFmpeg on Android

After a lot of research, right now this is the most updated compiled library for Android that I found:

https://github.com/bravobit/FFmpeg-Android

  • At this moment is using FFmpeg release n4.0-39-gda39990
  • Includes FFmpeg and FFProbe
  • Contains Java interface to launch the commands
  • FFprobe or FFmpeg could be removed from the APK, check the wiki https://github.com/bravobit/FFmpeg-Android/wiki

A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found

This can also happen if you've recently upgraded Ant. I was using Ant 1.8.4 on a project, and upgraded Ant to 1.9.4, and started to get this error when building a fat jar using Ant.

The solution for me was to downgrade back to Ant 1.8.4 for the command line and Eclipse using the process detailed here

What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

The single * means that there can be any number of extra positional arguments. foo() can be invoked like foo(1,2,3,4,5). In the body of foo() param2 is a sequence containing 2-5.

The double ** means there can be any number of extra named parameters. bar() can be invoked like bar(1, a=2, b=3). In the body of bar() param2 is a dictionary containing {'a':2, 'b':3 }

With the following code:

def foo(param1, *param2):
    print(param1)
    print(param2)

def bar(param1, **param2):
    print(param1)
    print(param2)

foo(1,2,3,4,5)
bar(1,a=2,b=3)

the output is

1
(2, 3, 4, 5)
1
{'a': 2, 'b': 3}

how to get file path from sd card in android

As some people indicated, the officially accepted answer does not quite return the external removable SD card. And i ran upon the following thread that proposes a method I've tested on some Android devices and seems to work reliably, so i thought of re-sharing here as i don't see it in the other responses:

http://forums.androidcentral.com/samsung-galaxy-s7/668364-whats-external-sdcard-path.html

Kudos to paresh996 for coming up with the answer itself, and i can attest I've tried on Samsung S7 and S7edge and seems to work.

Now, i needed a method that returned a valid path where to read files, and that considered the fact that there might not be an external SD, in which case the internal storage should be returned, so i modified the code from paresh996 to this :

File getStoragePath() {
    String removableStoragePath;
    File fileList[] = new File("/storage/").listFiles();
    for (File file : fileList) {
       if(!file.getAbsolutePath().equalsIgnoreCase(Environment.getExternalStorageDirectory().getAbsolutePath()) && file.isDirectory() && file.canRead()) {
            return file;
        }
    }
    return Environment.getExternalStorageDirectory();
}

There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

I had an issue where I was pushing to my remote repo from a local repo that didn't match up with history of remote. This is what worked for me.

I cloned my repo locally so I knew I was working with fresh copy of repo:

git clone Your_REPO_URL_HERE.git

Switch to the branch you are trying to get into the remote:

git checkout Your_BRANCH_NAME_HERE

Add the remote of the original:

git remote add upstream Your_REMOTE_REPO_URL_HERE.git

Do a git fetch and git pull:

git fetch --all

git pull upstream Your_BRANCH_NAME_HERE

If you have merge conflicts, resolve them with

git mergetool kdiff3 

or other merge tool of your choice.

Once conflicts are resolved and saved. Commit and push changes.

Now go to the gitub.com repo of the original and attempt to create a pull request. You should have option to create pull request and not see the "Nothing to compare, branches are entirely different commit histories" Note: You may need to choose compare across forks for your pull request.

Getting value from table cell in JavaScript...not jQuery

If I understand your question correctly, you are looking for innerHTML:

alert(col.firstChild.innerHTML);

customize Android Facebook Login button

The best way I have found to do this, if you want to fully customize the button is to create a button, or any View you want (in my case it was a LinearLayout) and set an OnClickListener to that view, and call the following in the onClick event:

com.facebook.login.widget.LoginButton btn = new LoginButton(this);
btn.performClick();

Materialize CSS - Select Doesn't Seem to Render

For default browser,

<head>
     select {
            display: inline !important;
         }
</head>

Or the Jquery solution after the link t Jquery library and your local/CDN materialize files

<script>
(function($){
  $(function(){
    // Plugin initialization
    $('select').not('.disabled').formSelect();
  }); 
})(jQuery); // end of jQuery name space

I really like this framework, but what on earth to have display:none...

Subset dataframe by multiple logical conditions of rows to remove

And also

library(dplyr)
data %>% filter(!v1 %in% c("b", "d", "e"))

or

data %>% filter(v1 != "b" & v1 != "d" & v1 != "e")

or

data %>% filter(v1 != "b", v1 != "d", v1 != "e")

Since the & operator is implied by the comma.

How to make an HTTP POST web request

MSDN has a sample.

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestPostExample
    {
        public static void Main()
        {
            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create("http://www.contoso.com/PostAccepter.aspx");
            // Set the Method property of the request to POST.
            request.Method = "POST";
            // Create POST data and convert it to a byte array.
            string postData = "This is a test that posts this string to a Web server.";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            // Get the request stream.
            Stream dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close();
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();
        }
    }
}

java.lang.VerifyError: Expecting a stackmap frame at branch target JDK 1.7

Java 7 introduced stricter verification and changed the class format a bit—to contain a stack map used to verify that code is correct. The exception you see means that some method doesn't have a valid stack map.

Java version or bytecode instrumentation could both be to blame. Usually this means that a library used by the application generates invalid bytecode that doesn't pass the stricter verification. So nothing else than reporting it as a bug to the library can be done by the developer.

As a workaround you can add -noverify to the JVM arguments in order to disable verification. In Java 7 it was also possible to use -XX:-UseSplitVerifier to use the less strict verification method, but that option was removed in Java 8.

Find files with size in Unix

find . -size +10000k -exec ls -sd {} +

If your version of find won't accept the + notation (which acts rather like xargs does), then you might use (GNU find and xargs, so find probably supports + anyway):

find . -size +10000k -print0 | xargs -0 ls -sd

or you might replace the + with \; (and live with the relative inefficiency of this), or you might live with problems caused by spaces in names and use the portable:

find . -size +10000k -print | xargs ls -sd

The -d on the ls commands ensures that if a directory is ever found (unlikely, but...), then the directory information will be printed, not the files in the directory. And, if you're looking for files more than 1 MB (as a now-deleted comment suggested), you need to adjust the +10000k to 1000k or maybe +1024k, or +2048 (for 512-byte blocks, the default unit for -size). This will list the size and then the file name. You could avoid the need for -d by adding -type f to the find command, of course.

Flutter plugin not installed error;. When running flutter doctor

hello everyone I had the same issue and non of the above answers fixed so I went to the flutter official GitHub and found the answer there here is the link and you have to follow all these steps.

https://github.com/flutter/flutter/issues/67986

flutter upgrade

flutter config --android-studio-dir="C:\Program Files\Android\Android Studio"

for mac you can do the following as answered by Andrew

ln -s ~/Library/Application\ Support/Google/AndroidStudio4.1/plugins ~/Library/Application\ Support/AndroidStudio4.1

flutter doctor -v

then if the issue still persistes then just shift to the beta channel and the upgrade flutter then it will fix it.

flutter channel beta

flutter upgrade

you can enable flutter web as an optional steps

https://flutter.dev/docs/get-started/web

What is the max size of localStorage values?

Here's a straightforward script for finding out the limit:

if (localStorage && !localStorage.getItem('size')) {
    var i = 0;
    try {
        // Test up to 10 MB
        for (i = 250; i <= 10000; i += 250) {
            localStorage.setItem('test', new Array((i * 1024) + 1).join('a'));
        }
    } catch (e) {
        localStorage.removeItem('test');
        localStorage.setItem('size', i - 250);            
    }
}

Here's the gist, JSFiddle and blog post.

The script will test setting increasingly larger strings of text until the browser throws and exception. At that point it’ll clear out the test data and set a size key in localStorage storing the size in kilobytes.

JavaScript: Create and destroy class instance through class method

You can only manually delete properties of objects. Thus:

var container = {};

container.instance = new class();

delete container.instance;

However, this won't work on any other pointers. Therefore:

var container = {};

container.instance = new class();

var pointer = container.instance;

delete pointer; // false ( ie attempt to delete failed )

Furthermore:

delete container.instance; // true ( ie attempt to delete succeeded, but... )

pointer; // class { destroy: function(){} }

So in practice, deletion is only useful for removing object properties themselves, and is not a reliable method for removing the code they point to from memory.

A manually specified destroy method could unbind any event listeners. Something like:

function class(){
  this.properties = { /**/ }

  function handler(){ /**/ }

  something.addEventListener( 'event', handler, false );

  this.destroy = function(){
    something.removeEventListener( 'event', handler );
  }
}

What is .htaccess file?

.htaccess is a configuration file for use on web servers running the Apache Web Server software.

When a .htaccess file is placed in a directory which is in turn 'loaded via the Apache Web Server', then the .htaccess file is detected and executed by the Apache Web Server software.

These .htaccess files can be used to alter the configuration of the Apache Web Server software to enable/disable additional functionality and features that the Apache Web Server software has to offer.

These facilities include basic redirect functionality, for instance if a 404 file not found error occurs, or for more advanced functions such as content password protection or image hot link prevention.

Whenever any request is sent to the server it always passes through .htaccess file. There are some rules are defined to instruct the working.

What is {this.props.children} and when you should use it?

What even is ‘children’?

The React docs say that you can use props.children on components that represent ‘generic boxes’ and that don’t know their children ahead of time. For me, that didn’t really clear things up. I’m sure for some, that definition makes perfect sense but it didn’t for me.

My simple explanation of what this.props.children does is that it is used to display whatever you include between the opening and closing tags when invoking a component.

A simple example:

Here’s an example of a stateless function that is used to create a component. Again, since this is a function, there is no this keyword so just use props.children

const Picture = (props) => {
  return (
    <div>
      <img src={props.src}/>
      {props.children}
    </div>
  )
}

This component contains an <img> that is receiving some props and then it is displaying {props.children}.

Whenever this component is invoked {props.children} will also be displayed and this is just a reference to what is between the opening and closing tags of the component.

//App.js
render () {
  return (
    <div className='container'>
      <Picture key={picture.id} src={picture.src}>
          //what is placed here is passed as props.children  
      </Picture>
    </div>
  )
}

Instead of invoking the component with a self-closing tag <Picture /> if you invoke it will full opening and closing tags <Picture> </Picture> you can then place more code between it.

This de-couples the <Picture> component from its content and makes it more reusable.

Reference: A quick intro to React’s props.children

Uncaught ReferenceError: function is not defined with onclick

Never use .onclick(), or similar attributes from a userscript! (It's also poor practice in a regular web page).

The reason is that userscripts operate in a sandbox ("isolated world"), and onclick operates in the target-page scope and cannot see any functions your script creates.

Always use addEventListener()Doc (or an equivalent library function, like jQuery .on()).

So instead of code like:

something.outerHTML += '<input onclick="resetEmotes()" id="btnsave" ...>'


You would use:

something.outerHTML += '<input id="btnsave" ...>'

document.getElementById ("btnsave").addEventListener ("click", resetEmotes, false);

For the loop, you can't pass data to an event listener like that See the doc. Plus every time you change innerHTML like that, you destroy the previous event listeners!

Without refactoring your code much, you can pass data with data attributes. So use code like this:

for (i = 0; i < EmoteURLLines.length; i++) {
    if (checkIMG (EmoteURLLines[i])) {
        localStorage.setItem ("nameEmotes", JSON.stringify (EmoteNameLines));
        localStorage.setItem ("urlEmotes", JSON.stringify (EmoteURLLines));
        localStorage.setItem ("usageEmotes", JSON.stringify (EmoteUsageLines));
        if (i == 0) {
            console.log (resetSlot ());
        }
        emoteTab[2].innerHTML  += '<span style="cursor:pointer;" id="' 
                                + EmoteNameLines[i] 
                                + '" data-usage="' + EmoteUsageLines[i] + '">'
                                + '<img src="' + EmoteURLLines[i] + '" /></span>'
                                ;
    } else {
        alert ("The maximum emote (" + EmoteNameLines[i] + ") size is (36x36)");
    }
}
//-- Only add events when innerHTML overwrites are done.
var targetSpans = emoteTab[2].querySelectorAll ("span[data-usage]");
for (var J in targetSpans) {
    targetSpans[J].addEventListener ("click", appendEmote, false);
}

Where appendEmote is like:

function appendEmote (zEvent) {
    //-- this and the parameter are special in event handlers.  see the linked doc.
    var emoteUsage  = this.getAttribute ("data-usage");
    shoutdata.value += emoteUsage;
}


WARNINGS:

  • Your code reuses the same id for several elements. Don't do this, it's invalid. A given ID should occur only once per page.
  • Every time you use .outerHTML or .innerHTML, you trash any event handlers on the affected nodes. If you use this method beware of that fact.

Select the first 10 rows - Laravel Eloquent

First you can use a Paginator. This is as simple as:

$allUsers = User::paginate(15);

$someUsers = User::where('votes', '>', 100)->paginate(15);

The variables will contain an instance of Paginator class. all of your data will be stored under data key.

Or you can do something like:

Old versions Laravel.

Model::all()->take(10)->get();

Newer version Laravel.

Model::all()->take(10);

For more reading consider these links:

Online code beautifier and formatter

For PHP, Java, C++, C, Perl, JavaScript, CSS you can try:

http://www.prettyprinter.de/index.php

How to change text color of simple list item

I realize this question is a bit old but here's a really simple solution that was missing. You don't need to create a custom ListView or even a custom layout.

Just create an anonymous subclass of ArrayAdapter and override getView(). Let super.getView() handle all the heavy lifting. Since simple_list_item_1 is just a text view you can customize it (e.g. set textColor) and then return it.

Here's an example from one of my apps. I'm displaying a list of recent locations and I want all occurrences of "Current Location" to be blue and the rest white.

ListView listView = (ListView) this.findViewById(R.id.listView);
listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, MobileMuni.getBookmarkStore().getRecentLocations()) {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView textView = (TextView) super.getView(position, convertView, parent);

        String currentLocation = RouteFinderBookmarksActivity.this.getResources().getString(R.string.Current_Location);
        int textColor = textView.getText().toString().equals(currentLocation) ? R.color.holo_blue : R.color.text_color_btn_holo_dark;
        textView.setTextColor(RouteFinderBookmarksActivity.this.getResources().getColor(textColor));

        return textView;
    }
});

How to use Python to execute a cURL command?

This could be achieve with the below mentioned psuedo code approach

Import os import requests Data = os.execute(curl URL) R= Data.json()

MySQL timezone change?

While Bryon's answer is helpful, I'd just add that his link is for PHP timezone names, which are not the same as MySQL timezone names.

If you want to set your timezone for an individual session to GMT+1 (UTC+1 to be precise) just use the string '+01:00' in that command. I.e.:

SET time_zone = '+01:00';

To see what timezone your MySQL session is using, just execute this:

SELECT @@global.time_zone, @@session.time_zone;

This is a great reference with more details: MySQL 5.5 Reference on Time Zones

how to make UITextView height dynamic according to text length?

Declaration here

    fileprivate weak var textView: UITextView!

Call your setupview here

    override func viewDidLoad() {
        super.viewDidLoad()

         setupViews()
    }

Setup here

    fileprivate func setupViews() {

    let textView = UITextView()
    textView.translatesAutoresizingMaskIntoConstraints = false
    textView.text = "your text here"
    textView.font = UIFont.poppinsMedium(size: 14)
    textView.textColor = UIColor.brownishGrey
    textView.textAlignment = .left
    textView.isEditable = false
    textView.isScrollEnabled = false
    textView.textContainerInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)

   self.view.addSubview(textView)

   self.textView = textView

   setupConstraints()

   }

Setup constraints here

   fileprivate func setupConstraints() {

    NSLayoutConstraint.activate([

        textView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
        textView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20),
        textView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20),
        textView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20),
        textView.heightAnchor.constraint(greaterThanOrEqualToConstant: 150),
        ])
  }