char* result = strcpy((char*)malloc(str.length()+1), str.c_str());
There are predefined macros that are used by most compilers, you can find the list here. GCC compiler predefined macros can be found here. Here is an example for gcc:
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
//define something for Windows (32-bit and 64-bit, this part is common)
#ifdef _WIN64
//define something for Windows (64-bit only)
#else
//define something for Windows (32-bit only)
#endif
#elif __APPLE__
#include <TargetConditionals.h>
#if TARGET_IPHONE_SIMULATOR
// iOS Simulator
#elif TARGET_OS_IPHONE
// iOS device
#elif TARGET_OS_MAC
// Other kinds of Mac OS
#else
# error "Unknown Apple platform"
#endif
#elif __linux__
// linux
#elif __unix__ // all unices not caught above
// Unix
#elif defined(_POSIX_VERSION)
// POSIX
#else
# error "Unknown compiler"
#endif
The defined macros depend on the compiler that you are going to use.
The _WIN64
#ifdef
can be nested into the _WIN32
#ifdef
because _WIN32
is even defined when targeting the Windows x64 version. This prevents code duplication if some header includes are common to both
(also WIN32
without underscore allows IDE to highlight the right partition of code).
In General:
An example of an easy way to post XML data and get the response (as a string) would be the following function:
public string postXMLData(string destinationUrl, string requestXml)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
return responseStr;
}
return null;
}
In your specific situation:
Instead of:
request.ContentType = "application/x-www-form-urlencoded";
use:
request.ContentType = "text/xml; encoding='utf-8'";
Also, remove:
string postData = "XMLData=" + Sendingxml;
And replace:
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
with:
byte[] byteArray = Encoding.UTF8.GetBytes(Sendingxml.ToString());
Maybe someone else has this problem at one point. If you use the UglifyJsPlugin
in webpack 2
you need to explicitly specify the sourceMap
flag. For example:
new webpack.optimize.UglifyJsPlugin({ sourceMap: true })
MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html
This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY)
and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.
Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).
look at sysinternals for a variety of tools to help you achieve that goal. psService for example would restart a service on a remote machine.
Create a Hashtable called "Properties" and add your properties to it.
Try this:
import React, { useCallback } from "react";
import { Linking } from "react-native";
OpenWEB = () => {
Linking.openURL(url);
};
const App = () => {
return <View onPress={() => OpenWeb}>OPEN YOUR WEB</View>;
};
Hope this will solve your problem.
X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
Variable1 Variable2
1 11 2
2 14 3
3 12 1
4 15 4
> X[X$Variable1!=11 & X$Variable1!=12, ]
Variable1 Variable2
2 14 3
4 15 4
> X[ ! X$Variable1 %in% c(11,12), ]
Variable1 Variable2
2 14 3
4 15 4
You can functionalize this however you like.
I realised that I had pushed a commit with a typo in it. In order to undo, I did the following:
git commit --amend -m "T-1000, advanced prototype"
git push --force
Warning: force pushing your changes will overwrite the remote branch with your local one. Make sure that you aren't going to be overwriting anything that you want to keep. Also be cautious about force pushing an amended (rewritten) commit if anyone else shares the branch with you, because they'll need to rewrite their own history if they have the old copy of the commit that you've just rewritten.
You can get the script that SSMS provides by doing the following:
The script will look something like this:
USE [master]
GO
ALTER DATABASE [YourDatabaseName] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
USE [master]
GO
DROP DATABASE [YourDatabaseName]
GO
Almost 5 years after only the direct HTML formatting works for images on GitHub and other markdown options still prevent images from loading when specifying some custom sizes even with the wrong dimensions. I prefer to specify the desired width and get the height calculated automatically, for example,
<img src="https://github.com/your_image.png" alt="Your image title" width="250"/>
_x000D_
Unity is a library like many others that allows you to get an instance of a requested type without having to create it yourself. So given.
public interface ICalculator
{
void Add(int a, int b);
}
public class Calculator : ICalculator
{
public void Add(int a, int b)
{
return a + b;
}
}
You would use a library like Unity to register Calculator to be returned when the type ICalculator is requested aka IoC (Inversion of Control) (this example is theoretical, not technically correct).
IoCLlibrary.Register<ICalculator>.Return<Calculator>();
So now when you want an instance of an ICalculator you just...
Calculator calc = IoCLibrary.Resolve<ICalculator>();
IoC libraries can usually be configured to either hold a singleton or create a new instance every time you resolve a type.
Now let's say you have a class that relies on an ICalculator to be present you could have..
public class BankingSystem
{
public BankingSystem(ICalculator calc)
{
_calc = calc;
}
private ICalculator _calc;
}
And you can setup the library to inject a object into the constructor when it's created.
So DI or Dependency Injection means to inject any object another might require.
In JavaScript, most functions are both callable and instantiable: they have both a [[Call]] and [[Construct]] internal methods.
As callable objects, you can use parentheses to call them, optionally passing some arguments. As a result of the call, the function can return a value.
var player = makeGamePlayer("John Smith", 15, 3);
The code above calls function makeGamePlayer
and stores the returned value in the variable player
. In this case, you may want to define the function like this:
function makeGamePlayer(name, totalScore, gamesPlayed) {
// Define desired object
var obj = {
name: name,
totalScore: totalScore,
gamesPlayed: gamesPlayed
};
// Return it
return obj;
}
Additionally, when you call a function you are also passing an additional argument under the hood, which determines the value of this
inside the function. In the case above, since makeGamePlayer
is not called as a method, the this
value will be the global object in sloppy mode, or undefined in strict mode.
As constructors, you can use the new
operator to instantiate them. This operator uses the [[Construct]] internal method (only available in constructors), which does something like this:
.prototype
of the constructorthis
valuevar player = new GamePlayer("John Smith", 15, 3);
The code above creates an instance of GamePlayer
and stores the returned value in the variable player
. In this case, you may want to define the function like this:
function GamePlayer(name,totalScore,gamesPlayed) {
// `this` is the instance which is currently being created
this.name = name;
this.totalScore = totalScore;
this.gamesPlayed = gamesPlayed;
// No need to return, but you can use `return this;` if you want
}
By convention, constructor names begin with an uppercase letter.
The advantage of using constructors is that the instances inherit from GamePlayer.prototype
. Then, you can define properties there and make them available in all instances
Create a C# project and write the following code.
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
run_cmd();
}
private void run_cmd()
{
string fileName = @"C:\sample_script.py";
Process p = new Process();
p.StartInfo = new ProcessStartInfo(@"C:\Python27\python.exe", fileName)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine(output);
Console.ReadLine();
}
}
}
print "Python C# Test"
You will see the 'Python C# Test' in the console of C#.
I just want to give the solution that I came up with that handles all cases presented in this post that I derived from Vasek and devconsole. This solution also handles the special case when the phone is rotated more than once while fragments aren't visible.
Here is were I store the bundle for later use since onCreate and onSaveInstanceState are the only calls that are made when the fragment isn't visible
MyObject myObject;
private Bundle savedState = null;
private boolean createdStateInDestroyView;
private static final String SAVED_BUNDLE_TAG = "saved_bundle";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
savedState = savedInstanceState.getBundle(SAVED_BUNDLE_TAG);
}
}
Since destroyView isn't called in the special rotation situation we can be certain that if it creates the state we should use it.
@Override
public void onDestroyView() {
super.onDestroyView();
savedState = saveState();
createdStateInDestroyView = true;
myObject = null;
}
This part would be the same.
private Bundle saveState() {
Bundle state = new Bundle();
state.putSerializable(SAVED_BUNDLE_TAG, myObject);
return state;
}
Now here is the tricky part. In my onActivityCreated method I instantiate the "myObject" variable but the rotation happens onActivity and onCreateView don't get called. Therefor, myObject will be null in this situation when the orientation rotates more than once. I get around this by reusing the same bundle that was saved in onCreate as the out going bundle.
@Override
public void onSaveInstanceState(Bundle outState) {
if (myObject == null) {
outState.putBundle(SAVED_BUNDLE_TAG, savedState);
} else {
outState.putBundle(SAVED_BUNDLE_TAG, createdStateInDestroyView ? savedState : saveState());
}
createdStateInDestroyView = false;
super.onSaveInstanceState(outState);
}
Now wherever you want to restore the state just use the savedState bundle
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
if(savedState != null) {
myObject = (MyObject) savedState.getSerializable(SAVED_BUNDLE_TAG);
}
...
}
<form id="myform">
<input type="textbox" id="field"/>
<input type="button" value="submit">
</form>
<script>
$(function () {
$("#field").keyup(function (event) {
if (event.which === 13) {
document.myform.submit();
}
}
});
</script>
ImageButton
can't have text
(or, at least, android:text
isn't listed in its attributes).
The Trick is:
It looks like you need to use Button
(and look at drawableTop
or setCompoundDrawablesWithIntrinsicBounds(int,int,int,int))
.
Use ScriptEngine.eval(java.io.Reader)
to read the script
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// read script file
engine.eval(Files.newBufferedReader(Paths.get("C:/Scripts/Jsfunctions.js"), StandardCharsets.UTF_8));
Invocable inv = (Invocable) engine;
// call function from script file
inv.invokeFunction("yourFunction", "param");
Your question is a little unclear, but if what you're doing is trying to get your friend's latest changes, then typically what your friend needs to do is to push those changes up to a remote repo (like one hosted on GitHub), and then you fetch or pull those changes from the remote:
Your friend pushes his changes to GitHub:
git push origin <branch>
Clone the remote repository if you haven't already:
git clone https://[email protected]/abc/theproject.git
Fetch or pull your friend's changes (unnecessary if you just cloned in step #2 above):
git fetch origin
git merge origin/<branch>
Note that git pull
is the same as doing the two steps above:
git pull origin <branch>
The most important difference is this:
In case of persist
method, if the entity that is to be managed in the persistence context, already exists in persistence context, the new one is ignored. (NOTHING happened)
But in case of merge
method, the entity that is already managed in persistence context will be replaced by the new entity (updated) and a copy of this updated entity will return back. (from now on any changes should be made on this returned entity if you want to reflect your changes in persistence context)
You can set up your element
with
value="@model.productId"
and
onclick= addToWishList(this.value);
When I needed to do this, I followed Microsoft's example using Binding.ValidationRules and it worked first time.
See their article, How to: Implement Binding Validation: https://docs.microsoft.com/en-us/dotnet/desktop/wpf/data/how-to-implement-binding-validation?view=netframeworkdesktop-4.8
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
If you are having this issue and you are performing a populate somewhere along the lines, see this Mongoose issue.
Update to Mongoose 4.0 and the issue has been fixed.
Easy! Just use jQuery's click function:
$("#theElement").click();
As your methods an int datatype, you should use "==" instead of equals()
try replacing this if (id.equals(list[pos].getItemNumber()))
with
if (id.equals==list[pos].getItemNumber())
it will fix the error .
As said in previous answers the 'normal' way is to add it to a JScrollPane, but sometimes you don't want it to scroll (don't ask me when:)). Then you can add the TableHeader yourself. Like this:
JPanel tablePanel = new JPanel(new BorderLayout());
JTable table = new JTable();
tablePanel.add(table, BorderLayout.CENTER);
tablePanel.add(table.getTableHeader(), BorderLayout.NORTH);
for localhost,the defaut port is 8080,you can test the link http://localhost:8080 in you browser.if you can see tomcat home page,your tomcat is running
In Visual Studio the default stack size is 1 MB i think, so with a recursion depth of 10,000 each stack frame can be at most ~100 bytes which should be sufficient for a DFS algorithm.
Most compilers including Visual Studio let you specify the stack size. On some (all?) linux flavours the stack size isn't part of the executable but an environment variable in the OS. You can then check the stack size with ulimit -s
and set it to a new value with for example ulimit -s 16384
.
Here's a link with default stack sizes for gcc.
DFS without recursion:
std::stack<Node> dfs;
dfs.push(start);
do {
Node top = dfs.top();
if (top is what we are looking for) {
break;
}
dfs.pop();
for (outgoing nodes from top) {
dfs.push(outgoing node);
}
} while (!dfs.empty())
Not difficult, check this.
<button @click="disabled = !disabled">Toggle Enable</button>
<input type="text" id="name" class="form-control" name="name" v-model="form.name" :disabled="disabled">
For PowerShell versions prior to v6, you can do this:
Stop-Service 'YourServiceName'; Get-CimInstance -ClassName Win32_Service -Filter "Name='YourServiceName'" | Remove-CimInstance
For v6+, you can use the Remove-Service cmdlet.
Observe that starting in Windows PowerShell 3.0, the cmdlet Get-WmiObject has been superseded by Get-CimInstance.
Put the iframe
inside the <p>
and make the iframe
CSS
float:left;
display:inline-block;
Since Java 8 you can use lambdas and achieve shorter code:
File dir = new File(xmlFilesDirectory);
File[] files = dir.listFiles((d, name) -> name.endsWith(".xml"));
for more advanced python editing consider installing the simplefold vim plugin. it allows you do advanced code folding using regular expressions. i use it to fold my class and method definitions for faster editing.
In my case also \n was not working, I fixed issue by keeping number of lines to 0 and copied and pasted the text with new line itself for example instead of Hello \n World i pasted
Hello
World
in the interface builder.
I don't know about Windows (never used it), but on a Linux system you just have to create a build directory (in the top source directory)
mkdir build-dir
go inside it
cd build-dir
then run cmake
and point to the parent directory
cmake ..
and finally run make
make
Notice that make
and cmake
are different programs. cmake
is a Makefile
generator, and the make
utility is governed by a Makefile
textual file. See cmake & make wikipedia pages.
NB: On Windows, cmake
might operate so could need to be used differently. You'll need to read the documentation (like I did for Linux)
object.__del__(self)
is called when the instance is about to be destroyed.
>>> class Test:
... def __del__(self):
... print "deleted"
...
>>> test = Test()
>>> del test
deleted
Object is not deleted unless all of its references are removed(As quoted by ethan)
Also, From Python official doc reference:
del x doesn’t directly call x.del() — the former decrements the reference count for x by one, and the latter is only called when x‘s reference count reaches zero
A little cheat sheet on module queries.
To check all existing versions: e.g. go list -m -versions github.com/gorilla/mux
E.g. go get github.com/gorilla/[email protected]
As Tmdean correctly pointed out you can use the Mid()
function. The MSDN Library also has a great reference section on VBScript which you can find here:
In this document Google JSON Style Guide (recommendations for building JSON APIs at Google),
It recommends that:
Property names must be camelCased, ASCII strings.
The first character must be a letter, an underscore (_) or a dollar sign ($).
Example:
{
"thisPropertyIsAnIdentifier": "identifier value"
}
My team follows this convention.
It means use rake that bundler is aware of and is part of your Gemfile over any rake that bundler is not aware of and run the db:migrate task.
async function FileToString (file) {
try {
let res = await file.raw.text();
console.log(res);
} catch (err) {
throw err;
}
}
Can use getElementsByTagName
var x = document.getElementsByTagName("title")[0];
alert(x.innerHTML)
// or
alert(x.textContent)
// or
document.querySelector('title')
Edits as suggested by Paul
This happens when libraries added to the project doesn't have the correct path.
I recently needed to create a date string with UTC and DST, and based on Sheldon's answer I put this together:
Date.prototype.getTimezone = function(showDST) {_x000D_
var jan = new Date(this.getFullYear(), 0, 1);_x000D_
var jul = new Date(this.getFullYear(), 6, 1);_x000D_
_x000D_
var utcOffset = new Date().getTimezoneOffset() / 60 * -1;_x000D_
var dstOffset = (jan.getTimezoneOffset() - jul.getTimezoneOffset()) / 60;_x000D_
_x000D_
var utc = "UTC" + utcOffset.getSign() + (utcOffset * 100).preFixed(1000);_x000D_
var dst = "DST" + dstOffset.getSign() + (dstOffset * 100).preFixed(1000);_x000D_
_x000D_
if (showDST) {_x000D_
return utc + " (" + dst + ")";_x000D_
}_x000D_
_x000D_
return utc;_x000D_
}_x000D_
Number.prototype.preFixed = function (preCeiling) {_x000D_
var num = parseInt(this, 10);_x000D_
if (preCeiling && num < preCeiling) {_x000D_
num = Math.abs(num);_x000D_
var numLength = num.toString().length;_x000D_
var preCeilingLength = preCeiling.toString().length;_x000D_
var preOffset = preCeilingLength - numLength;_x000D_
for (var i = 0; i < preOffset; i++) {_x000D_
num = "0" + num;_x000D_
}_x000D_
}_x000D_
return num;_x000D_
}_x000D_
Number.prototype.getSign = function () {_x000D_
var num = parseInt(this, 10);_x000D_
var sign = "+";_x000D_
if (num < 0) {_x000D_
sign = "-";_x000D_
}_x000D_
return sign;_x000D_
}_x000D_
_x000D_
document.body.innerHTML += new Date().getTimezone() + "<br>";_x000D_
document.body.innerHTML += new Date().getTimezone(true);
_x000D_
<p>Output for Turkey (UTC+0200) and currently in DST: UTC+0300 (DST+0100)</p>_x000D_
<hr>
_x000D_
Use Css Selector for this, or learn more about Css Selector just go here
https://www.w3schools.com/cssref/css_selectors.asp
#main_text > .title {
/* Style goes here */
}
#main_text .title {
/* Style goes here */
}
In case you need to do that from the command line, just copy, adapt & paste this snippet:
mysql -e "CREATE DATABASE \`new_database\`;"
for table in `mysql -B -N -e "SHOW TABLES;" old_database`
do
mysql -e "RENAME TABLE \`old_database\`.\`$table\` to \`new_database\`.\`$table\`"
done
mysql -e "DROP DATABASE \`old_database\`;"
This was pretty well answered over here: How to make a YouTube embedded video a full page width one?
If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)
<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
of the video it should play on load. Here's a demo over at jsfiddle.
I had the same problem, here is my description of the problem
"I created a store procedure which would generate 2200 Rows and would get executed in almost 2 seconds however after calling the store procedure from SSRS 2008 and run the report it actually never ran and ultimately I have to kill the BIDS (Business Intelligence development Studio) from task manager".
What I Tried: I tried running the SP from reportuser Login but SP was running normal for that user as well, I checked Profiler but nothing worked out.
Solution:
Actually the problem is that even though SP is generating the result but SSRS engine is taking time to read these many rows and render it back. So I added WITH RECOMPILE option in SP and ran the report .. this is when miracle happened and my problem got resolve.
Well, basically what I found is that you can declare the array, but when you set it vba shows you an error.
So I put an special sub to declare global variables and arrays, something like:
Global example(10) As Variant
Sub set_values()
example(1) = 1
example(2) = 1
example(3) = 1
example(4) = 1
example(5) = 1
example(6) = 1
example(7) = 1
example(8) = 1
example(9) = 1
example(10) = 1
End Sub
And whenever I want to use the array, I call the sub first, just in case
call set_values
Msgbox example(5)
Perhaps is not the most correct way, but I hope it works for you
\df+ <function_name>
in psql.
Why cant you use the finally block?
Like
try {
} catch (Exception e) {
// THIS WILL EXECUTE IF THERE IS AN EXCEPTION IS THROWN IN THE TRY BLOCK
} finally {
// THIS WILL EXECUTE IRRESPECTIVE OF WHETHER AN EXCEPTION IS THROWN WITHIN THE TRY CATCH OR NOT
}
EDIT after question amended:
You can do:
int? returnFromFunction2 = null;
try {
returnFromFunction2 = function2();
return returnFromFunction2.value;
} catch (Exception e) {
// THIS WILL EXECUTE IF THERE IS AN EXCEPTION IS THROWN IN THE TRY BLOCK
} finally {
if (returnFromFunction2.HasValue) { // do something with value }
// THIS WILL EXECUTE IRRESPECTIVE OF WHETHER AN EXCEPTION IS THROWN WITHIN THE TRY CATCH OR NOT
}
Set the style of each ListViewItem to have Focusable set to false.
<ListView ItemsSource="{Binding Test}" >
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Focusable" Value="False"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
you could have them be within a certain brightness. that would control the ammount of "neon" colors a bit. for instance, if the "brightness"
brightness = sqrt(R^2+G^2+B^2)
was within a certain high bound, it would have a washed out, light color to it. Conversely, if it was within a certain low bound, it would be darker. This would eliminate any crazy, standout colors and if you chose a bound really high or really low, they would all be fairly close to either white or black.
For list comprehension lovers, this will write all the key : value
pairs in new lines in dog.txt
my_dict = {'foo': [1,2], 'bar':[3,4]}
# create list of strings
list_of_strings = [ f'{key} : {my_dict[key]}' for key in my_dict ]
# write string one by one adding newline
with open('dog.txt', 'w') as my_file:
[ my_file.write(f'{st}\n') for st in list_of_strings ]
I had the same problem and here was my way to solve it:
First, You must know your IP address. On my Windows PC, in the cmd windows i run ipconfig and select my IP V4 address. In my case 192.168.0.13
Second as mention above: runserver 192.168.0.13:8000
It worked for me. The error i did to get the message was the use of the gateway address not my PC address.
Extended Choice Parameter plugin will allow you to read the choices from a file.
Of course, now you have another problem: how to make sure the file is up-to-date (that can be done with a post-commit hook) and propagated to all the users (that can be done by placing it on a shared file server). But there may be better solutions.
You can omit tel number for letting user just choose from contacts, but inserting your sms text in the body. Code is for Xamarin Android:
var uri = Uri.Parse("smsto:"); //append your number here for explicit nb
var intent = new Intent(Intent.ActionSendto, uri);
intent.PutExtra("sms_body", text);
Context.StartActivity(intent);
where
Context is Xamarin.Essentials.Platform.CurrentActivity ?? Application.Context
The question title is ambiguous.
You can select dropdown option value by name
jQuery("#option_id").find("option:contains('Monday')").each(function()
{
if( jQuery(this).text() == 'Monday' )
{
jQuery(this).attr("selected","selected");
}
});
Although fractional pixels may appear to round up on individual elements (as @SkillDrick demonstrates very well) it's important to know that the fractional pixels are actually respected in the actual box model.
This can best be seen when elements are stacked next to (or on top of) each other; in other words, if I were to place 400 0.5 pixel divs side by side, they would have the same width as a single 200 pixel div. If they all actually rounded up to 1px (as looking at individual elements would imply) we'd expect the 200px div to be half as long.
This can be seen in this runnable code snippet:
body {_x000D_
color: white;_x000D_
font-family: sans-serif;_x000D_
font-weight: bold;_x000D_
background-color: #334;_x000D_
}_x000D_
_x000D_
.div_house div {_x000D_
height: 10px;_x000D_
background-color: orange;_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
div#small_divs div {_x000D_
width: 0.5px;_x000D_
}_x000D_
_x000D_
div#large_div div {_x000D_
width: 200px;_x000D_
}
_x000D_
<div class="div_house" id="small_divs">_x000D_
<p>0.5px div x 400</p>_x000D_
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>_x000D_
</div>_x000D_
<br>_x000D_
<div class="div_house" id="large_div">_x000D_
<p>200px div x 1</p>_x000D_
<div></div>_x000D_
</div>
_x000D_
Alternatively you can use Jetty which is (now) part of the Eclipe Platform (the Help system is running Jetty). Besides Jetty is used by Android, Windows Mobile..
To get started check the Eclipse Wiki or if you prefer a Video And check out this related Post!
For me that solved it: https://coderwall.com/p/-ckobg
PROVISIONING_PROFILE = ...
"PROVISIONING_PROFILE[sdk=iphoneos*]" = ...
CODE_SIGN_IDENTITY = ...
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ...
I made a little helper for Entity Framework 6 (.Net Core style), to include sub-entities in a nice way.
It is on NuGet now : Install-Package ThenInclude.EF6
using System.Data.Entity;
var thenInclude = context.One.Include(x => x.Twoes)
.ThenInclude(x=> x.Threes)
.ThenInclude(x=> x.Fours)
.ThenInclude(x=> x.Fives)
.ThenInclude(x => x.Sixes)
.Include(x=> x.Other)
.ToList();
The package is available on GitHub.
If you're just quickly looking to keep a cmd instance open instead of exiting immediately, simply doing the following is enough
set /p asd="Hit enter to continue"
at the end of your script and it'll keep the window open.
Note that this'll set asd
as an environment variable, and can be replaced with anything else.
Following one liner gives the list you want.
mvv = mvv_count_df.select("mvv").rdd.flatMap(lambda x: x).collect()
Using the examples from Sohnee and karim79. I tested this and it worked in both FF3.6 and IE6.
<script type="text/javascript">
$(document).ready(function(){
$("#logo").bind("load", function () { $(this).fadeIn('slow'); });
});
</script>
<img src="http://www.gimp.org/tutorials/Lite_Quickies/quintet_hst_big.jpg" id="logo" style="display:none"/>
EDIT: to convert to array
int[] asIntegers = arr.Select(s => int.Parse(s)).ToArray();
This should do the trick:
var asIntegers = arr.Select(s => int.Parse(s));
import matplotlib.pyplot as plt
plt.figure(figsize=(8,8))
plt.subplot(3,2,1)
plt.subplot(3,2,3)
plt.subplot(3,2,5)
plt.subplot(2,2,2)
plt.subplot(2,2,4)
The first code creates the first subplot in a layout that has 3 rows and 2 columns.
The three graphs in the first column denote the 3 rows. The second plot comes just below the first plot in the same column and so on.
The last two plots have arguments (2, 2)
denoting that the second column has only two rows, the position parameters move row wise.
Check if that file is included in Build Phases -> Compiled Sources
Try command + t
.
It works for me.
In the terminal: For Xcode 9.x and above
$ open /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app
For Xcode-beta 9.x and above
$ open /Applications/Xcode-beta.app/Contents/Developer/Applications/Simulator.app
I'm told that it's bad practice to overuse it, but you can always add !important
after your code to prioritize the css properties value.
.p{height:400px!important;}
For linux users, you should know the following:
$CLASSPATH is specifically what Java uses to look through multiple directories to find all the different classes it needs for your script (unless you explicitly tell it otherwise with the -cp override). Using -cp (--classpath) requires that you keep track of all the directories manually and copy-paste that line every time you run the program (not preferable IMO).
The colon (":") character separates the different directories. There is only one $CLASSPATH and it has all the directories in it. So, when you run "export CLASSPATH=...." you want to include the current value "$CLASSPATH" in order to append to it. For example:
export CLASSPATH=.
export CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java-5.1.12.jar
In the first line above, you start CLASSPATH out with just a simple 'dot' which is the path to your current working directory. With that, whenever you run java it will look in the current working directory (the one you're in) for classes. In the second line above, $CLASSPATH grabs the value that you previously entered (.) and appends the path to a mysql dirver. Now, java will look for the driver AND for your classes.
echo $CLASSPATH
is super handy, and what it returns should read like a colon-separated list of all the directories you want java looking in for what it needs to run your script.
Tomcat does not use CLASSPATH. Read what to do about that here: https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html
On OSX with a homebrew install the full path to the opencv folder should work:
face_cascade = cv2.CascadeClassifier('/usr/local/Cellar/opencv/3.4.0_1/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('/usr/local/Cellar/opencv/3.4.0_1/share/OpenCV/haarcascades/haarcascade_eye.xml')
Take care of the version number in the path.
The easy way to send messages even if the app is in background and foreground as follow:- To send a message using API, you can use a tool called AdvancedREST Client, its a chrome extension, and send a message with the following parameters.
Rest client tool Link: https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo
use this url:- https://fcm.googleapis.com/fcm/send Content-Type:application/json Authorization:key=Your Server key From or Authoization key(see below ref)
{ "data": {
"image": "https://static.pexels.com/photos/4825/red-love-romantic-flowers.jpg",
"message": "Firebase Push Message Using API"
"AnotherActivity": "True"
},
"to" : "device id Or Device token"
}
Authorization key can be obtained by visiting Google developers console and click on Credentials button on the left menu for your project. Among the API keys listed, the server key will be your authorization key.
And you need to put tokenID of the receiver in the “to” section of your POST request sent using API.
if you want get all values from form in simple array you may be do something like this.
function getValues(form) {
var listvalues = new Array();
var datastring = $("#" + form).serializeArray();
var data = "{";
for (var x = 0; x < datastring.length; x++) {
if (data == "{") {
data += "\"" + datastring[x].name + "\": \"" + datastring[x].value + "\"";
}
else {
data += ",\"" + datastring[x].name + "\": \"" + datastring[x].value + "\"";
}
}
data += "}";
data = JSON.parse(data);
listvalues.push(data);
return listvalues;
};
For me it is like this,
Access
Storage
Size
Insertion/Deletion
I have passed through that error today and did everything described above but didn't work for me. So I decided to view the core problem and logged onto the MySQL root folder in Windows 7 and did this solution:
Go to folder:
C:\AppServ\MySQL
Right click and Run as Administrator these files:
mysql_servicefix.bat
mysql_serviceinstall.bat
mysql_servicestart.bat
Then close the entire explorer window and reopen it or clear cache then login to phpMyAdmin again.
To add one more important information to above provided answers -
For a process
def proc = command.execute();
always try to use
def outputStream = new StringBuffer();
proc.waitForProcessOutput(outputStream, System.err)
//proc.waitForProcessOutput(System.out, System.err)
rather than
def output = proc.in.text;
to capture the outputs after executing commands in groovy as the latter is a blocking call (SO question for reason).
Try this:
Dim s = "RAJAN"
Dim firstChar = s(0)
You can even do this:
Dim firstChar = "RAJAN"(0)
Yes, you can use the ALTER TABLE t AUTO_INCREMENT = 42
statement. However, you need to be aware that this will cause the rebuilding of your entire table, at least with InnoDB and certain MySQL versions. If you have an already existing dataset with millions of rows, it could take a very long time to complete.
In my experience, it's better to do the following:
BEGIN WORK;
-- You may also need to add other mandatory columns and values
INSERT INTO t (id) VALUES (42);
ROLLBACK;
In this way, even if you're rolling back the transaction, MySQL will keep the auto-increment value, and the change will be applied instantly.
You can verify this by issuing a SHOW CREATE TABLE t
statement. You should see:
> SHOW CREATE TABLE t \G
*************************** 1. row ***************************
Table: t
Create Table: CREATE TABLE `t` (
...
) ENGINE=InnoDB AUTO_INCREMENT=43 ...
As mentioned several times here
-webkit-appearance:none;
also removes the arrows, which is not what you want in most cases.
An easy workaround I found is to simply use select2 instead of select. You can re-style a select2 element as well, and most importantly, select2 looks the same on Windows, Android, iOS and Mac.
JavaScript only has a Number type that stores floating point values.
There is no int.
Edit:
If you want to format the number as a string with two digits after the decimal point use:
(4).toFixed(2)
you can use the shell (bash/ksh).
$ var="12345678abc"
$ replace="test"
$ echo ${var//12345678/$replace}
testabc
You can retrieve the date by using the getDate function:
$("#datepicker").datepicker( 'getDate' );
The value is returned as a JavaScript Date object.
If you want to use this value when the user selects a date, you can use the onSelect event:
$("#datepicker").datepicker({
onSelect: function(dateText, inst) {
var dateAsString = dateText; //the first parameter of this function
var dateAsObject = $(this).datepicker( 'getDate' ); //the getDate method
}
});
The first parameter is in this case the selected Date as String. Use parseDate to convert it to a JS Date Object.
See http://docs.jquery.com/UI/Datepicker for the full jQuery UI DatePicker reference.
Have a look at these pages. They contain many open source CSV parsers. JSaPar is one of them.
As others have indicated, something of the form
x ? y : z
is an expression, not a (complete) statement. It is an rvalue which needs to get used someplace - like on the right side of an assignment, or a parameter to a function etc.
Perhaps you could look at this: http://download.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html
def findMaxSales(listoftuples):
newlist = []
tuple = ()
for item in listoftuples:
movie = item[0]
value = (item[1])
tuple = value, movie
newlist += [tuple]
newlist.sort()
highest = newlist[-1]
result = highest[1]
return result
movieList = [("Finding Dory", 486), ("Captain America: Civil
War", 408), ("Deadpool", 363), ("Zootopia", 341), ("Rogue One", 529), ("The Secret Life of Pets", 368), ("Batman v Superman", 330), ("Sing", 268), ("Suicide Squad", 325), ("The Jungle Book", 364)]
print(findMaxSales(movieList))
output --> Rogue One
I will correct usage for that method that @BullyWillPlaza suggested. Reason is that when I try to add add textArea to only contextMenu it's not visible, and if i add it to both to contextMenu and some panel it ecounters: Different parent double association if i try to switch to Design editor.
TexetObjcet.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)){
contextmenu.add(TexetObjcet);
contextmenu.show(TexetObjcet, 0, 0);
}
}
});
Make mouse listener like this for text object you need to have popup on. What this will do is when you right click on your text object it will then add that popup and display it. This way you don't encounter that error. Solution that @BullyWillPlaza made is very good, rich and fast to implement in your program so you should try it our see how you like it.
If you just want to get the information of current directory, you can type:
pwd
and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.
Create a video thumbnail for a video. It may return null if the video is corrupted or the format is not supported.
private void makeVideoPreview() {
Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(videoAbsolutePath, MediaStore.Images.Thumbnails.MINI_KIND);
saveImage(thumbnail);
}
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
You should not use space character while naming database objects. Even though it's possible by using double quotes(quoted identifiers), CREATE TABLE "chartered flight" ...
, it's not recommended. Take a closer look here
This belongs in a comment to Phil Hunt's answer but alas I don't have the rep.
To strip the ".00" off the end of your number string, parsename is super-handy. It tokenizes period-delimited strings and returns the specified element, starting with the rightmost token as element 1.
SELECT PARSENAME(CONVERT(varchar, CAST(987654321 AS money), 1), 2)
Yields "987,654,321"
Imports Newtonsoft.Json.Linq
Dim json As JObject = JObject.Parse(Me.TextBox1.Text)
MsgBox(json.SelectToken("Venue").SelectToken("ID"))
None of the above answers worked for me, here is my solution which updates a disabled input with the filename:
<script type="text/javascript">
document.getElementById('img_name').onchange = function () {
var filePath = this.value;
if (filePath) {
var fileName = filePath.replace(/^.*?([^\\\/]*)$/, '$1');
document.getElementById('img_name_input').value = fileName;
}
};
</script>
Better solution is to introduce another interface for async operations. New interface must inherit from original interface.
Example:
interface IIO
{
void DoOperation();
}
interface IIOAsync : IIO
{
Task DoOperationAsync();
}
class ClsAsync : IIOAsync
{
public void DoOperation()
{
DoOperationAsync().GetAwaiter().GetResult();
}
public async Task DoOperationAsync()
{
//just an async code demo
await Task.Delay(1000);
}
}
class Program
{
static void Main(string[] args)
{
IIOAsync asAsync = new ClsAsync();
IIO asSync = asAsync;
Console.WriteLine(DateTime.Now.Second);
asAsync.DoOperation();
Console.WriteLine("After call to sync func using Async iface: {0}",
DateTime.Now.Second);
asAsync.DoOperationAsync().GetAwaiter().GetResult();
Console.WriteLine("After call to async func using Async iface: {0}",
DateTime.Now.Second);
asSync.DoOperation();
Console.WriteLine("After call to sync func using Sync iface: {0}",
DateTime.Now.Second);
Console.ReadKey(true);
}
}
P.S. Redesign your async operations so they return Task instead of void, unless you really must return void.
In Oracle :
ALTER TABLE one ADD two_id INTEGER CONSTRAINT Fk_two_id REFERENCES two(id);
If you want to run .py files in Windows, Try installing Git bash Then download python(Required Version) from python.org and install in the main c drive folder
For me, its :
"C:\Python38"
then open Git Bash and go to the respective folder where your .py file is stored :
For me, its :
File Location : "Downloads" File Name : Train.py
So i changed my Current working Directory From "C:/User/(username)/" to "C:/User/(username)/Downloads"
then i will run the below command
" /c/Python38/python Train.py "
and it will run successfully.
But if it give the below error :
from sklearn.model_selection import train_test_split ModuleNotFoundError: No module named 'sklearn'
Then Do not panic :
and use this command :
" /c/Python38/Scripts/pip install sklearn "
and after it has installed sklearn go back and run the previous command :
" /c/Python38/python Train.py "
and it will run successfully.
!!!!HAPPY LEARNING !!!!
You can do
[n.name for n in tf.get_default_graph().as_graph_def().node]
Also, if you are prototyping in an IPython notebook, you can show the graph directly in notebook, see show_graph
function in Alexander's Deep Dream notebook
nullptr
can't be assigned to an integral type such as an int
but only a pointer type; either a built-in pointer type such as int *ptr
or a smart pointer such as std::shared_ptr<T>
I believe this is an important distinction because NULL
can still be assigned to both an integral type and a pointer as NULL
is a macro expanded to 0
which can serve as both an initial value for an int
as well as a pointer.
Modern IPython uses the "--matplotlib
" argument with an optional backend parameter. It defaults to "auto", which is usually good enough on Mac and Windows. I haven't tested it on Ubuntu or any other Linux distribution, but I would expect it to work.
ipython --matplotlib
The argument to OrderByDescending
is a function returning a key to sort with. In your case, the key is the string itself:
var result = _animals.OrderByDescending(a => a);
If you wanted to sort by length for example, you'll write:
var result = _animals.OrderByDescending(a => a.Length);
Check the configurations in {M2_HOME}\conf\setting.xml as mentioned in the following link.
http://www.mkyong.com/maven/where-is-maven-local-repository/
Hope this helps.
Removing Language="c#" in global.asax file resolved the issue for me.
Date argDate = new Date(); //set your date.
String argTime = "09:00"; //9 AM - 24 hour format :- Set your time.
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
String dateTime = sdf.format(argDate) + " " + argTime;
Date requiredDate = dateFormat.parse(dateTime);
In your asp.net app use this
using System.Configuration;
Response.Write(ConfigurationManager.OpenMachineConfiguration().FilePath);
In a case
statement, a ,
is the equivalent of ||
in an if
statement.
case car
when 'toyota', 'lexus'
# code
end
Why so complicated? When you can do:
var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;
If you need more times check out the window.performance object:
console.log(window.performance);
Will show you the timing object:
connectEnd Time when server connection is finished.
connectStart Time just before server connection begins.
domComplete Time just before document readiness completes.
domContentLoadedEventEnd Time after DOMContentLoaded event completes.
domContentLoadedEventStart Time just before DOMContentLoaded starts.
domInteractive Time just before readiness set to interactive.
domLoading Time just before readiness set to loading.
domainLookupEnd Time after domain name lookup.
domainLookupStart Time just before domain name lookup.
fetchStart Time when the resource starts being fetched.
loadEventEnd Time when the load event is complete.
loadEventStart Time just before the load event is fired.
navigationStart Time after the previous document begins unload.
redirectCount Number of redirects since the last non-redirect.
redirectEnd Time after last redirect response ends.
redirectStart Time of fetch that initiated a redirect.
requestStart Time just before a server request.
responseEnd Time after the end of a response or connection.
responseStart Time just before the start of a response.
timing Reference to a performance timing object.
navigation Reference to performance navigation object.
performance Reference to performance object for a window.
type Type of the last non-redirect navigation event.
unloadEventEnd Time after the previous document is unloaded.
unloadEventStart Time just before the unload event is fired.
How about nan_to_num()?
The traffic will show up in Fiddler under your computer's IP address.
The main difference between the two types of fetching is a moment when data gets loaded into a memory.
I have attached 2 photos to help you understand this.
you can also use VSCommands 2010 to run as different user:
Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.
@RestController
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {
@Value("${name}")//not necessary
private String name;//not necessary
private static String NAME_STATIC;
@Value("${name}")
public void setNameStatic(String name){
PropertyController.NAME_STATIC = name;
}
}
This is just another example of how you can use Dropzone.js in an existing form.
dropzone.js :
init: function() {
this.on("success", function(file, responseText) {
//alert("HELLO ?" + responseText);
mylittlefix(responseText);
});
return noop;
},
Then, later in the file I put
function mylittlefix(responseText) {
$('#botofform').append('<input type="hidden" name="files[]" value="'+ responseText +'">');
}
This assumes you have a div with id #botofform
that way when uploading you can use the uploaded files' names.
Note: my upload script returned theuploadedfilename.jpeg dubblenote you also would need to make a cleanup script that checks the upload directory for files not in use and deletes them ..if in a front end non authenticated form :)
public class LeadingZerosExample {
public static void main(String[] args) {
int number = 1500;
// String format below will add leading zeros (the %0 syntax)
// to the number above.
// The length of the formatted string will be 7 characters.
String formatted = String.format("%07d", number);
System.out.println("Number with leading zeros: " + formatted);
}
}
Open Developer Tools
...
-> More Tools
-> Developer Tools
Click Empty Cache and Hard Reload
function relativepath($to){
$a=explode("/",$_SERVER["PHP_SELF"] );
$index= array_search("$to",$a);
$str="";
for ($i = 0; $i < count($a)-$index-2; $i++) {
$str.= "../";
}
return $str;
}
Here is the best solution i made about that, you just need to specify at which level you want to stop, but the problem is that you have to use this folder name one time.
You can't. If you have a method called isBiggerThanMaxLong(long)
it should always return false
.
If you were to increment the bits of Long.MAX_VALUE
, the next value should be Long.MIN_VALUE
. Read up on twos-complement and that should tell you why.
Write yourself a Helper function:
public static bool IsBewteenTwoDates(this DateTime dt, DateTime start, DateTime end)
{
return dt >= start && dt <= end;
}
Then call: .IsBewteenTwoDates(DateTime.Today ,new DateTime(,,));
I looked to MS to find the answers. The first solution assumes the user account running the application process has access to the shared folder or drive (Same domain). Make sure your DNS is resolved or try using IP address. Simply do the following:
DirectoryInfo di = new DirectoryInfo(PATH);
var files = di.EnumerateFiles("*.*", SearchOption.AllDirectories);
If you want across different domains .NET 2.0 with credentials follow this model:
WebRequest req = FileWebRequest.Create(new Uri(@"\\<server Name>\Dir\test.txt"));
req.Credentials = new NetworkCredential(@"<Domain>\<User>", "<Password>");
req.PreAuthenticate = true;
WebResponse d = req.GetResponse();
FileStream fs = File.Create("test.txt");
// here you can check that the cast was successful if you want.
fs = d.GetResponseStream() as FileStream;
fs.Close();
What you should do is create a service to share data between controllers.
Nice tutorial https://www.youtube.com/watch?v=HXpHV5gWgyk
string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'_');
Alternatively, to change all characters except numbers and letters, try:
string = string.replace(/[^a-zA-Z0-9]/g,'_');
Correct Method is
.PopupPanel
{
border: solid 1px black;
position: fixed;
left: 50%;
top: 50%;
background-color: white;
z-index: 100;
height: 400px;
margin-top: -200px;
width: 600px;
margin-left: -300px;
}
Check out, if NUnit Test Adapter 2/3 is installed in VisualStudio.
(Tools>Extensions and Updates )
Make sure that correct processor architecture is chosen:
(Test>Test Settings>Default Processor Architecture)
If you found this thread trying to compare data fames in tests, then take a look at assert_frame_equal
method: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.testing.assert_frame_equal.html
This works for me
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
sns.factorplot(x='holiday',data=data,kind='count',size=5,aspect=1)
plt.savefig('holiday-vs-count.png')
In Spring Boot 2, the easiest way is to declare in your application.properties:
spring.jackson.serialization.WRITE_ENUMS_USING_TO_STRING=true
spring.jackson.deserialization.READ_ENUMS_USING_TO_STRING=true
and define the toString() method of your enums.
Working with Eclipse can be difficult at times, probably when debugging and designing layouts Eclipse sometimes get stuck and we have to restart Eclipse from time to time. Also you get problems with emulators.
Android studio was released very recently and this IDE is not yet heavily used by developers. Therefore, it may contain certain bugs.
This describes the difference between android android studio and eclipse project structure: Android Studio Project Structure (v.s. Eclipse Project Structure)
This teaches you how to use the android studio: http://www.infinum.co/the-capsized-eight/articles/android-studio-vs-eclipse-1-0
To even do better boolean mapping to Y/N, add to your hibernate configuration:
<!-- when using type="yes_no" for booleans, the line below allow booleans in HQL expressions: -->
<property name="hibernate.query.substitutions">true 'Y', false 'N'</property>
Now you can use booleans in HQL, for example:
"FROM " + SomeDomainClass.class.getName() + " somedomainclass " +
"WHERE somedomainclass.someboolean = false"
The line should be:
numpy.concatenate([a,b])
The arrays you want to concatenate need to be passed in as a sequence, not as separate arguments.
From the NumPy documentation:
numpy.concatenate((a1, a2, ...), axis=0)
Join a sequence of arrays together.
It was trying to interpret your b
as the axis parameter, which is why it complained it couldn't convert it into a scalar.
I'm assuming you're using your own array types as opposed to the built-in .NET arrays:
public string[] merge(input1, input2)
{
string[] output = new string[input1.length + input2.length];
for(int i = 0; i < output.length; i++)
{
if (i >= input1.length)
output[i] = input2[i-input1.length];
else
output[i] = input1[i];
}
return output;
}
Another way of doing this would be using the built in ArrayList class.
public ArrayList merge(input1, input2)
{
Arraylist output = new ArrayList();
foreach(string val in input1)
output.add(val);
foreach(string val in input2)
output.add(val);
return output;
}
Both examples are C#.
I like both @Qiao first answer and @Or's addition. For a sake of a little less processing I would like to add to Or's answer.
In @Or's answer keeping track of visited node is great. We can also allow the program to exit sooner that it currently is. At some point in the for loop the current_neighbour
will have to be the end
, and once that happens the shortest path is found and program can return.
I would modify the the method as follow, pay close attention to the for loop
graph = {
1: [2, 3, 4],
2: [5, 6],
3: [10],
4: [7, 8],
5: [9, 10],
7: [11, 12],
11: [13]
}
def bfs(graph_to_search, start, end):
queue = [[start]]
visited = set()
while queue:
# Gets the first path in the queue
path = queue.pop(0)
# Gets the last node in the path
vertex = path[-1]
# Checks if we got to the end
if vertex == end:
return path
# We check if the current node is already in the visited nodes set in order not to recheck it
elif vertex not in visited:
# enumerate all adjacent nodes, construct a new path and push it into the queue
for current_neighbour in graph_to_search.get(vertex, []):
new_path = list(path)
new_path.append(current_neighbour)
queue.append(new_path)
#No need to visit other neighbour. Return at once
if current_neighbour == end
return new_path;
# Mark the vertex as visited
visited.add(vertex)
print bfs(graph, 1, 13)
The output and everything else will be the same. However, the code will take less time to process. This is especially useful on larger graphs. I hope this helps someone in the future.
Here is an example to test behavior of daemon threads in case of jvm exit due to non existence of user threads.
Please note second last line in the output below, when main thread exited, daemon thread also died and did not print finally executed9 statement within finally block. This means that any i/o resources closed within finally block of a daemon thread will not be closed if JVM exits due to non existence of user threads.
public class DeamonTreadExample {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
int count = 0;
while (true) {
count++;
try {
System.out.println("inside try"+ count);
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
System.out.println("finally executed"+ count);
}
}
});
t.setDaemon(true);
t.start();
Thread.currentThread().sleep(10000);
System.out.println("main thread exited");
}
}
inside try1
finally executed1
inside try2
finally executed2
inside try3
finally executed3
inside try4
finally executed4
inside try5
finally executed5
inside try6
finally executed6
inside try7
finally executed7
inside try8
finally executed8
inside try9
finally executed9
inside try10
main thread exited
Using a more geometric approach, calculate the following distances:
ab = sqrt((a.x-b.x)**2 + (a.y-b.y)**2)
ac = sqrt((a.x-c.x)**2 + (a.y-c.y)**2)
bc = sqrt((b.x-c.x)**2 + (b.y-c.y)**2)
and test whether ac+bc equals ab:
is_on_segment = abs(ac + bc - ab) < EPSILON
That's because there are three possibilities:
foo.GetColumnValues(dm.mainColumn, typeof(string))
Alternatively, you could use a generic method:
public void GetColumnValues<T>(object mainColumn)
{
GetColumnValues(mainColumn, typeof(T));
}
and you could then use it like:
foo.GetColumnValues<string>(dm.mainColumn);
The exception is due to your JAXB (JSR-222) implementation believing that there are two things mapped with the same name (a field and a property). There are a couple of options for your use case:
OPTION #1 - Annotate the Field with @XmlAccessorType(XmlAccessType.FIELD)
If you want to annotation the field then you should specify @XmlAccessorType(XmlAccessType.FIELD)
Fields.java:
package forum10795793;
import java.util.*;
import javax.xml.bind.annotation.*;
@XmlRootElement(name = "fields")
@XmlAccessorType(XmlAccessType.FIELD)
public class Fields {
@XmlElement(name = "field")
List<Field> fields = new ArrayList<Field>();
public List<Field> getFields() {
return fields;
}
public void setFields(List<Field> fields) {
this.fields = fields;
}
}
Field.java:
package forum10795793;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Field {
@XmlAttribute(name = "mappedField")
String mappedField;
public String getMappedField() {
return mappedField;
}
public void setMappedField(String mappedField) {
this.mappedField = mappedField;
}
}
OPTION #2 - Annotate the Properties
The default accessor type is XmlAccessType.PUBLIC
. This means that by default JAXB implementations will map public fields and accessors to XML. Using the default setting you should annotate the public accessors where you want to override the default mapping behaviour.
Fields.java:
package forum10795793;
import java.util.*;
import javax.xml.bind.annotation.*;
@XmlRootElement(name = "fields")
public class Fields {
List<Field> fields = new ArrayList<Field>();
@XmlElement(name = "field")
public List<Field> getFields() {
return fields;
}
public void setFields(List<Field> fields) {
this.fields = fields;
}
}
Field.java:
package forum10795793;
import javax.xml.bind.annotation.*;
public class Field {
String mappedField;
@XmlAttribute(name = "mappedField")
public String getMappedField() {
return mappedField;
}
public void setMappedField(String mappedField) {
this.mappedField = mappedField;
}
}
For More Information
Both certificates should exist prior to the connection. They're usually created by Certification Authorities (not necessarily the same). (There are alternative cases where verification can be done differently, but some verification will need to be made.)
The server certificate should be created by a CA that the client trusts (and following the naming conventions defined in RFC 6125).
The client certificate should be created by a CA that the server trusts.
It's up to each party to choose what it trusts.
There are online CA tools that will allow you to apply for a certificate within your browser and get it installed there once the CA has issued it. They need not be on the server that requests client-certificate authentication.
The certificate distribution and trust management is the role of the Public Key Infrastructure (PKI), implemented via the CAs. The SSL/TLS client and servers and then merely users of that PKI.
When the client connects to a server that requests client-certificate authentication, the server sends a list of CAs it's willing to accept as part of the client-certificate request. The client is then able to send its client certificate, if it wishes to and a suitable one is available.
The main advantages of client-certificate authentication are:
You may be interested in Advantages of client certificates for client authentication? (on Security.SE).
This should work:
dists[((dists >= r) & (dists <= r+dr))]
The most elegant way~~
Long
is the Object
form of long
, and Integer
is the object form of int
.
The long
uses 64 bits. The int
uses 32 bits, and so can only hold numbers up to ±2 billion (-231 to +231-1).
You should use long
and int
, except where you need to make use of methods inherited from Object
, such as hashcode
. Java.util.collections
methods usually use the boxed (Object
-wrapped) versions, because they need to work for any Object
, and a primitive type, like int
or long
, is not an Object
.
Another difference is that long
and int
are pass-by-value, whereas Long
and Integer
are pass-by-reference value, like all non-primitive Java types. So if it were possible to modify a Long
or Integer
(it's not, they're immutable without using JNI code), there would be another reason to use one over the other.
A final difference is that a Long
or Integer
could be null
.
Click "View Detail..." a window will open where you can expand the "Inner Exception" my guess is that when you try to delete the record there is a reference constraint violation. The inner exception will give you more information on that so you can modify your code to remove any references prior to deleting the record.
You may catch multiple exceptions in single catch block.
try{
// somecode throwing multiple exceptions;
} catch (Exception1 | Exception2 | Exception3 exception){
// handle exception.
}
There is no .NET framework support for IMAP. You'll need to use some 3rd party component.
Try https://www.limilabs.com/mail, it's very affordable and easy to use, it also supports SSL:
using(Imap imap = new Imap())
{
imap.ConnectSSL("imap.company.com");
imap.Login("user", "password");
imap.SelectInbox();
List<long> uids = imap.SearchFlag(Flag.Unseen);
foreach (long uid in uids)
{
string eml = imap.GetMessageByUID(uid);
IMail message = new MailBuilder()
.CreateFromEml(eml);
Console.WriteLine(message.Subject);
Console.WriteLine(message.TextDataString);
}
imap.Close(true);
}
Please note that this is a commercial product I've created.
You can download it here: https://www.limilabs.com/mail.
String car [];
is a reference to an array of String-s. You can't see a length because there is no array there!
Django=2.2.12 django-cors-headers=3.2.1 djangorestframework=3.11.0
Follow the official instruction doesn't work
Finally use the old way to figure it out.
ADD:
# proj/middlewares.py
from rest_framework.authentication import SessionAuthentication
class CsrfExemptSessionAuthentication(SessionAuthentication):
def enforce_csrf(self, request):
return # To not perform the csrf check previously happening
#proj/settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'proj.middlewares.CsrfExemptSessionAuthentication',
),
}
Tried in Hive and got the below output
table1
1,wqe,chennai,india
2,stu,salem,india
3,mia,bangalore,india
4,yepie,newyork,USA
table2
1,wqe,chennai,india
2,stu,salem,india
3,mia,bangalore,india
5,chapie,Los angels,USA
Inner Join
SELECT * FROM table1 INNER JOIN table2 ON (table1.id = table2.id);
1 wqe chennai india 1 wqe chennai india
2 stu salem india 2 stu salem india
3 mia bangalore india 3 mia bangalore india
Left Join
SELECT * FROM table1 LEFT JOIN table2 ON (table1.id = table2.id);
1 wqe chennai india 1 wqe chennai india
2 stu salem india 2 stu salem india
3 mia bangalore india 3 mia bangalore india
4 yepie newyork USA NULL NULL NULL NULL
Left Semi Join
SELECT * FROM table1 LEFT SEMI JOIN table2 ON (table1.id = table2.id);
1 wqe chennai india
2 stu salem india
3 mia bangalore india
note: Only records in left table are displayed whereas for Left Join both the table records displayed
In Visual Studio 2012, the same can be done using the "Sync With Active Document" option in Solution Explorer
With sed, I usually implement non-greedy search by searching for anything except the separator until the separator :
echo "http://www.suon.co.uk/product/1/7/3/" | sed -n 's;\(http://[^/]*\)/.*;\1;p'
Output:
http://www.suon.co.uk
this is:
-n
s/<pattern>/<replace>/p
;
search command separator instead of /
to make it easier to type so s;<pattern>;<replace>;p
\(
... \)
, later accessible with \1
,\2
...http://
[]
, [ab/]
would mean either a
or b
or /
^
in []
means not
, so followed by anything but the thing in the []
[^/]
means anything except /
character*
is to repeat previous group so [^/]*
means characters except /
.sed -n 's;\(http://[^/]*\)
means search and remember http://
followed by any characters except /
and remember what you've found/
so add another /
at the end: sed -n 's;\(http://[^/]*\)/'
but we want to match the rest of the line after the domain so add .*
\1
) is the domain so replace matched line with stuff saved in group \1
and print: sed -n 's;\(http://[^/]*\)/.*;\1;p'
If you want to include backslash after the domain as well, then add one more backslash in the group to remember:
echo "http://www.suon.co.uk/product/1/7/3/" | sed -n 's;\(http://[^/]*/\).*;\1;p'
output:
http://www.suon.co.uk/
No longer works for spreadsheets Protected with Excel 2013 or later -- they improved the pw hash. So now need to unzip .xlsx and hack the internals.
I think you may have missed this part in the tutorial:
Instead of referencing System.Data and System.Data.SqlClient you need to grab from Nuget:
System.Data.Common and System.Data.SqlClient.
Currently this creates dependency in project.json –> aspnetcore50 section to these two libraries.
"aspnetcore50": { "dependencies": { "System.Runtime": "4.0.20-beta-22523", "System.Data.Common": "4.0.0.0-beta-22605", "System.Data.SqlClient": "4.0.0.0-beta-22605" } }
Try getting System.Data.Common and System.Data.SqlClient via Nuget and see if this adds the above dependencies for you, but in a nutshell you are missing System.Runtime.
Edit: As per Mozarts answer, if you are using .NET Core 3+, reference Microsoft.Data.SqlClient
instead.
You are prematurely optimizing. Also, you should really put some thought into whether GET should be used for stuff you're POST-ing, for security reasons.
The clue is in the error message - if you look at the documentation for json_decode
note that it can take a second param, which controls whether it returns an array or an object - it defaults to object.
So change your call to
$json = json_decode(file_get_contents($file), true);
And it'll return an associative array and your code should work fine.
I may be late, but the way I did it was to create a hidden submit input, and calling it's click handler upon submit. Something like (using jquery for simplicity):
<input type="text" id="example" name="example" value="" required>
<button type="button" onclick="submitform()" id="save">Save</button>
<input id="submit_handle" type="submit" style="display: none">
<script>
function submitform() {
$('#submit_handle').click();
}
</script>
$scope.reloadstat = function () { $state.go($state.current, {}, {reload: true}); };
I share some code how to fetch proxies from the site "https://free-proxy-list.net" and store data to a file compatible with tools like "Elite Proxy Switcher"(format IP:PORT):
##PROXY_UPDATER - get free proxies from https://free-proxy-list.net/
from lxml.html import fromstring
import requests
from itertools import cycle
import traceback
import re
######################FIND PROXIES#########################################
def get_proxies():
url = 'https://free-proxy-list.net/'
response = requests.get(url)
parser = fromstring(response.text)
proxies = set()
for i in parser.xpath('//tbody/tr')[:299]: #299 proxies max
proxy = ":".join([i.xpath('.//td[1]/text()')
[0],i.xpath('.//td[2]/text()')[0]])
proxies.add(proxy)
return proxies
######################write to file in format IP:PORT######################
try:
proxies = get_proxies()
f=open('proxy_list.txt','w')
for proxy in proxies:
f.write(proxy+'\n')
f.close()
print ("DONE")
except:
print ("MAJOR ERROR")
Consider a server which has the information of users, missions and their reward points.
Source: API Endpoints vs Resources
I think the problem is the way you call your javascript function. Your code is like so:
<input type="button" onclick="javascript: myFunc(myID)" value="button"/>
myID should be wrapped in quotes.
To see of the curent time is greater or equal to 14:08:10 do this:
if (time() >= strtotime("14:08:10")) {
echo "ok";
}
Depending on your input sources, make sure to account for timezone.
See PHP time() and PHP strtotime()
You were on the right track with response.getOutputStream()
, but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:
@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
// convert JSON to Employee
Employee emp = convertSomehow(json);
// generate the file
PdfUtil.showHelp(emp);
// retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
byte[] contents = (...);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
// Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
return response;
}
Notes:
showHelp
is not a good ideabyte[]
: example hereshowHelp()
to avoid overwriting the file if two users send a request at the same timeI think this will work.
<gridview>
<Columns>
<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument="<%# Container.DataItemIndex %>" />
</Columns>
</gridview>
If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).
Eclipse Classic is basically the full featured Eclipse without the Java EE part.
I think that it's better to use simply str_replace, like the manual says:
If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of ereg_replace() or preg_replace().
<?
$badUrl = "http://www.site.com/backend.php?/c=crud&m=index&t=care";
$goodUrl = str_replace('?/', '?', $badUrl);
Here is a solution that does not require a SQL context, but maintains the metadata of a DataFrame.
a = sc.parallelize([['a', 'foo'], ['b', 'hem'], ['c', 'haw']]).toDF(['a_id', 'extra'])
b = sc.parallelize([['p1', 'a'], ['p2', 'b'], ['p3', 'c']]).toDF(["other", "b_id"])
c = a.join(b, a.a_id == b.b_id)
Then, c.show()
yields:
+----+-----+-----+----+
|a_id|extra|other|b_id|
+----+-----+-----+----+
| a| foo| p1| a|
| b| hem| p2| b|
| c| haw| p3| c|
+----+-----+-----+----+
To put it simple. A calendar object stores information about time zone but when you perform cal.getTime() then the timezone information will be lost. So for Timezone conversions I will advice to use DateFormat classes...
Try below code :
Assign the path of the folder to variable FolderPath
before running the below code.
Sub sample()
Dim FolderPath As String, path As String, count As Integer
FolderPath = "C:\Documents and Settings\Santosh\Desktop"
path = FolderPath & "\*.xls"
Filename = Dir(path)
Do While Filename <> ""
count = count + 1
Filename = Dir()
Loop
Range("Q8").Value = count
'MsgBox count & " : files found in folder"
End Sub
I have successfully run our app, which requires Google Maps API 2, on an AndroVM virtual machine.
AndroVM does not come with Google Maps or Google Play installed, but provides a modified copy of the Cyanogen Gapps archive, which is a set of the proprietary Google apps installed on most Android devices.
The instructions, copied from the AndroVM FAQ:
How can I install Google Apps (including the Market/Play app) ?
- Download Google Apps : gapps-jb-20121011-androvm.tgz [basically the /system directory from the Cyanogen gapps archive without the GoogleTTS app which crashes on AndroVM]
- Untar the gapps…tgz file on your host – you’ll have a system directory created
- Get the management IP address of your AndroVM (“AndroVM Configuration” tool) and do “adb connect x.y.z.t”
- do “adb root”
- reconnect with “adn connect x.y.z.t”
- do “adb remount”
- do “adb push system/ /system/”
Your VM will reboot and you should have google apps including Market/Play.
You won’t have some Google Apps, like Maps, but they can be downloaded from the Market/Play.
So follow those instructions, then just install Google Maps using Google Play!
Some great side effects of using a VM rather than the emulator:
The only bump in the road so far has been lack of multi-touch gestures, which is a bummer for a mapping app! I plan to work around this with a hidden UI mechanism, so not such a huge problem.
If any of other solution doesn't fix it, try to override the styles to hide the sort togglers:
.sorting_asc:after, .sorting_desc:after {
content: "";
}
You can execute shell script in two ways,either by using cron job or by writing a shell script
Lets assume your script name is "yourscript.sh"
First check the user permission of the script. use below command to check user permission of the script
ll script.sh
If the script is in root,then use below command
sudo crontab -e
Second if the script holds the user "ubuntu", then use below command
crontab -e
Add the following line in your crontab:-
55 23 * * * /path/to/yourscript.sh
Another way of doing this is to write a script and run it in the backgroud
Here is the script where you have to put your script name(eg:- youscript.sh) which is going to run at 23:55pm everyday
#!/bin/bash
while true
do
/home/modassir/yourscript.sh
sleep 1d
done
save it in a file (lets name it "every-day.sh")
sleep 1d - means it waits for one day and then it runs again.
now give the permission to your script.use below command:-
chmod +x every-day.sh
now, execute this shell script in the background by using "nohup". This will keep executing the script even after you logout from your session.
use below command to execute the script.
nohup ./every-day.sh &
Note:- to run "yourscript.sh" at 23:55pm everyday,you have to execute "every-day.sh" script at exactly 23:55pm.
If you are setting the spinner values by arraylist
or array
you can set the spinner's selection by using the index of the value.
String myString = "some value"; //the value you want the position for
ArrayAdapter myAdap = (ArrayAdapter) mySpinner.getAdapter(); //cast to an ArrayAdapter
int spinnerPosition = myAdap.getPosition(myString);
//set the default according to value
spinner.setSelection(spinnerPosition);
see the link How to set selected item of Spinner by value, not by position?
Simple and easy. You can do this from the URI just like below!
public void getContents(Uri uri)
{
Cursor vidCursor = getActivity.getContentResolver().query(uri, null, null,
null, null);
if (vidCursor.moveToFirst())
{
int column_index =
vidCursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
Uri filePathUri = Uri.parse(vidCursor .getString(column_index));
String video_name = filePathUri.getLastPathSegment().toString();
String file_path=filePathUri.getPath();
Log.i("TAG", video_name + "\b" file_path);
}
}
item.date = $filter('date')(item.date, "dd/MM/yyyy"); // for conversion to string
http://docs.angularjs.org/api/ng.filter:date
But if you are using HTML5 type="date" then the ISO format yyyy-MM-dd MUST be used.
item.dateAsString = $filter('date')(item.date, "yyyy-MM-dd"); // for type="date" binding
<input type="date" ng-model="item.dateAsString" value="{{ item.dateAsString }}" pattern="dd/MM/YYYY"/>
http://www.w3.org/TR/html-markup/input.date.html
NOTE: use of pattern="" with type="date" looks non-standard, but it appears to work in the expected way in Chrome 31.
For check of email use email_validator
from email_validator import validate_email, EmailNotValidError
def check_email(email):
try:
v = validate_email(email) # validate and get info
email = v["email"] # replace with normalized form
print("True")
except EmailNotValidError as e:
# email is not valid, exception message is human-readable
print(str(e))
check_email("test@gmailcom")
Create list using C++ templates
i.e
template <class T> struct Node
{
T data;
Node * next;
};
template <class T> class List
{
Node<T> *head,*tail;
public:
void push(T const&); // push element
void pop(); // pop element
bool empty() // return true if empty.
};
Then you can write the code like:
List<MyClass>;
The type T
is not dynamic in run time.It is only for the compile time.
For complete example click here.
For C++ templates tutorial click here.
Try this:
SELECT REPLACE(RTRIM(REPLACE(REPLACE(RTRIM(REPLACE(CAST(CAST(YOUR_FLOAT_COLUMN_NAME AS DECIMAL(18,9)) AS VARCHAR(20)),'0',' ')),' ','0'),'.',' ')),' ','.') FROM YOUR_TABLE_NAME
Try the following css:
#innerbox
{
width:250px; /* or whatever width you want. */
max-width:250px; /* or whatever width you want. */
display: inline-block;
}
This makes the div take as little space as possible, and its width is defined by the css.
// Expanded answer
To make the buttons fixed widths do the following :
#innerbox input
{
width:150px; /* or whatever width you want. */
max-width:150px; /* or whatever width you want. */
}
However, you should be aware that as the size of the text changes, so does the space needed to display it. As such, it's natural that the containers need to expand. You should perhaps review what you are trying to do; and maybe have some predefined classes that you alter on the fly using javascript to ensure the content placement is perfect.
Near the top of the code with the Public Workshop(), I am assumeing this bit,
suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);
suitButton = new JCheckBox("Denim Jeans");
suitButton.setMnemonic(KeyEvent.VK_U);
should maybe be,
suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);
denimjeansButton = new JCheckBox("Denim Jeans");
denimjeansButton.setMnemonic(KeyEvent.VK_U);
I would Suggest that you do the folllowing,
<?php
function EXPORT_TABLES($host, $user, $pass, $name, $tables = false, $backup_name = false)
{
$mysqli = new mysqli($host, $user, $pass, $name);
$mysqli->select_db($name);
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES');
while ($row = $queryTables->fetch_row())
{
$target_tables[] = $row[0];
}
if ($tables !== false)
{
$target_tables = array_intersect($target_tables, $tables);
}
$content = "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8 */;\r\n--Database: `" . $name . "`\r\n\r\n\r\n";
foreach ($target_tables as $table)
{
$result = $mysqli->query('SELECT * FROM ' . $table);
$fields_amount = $result->field_count;
$rows_num = $mysqli->affected_rows;
$res = $mysqli->query('SHOW CREATE TABLE ' . $table);
$TableMLine = $res->fetch_row();
$content .= "\n\n" . $TableMLine[1] . ";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter = 0)
{
while ($row = $result->fetch_row())
{ //when started (and every after 100 command cycle):
if ($st_counter % 100 == 0 || $st_counter == 0)
{
$content .= "\nINSERT INTO " . $table . " VALUES";
}
$content .= "\n(";
for ($j = 0; $j < $fields_amount; $j++)
{
$row[$j] = str_replace("\n", "\\n", addslashes($row[$j]));
if (isset($row[$j]))
{
$content .= '"' . $row[$j] . '"';
}
else
{
$content .= '""';
} if ($j < ($fields_amount - 1))
{
$content.= ',';
}
}
$content .=")";
//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
if ((($st_counter + 1) % 100 == 0 && $st_counter != 0) || $st_counter + 1 == $rows_num)
{
$content .= ";";
}
else
{
$content .= ",";
} $st_counter = $st_counter + 1;
}
} $content .="\n\n\n";
}
$content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;";
$backup_name = $backup_name ? $backup_name : $name . "___(" . date('H-i-s') . "_" . date('d-m-Y') . ")__rand" . rand(1, 11111111) . ".sql";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . $backup_name . "\"");
echo $content;
exit;
}
?>
The enitre project for export and import can be found at https://github.com/tazotodua/useful-php-scripts.
try using begin.startOf('isoWeek');
instead of begin.startOf('week');
Marc Gravell's answer is very complete, but I thought I'd add something about this from the user's point of view, as well...
The main difference, from a user's perspective, is that, when you use IQueryable<T>
(with a provider that supports things correctly), you can save a lot of resources.
For example, if you're working against a remote database, with many ORM systems, you have the option of fetching data from a table in two ways, one which returns IEnumerable<T>
, and one which returns an IQueryable<T>
. Say, for example, you have a Products table, and you want to get all of the products whose cost is >$25.
If you do:
IEnumerable<Product> products = myORM.GetProducts();
var productsOver25 = products.Where(p => p.Cost >= 25.00);
What happens here, is the database loads all of the products, and passes them across the wire to your program. Your program then filters the data. In essence, the database does a SELECT * FROM Products
, and returns EVERY product to you.
With the right IQueryable<T>
provider, on the other hand, you can do:
IQueryable<Product> products = myORM.GetQueryableProducts();
var productsOver25 = products.Where(p => p.Cost >= 25.00);
The code looks the same, but the difference here is that the SQL executed will be SELECT * FROM Products WHERE Cost >= 25
.
From your POV as a developer, this looks the same. However, from a performance standpoint, you may only return 2 records across the network instead of 20,000....
Try this: (source: http://just-another-blog.net/programming/powershell-and-the-net-framework/)
Add-Type -AssemblyName System.Windows.Forms
$position = [System.Windows.Forms.Cursor]::Position
$position.X++
[System.Windows.Forms.Cursor]::Position = $position
while(1) {
$position = [System.Windows.Forms.Cursor]::Position
$position.X++
[System.Windows.Forms.Cursor]::Position = $position
$time = Get-Date;
$shorterTimeString = $time.ToString("HH:mm:ss");
Write-Host $shorterTimeString "Mouse pointer has been moved 1 pixel to the right"
#Set your duration between each mouse move
Start-Sleep -Seconds 150
}
$('html').keyup(function(e){
if(e.keyCode == 46) {
alert('Delete key released');
}
});
Source: javascript char codes key codes from www.cambiaresearch.com
There is this extensions that adds an event listener to attribute changes.
Usage:
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript"
src="https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange.js"></script>
Bind attrchange handler function to selected elements
$(selector).attrchange({
trackValues: true, /* Default to false, if set to true the event object is
updated with old and new value.*/
callback: function (event) {
//event - event object
//event.attributeName - Name of the attribute modified
//event.oldValue - Previous value of the modified attribute
//event.newValue - New value of the modified attribute
//Triggered when the selected elements attribute is added/updated/removed
}
});
There are lots of free tools that can do this.
I use PDFTK (a open source cross-platform command-line tool) for things like that.
If we use runnable method SwingUtilities.invokeLater() while using Document listener application is getting stuck sometimes and taking time to update the result(As per my experiment). Instead of that we can also use KeyReleased event for text field change listener as mentioned here.
usernameTextField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
JTextField textField = (JTextField) e.getSource();
String text = textField.getText();
textField.setText(text.toUpperCase());
}
});
MATLAB is, first and foremost, a commercial offering. Therefore, everything in MATLAB pretty much works out of the box. All the core functionality is solid, and if you're working on a special project then MATLAB probably has an add-on they can sell you that adds a lot of additional domain-specific .m files for you. It ain't cheap, but it works and it will get the job done without complaint.
Octave always shows its open-source, information-wants-to-be-free roots. It's free, and it will remind you that it's free at every opportunity. It's developed by volunteers who hate Windows with a passion. Therefore Octave runs on Windows grudgingly. It's quite surprising that as many MATLAB features exist as they do.
But here's the rub. Anytime you try to do something more than trivially complex, Octave suddenly breaks in subtle and hard to understand ways. Oops -- the terminal driver had an overflow somewhere deep in the OpenGL layer. You can't print. Oops -- the figure plots do strange things with their fonts. Good luck figuring out why. Oops -- there's some hidden dependency between Octave and some other obscure bit of free software, so it won't compile. Good luck figuring out which it is.
And the Octave response is hey! It's free software! You have all the source code, you can fix all those bugs yourself! Maybe if I had infinite time and resources on my hands, I could spend all my time fixing bugs in free software, but I personally don't. If I worked in academia, I might.
So at the core, the issue of whether to choose MATLAB or Octave comes down to one question. Interestingly, that question is always the same, when choosing between commercial vs. free software variants.
And the question is:
Do you have more money than time?
Yes. unless, there is an ambiguity.
I don't know which version of MySQL you're using, but here are possible locations of the my.cnf file for version 5.5 (taken from here) on Mac OS X:
/etc/my.cnf
/etc/mysql/my.cnf
SYSCONFDIR/my.cnf
$MYSQL_HOME/my.cnf
defaults-extra-file
(the file specified with --defaults-extra-file=path
, if any)~/.my.cnf
editText.setRawInputType(InputType.TYPE_CLASS_NUMBER);
Define tooltip text
<input type="text" id="firstname" name="firstname" tooltipText="Type in your firstname in this box">
Initialize and configure the script
<script type="text/javascript">
var tooltipObj = new DHTMLgoodies_formTooltip();
tooltipObj.setTooltipPosition('right');
tooltipObj.setPageBgColor('#EEE');
tooltipObj.setCloseMessage('Exit');
tooltipObj.initFormFieldTooltip();
</script>
so this is basically just two typos, one, the most unfortunate, for (int j = 2; j <= num; j++)
which is the reason for the unproductive testing of 1%2,1%3 ... 1%(10^15-1)
which goes on for very long time so the OP didn't get "any output". It should've been j < i;
instead. The other, minor one in comparison, is that i
should start from 2, not from 0:
for( i=2; i <= num; i++ )
{
for( j=2; j < i; j++ ) // j <= sqrt(i) is really enough
....
Surely it can't be reasonably expected of a console print-out of 28 trillion primes or so to be completed in any reasonable time-frame. So, the original intent of the problem was obviously to print out a steady stream of primes, indefinitely. Hence all the solutions proposing simple use of sieve of Eratosthenes are totally without merit here, because simple sieve of Eratosthenes is bounded - a limit must be set in advance.
What could work here is the optimized trial division which would save the primes as it finds them, and test against the primes, not just all numbers below the candidate.
Second alternative, with much better complexity (i.e. much faster) is to use a segmented sieve of Eratosthenes. Which is incremental and unbounded.
Both these schemes would use double-staged production of primes: one would produce and save the primes, to be used by the other stage in testing (or sieving), much above the limit of the first stage (below its square of course - automatically extending the first stage, as the second stage would go further and further up).
rtrim ($string , ","); is the easiest way.
List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });
I found an easy way to fix this issue, tested in IE and Chrome:
function setCaret(elemId, caret)
{
var elem = document.getElementById(elemId);
elem.setSelectionRange(caret, caret);
}
Pass text box id and caret position to this function.
Taken from the current C Standard (C99): http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf
6.7.2.2 Enumeration specifiers
[...]
Constraints
The expression that defines the value of an enumeration constant shall be an integer constant expression that has a value representable as an int.
[...]
Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration.
Not that compilers are any good at following the standard, but essentially: If your enum holds anything else than an int, you're in deep "unsupported behavior that may come back biting you in a year or two" territory.
Update: The latest publicly available draft of the C Standard (C11): http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1570.pdf contains the same clauses. Hence, this answer still holds for C11.
MySQL allows a more readable way to combine multiple updates into a single query. This seems to better fit the scenario you describe, is much easier to read, and avoids those difficult-to-untangle multiple conditions.
INSERT INTO table_users (cod_user, date, user_rol, cod_office)
VALUES
('622057', '12082014', 'student', '17389551'),
('2913659', '12082014', 'assistant','17389551'),
('6160230', '12082014', 'admin', '17389551')
ON DUPLICATE KEY UPDATE
cod_user=VALUES(cod_user), date=VALUES(date)
This assumes that the user_rol, cod_office
combination is a primary key. If only one of these is the primary key, then add the other field to the UPDATE list.
If neither of them is a primary key (that seems unlikely) then this approach will always create new records - probably not what is wanted.
However, this approach makes prepared statements easier to build and more concise.
Create an array of Views and apply it to: container.addView(viewarr[position]);
public class Layoutes extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
Layoutes(Context context){
this.context=context;
}
int layoutes[]={R.layout.one,R.layout.two,R.layout.three};
@Override
public int getCount() {
return layoutes.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return (view==(LinearLayout)object);
}
@Override
public Object instantiateItem(ViewGroup container, int position){
layoutInflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View one=layoutInflater.inflate(R.layout.one,container,false);
View two=layoutInflater.inflate(R.layout.two,container,false);
View three=layoutInflater.inflate(R.layout.three,container,false);
View viewarr[]={one,two,three};
container.addView(viewarr[position]);
return viewarr[position];
}
@Override
public void destroyItem(ViewGroup container, int position, Object object){
container.removeView((LinearLayout) object);
}
}
import React from 'react'; <--as normal
import PropTypes from 'prop-types'; <--add this as a second line
App.propTypes = {
monkey: PropTypes.string, <--omit "React."
cat: PropTypes.number.isRequired <--omit "React."
};
Wrong: React.PropTypes.string
Right: PropTypes.string
ACL was overkill for my requirements also.
I ended up creating a library similar to @Alexander's to inject a GrantedAuthority
list for Role->Permissions based on the role membership of a user.
For example, using a DB to hold the relationships -
@Autowired
RolePermissionsRepository repository;
public void setup(){
String roleName = "ROLE_ADMIN";
List<String> permissions = new ArrayList<String>();
permissions.add("CREATE");
permissions.add("READ");
permissions.add("UPDATE");
permissions.add("DELETE");
repository.save(new RolePermissions(roleName, permissions));
}
When an Authentication object is injected in the current security session, it will have the original roles/granted authorities.
This library provides 2 built-in integration points for Spring Security.
When the integration point is reached, the PermissionProvider is called to get the effective permissions for each role the user is a member of.
The distinct list of permissions are added as GrantedAuthority items in the Authentication object.
You can also implement a custom PermissionProvider
to store the relationships in config for example.
A more complete explanation here - https://stackoverflow.com/a/60251931/1308685
And the source code is here - https://github.com/savantly-net/spring-role-permissions