There is no compiler independent way of doing this, as neither the C (nor the C++) standards say that the floating point math types must support NAN or INF.
Edit: I just checked the wording of the C++ standard, and it says that these functions (members of the templated class numeric_limits):
quiet_NaN()
signalling_NaN()
wiill return NAN representations "if available". It doesn't expand on what "if available" means, but presumably something like "if the implementation's FP rep supports them". Similarly, there is a function:
infinity()
which returns a positive INF rep "if available".
These are both defined in the <limits>
header - I would guess that the C standard has something similar (probably also "if available") but I don't have a copy of the current C99 standard.
I've just had this same issue with Ionic.
It turns out nothing was wrong with my code, I simply had to quit the ionic serve session and run ionic serve again.
After going back into the app, my states worked fine.
I would also suggest pressing save on your app.js file a few times if you are running gulp, to make sure everything gets re-compiled.
Answer below the dotted line below is the original that's now outdated.
Here is the latest information ( Thank you @deadfish ):
add &hl=<language>
like &hl=pl
or &hl=en
example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl
All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en
......................................................................
To change the actual local market:
Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html
To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720
This is a quick-and-dirty solution that will work in simple cases but will break if (a) there are regex special characters in $delete
, or (b) there are any spaces at all in any items. Starting with:
array+=(pluto)
array+=(pippo)
delete=(pluto)
Delete all entries exactly matching $delete
:
array=(`echo $array | fmt -1 | grep -v "^${delete}$" | fmt -999999`)
resulting in
echo $array
-> pippo, and making sure it's an array:
echo $array[1]
-> pippo
fmt
is a little obscure: fmt -1
wraps at the first column (to put each item on its own line. That's where the problem arises with items in spaces.) fmt -999999
unwraps it back to one line, putting back the spaces between items. There are other ways to do that, such as xargs
.
Addendum: If you want to delete just the first match, use sed, as described here:
array=(`echo $array | fmt -1 | sed "0,/^${delete}$/{//d;}" | fmt -999999`)
This just works:
$body = @{
"UserSessionId"="12345678"
"OptionalEmail"="[email protected]"
} | ConvertTo-Json
$header = @{
"Accept"="application/json"
"connectapitoken"="97fe6ab5b1a640909551e36a071ce9ed"
"Content-Type"="application/json"
}
Invoke-RestMethod -Uri "http://MyServer/WSVistaWebClient/RESTService.svc/member/search" -Method 'Post' -Body $body -Headers $header | ConvertTo-HTML
I set the .NET CLR version to No Managed Code and everything started to work fine.
In v.2.x.x , we can use align
and justify
. We have below options for setup the horizontal and vertical alignment.
PROPS align
: 'start','center','end','baseline','stretch'
PRPS justify
: 'start','center','end','space-around','space-between'
<v-container fill-height fluid>
<v-row align="center"
justify="center">
<v-col></v-col>
</v-row>
</v-container>
For more details please refer this vuetify grid-system and you could check here with working codepen demo.
You could use align-center
for layout
and fill-height
for container.
Demo with v1.x.x
new Vue({
el: '#app'
})
_x000D_
.bg{
background: gray;
color: #fff;
font-size: 18px;
}
_x000D_
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.js"></script>
<div id="app">
<v-app>
<v-container bg fill-height grid-list-md text-xs-center>
<v-layout row wrap align-center>
<v-flex>
Hello I am center to vertically using "align-center".
</v-flex>
</v-layout>
</v-container>
</v-app>
</div>
_x000D_
if (x.equals(y))
This looks like an expensive operation. Are there any hash codes calculated this way?
It is not an expensive operation and no hash codes are calculated. Java does not magically calculate hash codes, equals(...)
is just a method call, not different from any other method call.
The JVM will most likely even optimize the method call away (inlining the comparison that takes place inside the method), so this call is not much more expensive than using ==
on two primitive int
values.
Note: Don't prematurely apply micro-optimizations; your assumptions like "this must be slow" are most likely wrong or don't matter, because the code isn't a performance bottleneck.
If you're using .NET 4 or above and you don't want to reference System.Web
, you can use WebUtility.HtmlEncode
from System
var encoded = WebUtility.HtmlEncode(unencoded);
This has the same effect as HttpUtility.HtmlEncode
and should be preferred over System.Security.SecurityElement.Escape
.
This is my answer in C , O(N) complexity time. Pass the array only once, only three variables. The solution is very intuitive and easy to understand.
#include <stdio.h>
int second(int arr[],int size)
{
int i, max , secondmax;
if (arr[0] > arr[1]){
max = arr[0];
secondmax = arr[1];
} else {
max = arr[1];
secondmax = arr[0];
}
for (i = 2; i < size; i++)
{
if ((arr[i] < max) && (arr[i] < secondmax)) {
continue;
}
if ((arr[i] < max) && (arr[i] > secondmax)) {
secondmax = arr[i];
continue;
}
if ((arr[i] > max)) {
secondmax = max;
max = arr[i];
continue;
}
}
return secondmax;
}
void main()
{
int arr[] = { 1,10,5,7};
int size = sizeof(arr) / sizeof(arr[0]);
int secondmax = second(arr,size);
printf("%d \n\n", secondmax);
}
Use count(d.ertek)
or count(d.id)
instead of count(d)
. This can be happen when you have composite primary key at your entity.
HTML
<div id='a'>
<div>
<a class='click'>abc</a>
</div>
</div>
You could use the XPATH as :
//div[@id='a']//a[@class='click']
output
<a class="click">abc</a>
That said your Python code should be as :
driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")
In my DROPDOWN case the Ben Bud's solution worked well, but I had a separate toggle button with an onClick handler. So the outside clicking logic conflicted with the button onClick toggler. Here is how I solved it by passing the button's ref as well:
import React, { useRef, useEffect, useState } from "react";
/**
* Hook that triggers onClose when clicked outside of ref and buttonRef elements
*/
function useOutsideClicker(ref, buttonRef, onOutsideClick) {
useEffect(() => {
function handleClickOutside(event) {
/* clicked on the element itself */
if (ref.current && !ref.current.contains(event.target)) {
return;
}
/* clicked on the toggle button */
if (buttonRef.current && !buttonRef.current.contains(event.target)) {
return;
}
/* If it's something else, trigger onClose */
onOutsideClick();
}
// Bind the event listener
document.addEventListener("mousedown", handleClickOutside);
return () => {
// Unbind the event listener on clean up
document.removeEventListener("mousedown", handleClickOutside);
};
}, [ref]);
}
/**
* Component that alerts if you click outside of it
*/
export default function DropdownMenu(props) {
const wrapperRef = useRef(null);
const buttonRef = useRef(null);
const [dropdownVisible, setDropdownVisible] = useState(false);
useOutsideClicker(wrapperRef, buttonRef, closeDropdown);
const toggleDropdown = () => setDropdownVisible(visible => !visible);
const closeDropdown = () => setDropdownVisible(false);
return (
<div>
<button onClick={toggleDropdown} ref={buttonRef}>Dropdown Toggler</button>
{dropdownVisible && <div ref={wrapperRef}>{props.children}</div>}
</div>
);
}
One can access each element of an array separately using the following code:
Object o=...;
if ( o.getClass().isArray() ) {
for(int i=0; i<Array.getLength(o); i++){
System.out.println(Array.get(o, i));
}
}
Notice that it is unnecessary to know what kind of underlying array it is, as this will work for any array.
Maybe something like this:
import matplotlib.pyplot
import pylab
x = [1,2,3,4]
y = [3,4,8,6]
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
EDIT:
Let me see if I understand you correctly now:
You have:
test1 | test2 | test3
test3 | 1 | 0 | 1
test4 | 0 | 1 | 0
test5 | 1 | 1 | 0
Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.
Let's say you results are stored in a 2-D list:
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
We want to transform them into two variables so we are able to plot them.
And I believe this code will give you what you are looking for:
import matplotlib
import pylab
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
x = []
y = []
for ind_1, sublist in enumerate(results):
for ind_2, ele in enumerate(sublist):
if ele == 1:
x.append(ind_1)
y.append(ind_2)
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
Notice that I do need to import pylab
, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.
If you use HashSet
instead of List
for listofGenres
you can do:
var genres = new HashSet<Genre>() { "action", "comedy" };
var movies = _db.Movies.Where(p => genres.Overlaps(p.Genres));
Not in any conventional sense of the phrase "inside CSS."
Here is a solution which blocks all non numeric input from being entered into the text-field.
html
<input type="text" id="numbersOnly" />
javascript
var input = document.getElementById('numbersOnly');
input.onkeydown = function(e) {
var k = e.which;
/* numeric inputs can come from the keypad or the numeric row at the top */
if ( (k < 48 || k > 57) && (k < 96 || k > 105)) {
e.preventDefault();
return false;
}
};?
I'm using Mac OS High Sierra and none of these worked for me. But after searching a lot I found one that worked!
This may seem trivial, but in fact about 2 months ago some clever guys made changes in brew repository, so doing just: brew install php71-intl
will show you error with message that such recipe doesn’t exists.
Fortunately, there is. There is temporary fix in another brew repo, so all you have to do is:
brew tap kyslik/homebrew-php
brew install kyslik/php/php71-intl
Simple Solution:
package com.util.calendarutil;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class CalUtil {
public static void main(String args[]){
DateFormat df = new SimpleDateFormat("dd/mm/yyyy");
Date dt = null;
try {
dt = df.parse("23/01/2016");
} catch (ParseException e) {
System.out.println("Error");
}
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
Date startDate = cal.getTime();
cal.add(Calendar.DATE, 6);
Date endDate = cal.getTime();
System.out.println("Start Date:"+startDate+"End Date:"+endDate);
}
}
This gives you just the helper method without the side effects of loading every ActionView::Helpers method into your model:
ActionController::Base.helpers.sanitize(str)
Do this
<footer style="position: fixed; bottom: 0; width: 100%;"> </footer>
You can also read about flex it is supported by all modern browsers
Update: I read about flex and tried it. It worked for me. Hope it does the same for you. Here is how I implemented.Here main is not the ID it is the div
body {
margin: 0;
display: flex;
min-height: 100vh;
flex-direction: column;
}
main {
display: block;
flex: 1 0 auto;
}
Here you can read more about flex https://css-tricks.com/snippets/css/a-guide-to-flexbox/
Do keep in mind it is not supported by older versions of IE.
You can try xml2js. It's a simple XML to JavaScript object converter. It gets your XML converted to a JS object so that you can access its content with ease.
Here are some other options:
I have used xml2js
and it has worked fine for me. The rest you might have to try out for yourself.
unit test: testing of individual module or independent component in an application is known to be unit testing , the unit testing will be done by developer.
integration test: combining all the modules and testing the application to verify the communication and the data flow between the modules are working properly or not , this testing also performed by developers.
funcional test checking the individual functionality of an application is mean to be functional testing
acceptance testing this testing is done by end user or customer whether the build application is according to the customer requirement , and customer specification this is known to be acceptance testing
In addition to the answer already accepted, for the scenario when you want to define a default property as a function of other properties you can use expression body notation on C#6.0 (and higher) for even more elegant and concise constructs like:
public class Person{
public string FullName => $"{First} {Last}"; // expression body notation
public string First { get; set; } = "First";
public string Last { get; set; } = "Last";
}
You can use the above in the following fashion
var p = new Person();
p.FullName; // First Last
p.First = "Jon";
p.Last = "Snow";
p.FullName; // Jon Snow
In order to be able to use the above "=>" notation, the property must be read only, and you do not use the get accessor keyword.
Details on MSDN
I use iFrame to insert the content from another page and CSS mentioned above is NOT working as expected. I have to use the parameter scrolling="no" even if I use HTML 5 Doctype
$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
ADD COLUMN `ping_status` INT(1) NOT NULL
AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";
I believe you need to have ADD COLUMN
and use AFTER
, not BEFORE
.
In case you want to place column at the beginning of a table, use the FIRST
statement:
$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
ADD COLUMN `ping_status` INT(1) NOT NULL
FIRST";
OMG, I tried to find a simple solution to this for hours. I knew the code was simple but no one provided me what I wanted. So finally got to work on some example code and made something simple that anyone can use no JQuery required. Simple javascript and css and html. In order for the animation to work you have to set the height and width or the animation wont work. Found that out the hard way.
<script>
function dostuff() {
if (document.getElementById('MyBox').style.height == "0px") {
document.getElementById('MyBox').setAttribute("style", "background-color: #45CEE0; height: 200px; width: 200px; transition: all 2s ease;");
}
else {
document.getElementById('MyBox').setAttribute("style", "background-color: #45CEE0; height: 0px; width: 0px; transition: all 2s ease;");
}
}
</script>
<div id="MyBox" style="height: 0px; width: 0px;">
</div>
<input type="button" id="buttontest" onclick="dostuff()" value="Click Me">
Change your data to that formats to use sqlite datetime formats.
YYYY-MM-DD
YYYY-MM-DD HH:MM
YYYY-MM-DD HH:MM:SS
YYYY-MM-DD HH:MM:SS.SSS
YYYY-MM-DDTHH:MM
YYYY-MM-DDTHH:MM:SS
YYYY-MM-DDTHH:MM:SS.SSS
HH:MM
HH:MM:SS
HH:MM:SS.SSS
now
DDDDDDDDDD
SELECT * FROM test WHERE date BETWEEN '2011-01-11' AND '2011-08-11'
import javax.xml.bind.DatatypeConverter;
public class f{
public static void main(String a[]){
String str = new String(DatatypeConverter.printBase64Binary(new String("user:123").getBytes()));
String res = DatatypeConverter.parseBase64Binary(str);
System.out.println(res);
}
}
this is working for me
i use this path
String FILENAME_PATH = "/mnt/sdcard/Download/Version";
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
You can just adjust your constraints:
where T : class
Then returning null is allowed.
According to https://docs.docker.com/engine/reference/builder/#run the default [Linux] shell for RUN
is /bin/sh -c
. You appear to be expecting bashisms, so you should use the "exec form" of RUN
to specify your shell.
RUN ["/bin/bash", "-c", "source /usr/local/bin/virtualenvwrapper.sh"]
Otherwise, using the "shell form" of RUN and specifying a different shell results in nested shells.
# don't do this...
RUN /bin/bash -c "source /usr/local/bin/virtualenvwrapper.sh"
# because it is the same as this...
RUN ["/bin/sh", "-c", "/bin/bash" "-c" "source /usr/local/bin/virtualenvwrapper.sh"]
If you have more than 1 command that needs a different shell, you should read https://docs.docker.com/engine/reference/builder/#shell and change your default shell by placing this before your RUN commands:
SHELL ["/bin/bash", "-c"]
Finally, if you have placed anything in the root user's .bashrc
file that you need, you can add the -l
flag to the SHELL
or RUN
command to make it a login shell and ensure that it gets sourced.
Note: I have intentionally ignored the fact that it is pointless to source a script as the only command in a RUN.
This way to check the condition while pressing 'YES' or 'NO' buttons in MessageBox window.
DialogResult d = MessageBox.Show("Are you sure ?", "Remove Panel", MessageBoxButtons.YesNo);
if (d == DialogResult.Yes)
{
//Contents
}
else if (d == DialogResult.No)
{
//Contents
}
I had a similar issue using the JAXB reference implementation and JBoss AS 7.1. I was able to write an integration test that confirmed JAXB worked outside of the JBoss environment (suggesting the problem might be the class loader in JBoss).
This is the code that was giving the error (i.e. not working):
private static final JAXBContext JC;
static {
try {
JC = JAXBContext.newInstance("org.foo.bar");
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
and this is the code that worked (ValueSet is one of the classes marshaled from my XML).
private static final JAXBContext JC;
static {
try {
ClassLoader classLoader = ValueSet.class.getClassLoader();
JC = JAXBContext.newInstance("org.foo.bar", classLoader);
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
In some cases I got the Class nor any of its super class is known to this context. In other cases I also got an exception of org.foo.bar.ValueSet cannot be cast to org.foo.bar.ValueSet (similar to the issue described here: ClassCastException when casting to the same class).
A simple solution that could work in some cases is to create and $compile a wrapper and then append your original element to it.
Something like...
link: function(scope, elem, attr){
var wrapper = angular.element('<div tooltip></div>');
elem.before(wrapper);
$compile(wrapper)(scope);
wrapper.append(elem);
}
This solution has the advantage that it keeps things simple by not recompiling the original element.
This wouldn't work if any of the added directive's require
any of the original element's directives or if the original element has absolute positioning.
When not told otherwise commands take over the foreground. You only have one "foreground" process running in a single shell session. The & symbol instructs commands to run in a background process and immediately returns to the command line for additional commands.
sh my_script.sh &
A background process will not stay alive after the shell session is closed. SIGHUP terminates all running processes. By default anyway. If your command is long-running or runs indefinitely (ie: microservice) you need to pr-pend it with nohup so it remains running after you disconnect from the session:
nohup sh my_script.sh &
EDIT: There does appear to be a gray area regarding the closing of background processes when & is used. Just be aware that the shell may close your process depending on your OS and local configurations (particularly on CENTOS/RHEL): https://serverfault.com/a/117157.
array hash_algos(void)
echo hash('sha384', 'Message to be hashed'.'salt');
Here is a link to reference http://php.net/manual/en/function.hash.php
What about 1.1E10, +1, -0, etc? Parsing all possible numbers is trickier than many people think. If you want to include as many numbers are possible you should use the to_number function in a PL/SQL function. From http://www.oracle-developer.net/content/utilities/is_number.sql:
CREATE OR REPLACE FUNCTION is_number (str_in IN VARCHAR2) RETURN NUMBER IS
n NUMBER;
BEGIN
n := TO_NUMBER(str_in);
RETURN 1;
EXCEPTION
WHEN VALUE_ERROR THEN
RETURN 0;
END;
/
SELECT from_unixtime( UNIX_TIMESTAMP(fild_with_timestamp) ) from "your_table"
This work for me
You may need to know the status and update a ProgressBar during the file download or use credentials before making the request.
Here it is, an example that covers these options. Lambda notation and String interpolation has been used:
using System.Net;
// ...
using (WebClient client = new WebClient()) {
Uri ur = new Uri("http://remotehost.do/images/img.jpg");
//client.Credentials = new NetworkCredential("username", "password");
String credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("Username" + ":" + "MyNewPassword"));
client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";
client.DownloadProgressChanged += (o, e) =>
{
Console.WriteLine($"Download status: {e.ProgressPercentage}%.");
// updating the UI
Dispatcher.Invoke(() => {
progressBar.Value = e.ProgressPercentage;
});
};
client.DownloadDataCompleted += (o, e) =>
{
Console.WriteLine("Download finished!");
};
client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");
}
10 years later but that problem still caught me.
So this is the answer to those that are too late as me.
This does not work
int b = (int) Math.ceil(a / 100);
Cause the result a / 100
turns out to be an integer and it's rounded so Math.ceil
can't do anything about it.
You have to avoid the rounded operation with this
int b = (int) Math.ceil((float) a / 100);
Now it works.
You should not use your domain models
in your views. ViewModels
are the correct way to do it.
You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.
If you never heard of viewmodels, take a look at this.
This is working for me, you might change your code like this
var responseData=x.toString();
to
var responseData=x.toString("binary");
and finally
response.write(new Buffer(toTransmit, "binary"));
for a solution that works without bash or certain features from read
you can use stty
to disable echo
stty_orig=$(stty -g)
stty -echo
read password
stty $stty_orig
The default value of end
is \n
meaning that after the print
statement it will print a new line. So simply stated end
is what you want to be printed after the print
statement has been executed
Eg: - print ("hello",end=" +")
will print hello +
You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.
Sample snippet for time-diff:
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
You can move your files to other folder and then pull whole folder.
adb shell mkdir /sdcard/tmp adb shell mv /sdcard/mydir/*.jpg /sdcard/tmp # move your jpegs to temporary dir adb pull /sdcard/tmp/ # pull this directory (be sure to put '/' in the end) adb shell mv /sdcard/tmp/* /sdcard/mydir/ # move them back adb shell rmdir /sdcard/tmp # remove temporary directory
I had a similar problem with R-studio. When I tried to do my plots, this message was showing up.
Eventually I realised that the reason behind this was that my "window" for the plots was too small, and I had to make it bigger to "fit" all the plots inside!
Hope to help
iframe have "sandbox" attribute that may block pop up etc
Add to the info plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
import Alamofire
class AlamofireDataManager {
fileprivate let queue: DispatchQueue
init(queue: DispatchQueue) { self.queue = queue }
private func createError(message: String, code: Int) -> Error {
return NSError(domain: "dataManager", code: code, userInfo: ["message": message ])
}
private func make(session: URLSession = URLSession.shared, request: URLRequest, closure: ((Result<[String: Any]>) -> Void)?) {
Alamofire.request(request).responseJSON { response in
let complete: (Result<[String: Any]>) ->() = { result in DispatchQueue.main.async { closure?(result) } }
switch response.result {
case .success(let value): complete(.success(value as! [String: Any]))
case .failure(let error): complete(.failure(error))
}
}
}
func searchRequest(term: String, closure: ((Result<[String: Any]>) -> Void)?) {
guard let url = URL(string: "https://itunes.apple.com/search?term=\(term.replacingOccurrences(of: " ", with: "+"))") else { return }
let request = URLRequest(url: url)
make(request: request) { response in closure?(response) }
}
}
private lazy var alamofireDataManager = AlamofireDataManager(queue: DispatchQueue(label: "DataManager.queue", qos: .utility))
//.........
alamofireDataManager.searchRequest(term: "jack johnson") { result in
print(result.value ?? "no data")
print(result.error ?? "no error")
}
import Foundation
class DataManager {
fileprivate let queue: DispatchQueue
init(queue: DispatchQueue) { self.queue = queue }
private func createError(message: String, code: Int) -> Error {
return NSError(domain: "dataManager", code: code, userInfo: ["message": message ])
}
private func make(session: URLSession = URLSession.shared, request: URLRequest, closure: ((_ json: [String: Any]?, _ error: Error?)->Void)?) {
let task = session.dataTask(with: request) { [weak self] data, response, error in
self?.queue.async {
let complete: (_ json: [String: Any]?, _ error: Error?) ->() = { json, error in DispatchQueue.main.async { closure?(json, error) } }
guard let self = self, error == nil else { complete(nil, error); return }
guard let data = data else { complete(nil, self.createError(message: "No data", code: 999)); return }
do {
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
complete(json, nil)
}
} catch let error { complete(nil, error); return }
}
}
task.resume()
}
func searchRequest(term: String, closure: ((_ json: [String: Any]?, _ error: Error?)->Void)?) {
let url = URL(string: "https://itunes.apple.com/search?term=\(term.replacingOccurrences(of: " ", with: "+"))")
let request = URLRequest(url: url!)
make(request: request) { json, error in closure?(json, error) }
}
}
private lazy var dataManager = DataManager(queue: DispatchQueue(label: "DataManager.queue", qos: .utility))
// .......
dataManager.searchRequest(term: "jack johnson") { json, error in
print(error ?? "nil")
print(json ?? "nil")
print("Update views")
}
The sample mvcmusicstore.codeplex.com opened in vs2015 missed some references, one of them System.web.mvc.
The fix for this was to remove it from the references and to add a reference: choose Extentions under Assemblies, there you can find and add System.Web.Mvc.
(The other assemblies I added with the nuget packages.)
Only "pre" tag:
<pre>Name: Waleed Hasees
Age: 33y
Address: Palestine / Jein</pre>
You can apply any CSS class on this tag.
Here is a solution to make an accessible audio player with valid xHTML and non-intrusive javascript thanks to W3C Web Audio API :
What to do :
First of all, we check if the browser implements Web Audio API:
if (typeof Audio === 'undefined') {
// abort
}
Then we instanciate an Audio
object:
var player = new Audio('mysong.ogg');
Then we can check if the browser is able to decode this type of file :
if(!player.canPlayType('audio/ogg')) {
// abort
}
Or even if it can play the codec :
if(!player.canPlayType('audio/ogg; codecs="vorbis"')) {
// abort
}
Then we can use player.play()
, player.pause()
;
I have done a tiny JQuery plugin that I called nanodio to test this.
You can check how it works on my demo page (sorry, but text is in french :p )
Just click on a link to play, and click again to pause. If the browser can read it natively, it will. If it can't, it should download the file.
This is just a little example, but you can improve it to use any element of your page as a control button or generate ones on the fly with javascript... Whatever you want.
A simpler way would be to do:
ObjectA.Verify(
a => a.Execute(
It.Is<Params>(p => p.Id == 7)
)
);
You can use XRegExp, an augmented, extensible, cross-browser implementation of regular expressions, including support for additional syntax, flags, and methods:
s
, to make dot match all characters (aka dotall or singleline mode), and x
, for free-spacing and comments (aka extended mode).Instead of
null,
use CustomerDTO customers =
new CustomerDTO()`;
CustomerDTO customer = null;
private static List<Author> getAllAuthors() {
initConnection();
List<Author> authors = new ArrayList<Author>();
Author author = new Author();
try {
stmt = (Statement) conn.createStatement();
String str = "SELECT * FROM author";
rs = (ResultSet) stmt.executeQuery(str);
while (rs.next()) {
int id = rs.getInt("nAuthorId");
String name = rs.getString("cAuthorName");
author.setnAuthorId(id);
author.setcAuthorName(name);
authors.add(author);
System.out.println(author.getnAuthorId() + " - " + author.getcAuthorName());
}
rs.close();
closeConnection();
} catch (Exception e) {
System.out.println(e);
}
return authors;
}
To highlight a block of code in Notepad++, please do the following steps
Style token
and select any of the five choices available ( styles from Using 1st style
to using 5th style
). Each is of different colors.If you want yellow color choose using 3rd style
.If you want to create your own style you can use Style Configurator
under Settings
menu.
I think you can use typeahead.js
. There are typescript definitions for it. so it'll be easy to use it i guess if you are using typescript for development.
If you need to include non-ASCII alphabetic characters, and if your regex flavor supports Unicode, then
\A\pL+\z
would be the correct regex.
Some regex engines don't support this Unicode syntax but allow the \w
alphanumeric shorthand to also match non-ASCII characters. In that case, you can get all alphabetics by subtracting digits and underscores from \w
like this:
\A[^\W\d_]+\z
\A
matches at the start of the string, \z
at the end of the string (^
and $
also match at the start/end of lines in some languages like Ruby, or if certain regex options are set).
Inner join two tables in linq C#
var result = from q1 in table1
join q2 in table2
on q1.Customer_Id equals q2.Customer_Id
select new { q1.Name, q1.Mobile, q2.Purchase, q2.Dates }
1) First you need to generate EDMX
model using your database. To do that you should add new item to your project:
ADO.NET Entity Data Model
from the Templates list. So now you have Model1.edmx
file in your project.
2) To generate classes using your model:
EDMX
model designer.EF 4.x DbContext Generator for C#
.Notice that two items are added to your project:
Model1.tt
(This template generates very simple POCO classes for each entity in your model) Model1.Context.tt
(This template generates a derived DbContext to use for querying and persisting data)3) Read/Write Data example:
var dbContext = new YourModelClass(); //class derived from DbContext
var contacts = from c in dbContext.Contacts select c; //read data
contacts.FirstOrDefault().FirstName = "Alex"; //edit data
dbContext.SaveChanges(); //save data to DB
Don't forget that you need 4.x version of EntityFramework. You can download EF 4.1 here: Entity Framework 4.1.
!elt.hasChildNodes()
Yes, I know, this is not jQuery, so you could use this:
!$(elt)[0].hasChildNodes()
Happy now?
Try this. Note there's no database specified - it just runs "on the server"
psql -U postgres -c "drop database databasename"
If that doesn't work, I have seen a problem with postgres holding onto orphaned prepared statements.
To clean them up, do this:
SELECT * FROM pg_prepared_xacts;
then for every id you see, run this:
ROLLBACK PREPARED '<id>';
You can also use between
:
df[df.some_date.between(start_date, end_date)]
If you have a named container then it can be started by running
docker container start container_name
where container_name is name of the container that must be given at the time of creating container. You can replace container_name
with the container id in case the container is not named. The container ID can be found by running:
docker ps -a
A solution that actually works and covers all cases:
offsetBy
not insetBy
.Rect
.Sample:
override func textRect(forBounds bounds: CGRect) -> CGRect {
return super.textRect(forBounds: bounds).offsetBy(dx: 0.0, dy: 4)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return super.editingRect(forBounds: bounds).offsetBy(dx: 0.0, dy: 4)
}
The best way is to create a variable of type Worksheet
, assign the worksheet and use it every time the VBA would implicitly use the ActiveSheet
.
This will help you avoid bugs that will eventually show up when your program grows in size.
For example something like Range("A1:C10").Sort Key1:=Range("A2")
is good when the macro works only on one sheet. But you will eventually expand your macro to work with several sheets, find out that this doesn't work, adjust it to ShTest1.Range("A1:C10").Sort Key1:=Range("A2")
... and find out that it still doesn't work.
Here is the correct way:
Dim ShTest1 As Worksheet
Set ShTest1 = Sheets("Test1")
ShTest1.Range("A1:C10").Sort Key1:=ShTest1.Range("A2")
Long after accept answer.
Use sprintf()
, or related functions, as many others have answers suggested, but use a better format specifier.
Using "%.*e"
, code solves various issues:
The maximum buffer size needed is far more reasonable, like 18 for float
(see below). With "%f"
, sprintf(buf, "%f", FLT_MAX);
could need 47+. sprintf(buf, "%f", DBL_MAX);
may need 317+
Using ".*"
allows code to define the number of decimal places needed to distinguish a string version of float x
and it next highest float
. For deatils, see Printf width specifier to maintain precision of floating-point value
Using "%e"
allows code to distinguish small float
s from each other rather than all printing "0.000000"
which is the result when |x| < 0.0000005
.
Example usage
#include <float.h>
#define FLT_STRING_SIZE (1+1+1+(FLT_DECIMAL_DIG-1)+1+1+ 4 +1)
// - d . dddddddd e - dddd \0
char buf[FLT_STRING_SIZE];
sprintf(buf, "%.*e", FLT_DECIMAL_DIG-1, some_float);
Ideas:
IMO, better to use 2x buffer size for scratch pads like buf[FLT_STRING_SIZE*2]
.
For added robustness, use snprintf()
.
As a 2nd alterative consider "%.*g"
. It is like "%f"
for values exponentially near 1.0 and like "%e"
for others.
Thanks for the above script. One little modification to add in the file ending correctly. Try this ...
$filenameFormat = "MyFileName" + " " + (Get-Date -Format "yyyy-MM-dd") **+ ".txt"**
Rename-Item -Path "C:\temp\MyFileName.txt" -NewName $filenameFormat
I know what you're trying to do, but why not simply do this:
$('div').addClass('hover');
The class is already defined in your CSS...
As for you original question, this has been asked before and it is not possible unfortunately. e.g. http://forum.jquery.com/topic/jquery-triggering-css-pseudo-selectors-like-hover
However, your desired functionality may be possible if your Stylesheet is defined in Javascript. see: http://www.4pmp.com/2009/11/dynamic-css-pseudo-class-styles-with-jquery/
Hope this helps!
A slightly modified version of Sophie's answer which allows to output the *.d files to a different folder (I will only paste the interesting part that generates the dependency files):
$(OBJDIR)/%.o: %.cpp
# Generate dependency file
mkdir -p $(@D:$(OBJDIR)%=$(DEPDIR)%)
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -MM -MT $@ $< -MF $(@:$(OBJDIR)/%.o=$(DEPDIR)/%.d)
# Generate object file
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $< -o $@
Note that the parameter
-MT $@
is used to ensure that the targets (i.e. the object file names) in the generated *.d files contain the full path to the *.o files and not just the file name.
I don't know why this parameter is NOT needed when using -MMD in combination with -c (as in Sophie's version). In this combination it seems to write the full path of the *.o files into the *.d files. Without this combination, -MMD also writes only the pure file names without any directory components into the *.d files. Maybe somebody knows why -MMD writes the full path when combined with -c. I have not found any hint in the g++ man page.
(a) wwww.somewebsite.com/a.txt
isn't a 'file URL'. It isn't a URL at all. If you put http://
on the front of it it would be an HTTP URL, which is clearly what you intend here.
(b) FileInputStream
is for files, not URLs.
(c) The way to get an input stream from any URL is via URL.openStream(),
or URL.getConnection().getInputStream(),
which is equivalent but you might have other reasons to get the URLConnection
and play with it first.
This is my implementation (based in: https://gist.github.com/3782074):
Usage: HTML:
<table class="download">...</table>
<a href="" download="name.csv">DOWNLOAD CSV</a>
JS:
$("a[download]").click(function(){
$("table.download").toCSV(this);
});
Code:
jQuery.fn.toCSV = function(link) {
var $link = $(link);
var data = $(this).first(); //Only one table
var csvData = [];
var tmpArr = [];
var tmpStr = '';
data.find("tr").each(function() {
if($(this).find("th").length) {
$(this).find("th").each(function() {
tmpStr = $(this).text().replace(/"/g, '""');
tmpArr.push('"' + tmpStr + '"');
});
csvData.push(tmpArr);
} else {
tmpArr = [];
$(this).find("td").each(function() {
if($(this).text().match(/^-{0,1}\d*\.{0,1}\d+$/)) {
tmpArr.push(parseFloat($(this).text()));
} else {
tmpStr = $(this).text().replace(/"/g, '""');
tmpArr.push('"' + tmpStr + '"');
}
});
csvData.push(tmpArr.join(','));
}
});
var output = csvData.join('\n');
var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(output);
$link.attr("href", uri);
}
Notes:
UPDATE:
My previous implementation worked fine but it didn't set the csv filename. The code was modified to use a filename but it requires an < a > element. It seems that you can't dynamically generate the < a > element and fire the "click" event (perhaps security reasons?).
DEMO
(Unfortunately jsfiddle fails to generate the file and instead it throws an error: 'please use POST request', don't let that error stop you from testing this code in your application).
I only put this code in my pom.xml and I executed the command maven install.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
You could attempt to load the the https page in an iframe and route all ajax requests in/out of the frame via some bridge, it's a hackaround but it might work (not sure if it will impose the same access restrictions given the secure context). Otherwise a local http proxy to reroute requests (like any cross domain calls) would be the accepted solution.
quantumpotato's issue:
Where types
is given by
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
one can use
if (types & UIRemoteNotificationTypeAlert)
instead of
if (types == UIRemoteNotificationTypeNone)
will allow you to check only whether notifications are enabled (and don't worry about sounds, badges, notification center, etc.). The first line of code (types & UIRemoteNotificationTypeAlert
) will return YES
if "Alert Style" is set to "Banners" or "Alerts", and NO
if "Alert Style" is set to "None", irrespective of other settings.
There is a way to do this using the system property "user.dir". The key part to understand is that getAbsoluteFile() must be called (as shown below) or else relative paths will be resolved against the default "user.dir" value.
import java.io.*;
public class FileUtils
{
public static boolean setCurrentDirectory(String directory_name)
{
boolean result = false; // Boolean indicating whether directory was set
File directory; // Desired current working directory
directory = new File(directory_name).getAbsoluteFile();
if (directory.exists() || directory.mkdirs())
{
result = (System.setProperty("user.dir", directory.getAbsolutePath()) != null);
}
return result;
}
public static PrintWriter openOutputFile(String file_name)
{
PrintWriter output = null; // File to open for writing
try
{
output = new PrintWriter(new File(file_name).getAbsoluteFile());
}
catch (Exception exception) {}
return output;
}
public static void main(String[] args) throws Exception
{
FileUtils.openOutputFile("DefaultDirectoryFile.txt");
FileUtils.setCurrentDirectory("NewCurrentDirectory");
FileUtils.openOutputFile("CurrentDirectoryFile.txt");
}
}
I was looking for the TOTAL size of the column and hit this article, my solution is based off of MarcE's.
SELECT sum(DATALENGTH(your_field)) AS FIELDSIZE FROM your_table
sort ip_addresses | uniq -c
This will print the count first, but other than that it should be exactly what you want.
That is weird, everything looks fine, are you sure it does not work for you? Because this main
surely works for me, so I would look somewhere else for the source of your problem.
#include <QFile>
#include <QTextStream>
int main()
{
QString filename = "Data.txt";
QFile file(filename);
if (file.open(QIODevice::ReadWrite)) {
QTextStream stream(&file);
stream << "something" << endl;
}
}
The code you provided is also almost the same as the one provided in detailed description of QTextStream so I am pretty sure, that the problem is elsewhere :)
Also note, that the file is not called Data
but Data.txt
and should be created/located in the directory from which the program was run (not necessarily the one where the executable is located).
The only way I could get it to work is if my Mac and my iPhone were on different networks. I have a main DSL modem call it network1 and a second network2 setup us an access point. They have SSIDs network1 and network2. If the phone was on network1 and the mac on network2 it would work, or vice versa. But if both were on network1 or both were on network2, it would NOT work.
You could also use echo with braces,
$ (echo hello; echo world)
hello
world
I have experienced that it is not safe (VS2010) to delete[] NULL (i.e. array syntax). I'm not sure whether this is according to the C++ standard.
It is safe to delete NULL (scalar syntax).
Try to comment string "sql-mode=..." in file my.cnf and than restart mysql.
This is useful when you want to have a global variable. You define the global variables in some source file, and declare them extern in a header file so that any file that includes that header file will then see the same global variable.
Here's one way:
Stream myStream = null;
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = theDialog.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
Modified from here:MSDN OpenFileDialog.OpenFile
EDIT Here's another way more suited to your needs:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
string filename = theDialog.FileName;
string[] filelines = File.ReadAllLines(filename);
List<Employee> employeeList = new List<Employee>();
int linesPerEmployee = 4;
int currEmployeeLine = 0;
//parse line by line into instance of employee class
Employee employee = new Employee();
for (int a = 0; a < filelines.Length; a++)
{
//check if to move to next employee
if (a != 0 && a % linesPerEmployee == 0)
{
employeeList.Add(employee);
employee = new Employee();
currEmployeeLine = 1;
}
else
{
currEmployeeLine++;
}
switch (currEmployeeLine)
{
case 1:
employee.EmployeeNum = Convert.ToInt32(filelines[a].Trim());
break;
case 2:
employee.Name = filelines[a].Trim();
break;
case 3:
employee.Address = filelines[a].Trim();
break;
case 4:
string[] splitLines = filelines[a].Split(' ');
employee.Wage = Convert.ToDouble(splitLines[0].Trim());
employee.Hours = Convert.ToDouble(splitLines[1].Trim());
break;
}
}
//Test to see if it works
foreach (Employee emp in employeeList)
{
MessageBox.Show(emp.EmployeeNum + Environment.NewLine +
emp.Name + Environment.NewLine +
emp.Address + Environment.NewLine +
emp.Wage + Environment.NewLine +
emp.Hours + Environment.NewLine);
}
}
}
In my case this error was caused by hot reloading, while introducing new classes. In that stage of the project, use normal watchers to compile your code.
ul {
list-style-type: none;
}
ul li:before {
content:'*'; /* Change this to unicode as needed*/
width: 1em !important;
margin-left: -1em;
display: inline-block;
}
I needed to generate mongodb ids on client side.
After digging into the mongodb source code i found they generate ObjectIDs using npm bson
lib.
If ever you need only to generate an ObjectID without installing the whole mongodb / mongoose package, you can import the lighter bson
library :
const bson = require('bson');
new bson.ObjectId(); // 5cabe64dcf0d4447fa60f5e2
Note: There is also an npm project named bson-objectid
being even lighter
Once you have Selected a group of sheets, you can use Selection
Consider:
Sub luxation()
ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
Selection.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:="C:\TestFolder\temp.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
End Sub
EDIT#1:
Further testing has reveled that this technique depends on the group of cells selected on each worksheet. To get a comprehensive output, use something like:
Sub Macro1()
Sheets("Sheet1").Activate
ActiveSheet.UsedRange.Select
Sheets("Sheet2").Activate
ActiveSheet.UsedRange.Select
Sheets("Sheet3").Activate
ActiveSheet.UsedRange.Select
ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
Selection.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\James\Desktop\pdfmaker.pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
True
End Sub
Usually I wrap the output into a list, which is very flexible (you can have any combination of numbers, strings, vectors, matrices, arrays, lists, objects int he output)
so like:
func2<-function(input) {
a<-input+1
b<-input+2
output<-list(a,b)
return(output)
}
output<-func2(5)
for (i in output) {
print(i)
}
[1] 6
[1] 7
As mentioned by h4z3, For a practical use, Sometimes your data is too big to directly load everything, or you have a generator, or real-time incoming data, you could use w+ to store in a file and read later.
1) Try putting an absolute link not relative link to your eot font - somehow old IE just don't know in which folder the css file is 2) make 2 extra @font-face declarations so it should look like this:
@font-face { /* for modern browsers and modern IE */
font-family: "Futura";
src: url("../fonts/Futura_Medium_BT.eot");
src: url("../fonts/Futura_Medium_BT.eot?#iefix") format("embedded-opentype"),
url( "../fonts/Futura_Medium_BT.ttf" ) format("truetype");
}
@font-face{ /* for old IE */
font-family: "Futura_IE";
src: url(/wp-content/themes/my-theme/fonts/Futura_Medium_BT.eot);
}
@font-face{ /* for old IE */
font-family: "Futura_IE2";
src:url(/wp-content/themes/my-theme/fonts/Futura_Medium_BT.eot?#iefix)
format("embedded-opentype");
}
.p{ font-family: "Futura", "Futura_IE", "Futura_IE2", Arial, sans-serif;
This is an example for wordpress template - absolute link should point from where your start index file is.
you could use a defaultdict. It will let you set dictionary values without worrying if the key already exists. If you access a key that has not been initialized yet it will return a value you specify (in the below example it will return None)
from collections import defaultdict
your_dict = defaultdict(lambda : None)
Here is a solution based on the answer by Henrik Karlsson but with proper event triggering (based on Bootstrap sources):
$(function(){
$('[data-hide]').on('click', function ___alert_hide(e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector === '#' ? [] : selector)
if (!$parent.length) {
$parent = $this.closest('.alert')
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.hide()
$parent.trigger($.Event('closed.bs.alert'))
})
});
The answer mostly for me, as a note.
With pandas it can be done as:
If lakes is your DataFrame:
area_dict = lakes.to_dict('records')
For functions, I suggest using this simple decorator I created.
def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
if 'log_time' in kw:
name = kw.get('log_name', method.__name__.upper())
kw['log_time'][name] = int((te - ts) * 1000)
else:
print('%r %2.22f ms' % (method.__name__, (te - ts) * 1000))
return result
return timed
@timeit
def foo():
do_some_work()
# 'foo' 0.000953 ms
Not only can you, but you have to make a special effort not to if you don't want to. :-)
When the browser encounters a classic script
tag when parsing the HTML, it stops parsing and hands over to the JavaScript interpreter, which runs the script. The parser doesn't continue until the script execution is complete (because the script might do document.write
calls to output markup that the parser should handle).
That's the default behavior, but you have a few options for delaying script execution:
Use JavaScript modules. A type="module"
script is deferred until the HTML has been fully parsed and the initial DOM created. This isn't the primary reason to use modules, but it's one of the reasons:
<script type="module" src="./my-code.js"></script>
<!-- Or -->
<script type="module">
// Your code here
</script>
The code will be fetched (if it's separate) and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. (If your module code is inline rather than in its own file, it is also deferred until HTML parsing is complete.)
This wasn't available when I first wrote this answer in 2010, but here in 2020, all major modern browsers support modules natively, and if you need to support older browsers, you can use bundlers like Webpack and Rollup.js.
Use the defer
attribute on a classic script tag:
<script defer src="./my-code.js"></script>
As with the module, the code in my-code.js
will be fetched and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. But, defer
doesn't work with inline script content, only with external files referenced via src
.
I don't think it's what you want, but you can use the async
attribute to tell the browser to fetch the JavaScript code in parallel with the HTML parsing, but then run it as soon as possible, even if the HTML parsing isn't complete. You can put it on a type="module"
tag, or use it instead of defer
on a classic script
tag.
Put the script
tag at the end of the document, just prior to the closing </body>
tag:
<!doctype html>
<html>
<!-- ... -->
<body>
<!-- The document's HTML goes here -->
<script type="module" src="./my-code.js"></script><!-- Or inline script -->
</body>
</html>
That way, even though the code is run as soon as its encountered, all of the elements defined by the HTML above it exist and are ready to be used.
It used to be that this caused an additional delay on some browsers because they wouldn't start fetching the code until the script
tag was encountered, but modern browsers scan ahead and start prefetching. Still, this is very much the third choice at this point, both modules and defer
are better options.
The spec has a useful diagram showing a raw script
tag, defer
, async
, type="module"
, and type="module" async
and the timing of when the JavaScript code is fetched and run:
Here's an example of the default behavior, a raw script
tag:
.found {_x000D_
color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script>_x000D_
if (typeof NodeList !== "undefined" && !NodeList.prototype.forEach) {_x000D_
NodeList.prototype.forEach = Array.prototype.forEach;_x000D_
}_x000D_
document.querySelectorAll("p").forEach(p => {_x000D_
p.classList.add("found");_x000D_
});_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
(See my answer here for details around that NodeList
code.)
When you run that, you see "Paragraph 1" in green but "Paragraph 2" is black, because the script ran synchronously with the HTML parsing, and so it only found the first paragraph, not the second.
In contrast, here's a type="module"
script:
.found {_x000D_
color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script type="module">_x000D_
document.querySelectorAll("p").forEach(p => {_x000D_
p.classList.add("found");_x000D_
});_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
Notice how they're both green now; the code didn't run until HTML parsing was complete. That would also be true with a defer
script
with external content (but not inline content).
(There was no need for the NodeList
check there because any modern browser supporting modules already has forEach
on NodeList
.)
In this modern world, there's no real value to the DOMContentLoaded
event of the "ready" feature that PrototypeJS, jQuery, ExtJS, Dojo, and most others provided back in the day (and still provide); just use modules or defer
. Even back in the day, there wasn't much reason for using them (and they were often used incorrectly, holding up page presentation while the entire jQuery library was loaded because the script
was in the head
instead of after the document), something some developers at Google flagged up early on. This was also part of the reason for the YUI recommendation to put scripts at the end of the body
, again back in the day.
I just posted another solution for accessing the DataContext of a parent element in Silverlight that works for me. It uses Binding ElementName
.
I agree with all the above solutions, but to point out whats the root cause of this issue is, that major role player in all above code is this line of code:
dataType:'json'
when you miss this line (which is optional), the data returned from server is treated as full length string (which is default return type). Adding this line of code informs jQuery to convert the possible json string into json object.
Any jQuery ajax calls should specify this line, if expecting json data object.
I ran into this when I reduced the number of user-input parameters in userInput from 3 to 1. This changed the variable output type of userInput from an array to a primitive.
Example:
myvar1 = userInput['param1']
myvar2 = userInput['param2']
to:
myvar = userInput
You could add justify-content: space-between
to the parent element. In doing so, the children flexbox items will be aligned to opposite sides with space between them.
#container {
width: 500px;
border: solid 1px #000;
display: flex;
justify-content: space-between;
}
#container {_x000D_
width: 500px;_x000D_
border: solid 1px #000;_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}_x000D_
_x000D_
#a {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
}_x000D_
_x000D_
#b {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
height: 200px;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="a">_x000D_
a_x000D_
</div>_x000D_
<div id="b">_x000D_
b_x000D_
</div>_x000D_
</div>
_x000D_
You could also add margin-left: auto
to the second element in order to align it to the right.
#b {
width: 20%;
border: solid 1px #000;
height: 200px;
margin-left: auto;
}
#container {_x000D_
width: 500px;_x000D_
border: solid 1px #000;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
#a {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
margin-right: auto;_x000D_
}_x000D_
_x000D_
#b {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
height: 200px;_x000D_
margin-left: auto;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="a">_x000D_
a_x000D_
</div>_x000D_
<div id="b">_x000D_
b_x000D_
</div>_x000D_
</div>
_x000D_
Unicode is a standard that defines, along with ISO/IEC 10646, Universal Character Set (UCS) which is a superset of all existing characters required to represent practically all known languages.
Unicode assigns a Name and a Number (Character Code, or Code-Point) to each character in its repertoire.
UTF-8 encoding, is a way to represent these characters digitally in computer memory. UTF-8 maps each code-point into a sequence of octets (8-bit bytes)
For e.g.,
UCS Character = Unicode Han Character
UCS code-point = U+24B62
UTF-8 encoding = F0 A4 AD A2 (hex) = 11110000 10100100 10101101 10100010 (bin)
I have set a php code which can help in case you want to access Instagram images without api on basis of hashtag
CONVERT(date, GETDATE())
and CONVERT(time, GETDATE())
works in SQL Server 2008. I'm uncertain about 2005.
The solution:
var list = (from t in ctn.Items
where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
orderby t.Delivery.SubmissionDate
select t).Take(5);
IF they Give Path Directory Error!
In MAC Then Go to Folder Get Info and Open Storage and Permission change to privileges Read To Write
The css clear: left
in your adm class should stop the div floating with the elements above it.
Aggregating with $lookup
and subsequent $group
is pretty cumbersome, so if (and that's a medium if) you're using node & Mongoose or a supporting library with some hints in the schema, you could use a .populate()
to fetch those documents:
var mongoose = require("mongoose"),
Schema = mongoose.Schema;
var productSchema = Schema({ ... });
var orderSchema = Schema({
_id : Number,
products: [ { type: Schema.Types.ObjectId, ref: "Product" } ]
});
var Product = mongoose.model("Product", productSchema);
var Order = mongoose.model("Order", orderSchema);
...
Order
.find(...)
.populate("products")
...
The techniques outlined above describe your options pretty well. But what are the users seeing? I can't imagine how a basic conflict like this between you and whoever is responsible for the software can't end up in confusion and antagonism with the users.
I'd do everything I could to find some other way out of the impasse - because other people could easily see any change you make as escalating the problem.
EDIT:
I'll score my first "undelete" and admit to posting the above when this question first appeared. I of course chickened out when I saw that it was from JOEL SPOLSKY. But it looks like it landed somewhere near. Don't need votes, but I'll put it on the record.
IME, triggers are so seldom the right answer for anything other than fine-grained integrity constraints outside the realm of business rules.
The following code example written in Java will allow you to execute any command on a foreign computer through SSH from within a java program. You will need to include the com.jcraft.jsch jar file.
/*
* SSHManager
*
* @author cabbott
* @version 1.0
*/
package cabbott.net;
import com.jcraft.jsch.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SSHManager
{
private static final Logger LOGGER =
Logger.getLogger(SSHManager.class.getName());
private JSch jschSSHChannel;
private String strUserName;
private String strConnectionIP;
private int intConnectionPort;
private String strPassword;
private Session sesConnection;
private int intTimeOut;
private void doCommonConstructorActions(String userName,
String password, String connectionIP, String knownHostsFileName)
{
jschSSHChannel = new JSch();
try
{
jschSSHChannel.setKnownHosts(knownHostsFileName);
}
catch(JSchException jschX)
{
logError(jschX.getMessage());
}
strUserName = userName;
strPassword = password;
strConnectionIP = connectionIP;
}
public SSHManager(String userName, String password,
String connectionIP, String knownHostsFileName)
{
doCommonConstructorActions(userName, password,
connectionIP, knownHostsFileName);
intConnectionPort = 22;
intTimeOut = 60000;
}
public SSHManager(String userName, String password, String connectionIP,
String knownHostsFileName, int connectionPort)
{
doCommonConstructorActions(userName, password, connectionIP,
knownHostsFileName);
intConnectionPort = connectionPort;
intTimeOut = 60000;
}
public SSHManager(String userName, String password, String connectionIP,
String knownHostsFileName, int connectionPort, int timeOutMilliseconds)
{
doCommonConstructorActions(userName, password, connectionIP,
knownHostsFileName);
intConnectionPort = connectionPort;
intTimeOut = timeOutMilliseconds;
}
public String connect()
{
String errorMessage = null;
try
{
sesConnection = jschSSHChannel.getSession(strUserName,
strConnectionIP, intConnectionPort);
sesConnection.setPassword(strPassword);
// UNCOMMENT THIS FOR TESTING PURPOSES, BUT DO NOT USE IN PRODUCTION
// sesConnection.setConfig("StrictHostKeyChecking", "no");
sesConnection.connect(intTimeOut);
}
catch(JSchException jschX)
{
errorMessage = jschX.getMessage();
}
return errorMessage;
}
private String logError(String errorMessage)
{
if(errorMessage != null)
{
LOGGER.log(Level.SEVERE, "{0}:{1} - {2}",
new Object[]{strConnectionIP, intConnectionPort, errorMessage});
}
return errorMessage;
}
private String logWarning(String warnMessage)
{
if(warnMessage != null)
{
LOGGER.log(Level.WARNING, "{0}:{1} - {2}",
new Object[]{strConnectionIP, intConnectionPort, warnMessage});
}
return warnMessage;
}
public String sendCommand(String command)
{
StringBuilder outputBuffer = new StringBuilder();
try
{
Channel channel = sesConnection.openChannel("exec");
((ChannelExec)channel).setCommand(command);
InputStream commandOutput = channel.getInputStream();
channel.connect();
int readByte = commandOutput.read();
while(readByte != 0xffffffff)
{
outputBuffer.append((char)readByte);
readByte = commandOutput.read();
}
channel.disconnect();
}
catch(IOException ioX)
{
logWarning(ioX.getMessage());
return null;
}
catch(JSchException jschX)
{
logWarning(jschX.getMessage());
return null;
}
return outputBuffer.toString();
}
public void close()
{
sesConnection.disconnect();
}
}
For testing.
/**
* Test of sendCommand method, of class SSHManager.
*/
@Test
public void testSendCommand()
{
System.out.println("sendCommand");
/**
* YOU MUST CHANGE THE FOLLOWING
* FILE_NAME: A FILE IN THE DIRECTORY
* USER: LOGIN USER NAME
* PASSWORD: PASSWORD FOR THAT USER
* HOST: IP ADDRESS OF THE SSH SERVER
**/
String command = "ls FILE_NAME";
String userName = "USER";
String password = "PASSWORD";
String connectionIP = "HOST";
SSHManager instance = new SSHManager(userName, password, connectionIP, "");
String errorMessage = instance.connect();
if(errorMessage != null)
{
System.out.println(errorMessage);
fail();
}
String expResult = "FILE_NAME\n";
// call sendCommand for each command and the output
//(without prompts) is returned
String result = instance.sendCommand(command);
// close only after all commands are sent
instance.close();
assertEquals(expResult, result);
}
Its simple If you are passing String X from A to B.
A--> B
In Activity A
1) Create Intent
2) Put data in intent using putExtra method of intent
3) Start activity
Intent i = new Intent(A.this, B.class);
i.putExtra("MY_kEY",X);
In Activity B
inside onCreate method
1) Get intent object
2) Get stored value using key(MY_KEY)
Intent intent = getIntent();
String result = intent.getStringExtra("MY_KEY");
This is the standard way to send data from A to B. you can send any data type, it could be int, boolean, ArrayList, String[]. Based on the datatype you stored in Activity as key, value pair retrieving method might differ like if you are passing int value then you will call
intent.getIntExtra("KEY");
You can even send Class objects too but for that, you have to make your class object implement the Serializable or Parceable interface.
How much data you can send across size. If data exceeds a certain amount in size then you might get TransactionTooLargeException. Suppose you are trying to send bitmap across the activity and if the size exceeds certain data size then you might see this exception.
The code that you looked at is not ideal. You should either:
Catch the exception and handle it;
in which case the throws
is
unnecesary.
Remove the try/catch
; in which case
the Exception will be handled by a
calling method.
Catch the exception, possibly perform some action and then rethrow the exception (not just the message)
This would be the command line statement.
"%JMETER_HOME%\bin\jmeter.bat" -n -t <jmx test file path> -l <csv result file path> -Djmeter.save.saveservice.output_format=csv
All good answers. To put it in simple language [BCNF] No partial key can depend on a key.
i.e No partial subset ( i.e any non trivial subset except the full set ) of a candidate key can be functionally dependent on some candidate key.
using $(this) improves performance, as the class/whatever attr u are using to search, need not be searched for multiple times in the entire webpage content.
There's no way to guarantee that two functions will execute in sync with each other which seems to be what you want to do.
The best you can do is to split up the function into several steps, then wait for both to finish at critical synchronization points using Process.join
like @aix's answer mentions.
This is better than time.sleep(10)
because you can't guarantee exact timings. With explicitly waiting, you're saying that the functions must be done executing that step before moving to the next, instead of assuming it will be done within 10ms which isn't guaranteed based on what else is going on on the machine.
Not having a compiler by me right now, I'll answer by asking a question:
Have you tried this? Does it work?
long key = -1L;
PreparedStatement statement = connection.prepareStatement();
statement.executeUpdate(YOUR_SQL_HERE, PreparedStatement.RETURN_GENERATED_KEYS);
ResultSet rs = statement.getGeneratedKeys();
if (rs != null && rs.next()) {
key = rs.getLong(1);
}
Disclaimer: Obviously, I haven't compiled this, but you get the idea.
PreparedStatement is a subinterface of Statement, so I don't see a reason why this wouldn't work, unless some JDBC drivers are buggy.
No, there is no "easy" way. Your best bet would be to do a loop where you first check each previous sibling, then move to the parent node and all of its previous siblings.
You'll need to break the selector into two, 1 to check if the current node could be the top level node in your selector, and 1 to check if it's descendants match.
Edit: This might as well be a plugin. You can use this with any selector in any HTML:
(function($) {
$.fn.closestPrior = function(selector) {
selector = selector.replace(/^\s+|\s+$/g, "");
var combinator = selector.search(/[ +~>]|$/);
var parent = selector.substr(0, combinator);
var children = selector.substr(combinator);
var el = this;
var match = $();
while (el.length && !match.length) {
el = el.prev();
if (!el.length) {
var par = el.parent();
// Don't use the parent - you've already checked all of the previous
// elements in this parent, move to its previous sibling, if any.
while (par.length && !par.prev().length) {
par = par.parent();
}
el = par.prev();
if (!el.length) {
break;
}
}
if (el.is(parent) && el.find(children).length) {
match = el.find(children).last();
}
else if (el.find(selector).length) {
match = el.find(selector).last();
}
}
return match;
}
})(jQuery);
Break leaves the loop completely and executes the statements after the loop. Whereas Continue leaves the current iteration and executes with the next value in the loop.
This Code Explains Everything :
public static void main(String[] args) {
for(int i=0;i<10;i++)
{
if (i==4)
{
break;
}
System.out.print(i+"\t");
}
System.out.println();
for(int i=0;i<10;i++)
{
if (i==4)
{
continue;
}
System.out.print(i+"\t");
}
}
Output:
0 1 2 3
0 1 2 3 5 6 7 8 9
I did it with transparent *.cur 1px to 1px, but it looks like small dot. :( I think it's the best cross-browser thing that I can do. CSS2.1 has no value 'none' for 'cursor' property - it was added in CSS3. Thats why it's workable not everywhere.
If you are just viewing the page output (not debugging code) then go to the Web.Config file and set debug to false. This changes load time from >15 secs to <1 sec
<system.web>
<compilation debug="false" strict="false" explicit="true" targetFramework="4.0" />
...
</system.web>
My problem is that when i use https for the remote URL, it doesn't work, so I use http instead. This allows me to publish/sync with GitHub from Team Explorer instantly.
The blocksize is usually selected to maximize the "occupancy". Search on CUDA Occupancy for more information. In particular, see the CUDA Occupancy Calculator spreadsheet.
The other answers explain why, but here is how.
Given an instance of Random
:
Random r = new Random(-229985452)
The first 6 numbers that r.nextInt(27)
generates are:
8
5
12
12
15
0
and the first 6 numbers that r.nextInt(27)
generates given Random r = new Random(-147909649)
are:
23
15
18
12
4
0
Then just add those numbers to the integer representation of the character `
(which is 96):
8 + 96 = 104 --> h
5 + 96 = 101 --> e
12 + 96 = 108 --> l
12 + 96 = 108 --> l
15 + 96 = 111 --> o
23 + 96 = 119 --> w
15 + 96 = 111 --> o
18 + 96 = 114 --> r
12 + 96 = 108 --> l
4 + 96 = 100 --> d
I'm using version 4.4.2 and none of the other answers worked for me. But adding useMongoClient
to the options and putting it into a variable that you call close
on seemed to work.
var db = mongoose.connect('mongodb://localhost:27017/somedb', { useMongoClient: true })
//do stuff
db.close()
To set short tags to open from a Vagrant install script on Ubuntu:
sed -i "s/short_open_tag = .*/short_open_tag = On/" /etc/php5/apache2/php.ini
I know this is an old question, but I stumbled across it when I was having a similar issue, and just wanted to share how I ended achieving the results you requested so future people can pick what works best for their situation.
First, I utilize the onsubmit
event in the form, and pass this
to the function to make it easier to deal with this particular form.
<form action="/system/wpacert" onsubmit="return closeSelf(this);" method="post" enctype="multipart/form-data" name="certform">
<div>Certificate 1: <input type="file" name="cert1"/></div>
<div>Certificate 2: <input type="file" name="cert2"/></div>
<div>Certificate 3: <input type="file" name="cert3"/></div>
<div><input type="submit" value="Upload"/></div>
</form>
In our function, we'll submit the form data, and then we'll close the window. This will allow it to submit the data, and once it's done, then it'll close the window and return you to your original window.
<script type="text/javascript">
function closeSelf (f) {
f.submit();
window.close();
}
</script>
Hope this helps someone out. Enjoy!
Option 2: This option will let you submit via AJAX, and if it's successful, it'll close the window. This prevents windows from closing prior to the data being submitted. Credits to http://jquery.malsup.com/form/ for their work on the jQuery Form Plugin
First, remove your onsubmit/onclick events from the form/submit button. Place an ID on the form so AJAX can find it.
<form action="/system/wpacert" method="post" enctype="multipart/form-data" id="certform">
<div>Certificate 1: <input type="file" name="cert1"/></div>
<div>Certificate 2: <input type="file" name="cert2"/></div>
<div>Certificate 3: <input type="file" name="cert3"/></div>
<div><input type="submit" value="Upload"/></div>
</form>
Second, you'll want to throw this script at the bottom, don't forget to reference the plugin. If the form submission is successful, it'll close the window.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function () {
$('#certform').ajaxForm(function () {
window.close();
});
});
</script>
You could always use CSS to simply adjust the width and the height of those elements that you want to do a colspan
and rowspan
and then simply omit displaying the overlapped DIVs. For example:
<div class = 'td colspan3 rowspan5'> Some data </div>
<style>
.td
{
display: table-cell;
}
.colspan3
{
width: 300px; /*3 times the standard cell width of 100px - colspan3 */
}
.rowspan5
{
height: 500px; /* 5 times the standard height of a cell - rowspan5 */
}
</style>
I solved this problem temporary by disabling the dfs permission.By adding below property code to conf/hdfs-site.xml
<property>
<name>dfs.permissions</name>
<value>false</value>
</property>
I have same issue ... at http://www.xaluan.com .. but after log. I find out that after jQuery run I make a function using one element id which not exists ..
Eg:
$('#aaa').remove() <span class="aaa">sss</spam>
so the id="aaa"
did not exist .. then jQuery stops running.. because errors like that
The solution below is interesting because it can be applied across multiple elements concomitantly and does not trigger an error when the element no longer exists on the page. The secret is that it is called passing as a parameter a function in which you must return the elements you want to be affected by the blink. Then this function is called back with each blink. HTML file below:
<!doctype>
<html>
<head>
<style>
.blink {color: red}
</style>
</head>
<body>
<h1>Blink test</h1>
<p>
Brazil elected President <span class="blink">Bolsonaro</span> because he
was the only candidate who did not promise <span class="blink">free things</span>
to the population. Previous politicians created an image that would
bring many benefits, but in the end, the state has been getting more and
more <span class="blink">burdened</span>. Brazil voted for the
realistic idea that <span class="blink">there is no free lunch</span>.
</p>
</body>
<script>
var blink =
{
interval_in_miliseconds:
400,
on:
true,
function_wich_returns_the_elements:
[],
activate:
function(function_wich_returns_the_elements)
{
this.function_wich_returns_the_elements = function_wich_returns_the_elements;
setInterval(blink.change, blink.interval_in_miliseconds);
},
change:
function()
{
blink.on = !blink.on;
var i, elements = [];
for (i in blink.function_wich_returns_the_elements)
{
elements = elements.concat(blink.function_wich_returns_the_elements[i]());
}
for (i in elements)
{
if (elements[i])
{
elements[i].style.opacity = blink.on ? 1 : .2;
}
}
}
};
blink.activate
(
[
function()
{
var
i,
node_collection = document.getElementsByClassName('blink'),
elements = [];
for (i = 0; i < node_collection.length; i++)
{
elements.push(node_collection[i]);
}
return elements;
}
]
);
</script>
</html>
var promise = $interval(function(){
if($location.path() == '/landing'){
$rootScope.$emit('testData',"test");
$interval.cancel(promise);
}
},2000);
Are you using HTML5? If so, check whether you have any <input type="hidden">
in your form with the property required
. Remove that required
property. Internet Explorer won't take this property, so it works but Chrome will.
I'm using Notepad 7.6 with "Plugin Admin" and I could not find XML Tools.
I had to install it manually like @some-java-guy did in his answer except that my plugins folder was located here: C:\Users\<my username>\AppData\Local\Notepad++\plugins
In that directory I created a new directory (named XmlTools) and copied XMLTools.dll there. (And I copied all dependencies to the Notepad++ directory in Program files.)
The answer from @KM is good as far as it goes but fails to fully follow up on one of his early bits of advice;
..., ignore compact code, ignore worrying about repeating code, ...
If you are looking to achieve the best performance then you should write a bespoke query for each possible combination of optional criteria. This might sound extreme, and if you have a lot of optional criteria then it might be, but performance is often a trade-off between effort and results. In practice, there might be a common set of parameter combinations that can be targeted with bespoke queries, then a generic query (as per the other answers) for all other combinations.
CREATE PROCEDURE spDoSearch
@FirstName varchar(25) = null,
@LastName varchar(25) = null,
@Title varchar(25) = null
AS
BEGIN
IF (@FirstName IS NOT NULL AND @LastName IS NULL AND @Title IS NULL)
-- Search by first name only
SELECT ID, FirstName, LastName, Title
FROM tblUsers
WHERE
FirstName = @FirstName
ELSE IF (@FirstName IS NULL AND @LastName IS NOT NULL AND @Title IS NULL)
-- Search by last name only
SELECT ID, FirstName, LastName, Title
FROM tblUsers
WHERE
LastName = @LastName
ELSE IF (@FirstName IS NULL AND @LastName IS NULL AND @Title IS NOT NULL)
-- Search by title only
SELECT ID, FirstName, LastName, Title
FROM tblUsers
WHERE
Title = @Title
ELSE IF (@FirstName IS NOT NULL AND @LastName IS NOT NULL AND @Title IS NULL)
-- Search by first and last name
SELECT ID, FirstName, LastName, Title
FROM tblUsers
WHERE
FirstName = @FirstName
AND LastName = @LastName
ELSE
-- Search by any other combination
SELECT ID, FirstName, LastName, Title
FROM tblUsers
WHERE
(@FirstName IS NULL OR (FirstName = @FirstName))
AND (@LastName IS NULL OR (LastName = @LastName ))
AND (@Title IS NULL OR (Title = @Title ))
END
The advantage of this approach is that in the common cases handled by bespoke queries the query is as efficient as it can be - there's no impact by the unsupplied criteria. Also, indexes and other performance enhancements can be targeted at specific bespoke queries rather than trying to satisfy all possible situations.
For those using homebrew you might fix this with:
$ brew link mysql
I encountered this same issue.
What solved it for me was to switch to another branch and then back to the original one.
Not sure what the underline cause was, but this fixed it.
Those types are there so that you can create arrays of the primitives, and not the boxed types. Since String isn't a primitive in Java, you can just use Array<String>
in Kotlin as the equivalent of a Java String[]
.
Update3: 06.2019 Some of the comments says that the answer is not clear, I'll try to clarify.
TL;DR:
Q: Can Windows containers run on Linux?
A: No. They cannot. Containers are using the underlying Operating System resources and drivers, so Windows containers can run on Windows only, and Linux containers can run on Linux only.
Q: But what about Docker for Windows? Or other VM-based solutions?
A: Docker for Windows allows you to simulate running Linux containers on Windows, but under the hood a Linux VM is created, so still Linux containers are running on Linux, and Windows containers are running on Windows.
Bonus: Read this very nice article about running Linux docker containers on Windows.
Q: So, what should I do with a .Net Framework 462 app, if I would like to run in a container?
A: It depends. Following several recommendations:
If you cannot migrate to .Net Core - As @Sebastian mentioned - you can convert your libraries to .Net Standard, and have 2 versions of app - one on .Net Framework 4.6.2, and one on .Net Core - it is not always obvious, Visual Studio supports it pretty well (with multi-targeting), but some dependencies can require extra care.
(Less recommended) In some cases, you can run windows containers. Windows containers are becoming more and more mature, with better support in platforms like Kubernetes. But to be able to run .Net Framework code, you still need to run on base image of "Server Core", which occupies about 1.4 GB. In same rare cases, you can migrate your code to .Net Core, but still run on Windows Nano servers, with an image size of 95 MB.
Leaving also the old updates for history
Update2: 08.2018 If you are using Docker-for-Windows, you can run now both windows and linux containers simultaneously: https://blogs.msdn.microsoft.com/premier_developer/2018/04/20/running-docker-windows-and-linux-containers-simultaneously/
Bonus: Not directly related to the question, but you can now run not only the linux container itself, but also orchestrator like kubernetes: https://blog.docker.com/2018/07/kubernetes-is-now-available-in-docker-desktop-stable-channel/
Updated at 2018:
Original answer in general is right, BUT several months ago, docker added experimental feature LCOW (official github repository).
From this post:
Doesn’t Docker for Windows already run Linux containers? That’s right. Docker for Windows can run Linux or Windows containers, with support for Linux containers via a Hyper-V Moby Linux VM (as of Docker for Windows 17.10 this VM is based on LinuxKit).
The setup for running Linux containers with LCOW is a lot simpler than the previous architecture where a Hyper-V Linux VM runs a Linux Docker daemon, along with all your containers. With LCOW, the Docker daemon runs as a Windows process (same as when running Docker Windows containers), and every time you start a Linux container Docker launches a minimal Hyper-V hypervisor running a VM with a Linux kernel, runc and the container processes running on top.
Because there’s only one Docker daemon, and because that daemon now runs on Windows, it will soon be possible to run Windows and Linux Docker containers side-by-side, in the same networking namespace. This will unlock a lot of exciting development and production scenarios for Docker users on Windows.
Original:
As mentioned in comments by @PanagiotisKanavos, containers are not for virtualization, and they are using the resources of the host machine. As a result, for now windows container cannot run "as-is" on linux machine.
But - you can do it by using VM - as it works on windows. You can install windows VM on your linux host, which will allow to run windows containers.
With it, IMHO run it this way on PROD environment will not be the best idea.
Also, this answer provides more details.
If you dont want to merge the changes and still want to update your local then run:
git reset --hard HEAD
This will reset your local with HEAD and then pull your remote using git pull.
If you've already committed your merge locally (but haven't pushed to remote yet), and want to revert it as well:
git reset --hard HEAD~1
This is expected behavior for an uncaught exception with display_errors off.
Your options here are to turn on display_errors via php or in the ini file or catch and output the exception.
ini_set("display_errors", 1);
or
try{
// code that may throw an exception
} catch(Exception $e){
echo $e->getMessage();
}
If you are throwing exceptions, the intention is that somewhere further down the line something will catch and deal with it. If not it is a server error (500).
Another option for you would be to use set_exception_handler to set a default error handler for your script.
function default_exception_handler(Exception $e){
// show something to the user letting them know we fell down
echo "<h2>Something Bad Happened</h2>";
echo "<p>We fill find the person responsible and have them shot</p>";
// do some logging for the exception and call the kill_programmer function.
}
set_exception_handler("default_exception_handler");
Function inside function: we can use the function as parameter too..
In other words, we can say an output of a function is also a reference for an object, see below how the output of inner function is referencing to the outside function like below..
def out_func(a):
def in_func(b):
print(a + b + b + 3)
return in_func
obj = out_func(1)
print(obj(5))
the result will be.. 14
Hope this helps.
If you are using jquery on your project, and do not want to implement the upload mechanism from scratch, you can use https://github.com/blueimp/jQuery-File-Upload.
They have a very nice api with multiple file selection, drag&drop support, progress bar, validation and preview images, cross-domain support, chunked and resumable file uploads. And they have sample scripts for multiple server languages(node, php, python and go).
If you are using laravel
5 or 6:
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link src="/images/test.png">
<!-- / is important and dont write public folder-->
_x000D_
Okay you got the syntax wrong here, correct way to do this is:
var arr: Criminal[] = [];
I'm assuming you are using var so that means declaring it somewhere inside the func()
,my suggestion would be use let
instead of var
.
If declaring it as c class property usse acces modifiers like private, public, protected.
If you are referring to the System.Net.HttpClient in .NET 4.5, you can get the content returned by GetAsync using the HttpResponseMessage.Content property as an HttpContent-derived object. You can then read the contents to a string using the HttpContent.ReadAsStringAsync method or as a stream using the ReadAsStreamAsync method.
The HttpClient class documentation includes this example:
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
I have been working on to write a custom module in Drupal 7 and got the same error:
Notice: Trying to get property of non-object
My code is something like this:
function example_node_access($node, $op, $account) {
if ($node->type == 'page' && $op == 'update') {
drupal_set_message('This poll has been published, you may not make changes to it.','error');
return NODE_ACCESS_DENY;
}
}
Solution:
I just added a condition if (is_object($sqlResult))
, and everything went fine.
Here is my final code:
function mediaten_node_access($node, $op, $account) {
if (is_object($node)){
if ($node->type == 'page' && $op == 'update') {
drupal_set_message('This poll has been published, you may not make changes.','error');
return NODE_ACCESS_DENY;
}
}
}
The short version
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://almondmendoza.com/android-applications/")));
should work as well...
You can try the following:
gitk --all
You can tell gitk
what to display using anything that git rev-list
understands, so if you just want a few branches, you can do:
gitk master origin/master origin/experiment
... or more exotic things like:
gitk --simplify-by-decoration --all
Right click on the project --> New --> Other --> Standard Deployment Descriptor(web.xml)
then press Next it will create WEB-INF
folder with a web.xml
file inside.
That's it done.
You can use the following code to check if a textbox object is null/empty
'Checks if the box is null
If Me.TextBox & "" <> "" Then
'Enter Code here...
End if
Short explanation looks like:
If you having troubles with interpreting results you could try BM.Sense results analysis service
Print lines where the third field is either snow
or snowman
only:
awk '$3~/^snow(man)?$/' file
Nobody mentioned it, but you can also simply use loc
with the index and column labels.
df.loc[2, 'Letters']
# 'C'
Or, if you prefer to use "Numbers" column as reference, you can also set is as an index.
df.set_index('Numbers').loc[3, 'Letters']
To clarify, the above example does work, my code in the example did not work for unrelated reasons.
If myvar is false, null or has never been used before (i.e. $scope.myvar or $rootScope.myvar never called), the div will not show. Once any value has been assigned to it, the div will show, except if the value is specifically false.
The following will cause the div to show:
$scope.myvar = "Hello World";
or
$scope.myvar = true;
The following will hide the div:
$scope.myvar = null;
or
$scope.myvar = false;
Postman doesn't support websocket. Most of the extension and app I had ever seen were not working properly.
Solution which I found
Just login/ open your application in your browser, and open browser console. Then enter your socket event, and press enter.
socket.emit("event_name", {"id":"123"}, (res)=>{console.log(res); });
There seems to be a lot of confusion here (also) in the answers.
git submodule init
is not intended to magically generate stuff in .git/config (from .gitmodules). It is intended to set up something in an entirely empty subdirectory after cloning the parent project, or pulling a commit that adds a previously non-existing submodule.
In other words, you follow a git clone
of a project that has submodules (which you will know by the fact that the clone checked out a .gitmodules file) by a git submodule update --init --recursive
.
You do not follow git submodule add ...
with a git submodule init
(or git submodule update --init
), that isn't supposed to work. In fact, the add will already update the appropriate .git/config if things work.
EDIT
If a previously non-existing git submodule was added by someone else, and you do a git pull
of that commit, then the directory of that submodule will be entirely empty (when you execute git submodule status
the new submodule's hash should be visible but will have a -
in front of it.) In this case you need to follow your git pull
also with a git submodule update --init
(plus --recursive
when it's a submodule inside a submodule) in order to get the new, previously non-existing, submodule checked out; just like after an initial clone of a project with submodules (where obviously you didn't have those submodules before either).
Here a completely working example
package main
import (
// Standard library packages
"fmt"
"strconv"
"log"
"net"
"net/http"
// Third party packages
"github.com/julienschmidt/httprouter"
"github.com/skratchdot/open-golang/open"
)
// https://blog.golang.org/context/userip/userip.go
func getIP(w http.ResponseWriter, req *http.Request, _ httprouter.Params){
fmt.Fprintf(w, "<h1>static file server</h1><p><a href='./static'>folder</p></a>")
ip, port, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
//return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)
fmt.Fprintf(w, "userip: %q is not IP:port", req.RemoteAddr)
}
userIP := net.ParseIP(ip)
if userIP == nil {
//return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)
fmt.Fprintf(w, "userip: %q is not IP:port", req.RemoteAddr)
return
}
// This will only be defined when site is accessed via non-anonymous proxy
// and takes precedence over RemoteAddr
// Header.Get is case-insensitive
forward := req.Header.Get("X-Forwarded-For")
fmt.Fprintf(w, "<p>IP: %s</p>", ip)
fmt.Fprintf(w, "<p>Port: %s</p>", port)
fmt.Fprintf(w, "<p>Forwarded for: %s</p>", forward)
}
func main() {
myport := strconv.Itoa(10002);
// Instantiate a new router
r := httprouter.New()
r.GET("/ip", getIP)
// Add a handler on /test
r.GET("/test", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
// Simply write some test data for now
fmt.Fprint(w, "Welcome!\n")
})
l, err := net.Listen("tcp", "localhost:" + myport)
if err != nil {
log.Fatal(err)
}
// The browser can connect now because the listening socket is open.
//err = open.Start("http://localhost:"+ myport + "/test")
err = open.Start("http://localhost:"+ myport + "/ip")
if err != nil {
log.Println(err)
}
// Start the blocking server loop.
log.Fatal(http.Serve(l, r))
}
Another way to address the timezone issue if you want to set the default timezone for the entire script to a certian timezone is to use
date_default_timezone_set()
then use one of the supported timezones.
>>> for line in s.splitlines():
... line = line.strip()
... if not line:continue
... ary.append(line.split(":"))
...
>>> ary
[['Name', ' John Smith'], ['Home', ' Anytown USA'], ['Misc', ' Data with spaces'
]]
>>> dict(ary)
{'Home': ' Anytown USA', 'Misc': ' Data with spaces', 'Name': ' John Smith'}
>>>
For me, I'm sure mysqld is started, and command line mysql can work properly. But the httpd server show the issue(can't connect to mysql through socket).
finally, I found when I start the mysqld service with service mysqld start, there are issues(selinux permission issue), and when I fix the selinux issue, and start the mysqld with "service mysqld start", the httpd connection issue disappear. But when I start the mysqld with mysqld_safe&, mysqld can be worked. (mysql client can work properly). But there are still issue when connect with httpd.
I was getting similar problem for other reason (url pattern test-response
not added in csrf token)
I resolved it by allowing my URL pattern in following property in config/local.properties
:
csrf.allowed.url.patterns = /[^/]+(/[^?])+(sop-response)$,/[^/]+(/[^?])+(merchant_callback)$,/[^/]+(/[^?])+(hop-response)$
modified to
csrf.allowed.url.patterns = /[^/]+(/[^?])+(sop-response)$,/[^/]+(/[^?])+(merchant_callback)$,/[^/]+(/[^?])+(hop-response)$,/[^/]+(/[^?])+(test-response)$
Update
If your popover is going to have a selector that is consistent then you can make use of selector
property of popover constructor.
var popOverSettings = {
placement: 'bottom',
container: 'body',
html: true,
selector: '[rel="popover"]', //Sepcify the selector here
content: function () {
return $('#popover-content').html();
}
}
$('body').popover(popOverSettings);
Other ways:
Mutation Event
/Mutation Observer
to identify if a particular element has been inserted on to the ul
or an element.var popOverSettings = { //Save the setting for later use as well
placement: 'bottom',
container: 'body',
html: true,
//content:" <div style='color:red'>This is your div content</div>"
content: function () {
return $('#popover-content').html();
}
}
$('ul').on('DOMNodeInserted', function () { //listed for new items inserted onto ul
$(event.target).popover(popOverSettings);
});
$("button[rel=popover]").popover(popOverSettings);
$('.pop-Add').click(function () {
$('ul').append("<li class='project-name'> <a>project name 2 <button class='pop-function' rel='popover'></button> </a> </li>");
});
But it is not recommended to use DOMNodeInserted Mutation Event for performance issues as well as support. This has been deprecated as well. So your best bet would be to save the setting and bind after you update with new element.
Another recommended way is to use MutationObserver instead of MutationEvent according to MDN, but again support in some browsers are unknown and performance a concern.
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
// create an observer instance
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
$(mutation.addedNodes).popover(popOverSettings);
});
});
// configuration of the observer:
var config = {
attributes: true,
childList: true,
characterData: true
};
// pass in the target node, as well as the observer options
observer.observe($('ul')[0], config);
public boolean isAlertPresent() {
try
{
driver.switchTo().alert();
system.out.println(" Alert Present");
}
catch (NoAlertPresentException e)
{
system.out.println("No Alert Present");
}
}
Try this command, it will help you to get ipaddress
adb shell ifconfig tiwlan0
tiwlan0 is the name of the wi-fi network interface on the device. This is generic command for getting ipaddress,
adb shell netcfg
It will output like this
usb0 DOWN 0.0.0.0 0.0.0.0 0×00001002
sit0 DOWN 0.0.0.0 0.0.0.0 0×00000080
ip6tnl0 DOWN 0.0.0.0 0.0.0.0 0×00000080
gannet0 DOWN 0.0.0.0 0.0.0.0 0×00001082
rmnet0 UP 112.79.87.220 255.0.0.0 0x000000c1
rmnet1 DOWN 0.0.0.0 0.0.0.0 0×00000080
rmnet2 DOWN 0.0.0.0 0.0.0.0 0×00000080
You can do this with the additional effects in jQuery UI: See here for details
Quick example:
$(this).hide("slide", { direction: "left" }, 1000);
$(this).show("slide", { direction: "left" }, 1000);
You can use the bind function to set the context of this
within a function.
function myFunc() {
console.log(this.str)
}
const myContext = {str: "my context"}
const boundFunc = myFunc.bind(myContext);
boundFunc(); // "my context"
Add: now you can use lambda to simplify your syntax. Requirement: Java 8+
public class A {
public static void main(String[] arg)
{
Thread th = new Thread(() -> {System.out.println("blah");});
th.start();
}
}
There is no way to protect image downloading. This is because the image has to be downloaded by the browser for it to be seen by the user. There are tricks (like the transparent background you specified) to restrict certain operations like image right click and saving to browser cache folder, but there isn't a way for truly protecting the images.
This one worked for me, try this
[RegularExpression("^[a-zA-Z &\-@.]*$", ErrorMessage = "--Your Message--")]
A developer recently added subtitle support to VideoView.
When the MediaPlayer
starts playing a music (or other source), it checks if there is a SubtitleController and shows this message if it's not set.
It doesn't seem to care about if the source you want to play is a music or video. Not sure why he did that.
Short answer: Don't care about this "Exception".
Edit :
Still present in Lollipop,
If MediaPlayer
is only used to play audio files and you really want to remove these errors in the logcat, the code bellow set an empty SubtitleController
to the MediaPlayer
.
It should not be used in production environment and may have some side effects.
static MediaPlayer getMediaPlayer(Context context){
MediaPlayer mediaplayer = new MediaPlayer();
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
return mediaplayer;
}
try {
Class<?> cMediaTimeProvider = Class.forName( "android.media.MediaTimeProvider" );
Class<?> cSubtitleController = Class.forName( "android.media.SubtitleController" );
Class<?> iSubtitleControllerAnchor = Class.forName( "android.media.SubtitleController$Anchor" );
Class<?> iSubtitleControllerListener = Class.forName( "android.media.SubtitleController$Listener" );
Constructor constructor = cSubtitleController.getConstructor(new Class[]{Context.class, cMediaTimeProvider, iSubtitleControllerListener});
Object subtitleInstance = constructor.newInstance(context, null, null);
Field f = cSubtitleController.getDeclaredField("mHandler");
f.setAccessible(true);
try {
f.set(subtitleInstance, new Handler());
}
catch (IllegalAccessException e) {return mediaplayer;}
finally {
f.setAccessible(false);
}
Method setsubtitleanchor = mediaplayer.getClass().getMethod("setSubtitleAnchor", cSubtitleController, iSubtitleControllerAnchor);
setsubtitleanchor.invoke(mediaplayer, subtitleInstance, null);
//Log.e("", "subtitle is setted :p");
} catch (Exception e) {}
return mediaplayer;
}
This code is trying to do the following from the hidden API
SubtitleController sc = new SubtitleController(context, null, null);
sc.mHandler = new Handler();
mediaplayer.setSubtitleAnchor(sc, null)
change your Production.rb file line
config.assets.compile = false
into
config.assets.compile = true
and also add
config.assets.precompile = ['*.js', '*.css', '*.css.erb']
String[] a= {"tube", "are", "fun"};
Arrays.asList(a).contains("any");
This worked for me:
Note, you can also highlight multiple objects at the same time, so you could generate one script that contains create statements for all tables within the database.
::selection {background: transparent; color: transparent;}
::-moz-selection {background: transparent; color: transparent;}
^\d+(\.\d{1,2})?$
will allow:
244
10.89
9.5
will disallow:
10.895
10.
10.8.9
As this took me forever to figure out using the new window.getSelection API I am going to share for posterity. Note that MDN suggests there is wider support for window.getSelection, however, your mileage may vary.
const getSelectionCaretAndLine = () => {
// our editable div
const editable = document.getElementById('editable');
// collapse selection to end
window.getSelection().collapseToEnd();
const sel = window.getSelection();
const range = sel.getRangeAt(0);
// get anchor node if startContainer parent is editable
let selectedNode = editable === range.startContainer.parentNode
? sel.anchorNode
: range.startContainer.parentNode;
if (!selectedNode) {
return {
caret: -1,
line: -1,
};
}
// select to top of editable
range.setStart(editable.firstChild, 0);
// do not use 'this' sel anymore since the selection has changed
const content = window.getSelection().toString();
const text = JSON.stringify(content);
const lines = (text.match(/\\n/g) || []).length + 1;
// clear selection
window.getSelection().collapseToEnd();
// minus 2 because of strange text formatting
return {
caret: text.length - 2,
line: lines,
}
}
Here is a jsfiddle that fires on keyup. Note however, that rapid directional key presses, as well as rapid deletion seems to be skip events.
If you still want to print you can import future module
from __future__ import print_function
f = lambda x: print(x) if x%2 == 0 else False
Fiddle of my solution is here. But just in case it expires I will paste the code as well.
HTML:
<select id="sel">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
<input type="button" id="button" value="Change option to 2" />
JS:
var sel = document.getElementById('sel'),
button = document.getElementById('button');
button.addEventListener('click', function (e) {
sel.options[1].selected = true;
// firing the event properly according to StackOverflow
// http://stackoverflow.com/questions/2856513/how-can-i-trigger-an-onchange-event-manually
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
sel.dispatchEvent(evt);
}
else {
sel.fireEvent("onchange");
}
});
sel.addEventListener('change', function (e) {
alert('changed');
});
$options = array(
'options' => array('min_range' => 0)
);
if (filter_var($int, FILTER_VALIDATE_INT, $options) !== FALSE) {
// you're good
}
I know is quite old, but I'll say just for the sake of it - I was looking for the same problem and got here, but I needed the difference in days.
I used SELECT (UNIX_TIMESTAMP(DATE1) - UNIX_TIMESTAMP(DATE2))/60/60/24
Unix_timestamp returns the difference in seconds, and then I just divide into minutes(seconds/60), hours(minutes/60), days(hours/24).
Can't be done in pure HTML/JavaScript for security reasons.
Selecting a file for upload is the best you can do, and even then you won't get its full original path in modern browsers.
You may be able to put something together using Java or Flash (e.g. using SWFUpload as a basis), but it's a lot of work and brings additional compatibility issues.
Another thought would be opening an iframe
showing the user's C:
drive (or whatever) but even if that's possible nowadays (could be blocked for security reasons, haven't tried in a long time) it will be impossible for your web site to communicate with the iframe (again for security reasons).
What do you need this for?
If you aren't going to upload this to the App Store, you can also use a private method of UIView.
@interface UIView(Private)
- (UIViewController *)_viewControllerForAncestor;
@end
// Later in the code
UIViewController *vc = [myView _viewControllerForAncestor];
You can also select your default terminal by pressing F1 in VS Code and typing/selecting Terminal: Select Default Shell.
You might find useful microsoft msdn article How To: Use Regular Expressions to Constrain Input in ASP.NET. Take a look at "Common Regular Expressions" Table. It has validation example for
Non- negative integer
^\d+$
This expression validates that the field contains an integer greater than zero.
Locate the installation path of GlassFish. Then move to domains/domain-dir/logs/
and you'll find there the log files. If you have created the domain with NetBeans, the domain-dir is most probably called domain1
.
See this link for the official GlassFish documentation about logging.
A naive, CPU-intensive method to block execution for a number of milliseconds:
/**
* Delay for a number of milliseconds
*/
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
You can import one of them using import. For all other similar class , you need to specify Fully qualified class names. Otherwise you will get compilation error.
Eg:
import java.util.Date;
class Test{
public static void main(String [] args){
// your own date
my.own.Date myOwndate ;
// util.Date
Date utilDate;
}
}
It's quite easy. Just write this, for example:
npm install -g [email protected]
Or:
npm install -g npm@latest // For the last stable version
npm install -g npm@next // For the most recent release
Just verify...
function wopen_close(){
var w = window.open($url, '_blank', 'width=600, height=400, scrollbars=no, status=no, resizable=no, screenx=0, screeny=0');
w.onunload = function(){
if (window.closed) {
alert("window closed");
}else{
alert("just refreshed");
}
}
}
You can link directly with Media Fragments URI, just change the filename to file.webm#t=50
This is pretty cool, you can do all sorts of things. But I don't know the current state of browser support.
I know this is very late, but is useful for newbies. We can atuload url helper and it will be available throughout the application. For this in application\config\autoload.php modify as follows -
$autoload['helper'] = array('url');
You cannot do new T()
due to type erasure. The default constructor can only be
public Navigation() { this("", "", null); }
You can create other constructors to provide default values for trigger and description. You need an concrete object of T
.
Basically you want to join two tables together where their QID columns are both not null, correct? However, you aren't enforcing any other conditions, such as that the two QID values (which seems strange to me, but ok). Something as simple as the following (tested in MySQL) seems to do what you want:
SELECT * FROM `Y` INNER JOIN `X` ON (`Y`.`QID` IS NOT NULL AND `X`.`QID` IS NOT NULL);
This gives you every non-null row in Y joined to every non-null row in X.
Update: Rico says he also wants the rows with NULL values, why not just:
SELECT * FROM `Y` INNER JOIN `X`;
I use do-while loops all the time when reading in files. I work with a lot of text files that include comments in the header:
# some comments
# some more comments
column1 column2
1.234 5.678
9.012 3.456
... ...
i'll use a do-while loop to read up to the "column1 column2" line so that I can look for the column of interest. Here's the pseudocode:
do {
line = read_line();
} while ( line[0] == '#');
/* parse line */
Then I'll do a while loop to read through the rest of the file.