You can have a regular Python module, say config.py, like this:
truck = dict(
color = 'blue',
brand = 'ford',
)
city = 'new york'
cabriolet = dict(
color = 'black',
engine = dict(
cylinders = 8,
placement = 'mid',
),
doors = 2,
)
and use it like this:
import config
print(config.truck['color'])
You can do something like this to disable submit button when loading a new page with the same form:
$("#btnConfirm").bind("click", function (e) {
$("#btnConfirm ").css("pointer-events", "none");
});
The submit button could look like this:
<input
type="submit"
name="ACMS_POST_Form_Confirm"
value="confirm"
id="btnConfirm"
/>
Just for the sake of completeness, we can use the operators [
and [[
:
set.seed(1)
df <- data.frame(v1 = runif(10), v2 = letters[1:10])
Several options
df[df[1] < 0.5 | df[2] == "g", ]
df[df[[1]] < 0.5 | df[[2]] == "g", ]
df[df["v1"] < 0.5 | df["v2"] == "g", ]
df$name is equivalent to df[["name", exact = FALSE]]
Using dplyr
:
library(dplyr)
filter(df, v1 < 0.5 | v2 == "g")
Using sqldf
:
library(sqldf)
sqldf('SELECT *
FROM df
WHERE v1 < 0.5 OR v2 = "g"')
Output for the above options:
v1 v2
1 0.26550866 a
2 0.37212390 b
3 0.20168193 e
4 0.94467527 g
5 0.06178627 j
Below Command where project
is a folder which contains package.json
file
npm run --prefix project ${COMMAND}
is working as well. Useful in Docker based applications.
INPUT
STRMIDDLENAME
--------------
Aravind Chaterjee
Shivakumar
Robin Van Parsee
SELECT STRMIDDLENAME,
CASE WHEN INSTR(STRMIDDLENAME,' ',1,2) != 0 THEN SUBSTR(STRMIDDLENAME,1,1) || SUBSTR(STRMIDDLENAME,INSTR(STRMIDDLENAME,' ',1,1)+1,1)||
SUBSTR(STRMIDDLENAME,INSTR(STRMIDDLENAME,' ',1,2)+1,1)
WHEN INSTR(STRMIDDLENAME,' ',1,1) != 0 THEN SUBSTR(STRMIDDLENAME,1,1) || SUBSTR(STRMIDDLENAME,INSTR(STRMIDDLENAME,' ',1,1)+1,1)
ELSE SUBSTR(STRMIDDLENAME,1,1)
END AS FIRSTLETTERS
FROM Dual;
OUTPUT
STRMIDDLENAME FIRSTLETTERS
--------- -----------------
Aravind Chaterjee AC
Shivakumar S
Robin Van Parsee RVP
To adjust the length of the samples:
set key samplen X
(default is 4)
To adjust the vertical spacing of the samples:
set key spacing X
(default is 1.25)
and (for completeness), to adjust the fontsize:
set key font "<face>,<size>"
(default depends on the terminal)
And of course, all these can be combined into one line:
set key samplen 2 spacing .5 font ",8"
Note that you can also change the position of the key using set key at <position>
or any one of the pre-defined positions (which I'll just defer to help key
at this point)
This is a shot in the dark, but you might try shrinking the image and then enlarging it again. This can be done with Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)
. Make sure and set the filter parameter to true. It'll run in native code so it might be faster.
In Windows we need to run $git difftool --tool-help
command to see the various options like:
'git difftool --tool=<tool>' may be set to one of the following:
vimdiff
vimdiff2
vimdiff3
The following tools are valid, but not currently available:
araxis
bc
bc3
codecompare
deltawalker
diffmerge
diffuse
ecmerge
emerge
examdiff
gvimdiff
gvimdiff2
gvimdiff3
kdiff3
kompare
meld
opendiff
p4merge
tkdiff
winmerge
xxdiff
Some of the tools listed above only work in a windowed
environment. If run in a terminal-only session, they will fail.
and we can add any of them(for example winmerge) like
$ git difftool --tool=winmerge
For configuring notepad++ to see files before committing:
git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
and using $ git commit
will open the commit information in notepad++
README.md
or .mkdn
or .markdown
denotes that the file is markdown formatted.
Markdown is a markup language. With it you can easily display headers or have italic words, or bold or almost anything that can be done to text
The problem is that the position of the node doesn't mean much without a context.
The following code will give you the location of the node in its parent child nodes
using System;
using System.Xml;
public class XpathFinder
{
public static void Main(string[] args)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(args[0]);
foreach ( XmlNode xn in xmldoc.SelectNodes(args[1]) )
{
for (int i = 0; i < xn.ParentNode.ChildNodes.Count; i++)
{
if ( xn.ParentNode.ChildNodes[i].Equals( xn ) )
{
Console.Out.WriteLine( i );
break;
}
}
}
}
}
APC segfaults all day and all night, got no experience with eAccelerator but XCache is very reliable with loads of options and constant development.
Sometimes it takes longer to figure out the regex than to just write it out in python:
import string
s = "how much for the maple syrup? $20.99? That's ricidulous!!!"
for char in string.punctuation:
s = s.replace(char, ' ')
If you need other characters you can change it to use a white-list or extend your black-list.
Sample white-list:
whitelist = string.letters + string.digits + ' '
new_s = ''
for char in s:
if char in whitelist:
new_s += char
else:
new_s += ' '
Sample white-list using a generator-expression:
whitelist = string.letters + string.digits + ' '
new_s = ''.join(c for c in s if c in whitelist)
try this.. i had the same issue, below implementation worked for me
Reader reader = Files.newBufferedReader(Paths.get(<yourfilewithpath>), StandardCharsets.ISO_8859_1);
then use Reader where ever you want.
foreg:
CsvToBean<anyPojo> csvToBean = null;
try {
Reader reader = Files.newBufferedReader(Paths.get(csvFilePath),
StandardCharsets.ISO_8859_1);
csvToBean = new CsvToBeanBuilder(reader)
.withType(anyPojo.class)
.withIgnoreLeadingWhiteSpace(true)
.withSkipLines(1)
.build();
} catch (IOException e) {
e.printStackTrace();
}
i've successfully removed dependencies of a package using this bash line:
for dep in $(pip show somepackage | grep Requires | sed 's/Requires: //g; s/,//g') ; do pip uninstall -y $dep ; done
this worked on pip 1.5.4
I don't think you can detect the screen size purely with PHP but you can detect the user-agent..
<?php
if ( stristr($ua, "Mobile" )) {
$DEVICE_TYPE="MOBILE";
}
if (isset($DEVICE_TYPE) and $DEVICE_TYPE=="MOBILE") {
echo '<link rel="stylesheet" href="/css/mobile.css" />'
}
?>
Here's a link to a more detailed script: PHP Mobile Detect
Step 1
We need set format data in function date(): Function date() returns a string formatted according to the givenformat string using the given integer timestamp or the current time ifno timestamp is given. In other words, timestampis optional anddefaults to the value of time().
<?php
echo date("F j, Y");
?>
result: March 30, 2010
Step 2
For "yesterday" date use php function mktime(): Function mktime() returns the Unix timestamp corresponding to thearguments given. This timestamp is a long integer containing the numberof seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and thetime specified. Arguments may be left out in order from right to left; any argumentsthus omitted will be set to the current value according to the localdate and time.
<?php
echo mktime(0, 0, 0, date("m"), date("d")-1, date("Y"));
?>
result: 1269820800
Step 3
Now merge all and look at this:
<?php
$yesterday = date("Y-m-d", mktime(0, 0, 0, date("m") , date("d")-1,date("Y")));
echo $yesterday;
?>
result: March 29, 2010
Operating similarly, it is possible to receive time hour back.
<?php
$yesterday = date("H:i:s",mktime(date("H"), 0, 0, date("m"),date("d"), date("Y")));
echo $yesterday;
?>
result: 20:00:00
or 7 days ago:
<?php
$week = date("Y-m-d",mktime(0, 0, 0, date("m"), date("d")-7,date("Y")));
echo $week;
?>
result: 2010-03-23
Here is a Javascript solution (for folks like me who were looking for an answer to the title):
function SaveToDisk(fileURL, fileName) {
// for non-IE
if (!window.ActiveXObject) {
var save = document.createElement('a');
save.href = fileURL;
save.target = '_blank';
save.download = fileName || 'unknown';
var evt = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
});
save.dispatchEvent(evt);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
}
// for IE < 11
else if ( !! window.ActiveXObject && document.execCommand) {
var _window = window.open(fileURL, '_blank');
_window.document.close();
_window.document.execCommand('SaveAs', true, fileName || fileURL)
_window.close();
}
}
source: http://muaz-khan.blogspot.fr/2012/10/save-files-on-disk-using-javascript-or.html
Unfortunately the working for me with IE11, which is not accepting new MouseEvent. I use the following in that case:
//...
try {
var evt = new MouseEvent(...);
} catch (e) {
window.open(fileURL, fileName);
}
//...
QRGen is a good library that creates a layer on top of ZXing and makes QR Code generation in Java a piece of cake.
Just to add another option to Dónal's answer, you can also still use the good old java.lang.Object.getClass()
method.
You can put an <a>
element inside the <div>
and set it to display: block
and height: 100%
.
Quoting text from Apple's Technical Note on Unwind Segue: To add an unwind segue that will only be triggered programmatically, control+drag from the scene's view controller icon to its exit icon, then select an unwind action for the new segue from the popup menu.
Here is a very rushed proof of concept.
I'm sure there are at least 2 places where there can be improvements, and I'm also sure that this would not survive long in the wild. Any feedback to make it more presentable or usable is welcome.
The key is setting an id for your script element. The only catch is that this means you can only call the script once since it looks for that ID to pull the query string. This could be fixed if, instead, the script loops through all query elements to see if any of them point to it, and if so, uses the last instance of such an script element. Anyway, on with the code:
window.onload = function() {
//Notice that both possible parameters are pre-defined.
//Which is probably not required if using proper object notation
//in query string, or if variable-variables are possible in js.
var header;
var text;
//script gets the src attribute based on ID of page's script element:
var requestURL = document.getElementById("myScript").getAttribute("src");
//next use substring() to get querystring part of src
var queryString = requestURL.substring(requestURL.indexOf("?") + 1, requestURL.length);
//Next split the querystring into array
var params = queryString.split("&");
//Next loop through params
for(var i = 0; i < params.length; i++){
var name = params[i].substring(0,params[i].indexOf("="));
var value = params[i].substring(params[i].indexOf("=") + 1, params[i].length);
//Test if value is a number. If not, wrap value with quotes:
if(isNaN(parseInt(value))) {
params[i] = params[i].replace(value, "'" + value + "'");
}
// Finally, use eval to set values of pre-defined variables:
eval(params[i]);
}
//Output to test that it worked:
document.getElementById("docTitle").innerHTML = header;
document.getElementById("docText").innerHTML = text;
};
<script id="myScript" type="text/javascript"
src="test.js?header=Test Page&text=This Works"></script>
<h1 id="docTitle"></h1>
<p id="docText"></p>
Perhaps what you are looking for is something like this:
x=np.array(0)
In this way you can create an array without any element. It similar than:
x=[]
This way you will be able to append new elements to your array in advance.
<?php
// Initialize the session.
session_start();
// Unset all of the session variables.
unset($_SESSION['username']);
// Finally, destroy the session.
session_destroy();
// Include URL for Login page to login again.
header("Location: login.php");
exit;
?>
The long boring solution, which is not involved with CLI, you can manually navigate to:
your local repo folder ? .git folder (hidden) ? config file
then choose your text editor to open it and look for url located under the [remote "origin"] section.
Sometimes, XCode does not forget the line which had an "Editor Placeholder" even if you have replaced it with a value. Cut the portion of the code where XCode is complaining and paste the code back to the same place to make the error message go away. This worked for me.
Say Parent pom.xml contains 6 modules and you want to run A, B and F.
<modules>
<module>A</module>
<module>B</module>
<module>C</module>
<module>D</module>
<module>E</module>
<module>F</module>
</modules>
1- cd into parent project
mvn --projects A,B,F --also-make clean install
OR
mvn -pl A,B,F -am clean install
OR
mvn -pl A,B,F -amd clean install
Note: When you specify a project with the -am option, Maven will build all of the projects that the specified project depends upon (either directly or indirectly). Maven will examine the list of projects and walk down the dependency tree, finding all of the projects that it needs to build.
While the -am command makes all of the projects required by a particular project in a multi-module build, the -amd or --also-make-dependents option configures Maven to build a project and any project that depends on that project. When using --also-make-dependents, Maven will examine all of the projects in our reactor to find projects that depend on a particular project. It will automatically build those projects and nothing else.
The other suggestions are good if you have "SQL only".
However I suggest, that - if possible - you calculate the date in your program and insert it as string in the SQL query.
At least for for big tables (i.e. several million rows, maybe combined with joins) that will give you a considerable speed improvement as the optimizer can work with that much better.
adding HttpClientModule
in app.module.ts
file in import
section fixed my issue.
Try running the following program. You just have to be sure your window has the focus when you hit Return--to ensure that it does, first click the button a couple of times until you see some output, then without clicking anywhere else hit Return.
import tkinter as tk
root = tk.Tk()
root.geometry("300x200")
def func(event):
print("You hit return.")
root.bind('<Return>', func)
def onclick():
print("You clicked the button")
button = tk.Button(root, text="click me", command=onclick)
button.pack()
root.mainloop()
Then you just have tweak things a little when making both the button click
and hitting Return
call the same function--because the command function needs to be a function that takes no arguments, whereas the bind function needs to be a function that takes one argument(the event object):
import tkinter as tk
root = tk.Tk()
root.geometry("300x200")
def func(event):
print("You hit return.")
def onclick(event=None):
print("You clicked the button")
root.bind('<Return>', onclick)
button = tk.Button(root, text="click me", command=onclick)
button.pack()
root.mainloop()
Or, you can just forgo using the button's command argument and instead use bind() to attach the onclick function to the button, which means the function needs to take one argument--just like with Return:
import tkinter as tk
root = tk.Tk()
root.geometry("300x200")
def func(event):
print("You hit return.")
def onclick(event):
print("You clicked the button")
root.bind('<Return>', onclick)
button = tk.Button(root, text="click me")
button.bind('<Button-1>', onclick)
button.pack()
root.mainloop()
Here it is in a class setting:
import tkinter as tk
class Application(tk.Frame):
def __init__(self):
self.root = tk.Tk()
self.root.geometry("300x200")
tk.Frame.__init__(self, self.root)
self.create_widgets()
def create_widgets(self):
self.root.bind('<Return>', self.parse)
self.grid()
self.submit = tk.Button(self, text="Submit")
self.submit.bind('<Button-1>', self.parse)
self.submit.grid()
def parse(self, event):
print("You clicked?")
def start(self):
self.root.mainloop()
Application().start()
You can look into using LESS, which is a JavaScript file that pre-processes your CSS so you can include logic and variables into your CSS. So for your example, in LESS you would write width: 100% - 100px;
to achieve exactly what you wanted :)
string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>(); foreach (var line in lines) { string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); list1.Add(values[0]); list2.Add(values[1]); }
Installing framework 4.0 redistributable is also enough to create application pool. You can download it from here.
set -x
is fine.
Another way to print each executed command is to use trap
with DEBUG
.
Put this line at the beginning of your script :
trap 'echo "# $BASH_COMMAND"' DEBUG
You can find a lot of other trap
usages here.
So in terms of the PathMatchingResourcePatternResolver this is what is needed in the code:
@Autowired
ResourcePatternResolver resourceResolver;
public void getResources() {
resourceResolver.getResources("classpath:config/*.xml");
}
The JSON spec requires UTF-8 support by decoders. As a result, all JSON decoders can handle UTF-8 just as well as they can handle the numeric escape sequences. This is also the case for Javascript interpreters, which means JSONP will handle the UTF-8 encoded JSON as well.
The ability for JSON encoders to use the numeric escape sequences instead just offers you more choice. One reason you may choose the numeric escape sequences would be if a transport mechanism in between your encoder and the intended decoder is not binary-safe.
Another reason you may want to use numeric escape sequences is to prevent certain characters appearing in the stream, such as <
, &
and "
, which may be interpreted as HTML sequences if the JSON code is placed without escaping into HTML or a browser wrongly interprets it as HTML. This can be a defence against HTML injection or cross-site scripting (note: some characters MUST be escaped in JSON, including "
and \
).
Some frameworks, including PHP's implementation of JSON, always do the numeric escape sequences on the encoder side for any character outside of ASCII. This is intended for maximum compatibility with limited transport mechanisms and the like. However, this should not be interpreted as an indication that JSON decoders have a problem with UTF-8.
So, I guess you just could decide which to use like this:
Just use UTF-8, unless your method of storage or transport between encoder and decoder is not binary-safe.
Otherwise, use the numeric escape sequences.
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>
the code behind for the window:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModelBase();
}
}
The ViewModel:
public class ViewModelBase
{
private ICommand _clickCommand;
public ICommand ClickCommand
{
get
{
return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
}
}
public bool CanExecute
{
get
{
// check if executing is allowed, i.e., validate, check if a process is running, etc.
return true/false;
}
}
public void MyAction()
{
}
}
Command Handler:
public class CommandHandler : ICommand
{
private Action _action;
private Func<bool> _canExecute;
/// <summary>
/// Creates instance of the command handler
/// </summary>
/// <param name="action">Action to be executed by the command</param>
/// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
public CommandHandler(Action action, Func<bool> canExecute)
{
_action = action;
_canExecute = canExecute;
}
/// <summary>
/// Wires CanExecuteChanged event
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Forcess checking if execute is allowed
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return _canExecute.Invoke();
}
public void Execute(object parameter)
{
_action();
}
}
I hope this will give you the idea.
[^\s-]
should work and so will
[^-\s]
[]
: The char class^
: Inside the char class ^
is the
negator when it appears in the beginning.\s
: short for a white space-
: a literal hyphen. A hyphen is a
meta char inside a char class but not
when it appears in the beginning or
at the end.You could also turn on autoextend for the whole database using this command:
ALTER DATABASE DATAFILE 'C:\ORACLEXE\APP\ORACLE\ORADATA\XE\SYSTEM.DBF'
AUTOEXTEND ON NEXT 1M MAXSIZE 1024M;
Just change the filepath to point to your system.dbf file.
Credit Here
You can specify a Python version for pip
to use:
pip3.4 install requests
Python 3.4 has pip support built-in, so you can also use:
python3.4 -m pip install
If you're running Ubuntu (or probably Debian as well), you'll need to install the system pip3
separately:
sudo apt-get install python3-pip
This will install the pip3
executable, so you can use it, as well as the earlier mentioned python3.4 -m pip
:
pip3 install requests
<audio src="/music/good_enough.mp3">
<p>If you are reading this, it is because your browser does not support the audio element. </p>
</audio>
and if you want the controls
<audio src="/music/good_enough.mp3" controls>
<p>If you are reading this, it is because your browser does not support the audio element.</p>
</audio>
and also using embed
<embed src="/music/good_enough.mp3" width="180" height="90" loop="false" autostart="false" hidden="true" />
Since you add ..
after cmake, it will jump up and up (just like cd ..
) in the directory. But if you want to run cmake under the same folder with CMakeLists.txt, please use .
instead of ..
.
For the following HTML document:
<html>
<body>
<a href="http://www.example.com">Example</a>
<a href="http://www.stackoverflow.com">SO</a>
</body>
</html>
The xpath query /html/body//a/@href
(or simply //a/@href
) will return:
http://www.example.com http://www.stackoverflow.com
To select a specific instance use /html/body//a[N]/@href
,
$ /html/body//a[2]/@href http://www.stackoverflow.com
To test for strings contained in the attribute and return the attribute itself place the check on the tag not on the attribute:
$ /html/body//a[contains(@href,'example')]/@href http://www.example.com
Mixing the two:
$ /html/body//a[contains(@href,'com')][2]/@href http://www.stackoverflow.com
Now supported in internal-ip!
An RTCPeerConnection
can be used. In browsers like Chrome where a getUserMedia
permission is required, we can just detect available input devices and request for them.
const internalIp = async () => {
if (!RTCPeerConnection) {
throw new Error("Not supported.")
}
const peerConnection = new RTCPeerConnection({ iceServers: [] })
peerConnection.createDataChannel('')
peerConnection.createOffer(peerConnection.setLocalDescription.bind(peerConnection), () => { })
peerConnection.addEventListener("icecandidateerror", (event) => {
throw new Error(event.errorText)
})
return new Promise(async resolve => {
peerConnection.addEventListener("icecandidate", async ({candidate}) => {
peerConnection.close()
if (candidate && candidate.candidate) {
const result = candidate.candidate.split(" ")[4]
if (result.endsWith(".local")) {
const inputDevices = await navigator.mediaDevices.enumerateDevices()
const inputDeviceTypes = inputDevices.map(({ kind }) => kind)
const constraints = {}
if (inputDeviceTypes.includes("audioinput")) {
constraints.audio = true
} else if (inputDeviceTypes.includes("videoinput")) {
constraints.video = true
} else {
throw new Error("An audio or video input device is required!")
}
const mediaStream = await navigator.mediaDevices.getUserMedia(constraints)
mediaStream.getTracks().forEach(track => track.stop())
resolve(internalIp())
}
resolve(result)
}
})
})
}
import csv
with open('input.csv','r') as csvinput:
with open('output.csv', 'w') as csvoutput:
writer = csv.writer(csvoutput)
for row in csv.reader(csvinput):
if row[0] == "Name":
writer.writerow(row+["Berry"])
else:
writer.writerow(row+[row[0]])
Maybe something like that is what you intended?
Also, csv stands for comma separated values. So, you kind of need commas to separate your values like this I think:
Name,Code
blackberry,1
wineberry,2
rasberry,1
blueberry,1
mulberry,2
Oracle VM ware has an update for Windows 10. I was getting this error until I installed this update.
You have:
foreach (var category in Model.Categories)
and then
@foreach (var product in Model)
Based on that view and model it seems that Model
is of type Product
if yes then the second foreach
is not valid. Actually the first one could be the one that is invalid if you return a collection of Product
.
UPDATE:
You are right, I am returning the model of type Product. Also, I do understand what is wrong now that you've pointed it out. How am I supposed to do what I'm trying to do then if I can't do it this way?
I'm surprised your code compiles when you said you are returning a model of Product
type. Here's how you can do it:
@foreach (var category in Model)
{
<h3><u>@category.Name</u></h3>
<div>
<ul>
@foreach (var product in category.Products)
{
<li>
put the rest of your code
</li>
}
</ul>
</div>
}
That suggest that instead of returning a Product
, you return a collection of Category
with Products. Something like this in EF:
// I am typing it here directly
// so I'm not sure if this is the correct syntax.
// I assume you know how to do this,
// anyway this should give you an idea.
context.Categories.Include(o=>o.Product)
If you are using firestore (and not just storing the timestamp as a string) a date field in a document will return a Timestamp. The Timestamp object contains a toDate()
method.
Using timeago you can create a relative time quite simply:
_ago(Timestamp t) {
return timeago.format(t.toDate(), 'en_short');
}
build() {
return Text(_ago(document['mytimestamp'])));
}
Make sure to set _firestore.settings(timestampsInSnapshotsEnabled: true);
to return a Timestamp instead of a Date object.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
application.isStatusBarHidden = true
return true
}
While the others answers are correct in so far as they show what a mere +
usually does (namely, leave the number as it is, if it is one), they are incomplete in so far as they don't explain what happens.
To be exact, +x
evaluates to x.__pos__()
and ++x
to x.__pos__().__pos__()
.
I could imagine a VERY weird class structure (Children, don't do this at home!) like this:
class ValueKeeper(object):
def __init__(self, value): self.value = value
def __str__(self): return str(self.value)
class A(ValueKeeper):
def __pos__(self):
print 'called A.__pos__'
return B(self.value - 3)
class B(ValueKeeper):
def __pos__(self):
print 'called B.__pos__'
return A(self.value + 19)
x = A(430)
print x, type(x)
print +x, type(+x)
print ++x, type(++x)
print +++x, type(+++x)
In the examples below the client is the browser and the server is the webserver hosting the website.
Before you can understand these technologies, you have to understand classic HTTP web traffic first.
The server sends an event to the client when there's new information available.
The server and the client can now send each other messages when new data (on either side) is available.
Comet is a collection of techniques prior to HTML5 which use streaming and long-polling to achieve real time applications. Read more on wikipedia or this article.
Now, which one of them should I use for a realtime app (that I need to code). I have been hearing a lot about websockets (with socket.io [a node.js library]) but why not PHP ?
You can use PHP with WebSockets, check out Ratchet.
To get the installed dotnet version,
Create a Console app.
Add this class
Run that
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class GetDotNetVersion
{
public static void Get45PlusFromRegistry()
{
const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";
using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
{
if (ndpKey != null && ndpKey.GetValue("Release") != null)
{
Console.WriteLine(".NET Framework Version: " + CheckFor45PlusVersion((int)ndpKey.GetValue("Release")));
}
else
{
Console.WriteLine(".NET Framework Version 4.5 or later is not detected.");
}
}
}
// Checking the version using >= will enable forward compatibility.
private static string CheckFor45PlusVersion(int releaseKey)
{
if (releaseKey >= 394802)
return "4.6.2 or later";
if (releaseKey >= 394254)
{
return "4.6.1";
}
if (releaseKey >= 393295)
{
return "4.6";
}
if ((releaseKey >= 379893))
{
return "4.5.2";
}
if ((releaseKey >= 378675))
{
return "4.5.1";
}
if ((releaseKey >= 378389))
{
return "4.5";
}
// This code should never execute. A non-null release key shoul
// that 4.5 or later is installed.
return "No 4.5 or later version detected";
}
}
// Calling the GetDotNetVersion.Get45PlusFromRegistry method produces
// output like the following:
// .NET Framework Version: 4.6.1
}
In Ubuntu 12.04 I had to install openjdk-7-jdk
then javac was working !
then I could use
/usr/lib/jvm/java-7-openjdk-amd64
I am not sure if this was possible in TypeScript when the question was originally asked, but my preferred solution is with generics:
class Zoo<T extends Animal> {
constructor(public readonly AnimalClass: new () => T) {
}
}
This way variables penguin
and lion
infer concrete type Penguin
or Lion
even in the TypeScript intellisense.
const penguinZoo = new Zoo(Penguin);
const penguin = new penguinZoo.AnimalClass(); // `penguin` is of `Penguin` type.
const lionZoo = new Zoo(Lion);
const lion = new lionZoo.AnimalClass(); // `lion` is `Lion` type.
I had the same problem and realized I was setting both the LayoutManager and adapter after retrieving the data from my source instead of setting the two in the onCreate method.
salesAdapter = new SalesAdapter(this,ordersList);
salesView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
salesView.setAdapter(salesAdapter);
Then notified the adapter on data change
//get the Orders
Orders orders;
JSONArray ordersArray = jObj.getJSONArray("orders");
for (int i = 0; i < ordersArray.length() ; i++) {
JSONObject orderItem = ordersArray.getJSONObject(i);
//populate the Order model
orders = new Orders(
orderItem.getString("order_id"),
orderItem.getString("customer"),
orderItem.getString("date_added"),
orderItem.getString("total"));
ordersList.add(i,orders);
salesAdapter.notifyDataSetChanged();
}
You get "close existing connections to destination database" option only in "Databases context >> Restore Wizard" and NOT ON context of any particular database.
Right Click on the Databases under your Server-Name as shown below:
and select the option: "Restore Database..." from it.
In the "Restore Database" wizard,
Here you can find the checkbox saying, "close existing connections to destination database"
Just check it, and you can proceed for the restore operation.
It automatically will resume all connections after completion of the Restore.
Open Project properties by selecting project then go to
View>Properties Windows
and make sure Anonymous Authentication is Enabled
It seems most web sites out on the internet use 1460 bytes for the value of MTU. Sometimes it's 1452 and if you are on a VPN it will drop even more for the IPSec headers.
The default window size varies quite a bit up to a max of 65535 bytes. I use http://tcpcheck.com to look at my own source IP values and to check what other Internet vendors are using.
This is probably because an empty line at the end of your input file.
Try this:
for x in f:
try:
print int(x.strip(),16)
except ValueError:
print "Invalid input:", x
Example in scala (useful in sbt file):
import collection.JavaConverters._
import java.net._
def getIpAddress: String = {
val enumeration = NetworkInterface.getNetworkInterfaces.asScala.toSeq
val ipAddresses = enumeration.flatMap(p =>
p.getInetAddresses.asScala.toSeq
)
val address = ipAddresses.find { address =>
val host = address.getHostAddress
host.contains(".") && !address.isLoopbackAddress
}.getOrElse(InetAddress.getLocalHost)
address.getHostAddress
}
Similar: To view unmerged branches:
git branch --all --no-merged
Those can be suspect but I recommend the answer by cxreg
The compiler cannot guess what should be passed for the base constructor argument. You have to do it explicitly:
public class child : parent {
public child(int i) : base(i) {
Console.WriteLine("child");
}
}
Improved Version of "Josh Marinacci" answer , it will read beyond Z column (i.e. AA1).
var XLSX = require('xlsx');
var workbook = XLSX.readFile('test.xlsx');
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function(y) {
var worksheet = workbook.Sheets[y];
var headers = {};
var data = [];
for(z in worksheet) {
if(z[0] === '!') continue;
//parse out the column, row, and value
var tt = 0;
for (var i = 0; i < z.length; i++) {
if (!isNaN(z[i])) {
tt = i;
break;
}
};
var col = z.substring(0,tt);
var row = parseInt(z.substring(tt));
var value = worksheet[z].v;
//store header names
if(row == 1 && value) {
headers[col] = value;
continue;
}
if(!data[row]) data[row]={};
data[row][headers[col]] = value;
}
//drop those first two rows which are empty
data.shift();
data.shift();
console.log(data);
});
Use this nifty freeware utility:
CurrPorts is network monitoring software that displays the list of all currently opened TCP/IP and UDP ports on your local computer.
I have a naive solution but useful. Here is the code:
<Grid Name="TVGrid" Background="#7F000000"> <ScrollBar Background="Black" Orientation="Vertical" Height="35" HorizontalAlignment="Left" Margin="215,254,0,0" Minimum="0" Maximum="10" LargeChange="10" Value="{Binding ElementName=channeltext2, Path=Text}" x:Name="scroll" VerticalAlignment="Top" Width="12" RenderTransformOrigin="0.5,0.5" ValueChanged="scroll_ValueChanged" >
<ScrollBar.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform Angle="-180"/>
<TranslateTransform/>
</TransformGroup>
</ScrollBar.RenderTransform>
</ScrollBar>
<TextBox Name="channeltext" HorizontalContentAlignment="Center" FontSize="20" Background="Black" Foreground="White" Height="35" HorizontalAlignment="Left" Margin="147,254,0,0" VerticalAlignment="Top" Width="53" Text="0" />
<TextBox Name="channeltext2" Visibility="Hidden" HorizontalContentAlignment="Center" FontSize="20" Background="Black" Foreground="White" Height="35" HorizontalAlignment="Left" Margin="147,254,0,0" VerticalAlignment="Top" Width="53" Text="0" /> </Grid>
#define NUM_TYPES 4
You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.
You have two options:
Grant write permissions to the folder to the user or group you log in with (myuser
), or change the ownership of the folder to the user, or
Disable a transfer to temporary file.
In Preferences, go to Transfer > Endurance page and in Enable transfer resume/transfer to temporary file name for select Disable:
Static methods are not instantiated as such, they're just available without an object reference.
A call to a static method is done through the class name, not through an object reference, and the Intermediate Language (IL) code to call it will call the abstract method through the name of the class that defined it, not necessarily the name of the class you used.
Let me show an example.
With the following code:
public class A
{
public static void Test()
{
}
}
public class B : A
{
}
If you call B.Test, like this:
class Program
{
static void Main(string[] args)
{
B.Test();
}
}
Then the actual code inside the Main method is as follows:
.entrypoint
.maxstack 8
L0000: nop
L0001: call void ConsoleApplication1.A::Test()
L0006: nop
L0007: ret
As you can see, the call is made to A.Test, because it was the A class that defined it, and not to B.Test, even though you can write the code that way.
If you had class types, like in Delphi, where you can make a variable referring to a type and not an object, you would have more use for virtual and thus abstract static methods (and also constructors), but they aren't available and thus static calls are non-virtual in .NET.
I realize that the IL designers could allow the code to be compiled to call B.Test, and resolve the call at runtime, but it still wouldn't be virtual, as you would still have to write some kind of class name there.
Virtual methods, and thus abstract ones, are only useful when you're using a variable which, at runtime, can contain many different types of objects, and you thus want to call the right method for the current object you have in the variable. With static methods you need to go through a class name anyway, so the exact method to call is known at compile time because it can't and won't change.
Thus, virtual/abstract static methods are not available in .NET.
All of the above did not work for me. Cloning the repo was working correctly but I was still getting an unrecognized import
error.
As it stands for Go v1.13, I found in the doc that we should use the GOPRIVATE env variable like so:
$ GOPRIVATE=github.com/ORGANISATION_OR_USER_NAME go get -u github.com/ORGANISATION_OR_USER_NAME/REPO_NAME
enter the android terminal and then you can type the following commands :dumpsys cpuinfo
shell@android:/ $ dumpsys cpuinfo
Load: 0.8 / 0.75 / 1.15
CPU usage from 69286ms to 9283ms ago with 99% awake:
47% 1118/com.wxg.sodproject: 12% user + 35% kernel
1.6% 1225/android.process.media: 1% user + 0.6% kernel
1.3% 263/mpdecision: 0.1% user + 1.2% kernel
0.1% 32747/kworker/u:1: 0% user + 0.1% kernel
0.1% 883/com.android.systemui: 0.1% user + 0% kernel
0.1% 521/system_server: 0.1% user + 0% kernel / faults: 14 minor
0.1% 1826/com.quicinc.trepn: 0.1% user + 0% kernel
0.1% 2462/kworker/0:2: 0.1% user + 0% kernel
0.1% 32649/kworker/0:0: 0% user + 0.1% kernel
0% 118/mmcqd/0: 0% user + 0% kernel
0% 179/surfaceflinger: 0% user + 0% kernel
0% 46/kinteractiveup: 0% user + 0% kernel
0% 141/jbd2/mmcblk0p26: 0% user + 0% kernel
0% 239/sdcard: 0% user + 0% kernel
0% 1171/com.xiaomi.channel:pushservice: 0% user + 0% kernel / faults: 1 minor
0% 1207/com.xiaomi.channel: 0% user + 0% kernel / faults: 1 minor
0% 32705/kworker/0:1: 0% user + 0% kernel
12% TOTAL: 3.2% user + 9.4% kernel + 0% iowait
this worked perfectly for me:
for(a in array)console.log(array[a])
you can extract any array created in console for find/replace cleanup and posterior usage of this data extracted
Here's the method I use (for similar things, not just title):
<?
ob_start (); // Buffer output
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title><!--TITLE--></title>
</head>
<body>
<?
$pageTitle = 'Title of Page'; // Call this in your pages' files to define the page title
?>
</body>
</html>
<?
$pageContents = ob_get_contents (); // Get all the page's HTML into a string
ob_end_clean (); // Wipe the buffer
// Replace <!--TITLE--> with $pageTitle variable contents, and print the HTML
echo str_replace ('<!--TITLE-->', $pageTitle, $pageContents);
?>
PHP usually works be executing any bits of code and printing all output directly to the browser. If you say "echo 'Some text here.';"
, that string will get sent the browser and is emptied from memory.
What output buffering does is say "Print all output to a buffer. Hold onto it. Don't send ANYTHING to the browser until I tell you to."
So what this does is it buffers all your pages' HTML into the buffer, then at the very end, after the tag, it uses ob_get_contents () to get the contents of the buffer (which is usually all your page's HTML source code which would have been sent the browser already) and puts that into a string.
ob_end_clean () empties the buffer and frees some memory. We don't need the source code anymore because we just stored it in $pageContents.
Then, lastly, I do a simple find & replace on your page's source code ($pageContents) for any instances of '' and replace them to whatever the $pageTitle variable was set to. Of course, it will then replace <title><!--TITLE--></title>
with Your Page's Title. After that, I echo the $pageContents, just like the browser would have.
It effectively holds onto output so you can manipulate it before sending it to the browser.
Hopefully my comments are clear enough. Look up ob_start () in the php manual ( http://php.net/ob_start ) if you want to know exactly how that works (and you should) :)
Try jQuery animate()
method, ex.
$("#divid").animate({'width':perc+'%'});
SELECT t1.cname, t1.wmname, t2.max
FROM makerar t1 JOIN (
SELECT cname, MAX(avg) max
FROM makerar
GROUP BY cname ) t2
ON t1.cname = t2.cname AND t1.avg = t2.max;
Using rank()
window function:
SELECT cname, wmname, avg
FROM (
SELECT cname, wmname, avg, rank()
OVER (PARTITION BY cname ORDER BY avg DESC)
FROM makerar) t
WHERE rank = 1;
Note
Either one will preserve multiple max values per group. If you want only single record per group even if there is more than one record with avg equal to max you should check @ypercube's answer.
You can use urllib.parse.urljoin
:
>>> from urllib.parse import urljoin
>>> urljoin('/media/path/', 'js/foo.js')
'/media/path/js/foo.js'
But beware:
>>> urljoin('/media/path', 'js/foo.js')
'/media/js/foo.js'
>>> urljoin('/media/path', '/js/foo.js')
'/js/foo.js'
The reason you get different results from /js/foo.js
and js/foo.js
is because the former begins with a slash which signifies that it already begins at the website root.
On Python 2, you have to do
from urlparse import urljoin
Try adding a pair of class attributes, say 'even' and 'odd', to alternating list elements, e.g.
<ul>
<li class="even"><a href="link">Link 1</a></li>
<li class="odd"><a href="link">Link 2</a></li>
<li class="even"><a href="link">Link 3</a></li>
<li class="odd"><a href="link">Link 4</a></li>
<li class="even"><a href="link">Link 5</a></li>
</ul>
In a <style> section of the HTML page, or in a linked stylesheet, you would define those same classes, specifying your desired background colours:
li.even { background-color: red; }
li.odd { background-color: blue; }
You might want to use a template library as your needs evolve to provide you with greater flexibility and to cut down on the typing. Why type all those list elements by hand?
One can also use the java.util.EnumSet like this
@Test
void test(){
Enum aEnum =DayOfWeek.MONDAY;
printAll(aEnum);
}
void printAll(Enum value){
Set allValues = EnumSet.allOf(value.getClass());
System.out.println(allValues);
}
No magic involved, just subtract from the offset top of the element
$('html, body').animate({scrollTop: $('#contact').offset().top -100 }, 'slow');
What about this:
var txt="";
var nyc = {
fullName: "New York City",
mayor: "Michael Bloomberg",
population: 8000000,
boroughs: 5
};
for (var x in nyc){
txt += nyc[x];
}
As Filburt says; but also note that it's usually better to write
test="not(Count = 'N/A')"
If there's exactly one Count element they mean the same thing, but if there's no Count, or if there are several, then the meanings are different.
6 YEARS LATER
Since this answer seems to have become popular, but may be a little cryptic to some readers, let me expand it.
The "=" and "!=" operator in XPath can compare two sets of values. In general, if A and B are sets of values, then "=" returns true if there is any pair of values from A and B that are equal, while "!=" returns true if there is any pair that are unequal.
In the common case where A selects zero-or-one nodes, and B is a constant (say "NA"), this means that not(A = "NA")
returns true if A is either absent, or has a value not equal to "NA". By contrast, A != "NA"
returns true if A is present and not equal to "NA". Usually you want the "absent" case to be treated as "not equal", which means that not(A = "NA")
is the appropriate formulation.
You can use following methods to handle drop down in selenium.
For more details you can refer http://www.codealumni.com/handle-drop-selenium-webdriver/ this post.
It will definately help you a lot in resolving your queries.
If you want to just compare dates,
yourdatetime.date() < datetime.today().date()
Or, obviously,
yourdatetime.date() == datetime.today().date()
If you want to check that they're the same date.
The documentation is usually helpful. It is also usually the first google result for python thing_i_have_a_question_about
. Unless your question is about a function/module named "snake".
Basically, the datetime
module has three types for storing a point in time:
date
for year, month, day of monthtime
for hours, minutes, seconds, microseconds, time zone infodatetime
combines date and time. It has the methods date()
and time()
to get the corresponding date
and time
objects, and there's a handy combine
function to combine date
and time
into a datetime
.Can I use a field of the type ... and retrieve it after the GET / POST method ...
Yes (haven't you tried?)
Are there any other ways of using hidden fields in PHP?
You mean other ways of retrieving the value? No.
Of course you can use hidden fields for what ever you want.
Btw. input
fiels have no end tag. So write either just <input ...>
or as self-closing tag <input .../>
.
Remove www. from beginning of string, this is the easiest way (ltrim)
$a="www.google.com";
echo ltrim($a, "www.");
I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:
<select [(ngModel)]="simpleValue"> // value is a string or number
<option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option>
</select>
If you want to match on the actual object, I'd do it like this:
<select [(ngModel)]="objValue"> // value is an object
<option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option>
</select>
Beginning with API level 3 you can use onUserInteraction() on an Activity with a boolean to determine if the user is interacting with the device.
http://developer.android.com/reference/android/app/Activity.html#onUserInteraction()
@Override
public void onUserInteraction() {
super.onUserInteraction();
userIsInteracting = true;
}
As a field on the Activity I have:
private boolean userIsInteracting;
Finally, my spinner:
mSpinnerView.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long arg3) {
spinnerAdapter.setmPreviousSelectedIndex(position);
if (userIsInteracting) {
updateGUI();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
As you come and go through the activity the boolean is reset to false. Works like a charm.
I used a combination of the answers from rohancragg, Mukul Goel, and NullSoulException from above. However I had an additional error:
ORA-01157: cannot identify/lock data file string - see DBWR trace file
To which I found the answer here: http://nimishgarg.blogspot.com/2014/01/ora-01157-cannot-identifylock-data-file.html
Incase the above post gets deleted I am including the commands here as well.
C:\>sqlplus sys/sys as sysdba
SQL*Plus: Release 11.2.0.3.0 Production on Tue Apr 30 19:07:16 2013
Copyright (c) 1982, 2011, Oracle. All rights reserved.
Connected to an idle instance.
SQL> startup
ORACLE instance started.
Total System Global Area 778387456 bytes
Fixed Size 1384856 bytes
Variable Size 520097384 bytes
Database Buffers 251658240 bytes
Redo Buffers 5246976 bytes
Database mounted.
ORA-01157: cannot identify/lock data file 11 – see DBWR trace file
ORA-01110: data file 16: 'E:\oracle\app\nimish.garg\oradata\orcl\test_ts.dbf'
SQL> select NAME from v$datafile where file#=16;
NAME
--------------------------------------------------------------------------------
E:\ORACLE\APP\NIMISH.GARG\ORADATA\ORCL\TEST_TS.DBF
SQL> alter database datafile 16 OFFLINE DROP;
Database altered.
SQL> alter database open;
Database altered.
Thanks everyone you saved my day!
Fissh
If you want to import a json file into Elasticsearch and create an index, use this Python script.
import json
from elasticsearch import Elasticsearch
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
i = 0
with open('el_dharan.json') as raw_data:
json_docs = json.load(raw_data)
for json_doc in json_docs:
i = i + 1
es.index(index='ind_dharan', doc_type='doc_dharan', id=i, body=json.dumps(json_doc))
I had the same issue and solved by making sure that 1. when you make the style.css file, make sure you didn't just rename a text file as "style.css", make sure it's really the .css format (e.g, use visual studio code); 2. put that style.css file in the same folder with your .rmd file. Hopefully this works for you.
In my understanding according to Python glossary, when you create a instance of objects that are hashable, an unchangeable value is also calculated according to the members or values of the instance. For example, that value could then be used as a key in a dict as below:
>>> tuple_a = (1,2,3)
>>> tuple_a.__hash__()
2528502973977326415
>>> tuple_b = (2,3,4)
>>> tuple_b.__hash__()
3789705017596477050
>>> tuple_c = (1,2,3)
>>> tuple_c.__hash__()
2528502973977326415
>>> id(a) == id(c) # a and c same object?
False
>>> a.__hash__() == c.__hash__() # a and c same value?
True
>>> dict_a = {}
>>> dict_a[tuple_a] = 'hiahia'
>>> dict_a[tuple_c]
'hiahia'
we can find that the hash value of tuple_a and tuple_c are the same since they have the same members. When we use tuple_a as the key in dict_a, we can find that the value for dict_a[tuple_c] is the same, which means that, when they are used as the key in a dict, they return the same value because the hash values are the same. For those objects that are not hashable, the method hash is defined as None:
>>> type(dict.__hash__)
<class 'NoneType'>
I guess this hash value is calculated upon the initialization of the instance, not in a dynamic way, that's why only immutable objects are hashable. Hope this helps.
Nick's answer works great. Be careful when specifying a complete() function inside the animate() call because it will get executed twice since you have two selectors declared (html and body).
$("html, body").animate(
{ scrollTop: "300px" },
{
complete : function(){
alert('this alert will popup twice');
}
}
);
Here's how you can avoid the double callback.
var completeCalled = false;
$("html, body").animate(
{ scrollTop: "300px" },
{
complete : function(){
if(!completeCalled){
completeCalled = true;
alert('this alert will popup once');
}
}
}
);
If you are talking about test/dev environments, then just use the debug option. It will auto-reload the flask app when a code change happens.
app.run(debug=True)
Or, from the shell:
$ export FLASK_DEBUG=1
$ flask run
Do a str.replace('; ', ', ')
and then a str.split(', ')
you can also try with this answer :
<img src="~/Content/img/@Html.DisplayFor(model =>model.ImagePath)" style="height:200px;width:200px;"/>
this worked for me:
import glob
images = glob.glob('*.JPG' or '*.jpg' or '*.png')
max.setOnKeyListener(new OnKeyListener(){
@Override
public boolean onKey(View v, int keyCode, KeyEvent event){
if(keyCode == event.KEYCODE_ENTER){
//do what you want
}
}
});
The problem with Javascript's MIME type is that there hasn't been a standard for years. Now we've got application/javascript as an official MIME type.
But actually, the MIME type doesn't matter at all, as the browser can determine the type itself. That's why the HTML5 specs state that the type="text/javascript"
is no longer required.
Simplest Definition of Looper & Handler:
Looper is a class that turns a thread into a Pipeline Thread and Handler gives you a mechanism to push tasks into it from any other threads.
Details in general wording:
So a PipeLine Thread is a thread which can accept more tasks from other threads through a Handler.
The Looper is named so because it implements the loop – takes the next task, executes it, then takes the next one and so on. The Handler is called a handler because it is used to handle or accept that next task each time from any other thread and pass to Looper (Thread or PipeLine Thread).
Example:
A Looper and Handler or PipeLine Thread's very perfect example is to download more than one images or upload them to a server (Http) one by one in a single thread instead of starting a new Thread for each network call in the background.
Read more here about Looper and Handler and the definition of Pipeline Thread:
You could break by RETURN
. For example
def a = [1, 2, 3, 4, 5, 6, 7]
def ret = 0
a.each {def n ->
if (n > 5) {
ret = n
return ret
}
}
It works for me!
The problem is that t.join() blocks the click event, the main thread does not get back to the event loop to process repaints. See Why ttk Progressbar appears after process in Tkinter or TTK progress bar blocked when sending email
Finally I solve the issues using below code. This type of error will happen when there is a mismatch between In/Out parameter as declare in procedure and in java code declareParameters
. Here we need to defined oracle return tab
public class ManualSaleStoredProcedureDao {
private SimpleJdbcCall getAllSytemUsers;
public List<SystemUser> getAllSytemUsers(String clientCode) {
MapSqlParameterSource in = new MapSqlParameterSource();
in.addValue("pi_client_code", clientCode);
Map<String, Object> result = getAllSytemUsers.execute(in);
@SuppressWarnings("unchecked")
List<SystemUser> systemUsers = (List<SystemUser>) result
.get(VSCConstants.GET_SYSTEM_USER_OUT_PARAM1);
return systemUsers;
}
public void setDataSource(DataSource dataSource) {
getAllSytemUsers = new SimpleJdbcCall(dataSource)
.withSchemaName(VSCConstants.SCHEMA)
.withProcedureName(VSCConstants.GET_SYSTEM_USER_PROC_NAME)
.declareParameters(
new SqlParameter(
"pi_client_code",
OracleTypes.NUMBER,
"pi_client_code"),
new SqlInOutParameter(
"po_system_users",
OracleTypes.ARRAY,
"T_SYSTEM_USER_TAB",
new OracleSystemUser()));
}
grep
find the lines and output the line numbers, but does not let you "program" other things. If you want to include arbitrary text and do other "programming", you can use awk,
$ awk '/null/{c++;print $0," - Line number: "NR}END{print "Total null count: "c}' file
example two null, - Line number: 2
example four null, - Line number: 4
Total null count: 2
Or only using the shell(bash/ksh)
c=0
while read -r line
do
case "$line" in
*null* ) (
((c++))
echo "$line - Line number $c"
;;
esac
done < "file"
echo "total count: $c"
To generate a random number between min and max, use:
int randNum = rand()%(max-min + 1) + min;
(Includes max and min)
size_t is defined by the C standard to be the unsigned integer return type of the sizeof operator (C99 6.3.5.4.4), and the argument of malloc and friends (C99 7.20.3.3 etc). The actual range is set such that the maximum (SIZE_MAX) is at least 65535 (C99 7.18.3.2).
However, this doesn't let us determine sizeof(size_t). The implementation is free to use any representation it likes for size_t - so there is no upper bound on size - and the implementation is also free to define a byte as 16-bits, in which case size_t can be equivalent to unsigned char.
Putting that aside, however, in general you'll have 32-bit size_t on 32-bit programs, and 64-bit on 64-bit programs, regardless of the data model. Generally the data model only affects static data; for example, in GCC:
`-mcmodel=small'
Generate code for the small code model: the program and its
symbols must be linked in the lower 2 GB of the address space.
Pointers are 64 bits. Programs can be statically or dynamically
linked. This is the default code model.
`-mcmodel=kernel'
Generate code for the kernel code model. The kernel runs in the
negative 2 GB of the address space. This model has to be used for
Linux kernel code.
`-mcmodel=medium'
Generate code for the medium model: The program is linked in the
lower 2 GB of the address space but symbols can be located
anywhere in the address space. Programs can be statically or
dynamically linked, but building of shared libraries are not
supported with the medium model.
`-mcmodel=large'
Generate code for the large model: This model makes no assumptions
about addresses and sizes of sections.
You'll note that pointers are 64-bit in all cases; and there's little point to having 64-bit pointers but not 64-bit sizes, after all.
If you are rooted, download the app Root Explorer. Best File manager for rooted users. Anyways, System/app has all the default apks that came with the phone, and data/apk has all the apks of the apps you have installed. Just long press on the apk you want (while in Root Explorer), get to your /sdcard folder and just paste.
echo "Subject: test" | /usr/sbin/sendmail [email protected]
This enables you to do it within one command line without having to echo a text file. This answer builds on top of @mti2935's answer. So credit goes there.
In dead simple way it makes this meaning.
Functions :
These subprograms return a single value; mainly used to compute and return a value.
Procedure :
These subprograms do not return a value directly; mainly used to perform an action.
Example Program:
CREATE OR REPLACE PROCEDURE greetings
BEGIN
dbms_output.put_line('Hello World!');
END ;
/
Executing a Standalone Procedure :
A standalone procedure can be called in two ways:
• Using the EXECUTE
keyword
• Calling the name of procedure from a PL/SQL block
The procedure can also be called from another PL/SQL block:
BEGIN
greetings;
END;
/
Function:
CREATE OR REPLACE FUNCTION totalEmployees
RETURN number IS
total number(3) := 0;
BEGIN
SELECT count(*) into total
FROM employees;
RETURN total;
END;
/
Following program calls the function totalCustomers
from an another block
DECLARE
c number(3);
BEGIN
c := totalEmployees();
dbms_output.put_line('Total no. of Employees: ' || c);
END;
/
[edit] Warning: Do not use rand()
for statistics, simulation, cryptography or anything serious.
It's good enough to make numbers look random for a typical human in a hurry, no more.
See @Jefffrey's reply for better options, or this answer for crypto-secure random numbers.
Generally, the high bits show a better distribution than the low bits, so the recommended way to generate random numbers of a range for simple purposes is:
((double) rand() / (RAND_MAX+1)) * (max-min+1) + min
Note: make sure RAND_MAX+1 does not overflow (thanks Demi)!
The division generates a random number in the interval [0, 1); "stretch" this to the required range. Only when max-min+1 gets close to RAND_MAX you need a "BigRand()" function like posted by Mark Ransom.
This also avoids some slicing problems due to the modulo, which can worsen your numbers even more.
The built-in random number generator isn't guaranteed to have a the quality required for statistical simulations. It is OK for numbers to "look random" to a human, but for a serious application, you should take something better - or at least check its properties (uniform distribution is usually good, but values tend to correlate, and the sequence is deterministic). Knuth has an excellent (if hard-to-read) treatise on random number generators, and I recently found LFSR to be excellent and darn simple to implement, given its properties are OK for you.
I usually use set_time_limit(30) within the main loop (so each loop iteration is limited to 30 seconds rather than the whole script).
I do this in multiple database update scripts, which routinely take several minutes to complete but less than a second for each iteration - keeping the 30 second limit means the script won't get stuck in an infinite loop if I am stupid enough to create one.
I must admit that my choice of 30 seconds for the limit is somewhat arbitrary - my scripts could actually get away with 2 seconds instead, but I feel more comfortable with 30 seconds given the actual application - of course you could use whatever value you feel is suitable.
Hope this helps!
These answers are all very good, but I wanted to share another thing I discovered on stackoverflow that is really quite useful, here is the direct link
Basically, @DidzisElferts shows how you can get all the colours, coordinates, etc that ggplot uses to build a plot you created. Very nice!
p <- ggplot(mpg,aes(x=class,fill=class)) + geom_bar()
ggplot_build(p)$data
[[1]]
fill y count x ndensity ncount density PANEL group ymin ymax xmin xmax
1 #F8766D 5 5 1 1 1 1.111111 1 1 0 5 0.55 1.45
2 #C49A00 47 47 2 1 1 1.111111 1 2 0 47 1.55 2.45
3 #53B400 41 41 3 1 1 1.111111 1 3 0 41 2.55 3.45
4 #00C094 11 11 4 1 1 1.111111 1 4 0 11 3.55 4.45
5 #00B6EB 33 33 5 1 1 1.111111 1 5 0 33 4.55 5.45
6 #A58AFF 35 35 6 1 1 1.111111 1 6 0 35 5.55 6.45
7 #FB61D7 62 62 7 1 1 1.111111 1 7 0 62 6.55 7.45
SELECT *
FROM tbl
WHERE id = 1
ORDER BY signin DESC
LIMIT 1;
The obvious index would be on (id)
, or a multicolumn index on (id, signin DESC)
.
Conveniently for the case, MySQL sorts NULL
values last in descending order. That's what you typically want if there can be NULL
values: the row with the latest not-null signin
.
To get NULL
values first:
ORDER BY signin IS NOT NULL, signin DESC
You may want to append more expressions to ORDER BY
to get a deterministic pick from (potentially) multiple rows with NULL
.
The same applies without NULL
if signin
is not defined UNIQUE
.
Related:
The SQL standard does not explicitly define a default sort order for NULL
values. The behavior varies quite a bit across different RDBMS. See:
But there are the NULLS FIRST
/ NULLS LAST
clauses defined in the SQL standard and supported by most major RDBMS, but not by MySQL. See:
Firstly you need to add a where T:class
constraint - you can't call GetValue
on value types unless they're passed by ref
.
Secondly GetValue
is very slow and gets called a lot.
To get round this we can create a delegate and call that instead:
MethodInfo method = property.GetGetMethod(true);
Delegate.CreateDelegate(typeof(Func<TClass, TProperty>), method );
The problem is that we don't know TProperty
, but as usual on here Jon Skeet has the answer - we can use reflection to retrieve the getter delegate, but once we have it we don't need to reflect again:
public class ReflectionUtility
{
internal static Func<object, object> GetGetter(PropertyInfo property)
{
// get the get method for the property
MethodInfo method = property.GetGetMethod(true);
// get the generic get-method generator (ReflectionUtility.GetSetterHelper<TTarget, TValue>)
MethodInfo genericHelper = typeof(ReflectionUtility).GetMethod(
"GetGetterHelper",
BindingFlags.Static | BindingFlags.NonPublic);
// reflection call to the generic get-method generator to generate the type arguments
MethodInfo constructedHelper = genericHelper.MakeGenericMethod(
method.DeclaringType,
method.ReturnType);
// now call it. The null argument is because it's a static method.
object ret = constructedHelper.Invoke(null, new object[] { method });
// cast the result to the action delegate and return it
return (Func<object, object>) ret;
}
static Func<object, object> GetGetterHelper<TTarget, TResult>(MethodInfo method)
where TTarget : class // target must be a class as property sets on structs need a ref param
{
// Convert the slow MethodInfo into a fast, strongly typed, open delegate
Func<TTarget, TResult> func = (Func<TTarget, TResult>) Delegate.CreateDelegate(typeof(Func<TTarget, TResult>), method);
// Now create a more weakly typed delegate which will call the strongly typed one
Func<object, object> ret = (object target) => (TResult) func((TTarget) target);
return ret;
}
}
So now your method becomes:
public static DataTable ToDataTable<T>(this IEnumerable<T> items)
where T: class
{
// ... create table the same way
var propGetters = new List<Func<T, object>>();
foreach (var prop in props)
{
Func<T, object> func = (Func<T, object>) ReflectionUtility.GetGetter(prop);
propGetters.Add(func);
}
// Add the property values per T as rows to the datatable
foreach (var item in items)
{
var values = new object[props.Length];
for (var i = 0; i < props.Length; i++)
{
//values[i] = props[i].GetValue(item, null);
values[i] = propGetters[i](item);
}
table.Rows.Add(values);
}
return table;
}
You could further optimise it by storing the getters for each type in a static dictionary, then you will only have the reflection overhead once for each type.
for guzzle you can try this :
$client = new Client(env('API_HOST'));
$client->setSslVerification(false);
tested on guzzle/guzzle 3.*
In Tomcat 8.0.44 I did this: create the JNDI on Tomcat's server.xml between the tag "GlobalNamingResources" For example:
<GlobalNamingResources>_x000D_
<!-- Editable user database that can also be used by_x000D_
UserDatabaseRealm to authenticate users_x000D_
-->_x000D_
<!-- Other previus resouces -->_x000D_
<Resource auth="Container" driverClassName="org.postgresql.Driver" global="jdbc/your_jndi" _x000D_
maxActive="100" maxIdle="20" maxWait="1000" minIdle="5" name="jdbc/your_jndi" password="your_password" _x000D_
type="javax.sql.DataSource" url="jdbc:postgresql://localhost:5432/your_database?user=postgres" username="database_username"/>_x000D_
</GlobalNamingResources>
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<Context reloadable="true" >_x000D_
<ResourceLink name="jdbc/your_jndi"_x000D_
global="jdbc/your_jndi"_x000D_
auth="Container"_x000D_
type="javax.sql.DataSource" />_x000D_
</Context>
_x000D_
So if you're using Hiberte with spring you can tell to him to use the JNDI in your persistence.xml
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"_x000D_
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"_x000D_
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">_x000D_
<persistence-unit name="UNIT_NAME" transaction-type="RESOURCE_LOCAL">_x000D_
<provider>org.hibernate.ejb.HibernatePersistence</provider>_x000D_
_x000D_
<properties>_x000D_
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />_x000D_
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL82Dialect" />_x000D_
_x000D_
<!-- <property name="hibernate.jdbc.time_zone" value="UTC"/>-->_x000D_
<property name="hibernate.hbm2ddl.auto" value="update" />_x000D_
<property name="hibernate.show_sql" value="false" />_x000D_
<property name="hibernate.format_sql" value="true"/> _x000D_
</properties>_x000D_
</persistence-unit>_x000D_
</persistence>
_x000D_
So in your spring.xml you can do that:
<bean id="postGresDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">_x000D_
<property name="jndiName" value="java:comp/env/jdbc/your_jndi" />_x000D_
</bean>_x000D_
_x000D_
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">_x000D_
<property name="persistenceUnitName" value="UNIT_NAME" />_x000D_
<property name="dataSource" ref="postGresDataSource" />_x000D_
<property name="jpaVendorAdapter"> _x000D_
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />_x000D_
</property>_x000D_
</bean>
_x000D_
<property name="jndiName" value="java:comp/env/jdbc/your_jndi" />
_x000D_
In this example I used spring with xml but you can do this programmaticaly if you prefer.
That's it, I hope helped.
This query will work for you
Select b.id as 'id', u.id as 'freelancer_id', u.name as
'free_lancer_name', p.user_id as 'project_owner', b.price as
'bid_price', b.number_of_days as 'days' from User u, Project p, Bid b
where b.user_id = u.id and b.project_id = p.id
I find setdefault
quite useful; It checks if a key is present and adds it if not:
d = {}
d.setdefault('new jersey', {}).setdefault('mercer county', {})['plumbers'] = 3
setdefault
always returns the relevant key, so you are actually updating the values of 'd
' in place.
When it comes to iterating, I'm sure you could write a generator easily enough if one doesn't already exist in Python:
def iterateStates(d):
# Let's count up the total number of "plumbers" / "dentists" / etc.
# across all counties and states
job_totals = {}
# I guess this is the annoying nested stuff you were talking about?
for (state, counties) in d.iteritems():
for (county, jobs) in counties.iteritems():
for (job, num) in jobs.iteritems():
# If job isn't already in job_totals, default it to zero
job_totals[job] = job_totals.get(job, 0) + num
# Now return an iterator of (job, number) tuples
return job_totals.iteritems()
# Display all jobs
for (job, num) in iterateStates(d):
print "There are %d %s in total" % (job, num)
Just because I came here looking for a one-time solution (in my case, I usually use vim
but this one time I wanted to use VS Code) for a single command and others might want to know as well:
GIT_EDITOR='code -w' git rebase -i …
Here's my git
/hub
version just for context:
git version 2.24.2 (Apple Git-127)
hub version 2.14.1
Use that instead, if you wish to change the attribute data-num of node element, not of data object:
$('#changeData').click(function (e) {
e.preventDefault();
var num = +$('#foo').attr("data-num");
console.log(num);
num = num + 1;
console.log(num);
$('#foo').attr('data-num', num);
});
PS: but you should use the data() object in virtually all cases, but not all...
Download the latest CMake Mac binary distribution here: https://cmake.org/download/ (current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)
Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.
Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"
Reload your .bashrc file: source ~/.bashrc
Verify the latest cmake version is installed: cmake --version
You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.
Expansion of the same answer
THIS IS A ROUGH ESTIMATION TABLE FOR QUICK DECISIONS!
x-x
Type | A= worst case (x/3) | B = best case (x) | words estimate (A/4.5) - (B/4.5)
-----------+---------------------------------------------------------------------------
TINYTEXT | 85 | 255 | 18 - 56
TEXT | 21,845 | 65,535 | 4,854.44 - 14,563.33
MEDIUMTEXT | 5,592,415 | 16,777,215 | 1,242,758.8 - 3,728,270
LONGTEXT | 1,431,655,765 | 4,294,967,295 | 318,145,725.5 - 954,437,176.6
Please refer to Chris V's answer as well : https://stackoverflow.com/a/35785869/1881812
I assume with the second line you actually mean:
Thing *thing = new Thing("uiae");
which would be the standard way of creating new dynamic objects (necessary for dynamic binding and polymorphism) and storing their address to a pointer. Your code does what JaredPar described, namely creating two objects (one passed a const char*
, the other passed a const Thing&
), and then calling the destructor (~Thing()
) on the first object (the const char*
one).
By contrast, this:
Thing thing("uiae");
creates a static object which is destroyed automatically upon exiting the current scope.
You can add style to your text:
style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
text-shadow: rgb(255, 255, 255) -2px -2px 0px, rgb(255, 255, 255) -2px 2px 0px,
rgb(255, 255, 255) 2px -2px 0px, rgb(255, 255, 255) 2px 2px 0px;"
White, in this example. Does not work in IE :)
Variables have a type and a value.
When you use these variables (in PHP), sometimes you don't have the good type. For example, if you do
if ($var == 1) {... do something ...}
PHP have to convert ("to cast") $var to integer. In this case, "$var == 1" is true because any non-empty string is casted to 1.
When using ===, you check that the value AND THE TYPE are equal, so "$var === 1" is false.
This is useful, for example, when you have a function that can return false (on error) and 0 (result) :
if(myFunction() == false) { ... error on myFunction ... }
This code is wrong as if myFunction()
returns 0, it is casted to false and you seem to have an error. The correct code is :
if(myFunction() === false) { ... error on myFunction ... }
because the test is that the return value "is a boolean and is false" and not "can be casted to false".
Forget using plt.title
and place the text directly with plt.text
. An over-exaggerated example is given below:
import pylab as plt
fig = plt.figure(figsize=(5,10))
figure_title = "Normal title"
ax1 = plt.subplot(1,2,1)
plt.title(figure_title, fontsize = 20)
plt.plot([1,2,3],[1,4,9])
figure_title = "Raised title"
ax2 = plt.subplot(1,2,2)
plt.text(0.5, 1.08, figure_title,
horizontalalignment='center',
fontsize=20,
transform = ax2.transAxes)
plt.plot([1,2,3],[1,4,9])
plt.show()
Just in case you are looking for a way to trim and keep the LAST 10 characters of a string.
s = s.substring(Math.max(s.length(),10) - 10);
I think you are near to a possible solution.
Execute mainloop
in a separate thread and extend it with the property shutdown_flag
. The signal can be caught with signal.signal(signal.SIGTERM, handler)
in the main thread (not in a separate thread). The signal handler should set shutdown_flag
to True and wait for the thread to end with thread.join()
Update: If you are using a newer version of MVC, the same process applies, just be sure to use the correct version number in the web.config's <host>
line.
Well, I found myself experiencing the same thing you did, and after a bit further research, I found out what the problem is!
You need to include the default MVC3 web.config for the Views folder. MVC3 has two: one in the root for your application, and one for the views folder. This has a section for included namespaces. Be sure that yours looks something like this:
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
</system.web.webPages.razor>
I suggest that you create a new MVC3 project, then just copy the web.config created for you into your views folder.
Important Once you've done that, you need to close the file and reopen it. Voila! Intellisense!
You can simply add this class.
.btn {
white-space:normal !important;
word-wrap: break-word;
}
RMDIR path_to_folder /S
ex. RMDIR "C:\tmp" /S
Note that you'll be prompted if you're really going to delete the "C:\tmp" folder. Combining it with /Q switch will remove the folder silently (ex. RMDIR "C:\tmp" /S /Q
)
I took the liberty of modifying ConorLuddy's answer to address both 24 hour time and 12 hour time.
function minutesToHHMM (mins, twentyFour = false) {
let h = Math.floor(mins / 60);
let m = mins % 60;
m = m < 10 ? '0' + m : m;
if (twentyFour) {
h = h < 10 ? '0' + h : h;
return `${h}:${m}`;
} else {
let a = 'am';
if (h >= 12) a = 'pm';
if (h > 12) h = h - 12;
return `${h}:${m} ${a}`;
}
}
<script type="text/javascript" src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
}
</script>
Think of a situation like this,
NOTE:
Came here with a similar question, the above didn't work for me in: "rxjs": "^6.0.0"
, in order to generate an observable that emits no data I needed to do:
import {Observable,empty} from 'rxjs';
class ActivatedRouteStub {
params: Observable<any> = empty();
}
If your components are global you can simply do:
var nameOfComponent = "SomeComponent";_x000D_
React.createElement(window[nameOfComponent], {});
_x000D_
Better one line solution:
var answerInt = [];
var answerString = "1 2 3 4";
answerString.split(' ').forEach(function (item) {
answerInt.push(parseInt(item))
});
Please make sure that id datatype is Long instead of String, if that will be string then @GeneratedValue annotation will not work and the sql generating for
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private String id;
create table VMS_AUDIT_RECORDS (id **varchar(255)** not null auto_increment primary key (id))
that needs to be
create table VMS_AUDIT_RECORDS (id **bigint** not null auto_increment primary key (id))
This works:
$("#myselect").find('option').removeAttr("selected");
or
$("#myselect").find('option:selected').removeAttr("selected");
A general solution requires parsing the URL into a RFC 2396 compliant URI (note that this is an old version of the URI standard, which java.net.URI uses).
I have written a Java URL parsing library that makes this possible: galimatias. With this library, you can achieve your desired behaviour with this code:
String urlString = //...
URLParsingSettings settings = URLParsingSettings.create()
.withStandard(URLParsingSettings.Standard.RFC_2396);
URL url = URL.parse(settings, urlString);
Note that galimatias is in a very early stage and some features are experimental, but it is already quite solid for this use case.
I had weird situation when i need to print react component which receives big amount of data and paint in on canvas. I've tried all mentioned approaches, non of them worked reliably for me, with requestAnimationFrame inside setTimeout i get empty canvas in 20% of the time, so i did the following:
nRequest = n => range(0,n).reduce(
(acc,val) => () => requestAnimationFrame(acc), () => requestAnimationFrame(this.save)
);
Basically i made a chain of requestAnimationFrame's, not sure is this good idea or not but this works in 100% of the cases for me so far (i'm using 30 as a value for n variable).
use a css3 class "spinner". It's more beautiful and you don't need .gif
.spinner {
position: absolute;
left: 50%;
top: 50%;
height:60px;
width:60px;
margin:0px auto;
-webkit-animation: rotation .6s infinite linear;
-moz-animation: rotation .6s infinite linear;
-o-animation: rotation .6s infinite linear;
animation: rotation .6s infinite linear;
border-left:6px solid rgba(0,174,239,.15);
border-right:6px solid rgba(0,174,239,.15);
border-bottom:6px solid rgba(0,174,239,.15);
border-top:6px solid rgba(0,174,239,.8);
border-radius:100%;
}
@-webkit-keyframes rotation {
from {-webkit-transform: rotate(0deg);}
to {-webkit-transform: rotate(359deg);}
}
@-moz-keyframes rotation {
from {-moz-transform: rotate(0deg);}
to {-moz-transform: rotate(359deg);}
}
@-o-keyframes rotation {
from {-o-transform: rotate(0deg);}
to {-o-transform: rotate(359deg);}
}
@keyframes rotation {
from {transform: rotate(0deg);}
to {transform: rotate(359deg);}
}
Exemple of what is looks like : http://jsbin.com/roqakuxebo/1/edit
You can find a lot of css spinners like this here : http://cssload.net/en/spinners/
s.replace(u'Â ', '') # u before string is important
and make your .py
file unicode.
Usually, if you are using bootstrap you can do this to set a min-height of 100%.
<div class="container-fluid min-vh-100"></div>
this will also solve the footer not sticking at the bottom.
you can also do this from CSS with the following class
.stickDamnFooter{min-height: 100vh;}
if this class does not stick your footer just add position: fixed; to that same css class and you will not have this issue in a lifetime. Cheers.
The UUID stands for Universally Unique Identifier. UUID is an simple 128 bit digit which uniquely distributed across the world.
Bluetooth sends data over air and all nearby device can receive it. Let's suppose, sometimes you have to send some important files via Bluetooth and all near by devices can access it in range. So when you pair with the other devices, they simply share the UUID number and match before sharing the files. When you send any file then your device encrypt that file with appropriate device UUID and share over the network. Now all Bluetooth devices in the range can access the encrypt file but they required right UUID number. So Only right UUID devices have access to encrypt the file and others will reject cause of wrong UUID.
In short, you can use UUID as a secret password for sharing files between any two Bluetooth devices.
Here is an example. Imagine that you are going to put the files and directory names (under the current folder) to an array and count its items. The script would be like;
my_array=( `ls` )
my_array_length=${#my_array[@]}
echo $my_array_length
Or, you can iterate over this array by adding the following script:
for element in "${my_array[@]}"
do
echo "${element}"
done
Please note that this is the core concept and the input is considered to be sanitized before, i.e. removing extra characters, handling empty Strings, and etc. (which is out of the topic of this thread).
I just added the oracle folder to my environmental variables and that fixed my identical error
Note: The following method will work on windows.
An alternative method (if it is ok to run a single version of PHP at a time) is to define multiple Apache services, each of which will use a different PHP version.
First of all use conditions in the Apache configuration file:
<ifdefine php54>
SetEnv PHPRC C:/apache/php54/
ScriptAlias /php/ "C:/apache/php54/"
AddType application/x-httpd-php .php
Action application/x-httpd-php "/php/php-cgi.exe"
</ifdefine>
<ifdefine php55>
SetEnv PHPRC C:/apache/php55/
ScriptAlias /php/ "C:/apache/php55/"
AddType application/x-httpd-php .php
Action application/x-httpd-php "/php/php-cgi.exe"
</ifdefine>
Now using the httpd.exe create two separate services from command line (elevated to administrator):
httpd.exe -k install -n Apache224_php54 -D php54
httpd.exe -k install -n Apache224_php55 -D php55
Now you can start one of the above services at a time (should shutdown one before starting the other).
If you have previously installed Apache as service you can remove that using below command (replace the service name with the one you have used):
apache -k uninstall -n Apache224
One further note is that I personally use a "notification area icon program" called "Seobiseu" to start and stop services as needed. I have added the two above services to it.
You can use the following
import { find } from 'lodash'
Then to return the entire object (not only its key or value) from the list with the following:
let match = find(savedViews, { 'ID': 'id to match'});
I also had this question, but in my case I didn't want to use a regex, because my JSON value may contain quotation marks. Hopefully my answer will help others in the future.
I solved this issue by using a standard string slice to remove the first and last characters. This works for me, because I used JSON.stringify()
on the textarea
that produced it and as a result, I know that I'm always going to have the "
s at each end of the string.
In this generalized example, response
is the JSON object my AJAX returns, and key
is the name of my JSON key.
response.key.slice(1, response.key.length-1)
I used it like this with a regex replace
to preserve the line breaks and write the content of that key to a paragraph block in my HTML:
$('#description').html(studyData.description.slice(1, studyData.description.length-1).replace(/\\n/g, '<br/>'));
In this case, $('#description')
is the paragraph tag I'm writing to. studyData
is my JSON object, and description
is my key with a multi-line value.
SWIFT 4
view.layer.contents = #imageLiteral(resourceName: "webbg").cgImage
None of the examples in this answer seem to work with Daylight Saving Time adjustment days. On those days, the number of hours in a day are not 24 (they are 23 or 25, depending on if you are "springing forward" or "falling back".)
The below AddDays javascript function accounts for daylight saving time:
function addDays(date, amount) {
var tzOff = date.getTimezoneOffset() * 60 * 1000,
t = date.getTime(),
d = new Date(),
tzOff2;
t += (1000 * 60 * 60 * 24) * amount;
d.setTime(t);
tzOff2 = d.getTimezoneOffset() * 60 * 1000;
if (tzOff != tzOff2) {
var diff = tzOff2 - tzOff;
t += diff;
d.setTime(t);
}
return d;
}
Here are the tests I used to test the function:
var d = new Date(2010,10,7);
var d2 = AddDays(d, 1);
document.write(d.toString() + "<br />" + d2.toString());
d = new Date(2010,10,8);
d2 = AddDays(d, -1)
document.write("<hr /><br />" + d.toString() + "<br />" + d2.toString());
d = new Date('Sun Mar 27 2011 01:59:00 GMT+0100 (CET)');
d2 = AddDays(d, 1)
document.write("<hr /><br />" + d.toString() + "<br />" + d2.toString());
d = new Date('Sun Mar 28 2011 01:59:00 GMT+0100 (CET)');
d2 = AddDays(d, -1)
document.write("<hr /><br />" + d.toString() + "<br />" + d2.toString());
If you want to click on all checkboxes at once, a method like this will do:
private void ClickAllCheckboxes()
{
foreach (IWebElement e in driver.FindElements(By.xpath("//input[@type='checkbox']")))
{
if(!e.Selected)
e.Click();
}
}
Your own answer technically wasn't incorrect, but you got the index wrong since indexes start at 0, not 1. That's why you got the wrong selection.
document.getElementById('personlist').getElementsByTagName('option')[**10**].selected = 'selected';
Also, your answer is actually a good one for cases where the tags aren't entirely English or numeric.
If they use, for example, Asian characters, the other solutions telling you to use .value() may not always function and will just not do anything. Selecting by tag is a good way to ignore the actual text and select by the element itself.
I know the question doesn't state SQL Server express, but its worth pointing out that the SQL Server Express editions don't come with the profiler (very annoying), and I suspect that they also don't come with the query analyzer.
answer = True
myvar = 'the answer is ' + str(answer) #since answer variable is in boolean format, therefore, we have to convert boolean into string format which can be easily done using this
print(myvar)
In summary, two ways were introduced
1) using order by DBMS_RANDOM.VALUE clause
2) using sample([%]) function
The first way has advantage in 'CORRECTNESS' which means you will never fail get result if it actually exists, while in the second way you may get no result even though it has cases satisfying the query condition since information is reduced during sampling.
The second way has advantage in 'EFFICIENT' which mean you will get result faster and give light load to your database. I was given an warning from DBA that my query using the first way gives loads to the database
You can choose one of two ways according to your interest!
Arulx Z's answer was exactly what I was looking for.
I'm writing an app with Navigation Drawer with recyclerview and webviews, for keeping the web browsing inside the app regardless of hyperlinks clicked (thus not launching the external web browser). For that it will suffice to put the following 2 lines of code:
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.setWebViewClient(new WebViewClient());?
exactly under your WebView statement.
Here's a example of my implemented WebView code:
public class WebView1 extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView wv = (WebView) findViewById(R.id.wv1); //webview statement
wv.setWebViewClient(new WebViewClient()); //the lines of code added
wv.setWebChromeClient(new WebChromeClient()); //same as above
wv.loadUrl("http://www.google.com");
}}
this way, every link clicked in the website will load inside your WebView. (Using Android Studio 1.2.2 with all SDK's updated)
numbers = [1, 2, 3]
numsum = sum(list(numbers))
print(numsum)
This would work, if your are trying to Sum up a list.
My approach directly deserializes to IDictionary, without JObject or ExpandObject in between. The code uses converter, which is basically copied from ExpandoObjectConverter class found in JSON.NET sourcecode, but using IDictionary instead of ExpandoObject.
Usage:
var settings = new JsonSerializerSettings()
{
Converters = { new DictionaryConverter() },
};
var result = JsonConvert.DeserializeObject<IDictionary<string, object>>(json, settings);
Code:
// based on ExpandoObjectConverter, but using arrays instead of IList, to behave similar to System.Web.Script.Serialization.JavaScriptSerializer
public class DictionaryConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return ReadValue(reader);
}
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(IDictionary<string, object>));
}
public override bool CanWrite
{
get { return false; }
}
private object ReadValue(JsonReader reader)
{
while (reader.TokenType == JsonToken.Comment)
{
if (!reader.Read())
throw JsonSerializationExceptionCreate(reader, "Unexpected end when reading IDictionary<string, object>.");
}
switch (reader.TokenType)
{
case JsonToken.StartObject:
return ReadObject(reader);
case JsonToken.StartArray:
return ReadList(reader);
default:
if (IsPrimitiveToken(reader.TokenType))
return reader.Value;
throw JsonSerializationExceptionCreate(reader, string.Format(CultureInfo.InvariantCulture, "Unexpected token when converting IDictionary<string, object>: {0}", reader.TokenType));
}
}
private object ReadList(JsonReader reader)
{
List<object> list = new List<object>();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.Comment:
break;
default:
object v = ReadValue(reader);
list.Add(v);
break;
case JsonToken.EndArray:
return list;
}
}
throw JsonSerializationExceptionCreate(reader, "Unexpected end when reading IDictionary<string, object>.");
}
private object ReadObject(JsonReader reader)
{
IDictionary<string, object> dictionary = new Dictionary<string, object>();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
string propertyName = reader.Value.ToString();
if (!reader.Read())
throw JsonSerializationExceptionCreate(reader, "Unexpected end when reading IDictionary<string, object>.");
object v = ReadValue(reader);
dictionary[propertyName] = v;
break;
case JsonToken.Comment:
break;
case JsonToken.EndObject:
return dictionary;
}
}
throw JsonSerializationExceptionCreate(reader, "Unexpected end when reading IDictionary<string, object>.");
}
//based on internal Newtonsoft.Json.JsonReader.IsPrimitiveToken
internal static bool IsPrimitiveToken(JsonToken token)
{
switch (token)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Undefined:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.Bytes:
return true;
default:
return false;
}
}
// based on internal Newtonsoft.Json.JsonSerializationException.Create
private static JsonSerializationException JsonSerializationExceptionCreate(JsonReader reader, string message, Exception ex = null)
{
return JsonSerializationExceptionCreate(reader as IJsonLineInfo, reader.Path, message, ex);
}
// based on internal Newtonsoft.Json.JsonSerializationException.Create
private static JsonSerializationException JsonSerializationExceptionCreate(IJsonLineInfo lineInfo, string path, string message, Exception ex)
{
message = JsonPositionFormatMessage(lineInfo, path, message);
return new JsonSerializationException(message, ex);
}
// based on internal Newtonsoft.Json.JsonPosition.FormatMessage
internal static string JsonPositionFormatMessage(IJsonLineInfo lineInfo, string path, string message)
{
if (!message.EndsWith(Environment.NewLine))
{
message = message.Trim();
if (!message.EndsWith(".", StringComparison.Ordinal))
message += ".";
message += " ";
}
message += string.Format(CultureInfo.InvariantCulture, "Path '{0}'", path);
if (lineInfo != null && lineInfo.HasLineInfo())
message += string.Format(CultureInfo.InvariantCulture, ", line {0}, position {1}", lineInfo.LineNumber, lineInfo.LinePosition);
message += ".";
return message;
}
}
J2V8 is best solution of your problem. It's run Nodejs application on jvm(java and android).
J2V8 is Java Bindings for V8, But Node.js integration is available in J2V8 (version 4.4.0)
Github : https://github.com/eclipsesource/J2V8
Example : http://eclipsesource.com/blogs/2016/07/20/running-node-js-on-the-jvm/
I've run into the very same issue, when mistakenly named variable with the very same name, as function.
So this:
isLive = isLive(data);
failed, generating OP's mentioned error message.
Fix to this was as simple as changing above line to:
isItALive = isLive(data);
I don't know, how much does it helps in this situation, but I decided to put this answer for others looking for a solution for similar problems.
javac -cp "jar_path/*" $(find . -name '*.java')
(I prefer not to use xargs because it can split them up and run javac multiple times, each with a subset of java files, some of which may import other ones not specified on the same javac command line)
If you have an App.java entrypoint, freaker's way with -sourcepath is best. It compiles every other java file it needs, following the import-dependencies. eg:
javac -cp "jar_path/*" -sourcepath src/ src/com/companyname/modulename/App.java
You can also specify a target class-file dir: -d target/
.
I think this code is short and clear:
int id;
String name;
JSONArray array = new JSONArray(string_of_json_array);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
id = row.getInt("id");
name = row.getString("name");
}
Is that what you were looking for?
I found the pipe operator did not work for me when using option 3 to concat several MP4s on a Mac in the accepted answer.
The following one-liner works on a Mac (High Sierra) to concatenate mp4s, with no intermediary file creation required.
ffmpeg -f concat -safe 0 -i <(for f in ./*.mp4; do echo "file '$PWD/$f'"; done) -c copy output.mp4
$data_arr = array('hello', 'developer', 'laravel' );
// We Have to remove Value "hello" from the array
// Check if the value is exists in the array
if (array_search('hello', $data_arr ) !== false) {
$key = array_search('hello', $data_arr );
unset( $data_arr[$key] );
}
# output:
// It will Return unsorted Indexed array
print( $data_arr )
// To Sort Array index use this
$data_arr = array_values( $data_arr );
// Now the array key is sorted
I know this is not an ideal question to answer but as the OP seems to be a beginner, I'd love to share some basic knowledge with him... Hope everybody understands
OP, you can convert a string to type Boolean
by using any of the methods stated below:
string sample = "True";
bool myBool = bool.Parse(sample);
///or
bool myBool = Convert.ToBoolean(sample);
bool.Parse
expects one parameter which in this case is sample
, .ToBoolean
also expects one parameter.
You can use TryParse
which is the same as Parse
but it doesn't throw any exception :)
string sample = "false";
Boolean myBool;
if (Boolean.TryParse(sample , out myBool))
{
}
Please note that you cannot convert any type of string to type Boolean
because the value of a Boolean
can only be True
or False
Hope you understand :)
I think the best that's possible in cross-browser JavaScript is window.print()
, which (in Firefox 3, for me) brings up the 'print' dialog and not the print preview dialog.
FYI, the print dialog is your computer's Print popup, what you get when you do Ctrl-p. The print preview is Firefox's own Preview window, and it has more options. It's what you get with Firefox Menu > Print...
There is a way to remove the line.
1) Follow this tutorial: android-tabs-with-fragments
2) Then apply the RelativeLayout change that Leaudro suggested above (apply the layout props to all FrameLayouts).
You can also add an ImageView to the tab.xml in item #1 and get a very iPhone like look to the tabs.
Here is a screenshot of what I'm working on right now. I still have some work to do, mainly make a selector for the icons and ensure equal horizontal distribution, but you get the idea. In my case, I'm using fragments, but the same principals should apply to a standard tab view.
I had the same issue with Golang (debugging with Goland) after migration. The only (ridiculous) thing that helped is renaming the following folder:
sudo mv /usr/local/include /usr/local/old_include
Apparently it is related to old files that homebrew installed and now broken.
User ID For element, then
document.getElementById('selValue').value=Your Value;
$('#selValue').selectpicker('refresh');
If you don't want to add a wrapper, you could just add the code manually, since you know the ID you are targeting:
var myID = "xxx";
var newCode = "<div id='"+myID+"'>"+$("#"+myID).html()+"</div>";
const elem= document.getElementsByClassName('column')
for (let i = elem.length; 0 < i ; )
elem[--i].remove();
OR
const elem= document.getElementsByClassName('column')
while (elem.length > 0 )
elem[0].remove();
The problem is that your ui
property uses a forward declaration of class Ui::MainWindowClass
, hence the "incomplete type" error.
Including the header file in which this class is declared will fix the problem.
EDIT
Based on your comment, the following code:
namespace Ui
{
class MainWindowClass;
}
does NOT declare a class. It's a forward declaration, meaning that the class will exist at some point, at link time.
Basically, it just tells the compiler that the type will exist, and that it shouldn't warn about it.
But the class has to be defined somewhere.
Note this can only work if you have a pointer to such a type.
You can't have a statically allocated instance of an incomplete type.
So either you actually want an incomplete type, and then you should declare your ui
member as a pointer:
namespace Ui
{
// Forward declaration - Class will have to exist at link time
class MainWindowClass;
}
class MainWindow : public QMainWindow
{
private:
// Member needs to be a pointer, as it's an incomplete type
Ui::MainWindowClass * ui;
};
Or you want a statically allocated instance of Ui::MainWindowClass
, and then it needs to be declared.
You can do it in another header file (usually, there's one header file per class).
But simply changing the code to:
namespace Ui
{
// Real class declaration - May/Should be in a specific header file
class MainWindowClass
{};
}
class MainWindow : public QMainWindow
{
private:
// Member can be statically allocated, as the type is complete
Ui::MainWindowClass ui;
};
will also work.
Note the difference between the two declarations. First uses a forward declaration, while the second one actually declares the class (here with no properties nor methods).
I had this error for quite sometime now until I couldn't take it anymore so I have tried all possbile solutions above, but none worked for me. I noticed that the error only pops up on a certain project only (like what a user mentioned above) but not on other projects. Because of that, since nothing is working, I cloned my project again on a different folder and it started working again.
I hit this issue working with Server Sent Events. The problem was solved when I noticed that the domain name I used to initiate the connection included a trailing slash, e.g. https://foo.bar.bam/
failed with ERR_HTTP_PROTOCOL_ERROR
while https://foo.bar.bam
worked.
This works fine for me.
final R.drawable drawableResources = new R.drawable();
final Class<R.drawable> c = R.drawable.class;
final Field[] fields = c.getDeclaredFields();
for (int i=0; i < fields.length;i++)
{
resourceId[i] = fields[i].getInt(drawableResources);
/* till here you get all the images into the int array resourceId.*/
}
imageview= (ImageView)findViewById(R.id.imageView);
if(your condition)
{
imageview.setImageResource(resourceId[any]);
}
You can set Allow Non-modular includes in Framework Modules in Build Settings for the affected target to YES. This is the build setting you need to edit:
NOTE: You should use this feature to uncover the underlying error, which I have found to be frequently caused by duplication of angle-bracketed global includes in files with some dependent relationship, i.e.:
#import <Foo/Bar.h> // referred to in two or more dependent files
If setting Allow Non-modular includes in Frame Modules to YES results in a set of "X is an ambiguous reference" errors or something of the sort, you should be able to track down the offending duplicate(s) and eliminate them. After you've cleaned up your code, set Allow Non-modular includes in Frame Modules back to NO.
here is example of @dynamic
#import <Foundation/Foundation.h>
@interface Book : NSObject
{
NSMutableDictionary *data;
}
@property (retain) NSString *title;
@property (retain) NSString *author;
@end
@implementation Book
@dynamic title, author;
- (id)init
{
if ((self = [super init])) {
data = [[NSMutableDictionary alloc] init];
[data setObject:@"Tom Sawyer" forKey:@"title"];
[data setObject:@"Mark Twain" forKey:@"author"];
}
return self;
}
- (void)dealloc
{
[data release];
[super dealloc];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
{
NSString *sel = NSStringFromSelector(selector);
if ([sel rangeOfString:@"set"].location == 0) {
return [NSMethodSignature signatureWithObjCTypes:"v@:@"];
} else {
return [NSMethodSignature signatureWithObjCTypes:"@@:"];
}
}
- (void)forwardInvocation:(NSInvocation *)invocation
{
NSString *key = NSStringFromSelector([invocation selector]);
if ([key rangeOfString:@"set"].location == 0) {
key = [[key substringWithRange:NSMakeRange(3, [key length]-4)] lowercaseString];
NSString *obj;
[invocation getArgument:&obj atIndex:2];
[data setObject:obj forKey:key];
} else {
NSString *obj = [data objectForKey:key];
[invocation setReturnValue:&obj];
}
}
@end
int main(int argc, char **argv)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Book *book = [[Book alloc] init];
printf("%s is written by %s\n", [book.title UTF8String], [book.author UTF8String]);
book.title = @"1984";
book.author = @"George Orwell";
printf("%s is written by %s\n", [book.title UTF8String], [book.author UTF8String]);
[book release];
[pool release];
return 0;
}
public String getFileContentType(String fileName) {
String fileType = "Undetermined";
final File file = new File(fileName);
try
{
fileType = Files.probeContentType(file.toPath());
}
catch (IOException ioException)
{
System.out.println(
"ERROR: Unable to determine file type for " + fileName
+ " due to exception " + ioException);
}
return fileType;
}
When you create the colorbar
try using the fraction and/or shrink parameters.
From the documents:
fraction 0.15; fraction of original axes to use for colorbar
shrink 1.0; fraction by which to shrink the colorbar
Use a while loop that checks for the truthfulness of the array:
while array:
value = array.pop(0)
# do some calculation here
And it should do it without any errors or funny behaviour.
If you are using Apache 2.4
You have to check allow and deny rules
Check out http://httpd.apache.org/docs/2.4/upgrading.html#access
In 2.2, access control based on client hostname, IP address, and other characteristics of client requests was done using the directives Order, Allow, Deny, and Satisfy.
In 2.4, such access control is done in the same way as other authorization checks, using the new module mod_authz_host.
The new directive is Require:
2.2 configuration:
Order allow,deny
Allow from all
2.4 configuration:
Require all granted
Also don't forget to restart the apache server after these changes (# service httpd restart
)
That depends on the exact "object-oriented" feature-set you want to have. If you need stuff like overloading and/or virtual methods, you probably need to include function pointers in structures:
typedef struct {
float (*computeArea)(const ShapeClass *shape);
} ShapeClass;
float shape_computeArea(const ShapeClass *shape)
{
return shape->computeArea(shape);
}
This would let you implement a class, by "inheriting" the base class, and implementing a suitable function:
typedef struct {
ShapeClass shape;
float width, height;
} RectangleClass;
static float rectangle_computeArea(const ShapeClass *shape)
{
const RectangleClass *rect = (const RectangleClass *) shape;
return rect->width * rect->height;
}
This of course requires you to also implement a constructor, that makes sure the function pointer is properly set up. Normally you'd dynamically allocate memory for the instance, but you can let the caller do that, too:
void rectangle_new(RectangleClass *rect)
{
rect->width = rect->height = 0.f;
rect->shape.computeArea = rectangle_computeArea;
}
If you want several different constructors, you will have to "decorate" the function names, you can't have more than one rectangle_new()
function:
void rectangle_new_with_lengths(RectangleClass *rect, float width, float height)
{
rectangle_new(rect);
rect->width = width;
rect->height = height;
}
Here's a basic example showing usage:
int main(void)
{
RectangleClass r1;
rectangle_new_with_lengths(&r1, 4.f, 5.f);
printf("rectangle r1's area is %f units square\n", shape_computeArea(&r1));
return 0;
}
I hope this gives you some ideas, at least. For a successful and rich object-oriented framework in C, look into glib's GObject library.
Also note that there's no explicit "class" being modelled above, each object has its own method pointers which is a bit more flexible than you'd typically find in C++. Also, it costs memory. You could get away from that by stuffing the method pointers in a class
structure, and invent a way for each object instance to reference a class.
for manipulation of config files
i came up with this solution inspired by skensell answer
configLine [searchPattern] [replaceLine] [filePath]
it will:
Function:
function configLine {
local OLD_LINE_PATTERN=$1; shift
local NEW_LINE=$1; shift
local FILE=$1
local NEW=$(echo "${NEW_LINE}" | sed 's/\//\\\//g')
touch "${FILE}"
sed -i '/'"${OLD_LINE_PATTERN}"'/{s/.*/'"${NEW}"'/;h};${x;/./{x;q100};x}' "${FILE}"
if [[ $? -ne 100 ]] && [[ ${NEW_LINE} != '' ]]
then
echo "${NEW_LINE}" >> "${FILE}"
fi
}
the crazy exit status magic comes from https://stackoverflow.com/a/12145797/1262663
One thing I would point out from a performance perspective is that depending on how you pass parameters to a method, passing lots of parameters by value will slow the program down because each parameter has to be copied and then placed on the stack.
Using a single class to encompass all of the parameters would work better because a single parameter passed by reference would be elegant and cleaner, and quicker!
The proper data type for "2010-12-20 00:00:00.0000000" value is DATETIME2(7) / DT_DBTIME2 ().
But used data type for CYCLE_DATE field is DATETIME - DT_DATE. This means milliseconds precision with accuracy down to every third millisecond (yyyy-mm-ddThh:mi:ss.mmL where L can be 0,3 or 7).
The solution is to change CYCLE_DATE date type to DATETIME2 - DT_DBTIME2.
To use hash
, as @lhunath suggests, in a Bash script:
hash foo &> /dev/null
if [ $? -eq 1 ]; then
echo >&2 "foo not found."
fi
This script runs hash
and then checks if the exit code of the most recent command, the value stored in $?
, is equal to 1
. If hash
doesn't find foo
, the exit code will be 1
. If foo
is present, the exit code will be 0
.
&> /dev/null
redirects standard error and standard output from hash
so that it doesn't appear onscreen and echo >&2
writes the message to standard error.
All the previous reviews were tested by me, but there was no solution. But I did not give up.
SOLUTION
Uncomment the following lines in my NGINX configuration
[/etc/nginx/site-avaible/{sitename}.conf]
The same code should follow in the site-enable folder
#fastcgi_param SCRIPT_FILENAME $ document_root $ fastcgi_script_name;
And comment this:
fastcgi_param SCRIPT_FILENAME / www / {namesite} / public_html $ fastcgi_script_name;
I changed several times from the original:
#fastcgi_pass unix: /var/php-nginx/9882989289032.sock;
Going back to this:
#fastcgi_pass 127.0.0.1:9007;
And finally I found what worked ...
fastcgi_pass localhost: 8004;
I also recommend these lines...
#fastcgi_index index.php;
#include fastcgi_params;
And even the FastCGI timeout (only to improve performance)
fastcgi_read_timeout 3000;
During the process, I checked the NGINX log for all modifications. (This is very important because it shows the wrong parameter.) In my case it is like this, but it depends on the configuration:
error_log/var/log/nginx/{site}_error_log;
Test the NGINX Configuration
nginx -t
Attention this is one of the options ... Well on the same server, what did not work on this site works on others ... So keep in mind that the settings depends on the platform.
In this case it was for Joomla CMS.
No, VB.NET does not yet have such a feature. It will be available in the next iteration of VB (visual basic 10) however (link)
The T is just a literal to separate the date from the time, and the Z means "zero hour offset" also known as "Zulu time" (UTC). If your strings always have a "Z" you can use:
SimpleDateFormat format = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Or using Joda Time, you can use ISODateTimeFormat.dateTime()
.
You should always consider what the browser will see by the end. In this case, it will see this:
<img src='something' onmouseover='change(' ex1')' />
In other words, the "onmouseover" attribute is just change(
, and there's another "attribute" called ex1')'
with no value.
The truth is, HTML does not use \
for an escape character. But it does recognise "
and '
as escaped quote and apostrophe, respectively.
Armed with this knowledge, use this:
document.getElementById("something").innerHTML = "<img src='something' onmouseover='change("ex1")' />";
... That being said, you could just use JavaScript quotes:
document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\"ex1\")' />";
I will add my experience using saga in production system in addition to the library author's rather thorough answer.
Pro (using saga):
Testability. It's very easy to test sagas as call() returns a pure object. Testing thunks normally requires you to include a mockStore inside your test.
redux-saga comes with lots of useful helper functions about tasks. It seems to me that the concept of saga is to create some kind of background worker/thread for your app, which act as a missing piece in react redux architecture(actionCreators and reducers must be pure functions.) Which leads to next point.
Sagas offer independent place to handle all side effects. It is usually easier to modify and manage than thunk actions in my experience.
Con:
Generator syntax.
Lots of concepts to learn.
API stability. It seems redux-saga is still adding features (eg Channels?) and the community is not as big. There is a concern if the library makes a non backward compatible update some day.
Try doing:
INSERT INTO table3(NAME,AGE,SEX,CITY,ID,NUMBER)
SELECT t1.name,t1.age, t1.sex,t1.city,t1.id,t2.number
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id
By using LEFT JOIN, this will insert every record from table 1 in table3, and for the ones that match the join condition in table2, it will also insert their number.
In case anyone doesn't get results from the other answers, I fixed a similar problem by:
adding --hidden-import
flags as needed for any missing modules
cleaning up the associated folders and spec files:
rmdir /s /q dist
rmdir /s /q build
del /s /q my_service.spec
From the Official documentation,
For example, to set the background color to orange:
<meta name="theme-color" content="#db5945">
In addition, Chrome will show beautiful high-res favicons when they’re provided. Chrome for Android picks the highest res icon that you provide, and we recommend providing a 192×192px PNG file. For example:
<link rel="icon" sizes="192x192" href="nice-highres.png">
Here's typescript version. works on "react-router-dom": "^4.3.1"
export const AppRouter: React.StatelessComponent = () => {
return (
<BrowserRouter>
<Switch>
<Route exact path="/problem/:problemId" render={props => <ProblemPage {...props.match.params} />} />
<Route path="/" exact component={App} />
</Switch>
</BrowserRouter>
);
};
and component
export class ProblemPage extends React.Component<ProblemRouteTokens> {
public render(): JSX.Element {
return <div>{this.props.problemId}</div>;
}
}
where ProblemRouteTokens
export interface ProblemRouteTokens { problemId: string; }
You can set the flag directly using setter method. In Kotlin or
is the replacement for the Java bitwise or |
.
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
If you plan to use this regularly, create an Intent extension function
fun Intent.clearStack() {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
You can then directly call this function before starting the intent
intent.clearStack()
If you need the option to add additional flags in other situations, add an optional param to the extension function.
fun Intent.clearStack(additionalFlags: Int = 0) {
flags = additionalFlags or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
Use \t
and enclose the string with double-quotes:
$chunk = "abc\tdef\tghi";
In addition mysql passwords when not using the IDENTIFIED BY
clause, may be blank values, if non-blank, they may be encrypted. But yes USAGE
is used to modify an account by granting simple resource limiters such as MAX_QUERIES_PER_HOUR
, again this can be specified by also
using the WITH clause, in conjuction with GRANT USAGE
(no privileges added) or GRANT ALL
, you can also specify GRANT USAGE
at the global level, database level, table level,etc....
It's indeed doable to query the manifest or blob info from docker registry server without pulling the image to local disk.
You can refer to the Registry v2 API to fetch the manifest of image.
GET /v2/<name>/manifests/<reference>
Note, you have to handle different manifest version. For v2 you can directly get the size of layer and digest of blob. For v1 manifest, you can HEAD the blob download url to get the actual layer size.
There is a simple script for handling above cases that will be continuously maintained.
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
{
MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
}
}