Once you clear the interval using clearInterval
you could setInterval
once again. And to avoid repeating the callback externalize it as a separate function:
var ticker = function() {
console.log('idle');
};
then:
var myTimer = window.setInterval(ticker, 4000);
then when you decide to restart:
window.clearInterval(myTimer);
myTimer = window.setInterval(ticker, 4000);
Looking for EventHandling, ActionListener?
or code?
JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
textfield.setText("");
//textfield.setText(null); //or use this
}
});
Also See
How to Use Buttons
Please be aware, this is a simplified explanation intended as a first step in seeking to understand this complex functionality.
May be helpful for visual learners who want to visualise what their project state looks like after each of these commands:
For those who use Terminal with colour turned on (git config --global color.ui auto):
git reset --soft A
and you will see B and C's stuff in green (staged and ready to commit)
git reset --mixed A
(or git reset A
) and you will see B and C's stuff in red (unstaged and ready to be staged (green) and then committed)
git reset --hard A
and you will no longer see B and C's changes anywhere (will be as if they never existed)
Or for those who use a GUI program like 'Tower' or 'SourceTree'
git reset --soft A
and you will see B and C's stuff in the 'staged files' area ready to commit
git reset --mixed A
(or git reset A
) and you will see B and C's stuff in the 'unstaged files' area ready to be moved to staged and then committed
git reset --hard A
and you will no longer see B and C's changes anywhere (will be as if they never existed)
A method I used on a fairly large form (50+ fields) was to just reload the form with AJAX, basically making a call back to the server and just returning the fields with their default values. This made is much easier than trying to grab each field with JS and then setting it to it's default value. It also allowed to me to keep the default values in one place--the server's code. On this site, there were also some different defaults depending on the settings for the account and therefore I didn't have to worry about sending these to JS. The only small issue I had to deal with were some suggest fields that required initialization after the AJAX call, but not a big deal.
To reset the auto increment you have to get your sequence name by using following query.
Syntax:
SELECT pg_get_serial_sequence(‘tablename’, ‘ columnname‘);
Example:
SELECT pg_get_serial_sequence('demo', 'autoid');
The query will return the sequence name of autoid as "Demo_autoid_seq" Then use the following query to reset the autoid
Syntax:
ALTER SEQUENCE sequenceName RESTART WITH value;
Example:
ALTER SEQUENCE "Demo_autoid_seq" RESTART WITH 1453;
After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.
* The arguments which may be supplied in the recovery.command file:
* --send_intent=anystring - write the text out to recovery.intent
* --update_package=path - verify install an OTA package file
* --wipe_data - erase user data (and cache), then reboot
* --wipe_cache - wipe cache (but not user data), then reboot
* --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:
adb shell
recovery --wipe_data
Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.
EDIT:
For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command
For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c
I had the same question but about rather short vector<bool>
(afaik the standard allows to implement it internally differently than just a continuous array of boolean elements). Hence I repeated the slightly modified tests by Fabio Fracassi. The results are as follows (times, in seconds):
-O0 -O3
-------- --------
memset 0.666 1.045
fill 19.357 1.066
iterator 67.368 1.043
assign 17.975 0.530
for i 22.610 1.004
So apparently for these sizes, vector<bool>::assign()
is faster. The code used for tests:
#include <vector>
#include <cstring>
#include <cstdlib>
#define TEST_METHOD 5
const size_t TEST_ITERATIONS = 34359738;
const size_t TEST_ARRAY_SIZE = 200;
using namespace std;
int main(int argc, char** argv) {
std::vector<int> v(TEST_ARRAY_SIZE, 0);
for(size_t i = 0; i < TEST_ITERATIONS; ++i) {
#if TEST_METHOD == 1
memset(&v[0], false, v.size() * sizeof v[0]);
#elif TEST_METHOD == 2
std::fill(v.begin(), v.end(), false);
#elif TEST_METHOD == 3
for (std::vector<int>::iterator it=v.begin(), end=v.end(); it!=end; ++it) {
*it = 0;
}
#elif TEST_METHOD == 4
v.assign(v.size(),false);
#elif TEST_METHOD == 5
for (size_t i = 0; i < TEST_ARRAY_SIZE; i++) {
v[i] = false;
}
#endif
}
return EXIT_SUCCESS;
}
I used GCC 7.2.0 compiler on Ubuntu 17.10. The command line for compiling:
g++ -std=c++11 -O0 main.cpp
g++ -std=c++11 -O3 main.cpp
If you installed the SquashFS image you can run the script firstboot
. That will return OpenWrt to the defaults of when you flashed the router.
With your serial access just run firstboot and then power cycle the device.
I recently had to do this for Textboxes and Checkboxes but using JavaScript ...
How to reset textbox and checkbox controls in an ASP.net document
Here is the code ...
<script src="http://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
function ResetForm() {
//get the all the Input type elements in the document
var AllInputsElements = document.getElementsByTagName('input');
var TotalInputs = AllInputsElements.length;
//we have to find the checkboxes and uncheck them
//note: <asp:checkbox renders to <input type="checkbox" after compiling, which is why we use 'input' above
for(var i=0;i< TotalInputs ; i++ )
{
if(AllInputsElements[i].type =='checkbox')
{
AllInputsElements[i].checked = false;
}
}
//reset all textbox controls
$('input[type=text], textarea').val('');
Page_ClientValidateReset();
return false;
}
//This function resets all the validation controls so that they don't "fire" up
//during a post-back.
function Page_ClientValidateReset() {
if (typeof (Page_Validators) != "undefined") {
for (var i = 0; i < Page_Validators.length; i++) {
var validator = Page_Validators[i];
validator.isvalid = true;
ValidatorUpdateDisplay(validator);
}
}
}
</script>
And call it with a button or any other method ...
<asp:button id="btnRESET" runat="server" onclientclick="return ResetForm();" text="RESET" width="100px"></asp:button>
If you don't use ValidationControls on your website, just remove all the code refering to it above and the call Page_ClientValidateReset();
I am sure you can expand it for any other control using the DOM. And since there is no post to the server, it's faster and no "flashing" either.
With Git 2.23 (August 2019), you have the new command git restore
git restore --source=HEAD --staged --worktree -- aDirectory
# or, shorter
git restore -s@ -SW -- aDirectory
That would replace both the index and working tree with HEAD
content, like an reset --hard
would, but for a specific path.
Original answer (2013)
Note (as commented by Dan Fabulich) that:
git checkout -- <path>
doesn't do a hard reset: it replaces the working tree contents with the staged contents. git checkout HEAD -- <path>
does a hard reset for a path, replacing both the index and the working tree with the version from the HEAD
commit.As answered by Ajedi32, both checkout forms don't remove files which were deleted in the target revision.
If you have extra files in the working tree which don't exist in HEAD, a git checkout HEAD -- <path>
won't remove them.
Note: With git checkout --overlay HEAD -- <path>
(Git 2.22, Q1 2019), files that appear in the index and working tree, but not in <tree-ish>
are removed, to make them match <tree-ish>
exactly.
But that checkout can respect a git update-index --skip-worktree
(for those directories you want to ignore), as mentioned in "Why do excluded files keep reappearing in my git sparse checkout?".
With django 1.11, simply delete all migration files from the migrations
folder of each application (all files except __init__.py
). Then
python3 manage.py makemigrations
.python3 manage.py migrate
.And voilla, your database has been completely reset.
A reset button doesn't need any script at all (or name or id):
<input type="reset">
and you're done. But if you really must use script, note that every form control has a form property that references the form it's in, so you could do:
<input type="button" onclick="this.form.reset();">
But a reset button is a far better choice.
Building up on Dmitri Pavlutin and joshua.paling answers, here's an extended version that extracts the base64 content (removes the metadata at the beginning) and also ensures padding is done correctly.
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
let encoded = reader.result.toString().replace(/^data:(.*,)?/, '');
if ((encoded.length % 4) > 0) {
encoded += '='.repeat(4 - (encoded.length % 4));
}
resolve(encoded);
};
reader.onerror = error => reject(error);
});
}
In a Helper file,
Your can use Route::current()->uri()
to get current URL.
Hence, If you compare your route name to set active class on menu then it would be good if you use
Route::currentRouteName()
to get the name of route and compare
So since Python 3, map()
is an iterator, you need to keep in mind what do you need: an iterator or list
object.
As @AlexMartelli already mentioned, map()
is faster than list comprehension only if you don't use lambda
function.
I will present you some time comparisons.
Python 3.5.2 and CPython
I've used Jupiter notebook and especially %timeit
built-in magic command
Measurements: s == 1000 ms == 1000 * 1000 µs = 1000 * 1000 * 1000 ns
Setup:
x_list = [(i, i+1, i+2, i*2, i-9) for i in range(1000)]
i_list = list(range(1000))
Built-in function:
%timeit map(sum, x_list) # creating iterator object
# Output: The slowest run took 9.91 times longer than the fastest.
# This could mean that an intermediate result is being cached.
# 1000000 loops, best of 3: 277 ns per loop
%timeit list(map(sum, x_list)) # creating list with map
# Output: 1000 loops, best of 3: 214 µs per loop
%timeit [sum(x) for x in x_list] # creating list with list comprehension
# Output: 1000 loops, best of 3: 290 µs per loop
lambda
function:
%timeit map(lambda i: i+1, i_list)
# Output: The slowest run took 8.64 times longer than the fastest.
# This could mean that an intermediate result is being cached.
# 1000000 loops, best of 3: 325 ns per loop
%timeit list(map(lambda i: i+1, i_list))
# Output: 1000 loops, best of 3: 183 µs per loop
%timeit [i+1 for i in i_list]
# Output: 10000 loops, best of 3: 84.2 µs per loop
There is also such thing as generator expression, see PEP-0289. So i thought it would be useful to add it to comparison
%timeit (sum(i) for i in x_list)
# Output: The slowest run took 6.66 times longer than the fastest.
# This could mean that an intermediate result is being cached.
# 1000000 loops, best of 3: 495 ns per loop
%timeit list((sum(x) for x in x_list))
# Output: 1000 loops, best of 3: 319 µs per loop
%timeit (i+1 for i in i_list)
# Output: The slowest run took 6.83 times longer than the fastest.
# This could mean that an intermediate result is being cached.
# 1000000 loops, best of 3: 506 ns per loop
%timeit list((i+1 for i in i_list))
# Output: 10000 loops, best of 3: 125 µs per loop
list
object:Use list comprehension if it's custom function, use list(map())
if there is builtin function
list
object, you just need iterable one:Always use map()
!
Apparently it does not and I didn't quite expect it would. HOWEVER Ivan brings up a good possibility that has escaped Android people.
What is the purpose of an emulator? to EMULATE, right? I don't see why for testing purposes -provided the tester understands the limitations- the emulator might not add a Wifi emulator.
It could for example emulate WiFi access by using the underlying internet connection of the host. Obviously testing WPA/WEP differencess would not make sense but at least it could toggle access via WiFi.
Or some sort of emulator plugin where there would be a base WiFi emulator that would emulate WiFi access via the underlying connection but then via configuration it could emulate WPA/WEP by providing a list of fake WiFi networks and their corresponding fake passwords that would be matched against a configurable list of credentials.
After all the idea is to do initial testing on the emulator and then move on to the actual device.
Create a copy of executables of same service and paste it on the same path of the existing service and then uninstall.
In order to split by a string you'll have to use the string array overload.
string data = "THExxQUICKxxBROWNxxFOX";
return data.Split(new string[] { "xx" }, StringSplitOptions.None);
If you want you can throw a new Exception, with the original one set as an inner exception.
I know I am too late to answer but it's always better to show up rather than not showing up at all :). ES6 way to get it:
$http.get("data/SampleData.json").then(response => {
let id = 'xyz';
let item = response.data.results.find(result => result.id === id);
console.log(item); //your desired item
});
For C++, it can generate real float numbers within the range specified by dist
variable
#include <random> //If it doesnt work then use #include <tr1/random>
#include <iostream>
using namespace std;
typedef std::tr1::ranlux64_base_01 Myeng;
typedef std::tr1::normal_distribution<double> Mydist;
int main() {
Myeng eng;
eng.seed((unsigned int) time(NULL)); //initializing generator to January 1, 1970);
Mydist dist(1,10);
dist.reset(); // discard any cached values
for (int i = 0; i < 10; i++)
{
std::cout << "a random value == " << (int)dist(eng) << std::endl;
}
return (0);
}
I got du.exe
with my git distribution. Another place might be aforementioned Microsoft or Unxutils.
Once you got du.exe in your path. Here's your fileSizes.bat
:-)
@echo ___________
@echo DIRECTORIES
@for /D %%i in (*) do @CALL du.exe -hs "%%i"
@echo _____
@echo FILES
@for %%i in (*) do @CALL du.exe -hs "%%i"
@echo _____
@echo TOTAL
@du.exe -sh "%CD%"
?
___________
DIRECTORIES
37M Alps-images
12M testfolder
_____
FILES
765K Dobbiaco.jpg
1.0K testfile.txt
_____
TOTAL
58M D:\pictures\sample
Use first the method OpenTextFile
, and then...
either read the file at once with the method ReadAll
:
Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll
or line by line with the method ReadLine
:
Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
line = file.Readline
dict.Add row, line
row = row + 1
Loop
file.Close
'Loop over it
For Each line in dict.Items
WScript.Echo line
Next
There can be a performance benefit in WPF, as it removes the need for expensive DependencyProperties. This can be especially useful with collections
From your referenced page:
http://googlecode.blogspot.com/2009/12/google-analytics-launches-asynchronous.html
Firefox 3.6 is the first browser to officially offer support for this new feature. If you're curious, here are more details on the official HTML5 async specification.
I think this should be a comment or an edit to ThinkingMedia's answer on this very question (Check free disk space for current partition in bash), but I am not allowed to comment (not enough rep) and my edit has been rejected (reason: "this should be a comment or an answer"). So please, powers of the SO universe, don't damn me for repeating and fixing someone else's "answer". But someone on the internet was wrong!™ and they wouldn't let me fix it.
The code
df --output=avail -h "$PWD" | sed '1d;s/[^0-9]//g'
has a substantial flaw:
Yes, it will output 50G
free as 50 -- but it will also output 5.0M
free as 50 or 3.4G
free as 34 or 15K
free as 15.
To create a script with the purpose of checking for a certain amount of free disk space you have to know the unit you're checking against. Remove it (as sed
does in the example above) the numbers don't make sense anymore.
If you actually want it to work, you will have to do something like:
FREE=`df -k --output=avail "$PWD" | tail -n1` # df -k not df -h
if [[ $FREE -lt 10485760 ]]; then # 10G = 10*1024*1024k
# less than 10GBs free!
fi;
Also for an installer to df -k $INSTALL_TARGET_DIRECTORY
might make more sense than df -k "$PWD"
.
Finally, please note that the --output
flag is not available in every version of df / linux.
Another way to encode the message you intend is to add another field to track "set" fields:
syntax="proto3";
package qtprotobuf.examples;
message SparseMessage {
repeated uint32 fieldsUsed = 1;
bool attendedParty = 2;
uint32 numberOfKids = 3;
string nickName = 4;
}
message ExplicitMessage {
enum PARTY_STATUS {ATTENDED=0; DIDNT_ATTEND=1; DIDNT_ASK=2;};
PARTY_STATUS attendedParty = 1;
bool indicatedKids = 2;
uint32 numberOfKids = 3;
enum NO_NICK_STATUS {HAS_NO_NICKNAME=0; WOULD_NOT_ADMIT_TO_HAVING_HAD_NICKNAME=1;};
NO_NICK_STATUS noNickStatus = 4;
string nickName = 5;
}
This is especially appropriate if there is a large number of fields and only a small number of them have been assigned.
In python, usage would look like this:
import field_enum_example_pb2
m = field_enum_example_pb2.SparseMessage()
m.attendedParty = True
m.fieldsUsed.append(field_enum_example_pb2.SparseMessages.ATTENDEDPARTY_FIELD_NUMBER)
You can use Timer instead of Thread. This is whole my code
package dk.tellwork.tellworklite.tabs;
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import dk.tellwork.tellworklite.MainActivity;
import dk.tellwork.tellworklite.R;
@SuppressLint("HandlerLeak")
public class HomeActivity extends Activity {
Button chooseYourAcitivity, startBtn, stopBtn;
TextView labelTimer;
int passedSenconds;
Boolean isActivityRunning = false;
Timer timer;
TimerTask timerTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_home);
chooseYourAcitivity = (Button) findViewById(R.id.btnChooseYourActivity);
chooseYourAcitivity.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//move to Activities tab
switchTabInActivity(1);
}
});
labelTimer = (TextView)findViewById(R.id.labelTime);
passedSenconds = 0;
startBtn = (Button)findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (isActivityRunning) {
//pause running activity
timer.cancel();
startBtn.setText(getString(R.string.homeStartBtn));
isActivityRunning = false;
} else {
reScheduleTimer();
startBtn.setText(getString(R.string.homePauseBtn));
isActivityRunning = true;
}
}
});
stopBtn = (Button)findViewById(R.id.stopBtn);
stopBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
timer.cancel();
passedSenconds = 0;
labelTimer.setText("00 : 00 : 00");
startBtn.setText(getString(R.string.homeStartBtn));
isActivityRunning = false;
}
});
}
public void reScheduleTimer(){
timer = new Timer();
timerTask = new myTimerTask();
timer.schedule(timerTask, 0, 1000);
}
private class myTimerTask extends TimerTask{
@Override
public void run() {
// TODO Auto-generated method stub
passedSenconds++;
updateLabel.sendEmptyMessage(0);
}
}
private Handler updateLabel = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
int seconds = passedSenconds % 60;
int minutes = (passedSenconds / 60) % 60;
int hours = (passedSenconds / 3600);
labelTimer.setText(String.format("%02d : %02d : %02d", hours, minutes, seconds));
}
};
public void switchTabInActivity(int indexTabToSwitchTo){
MainActivity parentActivity;
parentActivity = (MainActivity) this.getParent();
parentActivity.switchTab(indexTabToSwitchTo);
}
}
For future readers, I found that I experienced a problem and was getting an unrecognised selector sent to instance
error that was caused by marking the target func
as private.
The func
MUST be publicly visible to be called by an object with a reference to a selector.
I'm a little late to the party, but I have a solution that might work for some who read this. It's in javascript instead of php, but there's a valid reason for it.
Full disclosure, I wrote this plugin...
Anyways.
The approach I've gone with is to allow a user to "Opt-In" to their profanity filtering. Basically profanity will be allowed by default, but if my users don't want to read it, they don't have to. This also helps with the "l33t sp3@k" issue.
The concept is a simple jquery plugin that gets injected by the server if the client's account is enabling profanity filtering. From there, it's just a couple simple lines that blot out the swears.
Here's the demo page
https://chaseflorell.github.io/jQuery.ProfanityFilter/demo/
<div id="foo">
ass will fail but password will not
</div>
<script>
// code:
$('#foo').profanityFilter({
customSwears: ['ass']
});
</script>
result
*** will fail but password will not
Instead of Str(RequestID)
, try convert(varchar(38), RequestID)
Trim just removes the trailing and leading whitespace. Use .replace(/ /g, "") if there are just spaces to be replaced.
this.maintabinfo = this.inner_view_data.replace(/ /g, "").toLowerCase();
The naming convention is part of the well-established JavaBeans specification and is supported by the classes in the java.beans package.
I had a similar requirement to this but my replace var contained an ampersand. Escaping the ampersand like this solved my problem:
replace="salt & pepper"
echo "pass the salt" | sed "s/salt/${replace/&/\&}/g"
If the newline is expected to be at the end of the string, then:
if (!s.empty() && s[s.length()-1] == '\n') {
s.erase(s.length()-1);
}
If the string can contain many newlines anywhere in the string:
std::string::size_type i = 0;
while (i < s.length()) {
i = s.find('\n', i);
if (i == std::string:npos) {
break;
}
s.erase(i);
}
Here's a simple function:
function setParent(el, newParent)
{
newParent.appendChild(el);
}
el
's childNodes
are the elements to be moved, newParent
is the element el
will be moved to, so you would execute the function like:
var l = document.getElementById('old-parent').childNodes.length;
var a = document.getElementById('old-parent');
var b = document.getElementById('new-parent');
for (var i = l; i >= 0; i--)
{
setParent(a.childNodes[0], b);
}
This a old question, but this can useful for someone In my case i can't using a sub query because i have a big query and i need using min() on my result, if i use sub query the db need reexecute my big query. i'm using Mysql
select t.*
from (select m.*, @g := 0
from MyTable m --here i have a big query
order by id, record_date) t
where (1 = case when @g = 0 or @g <> id then 1 else 0 end )
and (@g := id) IS NOT NULL
Basically I ordered the result and then put a variable in order to get only the first record in each group.
use $set do this process
.update({"_id": args.dashboardId, "viewData._id": widgetId}, {$set: {"viewData.$.widgetData": widgetDoc.widgetData}})
.exec()
.then(dashboardDoc => {
return {
result: dashboardDoc
};
});
I know i'm late, but I found a way using jquery which works on every browser(i tested it on chrome, firefox and Ie 9)and th fore-ground elements are always displayed instead of css3 transition property.
create 2 absolute wrapper and using z-index.
First set the elements that have to be in the fore-ground with the highest z-index property value, and the other elemets(all included in the body, so: body{}) with a lower z-index property value than the fore-ground elements'one , at least of 2 number lower.
HTML part:
<div class="wrapper" id="wrapper1"></div>
<div class="wrapper" id="wrapper2"></div>
css part:
.fore-groundElements{ //select all fore-ground elements
z-index:0; //>=0
}
.wrapper{
background-size: cover;
width:100%;
height:100%;
background-size: 100% 100%;
position:absolute;
}
#wrapper1{
z-index:-1;
}
#wrapper2{
z-index:-2;
}
body{
height:100%;
width:100%;
margin:0px;
display:cover;
z-index:-3 //<=-3
}
than the javascript/jquery one:
i needed to change the background image every three second so i used a set timeout.
this is the code:
$(document).ready(main);
var main = function(){
var imgPath=[imagesPath1,..,...]; // the array in which store the image paths
var newWrapper; // the wrapper to display
var currentWrapper; //the current displayed wrapper which has to be faded
var l=2; // the next image index to be displayed, it is set to 2 because the first two position of the array(first two images) start already setted up
var imgNumber= imgPath.length; //to know when the images are over and restart the carousel
var currentImg; //the next image path to be displayed
$('#wrapper1').css("background-image", 'url'+imgPath[0]); //pre set the first wrapper background images
$('#wrapper2').css("background-image", 'url'+imgPath[1]); //pre set the first wrapper background images
setInterval(myfunction,3000); //refresh the background image every three seconds
function myfunction(){
if(l===imgNumber-1){ //restart the carousel if every single image has already been displayed
l=0;
};
if(l%2==0||l%2==2){ //set the wrapper that will be displaied after the fadeOut callback function
currentWrapper='#wrapper1';
newWrapper='#wrapper2';
}else{
currentWrapper='#wrapper2';
newWrapper='#wrapper1';
};
currentImg=imgPath[l];
$(currentWrapper).fadeOut(1000,function(){ //fade out the current wrapper, so now the back-ground wrapper is fully displayed
$(newWrapper).css("z-index", "-1"); //move the shown wrapper in the fore-ground
$(currentWrapper).css("z-index","-2"); //move the hidden wrapper in the back ground
$(currentWrapper).css("background-image",'url'+currentImg); // sets up the next image that is now shown in the actually hidden background wrapper
$(currentWrapper).show(); //shows the background wrapper, which is not visible yet, and it will be shown the next time the setInterval event will be triggered
l++; //set the next image index that will be set the next time the setInterval event will be triggered
});
}; //end of myFunction
} //end of main
i hope that my answer is clear,if you need more explanation comment it.
sorry for my english :)
It's pretty straightforward using [
to extract:
grep
will give you the position in which it matched your search pattern (unless you use value = TRUE
).
grep("^G45", My.Data$x)
# [1] 2
Since you're searching within the values of a single column, that actually corresponds to the row index. So, use that with [
(where you would use My.Data[rows, cols]
to get specific rows and columns).
My.Data[grep("^G45", My.Data$x), ]
# x y
# 2 G459 2
The help-page for subset
shows how you can use grep
and grepl
with subset
if you prefer using this function over [
. Here's an example.
subset(My.Data, grepl("^G45", My.Data$x))
# x y
# 2 G459 2
As of R 3.3, there's now also the startsWith
function, which you can again use with subset
(or with any of the other approaches above). According to the help page for the function, it's considerably faster than using substring
or grepl
.
subset(My.Data, startsWith(as.character(x), "G45"))
# x y
# 2 G459 2
This is actually a failure of design. You shouldn't be using a return value for anything not a primitive for anything that is not relatively trivial.
The ideal solution should be implemented through a return parameter with a decision on reference/pointer and the proper use of a "const\'y\'ness" as a descriptor.
On top of this, you should realise that the label on an array in C and C++ is effectively a pointer and its subscription are effectively an offset or an addition symbol.
So the label or ptr array_ptr === array label thus returning foo[offset] is really saying return element at memory pointer location foo + offset of type return type.
You could use a regular expression like this
If Regex.IsMatch(number, "^[0-9 ]+$") Then
...
End If
Working out the character encoding of RSS feeds seems to be complicated. Even normal web pages often omit, or lie about, their encoding.
So you could try to use the correct way to detect the encoding and then fall back to some form of auto-detection (guessing).
For some reason AngularJS allows to get me confused. Their documentation is pretty horrible on this. More good examples of variations would be welcome.
Anyway, I have a slight variation on Ben Lesh's answer.
My data collections looks like this:
items =
[
{ key:"AD",value:"Andorra" }
, { key:"AI",value:"Anguilla" }
, { key:"AO",value:"Angola" }
...etc..
]
Now
<select ng-model="countries" ng-options="item.key as item.value for item in items"></select>
still resulted in the options value to be the index (0, 1, 2, etc.).
Adding Track By fixed it for me:
<select ng-model="blah" ng-options="item.value for item in items track by item.key"></select>
I reckon it happens more often that you want to add an array of objects into an select list, so I am going to remember this one!
Be aware that from AngularJS 1.4 you can't use ng-options any more, but you need to use ng-repeat
on your option tag:
<select name="test">
<option ng-repeat="item in items" value="{{item.key}}">{{item.value}}</option>
</select>
Well to start with, you should only deal with them as strings when you have to. Most of the time you should work with them in a data type which actually describes the data you're working with.
I would recommend that you use Joda Time, which is a much better API than Date
/Calendar
. It sounds like you should use the LocalDate
type in this case. You can then use:
int days = Days.daysBetween(date1, date2).getDays();
As described in Cast Functions and Operators:
The type for the result can be one of the following values:
BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]
Therefore, you should use:
SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT
Parcelable vs Serializable I refer these two.
For Java and Kotlin
1) Java
Serializable, the Simplicity
What is Serializable?
Serializable is a standard Java interface. It is not a part of the Android SDK. Its simplicity is its beauty. Just by implementing this interface your POJO will be ready to jump from one Activity to another.
public class TestModel implements Serializable {
String name;
public TestModel(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The beauty of serializable is that you only need to implement the Serializable interface on a class and its children. It is a marker interface, meaning that there is no method to implement, Java will simply do its best effort to serialize it efficiently.
The problem with this approach is that reflection is used and it is a slow process. This mechanism also tends to create a lot of temporary objects and cause quite a bit of garbage collection.
Parcelable, The Speed
What is Parcelable?
Parcelable is another interface. Despite its rival (Serializable in case you forgot), it is a part of the Android SDK. Now, Parcelable was specifically designed in such a way that there is no reflection when using it. That is because we are being really explicit for the serialization process.
public class TestModel implements Parcelable {
String name;
public TestModel(String name, String id) {
this.name = name;
}
protected TestModel(Parcel in) {
this.name = in.readString();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
}
public static final Parcelable.Creator<TestModel> CREATOR = new Parcelable.Creator<TestModel>() {
@Override
public TestModel createFromParcel(Parcel source) {
return new TestModel(source);
}
@Override
public TestModel[] newArray(int size) {
return new TestModel[size];
}
};
}
Now, The winner is
The results of the tests conducted by Philippe Breault show that Parcelable is more than 10x faster than Serializable. Some other Google engineers stand behind this statement as well.
According to them, the default Serializable approach is slower than Parcelable. And here we have an agreement between the two parties! BUT, it is unfair to compare these two at all! Because with Parcelable we are actually writing custom code. Code specifically created for that one POJO. Thus, no garbage is created and the results are better. But with the default Serializable approach, we rely on the automatic serialization process of Java. The process is apparently not custom at all and creates lots of garbage! Thus, the worse results.
Stop Stop!!!!, Before making decision
Now, there is another approach. The whole automatic process behind Serializable can be replaced by custom code which uses writeObject() & readObject() methods. These methods are specific. If we want to rely on the Serializable approach in combination with custom serialization behavior, then we must include these two methods with the same exact signature as the one below:
private void writeObject(java.io.ObjectOutputStream out)
throws IOException;
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
private void readObjectNoData()
throws ObjectStreamException;
And now a comparison between Parcelable and custom Serializable seems fair! The results may be surprising! The custom Serializable approach is more than 3x faster for writes and 1.6x faster for reads than Parcelable.
Edited:-----
2) Kotlinx Serialization
Kotlinx Serialization Library
For Kotlin serialization need to add below dependency and plugin
implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.9.1"
apply plugin: 'kotlinx-serialization'
Your build.gradle
file
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlinx-serialization'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.smile.kotlinxretrosample"
minSdkVersion 16
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.9.1"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:28.0.0'
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
Serializing is done quite easily, you need to annotate the intended class with the @Serializable
annotation as below
import kotlinx.serialization.Serializable
@Serializable
class Field {
var count: Int = 0
var name: String = ""
}
Two more annotations to note are transient
and optional
. Using transient will have the serializer ignore that field and using optional will allow the serializer not to break if a field is missing, but at the same time a default value will need to be provided.
@Optional
var isOptional: Boolean = false
@Transient
var isTransient: Boolean = false
Note: This can as well work with data classes.
Now to actually use this in action let’s take an example of how to convert a JSON to object and back
fun toObject(stringValue: String): Field {
return JSON.parse(Field.serializer(), stringValue)
}
fun toJson(field: Field): String {
//Notice we call a serializer method which is autogenerated from our class
//once we have added the annotation to it
return JSON.stringify(Field.serializer(), field)
}
For more
Mongodb v3.4
You need to do the following to create a secure database:
Make sure the user starting the process has permissions and that the directories exist (/data/db
in this case).
1) Start MongoDB without access control.
mongod --port 27017 --dbpath /data/db
2) Connect to the instance.
mongo --port 27017
3) Create the user administrator (in the admin authentication database).
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
4) Re-start the MongoDB instance with access control.
mongod --auth --port 27017 --dbpath /data/db
5) Connect and authenticate as the user administrator.
mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"
6) Create additional users as needed for your deployment (e.g. in the test authentication database).
use test
db.createUser(
{
user: "myTester",
pwd: "xyz123",
roles: [ { role: "readWrite", db: "test" },
{ role: "read", db: "reporting" } ]
}
)
7) Connect and authenticate as myTester.
mongo --port 27017 -u "myTester" -p "xyz123" --authenticationDatabase "test"
I basically just explained the short version of the official docs here: https://docs.mongodb.com/master/tutorial/enable-authentication/
Just for the sake of completeness, here is a solution with lambda and method reference:
Description: The following method
String
with the pattern yyyy-MM-dd
into a Timestamp
, if a valid input is given,null
, if a null
value is given,DateTimeParseException
, if an invalid input is givenCode:
static Timestamp convertStringToTimestamp(String strDate) {
return Optional.ofNullable(strDate) // wrap the String into an Optional
.map(str -> LocalDate.parse(str).atStartOfDay()) // convert into a LocalDate and fix the hour:minute:sec to 00:00:00
.map(Timestamp::valueOf) // convert to Timestamp
.orElse(null); // if no value is present, return null
}
Validation:
This method can be tested with those unit tests:
(with Junit5 and Hamcrest)
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenValidInput() {
// given
String strDate = "2020-01-30";
// when
final Timestamp result = convertStringToTimestamp(strDate);
// then
final LocalDateTime dateTime = LocalDateTime.ofInstant(result.toInstant(), ZoneId.systemDefault());
assertThat(dateTime.getYear(), is(2020));
assertThat(dateTime.getMonthValue(), is(1));
assertThat(dateTime.getDayOfMonth(), is(30));
}
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenInvalidInput() {
// given
String strDate = "7770-91-30";
// when, then
assertThrows(DateTimeParseException.class, () -> convertStringToTimestamp(strDate));
}
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenNullInput() {
// when
final Timestamp result = convertStringToTimestamp(null);
// then
assertThat(result, is(nullValue()));
}
Usually, the string to parse comes with another format. A way to deal with it is to use a formatter to convert it to another format. Here is an example:
Input: 20200130 11:30
Pattern: yyyyMMdd HH:mm
Output: Timestamp of this input
Code:
static Timestamp convertStringToTimestamp(String strDate) {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm");
return Optional.ofNullable(strDate) //
.map(str -> LocalDateTime.parse(str, formatter))
.map(Timestamp::valueOf) //
.orElse(null);
}
Test:
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenValidInput() {
// given
String strDate = "20200130 11:30";
// when
final Timestamp result = convertStringToTimestamp(strDate);
// then
final LocalDateTime dateTime = LocalDateTime.ofInstant(result.toInstant(), ZoneId.systemDefault());
assertThat(dateTime.getYear(), is(2020));
assertThat(dateTime.getMonthValue(), is(1));
assertThat(dateTime.getDayOfMonth(), is(30));
assertThat(dateTime.getHour(), is(11));
assertThat(dateTime.getMinute(), is(30));
}
maybe this is what you want
import pandas as pd
idx = pd.MultiIndex.from_product([['state1','state2'], ['county1','county2','county3','county4']])
df = pd.DataFrame({'pop': [12,15,65,42,78,67,55,31]}, index=idx)
pop state1 county1 12 county2 15 county3 65 county4 42 state2 county1 78 county2 67 county3 55 county4 31
df.groupby(level=0, group_keys=False).apply(lambda x: x.sort_values('pop', ascending=False)).groupby(level=0).head(3)
> Out[29]:
pop
state1 county3 65
county4 42
county2 15
state2 county1 78
county2 67
county3 55
Reinstalling the software fixes the issue, just make sure not to delete the htdocs folder in the process.
Just Go To the Genymotion Installation Directory and then in folder tools you will see adb.exe there open command prompt here and run adb commands
You can also use shorthand for describe as desc
for table description.
desc [db_name.]table_name;
or
use db_name;
desc table_name;
You can also use explain
for table description.
explain [db_name.]table_name;
See official doc
Will give output like:
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id | int(10) | NO | PRI | NULL | |
| name | varchar(20) | YES | | NULL | |
| age | int(10) | YES | | NULL | |
| sex | varchar(10) | YES | | NULL | |
| sal | int(10) | YES | | NULL | |
| location | varchar(20) | YES | | Pune | |
+----------+-------------+------+-----+---------+-------+
aapt dump badging test.apk | grep "VersionName" | sed -e "s/.*versionName='//" -e "s/' .*//"
This answers the question by returning only the version number as a result. However......
The goal as previously stated should be to find out if the apk on the server is newer than the one installed BEFORE attempting to download or install it. The easiest way to do this is include the version number in the filename of the apk hosted on the server eg myapp_1.01.apk
You will need to establish the name and version number of the apps already installed (if it is installed) in order to make the comparison. You will need a rooted device or a means of installing the aapt binary and busybox if they are not already included in the rom.
This script will get the list of apps from your server and compare with any installed apps. The result is a list flagged for upgrade/installation.
#/system/bin/sh
SERVER_LIST=$(wget -qO- "http://demo.server.com/apk/" | grep 'href' | grep '\.apk' | sed 's/.*href="//' | \
sed 's/".*//' | grep -v '\/' | sed -E "s/%/\\\\x/g" | sed -e "s/x20/ /g" -e "s/\\\\//g")
LOCAL_LIST=$(for APP in $(pm list packages -f | sed -e 's/package://' -e 's/=.*//' | sort -u); do \
INFO=$(echo -n $(aapt dump badging $APP | grep -e 'package: name=' -e 'application: label=')) 2>/dev/null; \
PACKAGE=$(echo $INFO | sed "s/.*package: name='//" | sed "s/'.*$//"); \
LABEL=$(echo $INFO | sed "s/.*application: label='//" | sed "s/'.*$//"); if [ -z "$LABEL" ]; then LABEL="$PACKAGE"; fi; \
VERSION=$(echo $INFO | sed -e "s/.*versionName='//" -e "s/' .*//"); \
NAME=$LABEL"_"$VERSION".apk"; echo "$NAME"; \
done;)
OFS=$IFS; IFS=$'\t\n'
for REMOTE in $SERVER_LIST; do
INSTALLED=0
REMOTE_NAME=$(echo $REMOTE | sed 's/_.*//'); REMOTE_VER=$(echo $REMOTE | sed 's/^[^_]*_//g' | sed 's/[^0-9]*//g')
for LOCAL in $LOCAL_LIST; do
LOCAL_NAME=$(echo $LOCAL | sed 's/_.*//'); LOCAL_VER=$(echo $LOCAL | sed 's/^[^_]*_//g' | sed 's/[^0-9]*//g')
if [ "$REMOTE_NAME" == "$LOCAL_NAME" ]; then INSTALLED=1; fi
if [ "$REMOTE_NAME" == "$LOCAL_NAME" ] && [ ! "$REMOTE_VER" == "$LOCAL_VER" ]; then echo remote=$REMOTE ver=$REMOTE_VER local=$LOCAL ver=$LOCAL_VER; fi
done
if [ "$INSTALLED" == "0" ]; then echo "$REMOTE"; fi
done
IFS=$OFS
As somebody asked how to do it without using aapt. It is also possible to extract apk info with apktool and a bit of scripting. This way is slower and not simple in android but will work on windows/mac or linux as long as you have working apktool setup.
#!/bin/sh
APK=/path/to/your.apk
TMPDIR=/tmp/apktool
rm -f -R $TMPDIR
apktool d -q -f -s --force-manifest -o $TMPDIR $APK
APK=$(basename $APK)
VERSION=$(cat $TMPDIR/apktool.yml | grep "versionName" | sed -e "s/versionName: //")
LABEL=$(cat $TMPDIR/res/values/strings.xml | grep 'string name="title"' | sed -e 's/.*">//' -e 's/<.*//')
rm -f -R $TMPDIR
echo ${LABEL}_$(echo $V).apk
Also consider a drop folder on your server. Upload apks to it and a cron task renames and moves them to your update folder.
#!/bin/sh
# Drop Folder script for renaming APKs
# Read apk file from SRC folder and move it to TGT folder while changing filename to APKLABEL_APKVERSION.apk
# If an existing version of the APK exists in the target folder then script will remove it
# Define METHOD as "aapt" or "apktool" depending upon what is available on server
# Variables
METHOD="aapt"
SRC="/home/user/public_html/dropfolders/apk"
TGT="/home/user/public_html/apk"
if [ -d "$SRC" ];then mkdir -p $SRC
if [ -d "$TGT" ]then mkdir -p $TGT
# Functions
get_apk_filename () {
if [ "$1" = "" ]; then return 1; fi
local A="$1"
case $METHOD in
"apktool")
local D=/tmp/apktool
rm -f -R $D
apktool d -q -f -s --force-manifest -o $D $A
local A=$(basename $A)
local V=$(cat $D/apktool.yml | grep "versionName" | sed -e "s/versionName: //")
local T=$(cat $D/res/values/strings.xml | grep 'string name="title"' | sed -e 's/.*">//' -e 's/<.*//')
rm -f -R $D<commands>
;;
"aapt")
local A=$(aapt dump badging $A | grep -e "application-label:" -e "VersionName")
local V=$(echo $A | sed -e "s/.*versionName='//" -e "s/' .*//")
local T=$(echo $A | sed -e "s/.*application-label:'//" -e "s/'.*//")
;;
esac
echo ${T}_$(echo $V).apk
}
# Begin script
for APK in $(ls "$SRC"/*.apk); do
APKNAME=$(get_apk_filename "$APK")
rm -f $TGT/$(echo APKNAME | sed "s/_.*//")_*.apk
mv "$APK" "$TGT"/$APKNAME
done
i created a package. it may meet your needs.
https://github.com/caoyongfeng0214/rn-overlaye
<View style={{paddingBottom:100}}>
<View> ...... </View>
<Overlay style={{left:0, right:0, bottom:0}}>
<View><Text>Footer</Text></View>
</Overlay>
</View>
For the folder name and drive, you can use:
echo %~dp0
You can get a lot more information using different modifiers:
%~I - expands %I removing any surrounding quotes (")
%~fI - expands %I to a fully qualified path name
%~dI - expands %I to a drive letter only
%~pI - expands %I to a path only
%~nI - expands %I to a file name only
%~xI - expands %I to a file extension only
%~sI - expanded path contains short names only
%~aI - expands %I to file attributes of file
%~tI - expands %I to date/time of file
%~zI - expands %I to size of file
The modifiers can be combined to get compound results:
%~dpI - expands %I to a drive letter and path only
%~nxI - expands %I to a file name and extension only
%~fsI - expands %I to a full path name with short names only
This is a copy paste from the "for /?" command on the prompt. Hope it helps.
Top 10 DOS Batch tips (Yes, DOS Batch...) shows batchparams.bat (link to source as a gist):
C:\Temp>batchparams.bat c:\windows\notepad.exe
%~1 = c:\windows\notepad.exe
%~f1 = c:\WINDOWS\NOTEPAD.EXE
%~d1 = c:
%~p1 = \WINDOWS\
%~n1 = NOTEPAD
%~x1 = .EXE
%~s1 = c:\WINDOWS\NOTEPAD.EXE
%~a1 = --a------
%~t1 = 08/25/2005 01:50 AM
%~z1 = 17920
%~$PATHATH:1 =
%~dp1 = c:\WINDOWS\
%~nx1 = NOTEPAD.EXE
%~dp$PATH:1 = c:\WINDOWS\
%~ftza1 = --a------ 08/25/2005 01:50 AM 17920 c:\WINDOWS\NOTEPAD.EXE
In your example, you prepended your source string with AccountKey=
but not your target string.
$c = $c -replace 'AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','AccountKey=DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA=='
By not including that in the target string, the resulting string will remove AccountKey=
instead of replacing it. You correctly do this with the AccountName=
example, which seems to support this conclusion since it is not giving you any problems. If you really mean to have that prepended, then this may resolve your issue.
For check email and phone number you need to do that
public static boolean isValidMobile(String phone) {
boolean check = false;
if (!Pattern.matches("[a-zA-Z]+", phone)) {
if (phone.length() < 9 || phone.length() > 13) {
// if(phone.length() != 10) {
check = false;
// txtPhone.setError("Not Valid Number");
} else {
check = android.util.Patterns.PHONE.matcher(phone).matches();
}
} else {
check = false;
}
return check;
}
public static boolean isEmailValid(String email) {
boolean check;
Pattern p;
Matcher m;
String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
p = Pattern.compile(EMAIL_STRING);
m = p.matcher(email);
check = m.matches();
return check;
}
String enter_mob_or_email="";//1234567890 or [email protected]
if (isValidMobile(enter_mob_or_email)) {// Phone number is valid
}else isEmailValid(enter_mob_or_email){//Email is valid
}else{// Not valid email or phone number
}
Here's a complete solution for those using Imagick in PHP:
$im = new \Imagick($filePath);
$im->setImageCompression(\Imagick::COMPRESSION_JPEG);
$im->setImageCompressionQuality(85);
$im->stripImage();
$im->setInterlaceScheme(\Imagick::INTERLACE_PLANE);
// Try between 0 or 5 radius. If you find radius of 5
// produces too blurry pictures decrease to 0 until you
// find a good balance between size and quality.
$im->gaussianBlurImage(0.05, 5);
// Include this part if you also want to specify a maximum size for the images
$size = $im->getImageGeometry();
$maxWidth = 1920;
$maxHeight = 1080;
// ----------
// | |
// ----------
if($size['width'] >= $size['height']){
if($size['width'] > $maxWidth){
$im->resizeImage($maxWidth, 0, \Imagick::FILTER_LANCZOS, 1);
}
}
// ------
// | |
// | |
// | |
// | |
// ------
else{
if($size['height'] > $maxHeight){
$im->resizeImage(0, $maxHeight, \Imagick::FILTER_LANCZOS, 1);
}
}
You can set the caret position using TextBox.CaretIndex. If the only thing you need is to set the cursor at the end, you can simply pass the string's length, eg:
txtBox.CaretIndex=txtBox.Text.Length;
You need to set the caret index at the length, not length-1, because this would put the caret before the last character.
You can use the format
method of the DateTime
class:
$date = new DateTime('2000-01-01');
$result = $date->format('Y-m-d H:i:s');
If format
fails for some reason, it will return FALSE
. In some applications, it might make sense to handle the failing case:
if ($result) {
echo $result;
} else { // format failed
echo "Unknown Time";
}
$(document).ready(function(){ _x000D_
$("#btn_clone").click(function(){ _x000D_
$("#a_clone").clone().appendTo("#b_clone"); _x000D_
}); _x000D_
});
_x000D_
.container{_x000D_
padding: 15px;_x000D_
border: 12px solid #23384E;_x000D_
background: #28BAA2;_x000D_
margin-top: 10px;_x000D_
}
_x000D_
<!DOCTYPE html> _x000D_
<html> _x000D_
<head> _x000D_
<title>jQuery Clone Method</title> _x000D_
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> _x000D_
_x000D_
_x000D_
</head> _x000D_
<body> _x000D_
<div class="container">_x000D_
<p id="a_clone"><b> This is simple example of clone method.</b></p> _x000D_
<p id="b_clone"><b>Note:</b>Click The Below button Click Me</p> _x000D_
<button id="btn_clone">Click Me!</button> _x000D_
</div> _x000D_
</body> _x000D_
</html>
_x000D_
Try this. It's working for me (Windows 10).
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
#fourcc = cv2.cv.CV_FOURCC(*'DIVX')
#out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
Class Row
will handle one row from your database.
Complete implementation of UpdateTask responsible for filling up UI.
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTable;
import javax.swing.SwingWorker;
public class JTableUpdateTask extends SwingWorker<JTable, Row> {
JTable table = null;
ResultSet resultSet = null;
public JTableUpdateTask(JTable table, ResultSet rs) {
this.table = table;
this.resultSet = rs;
}
@Override
protected JTable doInBackground() throws Exception {
List<Row> rows = new ArrayList<Row>();
Object[] values = new Object[6];
while (resultSet.next()) {
values = new Object[6];
values[0] = resultSet.getString("id");
values[1] = resultSet.getString("student_name");
values[2] = resultSet.getString("street");
values[3] = resultSet.getString("city");
values[4] = resultSet.getString("state");
values[5] = resultSet.getString("zipcode");
Row row = new Row(values);
rows.add(row);
}
process(rows);
return this.table;
}
protected void process(List<Row> chunks) {
ResultSetTableModel tableModel = (this.table.getModel() instanceof ResultSetTableModel ? (ResultSetTableModel) this.table.getModel() : null);
if (tableModel == null) {
try {
tableModel = new ResultSetTableModel(this.resultSet.getMetaData(), chunks);
} catch (SQLException e) {
e.printStackTrace();
}
this.table.setModel(tableModel);
} else {
tableModel.getRows().addAll(chunks);
}
tableModel.fireTableDataChanged();
}
}
Table Model:
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
/**
* Simple wrapper around Object[] representing a row from the ResultSet.
*/
class Row {
private final Object[] values;
public Row(Object[] values) {
this.values = values;
}
public int getSize() {
return values.length;
}
public Object getValue(int i) {
return values[i];
}
}
// TableModel implementation that will be populated by SwingWorker.
public class ResultSetTableModel extends AbstractTableModel {
private final ResultSetMetaData rsmd;
private List<Row> rows;
public ResultSetTableModel(ResultSetMetaData rsmd, List<Row> rows) {
this.rsmd = rsmd;
if (rows != null) {
this.rows = rows;
} else {
this.rows = new ArrayList<Row>();
}
}
public int getRowCount() {
return rows.size();
}
public int getColumnCount() {
try {
return rsmd.getColumnCount();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
public Object getValue(int row, int column) {
return rows.get(row).getValue(column);
}
public String getColumnName(int col) {
try {
return rsmd.getColumnName(col + 1);
} catch (SQLException e) {
e.printStackTrace();
}
return "";
}
public Class<?> getColumnClass(int col) {
String className = "";
try {
className = rsmd.getColumnClassName(col);
} catch (SQLException e) {
e.printStackTrace();
}
return className.getClass();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if(rowIndex > rows.size()){
return null;
}
return rows.get(rowIndex).getValue(columnIndex);
}
public List<Row> getRows() {
return this.rows;
}
public void setRows(List<Row> rows) {
this.rows = rows;
}
}
Main Application which builds UI and does the database connection
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;
public class MainApp {
static Connection conn = null;
static void init(final ResultSet rs) {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
final JTable table = new JTable();
table.setPreferredSize(new Dimension(300,300));
table.setMinimumSize(new Dimension(300,300));
table.setMaximumSize(new Dimension(300,300));
frame.add(table, BorderLayout.CENTER);
JButton button = new JButton("Start Loading");
button.setPreferredSize(new Dimension(30,30));
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JTableUpdateTask jTableUpdateTask = new JTableUpdateTask(table, rs);
jTableUpdateTask.execute();
}
});
frame.add(button, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/test";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url, userName, password);
PreparedStatement pstmt = conn.prepareStatement("Select id, student_name, street, city, state,zipcode from student");
ResultSet rs = pstmt.executeQuery();
init(rs);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Although probably not the best method you could add:
#div1 {
...
font-size:0;
}
Please try running
brew install docker
This will install the Docker engine, which will require Docker-Machine (+ VirtualBox) to run on the Mac.
If you want to install the newer Docker for Mac, which does not require virtualbox, you can install that through Homebrew's Cask:
brew install --cask docker
open /Applications/Docker.app
This would be easier to do with flexbox. Using flexbox will let you not to specify the height of your content and can adjust automatically on the height it contains.
here's the gist of the demo
.container{
display: flex;
height: 100%;
justify-content: center;
align-items: center;
}
html
<div class="container">
<div class='content'> //you can size this anyway you want
put anything you want here,
</div>
</div>
this solution it gonna be ok on Redhat 8.0
sudo yum install libxml2-devel
Had a similar problem. My solution was to give the inner table a fixed height of 1px and set the height of the td in the inner table to 100%. Against all odds, it works fine, tested in IE, Chrome and FF!
The simple solution you need to follow is
import { DomSanitizer } from '@angular/platform-browser';
constructor(private sanitizer: DomSanitizer){}
transformYourHtml(htmlTextWithStyle) {
return this.sanitizer.bypassSecurityTrustHtml(htmlTextWithStyle);
}
UILabel
has a property lineBreakMode
that you can set as per your requirement.
Focus on one specific thing. Disk I/O is slow, so I'd take that out of the test if all you are going to tweak is the database query.
And if you need to time your database execution, look for database tools instead, like asking for the query plan, and note that performance varies not only with the exact query and what indexes you have, but also with the data load (how much data you have stored).
That said, you can simply put your code in a function and run that function with timeit.timeit()
:
def function_to_repeat():
# ...
duration = timeit.timeit(function_to_repeat, number=1000)
This would disable the garbage collection, repeatedly call the function_to_repeat()
function, and time the total duration of those calls using timeit.default_timer()
, which is the most accurate available clock for your specific platform.
You should move setup code out of the repeated function; for example, you should connect to the database first, then time only the queries. Use the setup
argument to either import or create those dependencies, and pass them into your function:
def function_to_repeat(var1, var2):
# ...
duration = timeit.timeit(
'function_to_repeat(var1, var2)',
'from __main__ import function_to_repeat, var1, var2',
number=1000)
would grab the globals function_to_repeat
, var1
and var2
from your script and pass those to the function each repetition.
INSERT INTO Table1 SELECT * FROM Table2
You can add days to a date like this:
// add days to current **DateTime**
var addedDateTime = DateTime.Now.AddDays(10);
// add days to current **Date**
var addedDate = DateTime.Now.Date.AddDays(10);
// add days to any DateTime variable
var addedDateTime = anyDate.AddDay(10);
select * from left table where key field not in (select key field from right table)
It seems like you are expecting int
and unsigned int
to be a 16-bit integer. That's apparently not the case. Most likely, it's a 32-bit integer - which is large enough to avoid the wrap-around that you're expecting.
Note that there is no fully C-compliant way to do this because casting between signed/unsigned for values out of range is implementation-defined. But this will still work in most cases:
unsigned int x = 65529;
int y = (short) x; // If short is a 16-bit integer.
or alternatively:
unsigned int x = 65529;
int y = (int16_t) x; // This is defined in <stdint.h>
The reason is performance. If instance != null
(which will always be the case except the very first time), there is no need to do a costly lock
: Two threads accessing the initialized singleton simultaneously would be synchronized unneccessarily.
You can create a custom alertDialog and use a xml layout. in the layout, you can set the background color and textcolor.
Something like this:
Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
LayoutInflater inflater = (LayoutInflater)ActivityName.this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_layout,(ViewGroup)findViewById(R.id.layout_root));
dialog.setContentView(view);
Try:
cursor.column_names
mysql connector version:
mysql.connector.__version__
'2.2.9'
The command is bundle update
(there is no "r" in the "bundle").
To check if bundler is installed do : gem list bundler
or even which bundle
and the command will list either the bundler version or the path to it. If nothing is shown, then install bundler by typing gem install bundler
.
My previous answer was not enough accurate. As truly it was horrible :D But now I can post much more useful and correct answer.
I did some additional tests. You can find it's source by the following link and reCheck it on your environment by your own: https://github.com/ukushu/DataStructuresTestsAndOther.git
Short results:
Array need to use:
List need to use:
LinkedList need to use:
More details:
LinkedList<T>
internally is not a List in .NET. It's even does not implement IList<T>
. And that's why there are absent indexes and methods related to indexes.
LinkedList<T>
is node-pointer based collection. In .NET it's in doubly linked implementation. This means that prior/next elements have link to current element. And data is fragmented -- different list objects can be located in different places of RAM. Also there will be more memory used for LinkedList<T>
than for List<T>
or Array.
List<T>
in .Net is Java's alternative of ArrayList<T>
. This means that this is array wrapper. So it's allocated in memory as one contiguous block of data. If allocated data size exceeds 85000 bytes, it will be moved to Large Object Heap. Depending on the size, this can lead to heap fragmentation(a mild form of memory leak). But in the same time if size < 85000 bytes -- this provides a very compact and fast-access representation in memory.
Single contiguous block is preferred for random access performance and memory consumption but for collections that need to change size regularly a structure such as an Array generally need to be copied to a new location whereas a linked list only needs to manage the memory for the newly inserted/deleted nodes.
The other features of CodeLens like: Show Bugs, Show Test Status, etc (other than Show Reference) might be useful.
However, if the only way to disable Show References is to disable CodeLens altogether.
Then, I guess I could do just that.
Furthermore, I would do like I always have, 'right-click on a member and choose Find all References or Ctrl+K, R'
If I wanted to know what references the member -- I too like not having any extra information crammed into my code, like extra white-space.
In short, uncheck Codelens...
function realtime() {
let time = moment().format('hh:mm:ss.SS a').replace("m", "");
document.getElementById('time').innerHTML = time;
setInterval(() => {
time = moment().format('hh:mm:ss.SS A');
document.getElementById('time').innerHTML = time;
}, 0)
}
realtime();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
<div id="time"></div>
_x000D_
This solution is based on the one proposed by fei0x but it has the advantages that there is no need to join the value list of constants in the query and constants can be easily listed at the start of the query. It also works in recursive queries.
Basically, every constant is a single-value table declared in a WITH clause which can then be called anywhere in the remaining part of the query.
WITH
constant_1_str AS (VALUES ('Hello World')),
constant_2_int AS (VALUES (100))
SELECT *
FROM some_table
WHERE table_column = (table constant_1_str)
LIMIT (table constant_2_int)
Alternatively you can use SELECT * FROM constant_name
instead of TABLE constant_name
which might not be valid for other query languages different to postgresql.
I used the following code, it's working!
using System.Data.OleDb;
using System.IO;
using System.Text.RegularExpressions;
private void btopen_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog openFileDialog1 = new OpenFileDialog(); //create openfileDialog Object
openFileDialog1.Filter = "XML Files (*.xml; *.xls; *.xlsx; *.xlsm; *.xlsb) |*.xml; *.xls; *.xlsx; *.xlsm; *.xlsb";//open file format define Excel Files(.xls)|*.xls| Excel Files(.xlsx)|*.xlsx|
openFileDialog1.FilterIndex = 3;
openFileDialog1.Multiselect = false; //not allow multiline selection at the file selection level
openFileDialog1.Title = "Open Text File-R13"; //define the name of openfileDialog
openFileDialog1.InitialDirectory = @"Desktop"; //define the initial directory
if (openFileDialog1.ShowDialog() == DialogResult.OK) //executing when file open
{
string pathName = openFileDialog1.FileName;
fileName = System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
DataTable tbContainer = new DataTable();
string strConn = string.Empty;
string sheetName = fileName;
FileInfo file = new FileInfo(pathName);
if (!file.Exists) { throw new Exception("Error, file doesn't exists!"); }
string extension = file.Extension;
switch (extension)
{
case ".xls":
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
break;
case ".xlsx":
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
break;
default:
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
break;
}
OleDbConnection cnnxls = new OleDbConnection(strConn);
OleDbDataAdapter oda = new OleDbDataAdapter(string.Format("select * from [{0}$]", sheetName), cnnxls);
oda.Fill(tbContainer);
dtGrid.DataSource = tbContainer;
}
}
catch (Exception)
{
MessageBox.Show("Error!");
}
}
Yes of course you can write a text on canvas with ease, and you can set the font name, font size and font color. There are two method to build a text on Canvas, i.e. fillText() and strokeText(). fillText() method is used to make a text that can only be filled with color, whereas strokeText() is used to make a text that can only be given an outline color. So if we want to build a text that filled with color and have outline color, we must use both of them.
here the full example, how to write text on canvas :
<canvas id="Canvas01" width="400" height="200" style="border:2px solid #bbb; margin-left:10px; margin-top:10px;"></canvas>
<script>
var canvas = document.getElementById('Canvas01');
var ctx = canvas.getContext('2d');
ctx.fillStyle= "red";
ctx.font = "italic bold 35pt Tahoma";
//syntax : .fillText("text", x, y)
ctx.fillText("StacOverFlow",30,80);
</script>
Here the demo for this, and you can try your self for any modification: http://okeschool.com/examples/canvas/html5-canvas-text-color
You can set specific cache-headers for a whole folder in either your root web.config
:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- Note the use of the 'location' tag to specify which
folder this applies to-->
<location path="images">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
</staticContent>
</system.webServer>
</location>
</configuration>
Or you can specify these in a web.config
file in the content folder:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
</staticContent>
</system.webServer>
</configuration>
I'm not aware of a built in mechanism to target specific file types.
It's go to newline then add spaces to start second line at end of first line
Output
Hello
Goodbye
Passing an array of items as a collapsed parameter to the WHERE..IN clause will fail since query will take form of WHERE Age IN ("11, 13, 14, 16")
.
But you can pass your parameter as an array serialized to XML or JSON:
nodes()
method:StringBuilder sb = new StringBuilder();
foreach (ListItem item in ddlAge.Items)
if (item.Selected)
sb.Append("<age>" + item.Text + "</age>"); // actually it's xml-ish
sqlComm.CommandText = @"SELECT * from TableA WHERE Age IN (
SELECT Tab.col.value('.', 'int') as Age from @Ages.nodes('/age') as Tab(col))";
sqlComm.Parameters.Add("@Ages", SqlDbType.NVarChar);
sqlComm.Parameters["@Ages"].Value = sb.ToString();
OPENXML
method:using System.Xml.Linq;
...
XElement xml = new XElement("Ages");
foreach (ListItem item in ddlAge.Items)
if (item.Selected)
xml.Add(new XElement("age", item.Text);
sqlComm.CommandText = @"DECLARE @idoc int;
EXEC sp_xml_preparedocument @idoc OUTPUT, @Ages;
SELECT * from TableA WHERE Age IN (
SELECT Age from OPENXML(@idoc, '/Ages/age') with (Age int 'text()')
EXEC sp_xml_removedocument @idoc";
sqlComm.Parameters.Add("@Ages", SqlDbType.Xml);
sqlComm.Parameters["@Ages"].Value = xml.ToString();
That's a bit more on the SQL side and you need a proper XML (with root).
OPENJSON
method (SQL Server 2016+):using Newtonsoft.Json;
...
List<string> ages = new List<string>();
foreach (ListItem item in ddlAge.Items)
if (item.Selected)
ages.Add(item.Text);
sqlComm.CommandText = @"SELECT * from TableA WHERE Age IN (
select value from OPENJSON(@Ages))";
sqlComm.Parameters.Add("@Ages", SqlDbType.NVarChar);
sqlComm.Parameters["@Ages"].Value = JsonConvert.SerializeObject(ages);
Note that for the last method you also need to have Compatibility Level at 130+.
To understand the name: A stack trace is a a list of Exceptions( or you can say a list of "Cause by"), from the most surface Exception(e.g. Service Layer Exception) to the deepest one (e.g. Database Exception). Just like the reason we call it 'stack' is because stack is First in Last out (FILO), the deepest exception was happened in the very beginning, then a chain of exception was generated a series of consequences, the surface Exception was the last one happened in time, but we see it in the first place.
Key 1:A tricky and important thing here need to be understand is : the deepest cause may not be the "root cause", because if you write some "bad code", it may cause some exception underneath which is deeper than its layer. For example, a bad sql query may cause SQLServerException connection reset in the bottem instead of syndax error, which may just in the middle of the stack.
-> Locate the root cause in the middle is your job.
Key 2:Another tricky but important thing is inside each "Cause by" block, the first line was the deepest layer and happen first place for this block. For instance,
Exception in thread "main" java.lang.NullPointerException
at com.example.myproject.Book.getTitle(Book.java:16)
at com.example.myproject.Author.getBookTitles(Author.java:25)
at com.example.myproject.Bootstrap.main(Bootstrap.java:14)
Book.java:16 was called by Auther.java:25 which was called by Bootstrap.java:14, Book.java:16 was the root cause. Here attach a diagram sort the trace stack in chronological order.
For some reason the code supplied by m3z (with the DisplayHtml(string)
method) is not working in my case (except first time). I'm always displaying html from string. Here is my version after the battle with the WebBrowser control:
webBrowser1.Navigate("about:blank");
while (webBrowser1.Document == null || webBrowser1.Document.Body == null)
Application.DoEvents();
webBrowser1.Document.OpenNew(true).Write(html);
Working every time for me. I hope it helps someone.
I think, that will be good solution: /\S\w*/
In a nutshell, sys.argv
is a list of the words that appear in the command used to run the program. The first word (first element of the list) is the name of the program, and the rest of the elements of the list are any arguments provided. In most computer languages (including Python), lists are indexed from zero, meaning that the first element in the list (in this case, the program name) is sys.argv[0]
, and the second element (first argument, if there is one) is sys.argv[1]
, etc.
The test len(sys.argv) >= 2
simply checks wither the list has a length greater than or equal to 2, which will be the case if there was at least one argument provided to the program.
// Use ..
const Per = {
name: 'HAMZA',
age: 20,
coords: {
tele: '09',
lan: '190'
},
setAge(age: Number): void {
this.age = age;
},
getAge(): Number {
return age;
}
};
const { age, name }: { age: Number; name: String } = Per;
const {
coords: { tele, lan }
}: { coords: { tele: String; lan: String } } = Per;
console.log(Per.getAge());
I know, old post ... but it might be helpful to leave this here.
Modern browsers are now supporting the Fetch API.
You can use it like this:
fetch("<url>")
.then(data => data.json()) // could be .text() or .blob() depending on the data you are expecting
.then(console.log); // print your data
ps: It will make all CORS checks, since it's an improved XmlHttpRequest
.
I hope what you are trying to achieve is like this. For this please use Box layout.
package com.kcing.kailas.sample.client;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
public class Testing extends JFrame {
private JPanel jContentPane = null;
public Testing() {
super();
initialize();
}
private void initialize() {
this.setSize(300, 200);
this.setContentPane(getJContentPane());
this.setTitle("JFrame");
}
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(61, 11, 81, 140);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
jContentPane.add(panel);
JCheckBox c1 = new JCheckBox("Check1");
panel.add(c1);
c1 = new JCheckBox("Check2");
panel.add(c1);
c1 = new JCheckBox("Check3");
panel.add(c1);
c1 = new JCheckBox("Check4");
panel.add(c1);
}
return jContentPane;
}
public static void main(String[] args) throws Exception {
Testing frame = new Testing();
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
}
You can solve with snprintf and malloc.
char c_buff[50];
u8_number_val[] = { 0xbb, 0xcc, 0xdd, 0x0f, 0xef, 0x0f, 0x0e, 0x0d, 0x0c };
char *s_temp = malloc(u8_size * 2 + 1);
for (uint8_t i = 0; i < u8_size; i++)
{
snprintf(s_temp + i * 2, 3, "%02x", u8_number_val[i]);
}
snprintf(c_buff, strlen(s_temp)+1, "%s", s_temp );
printf("%s\n",c_buff);
free(s);
OUT: bbccdd0fef0f0e0d0c
There is no operator, but there is a method.
Math.pow(2, 3) // 8.0
Math.pow(3, 2) // 9.0
FYI, a common mistake is to assume 2 ^ 3
is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.
A similar option to what was posted above by janderson would be so simply use the .GetAttribute method in selenium 2. Using this, you can grab any item that has a specific value or label that you are looking for. This can be used to determine if an element has a label, style, value, etc. A common way to do this is to loop through the items in the drop down until you find the one that you want and select it. In C#
int items = driver.FindElement(By.XPath("//path_to_drop_Down")).Count();
for(int i = 1; i <= items; i++)
{
string value = driver.FindElement(By.XPath("//path_to_drop_Down/option["+i+"]")).GetAttribute("Value1");
if(value.Conatains("Label_I_am_Looking_for"))
{
driver.FindElement(By.XPath("//path_to_drop_Down/option["+i+"]")).Click();
//Clicked on the index of the that has your label / value
}
}
(Not exactly an answer for you, since do you want avoid opening the files, but maybe this helps others).
I have been using the open source GNU PSPP package to convert the sav tile to csv. You can download the Windows version at least from SourceForge [1]. Once you have the software, you can convert sav file to csv with following command line:
pspp-convert <input.sav> <output.csv>
[1] http://sourceforge.net/projects/pspp4windows/files/?source=navbar
You don't have to use gdb. GCC will do it.
gcc -S foo.c
This will create foo.s which is the assembly.
gcc -m32 -c -g -Wa,-a,-ad foo.c > foo.lst
The above version will create a listing file that has both the C and the assembly generated by it. GCC FAQ
In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj)
in your ModelForm.save
override, as ModelForm.save
later populates your m2m from self.cleaned_data['my_m2m']
which overwrites your changes. Instead call:
my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms
(It is fine to convert the incoming QuerySet to a list - the ManyToManyField
does that anyway.)
For lazy people, use mongodump
, it's faster:
mongodump -d <database_name> -o <directory_backup>
And to "restore/import" it (from directory_backup/dump/):
mongorestore -d <database_name> <directory_backup>
This way, you don't need to deal with all collections individually. Just specify the database.
Note that I would recommend against using mongodump
/mongorestore
for big data storages. It is very slow and once you get past 10/20GB of data it can take hours to restore.
To answer your question, no. That would be possible with div though. THe only question is would cause a hazzle if the functionality were done with div rather than tables.
I'm not sure if there is but if there was such a property it wouldn't be considered reliable. A WebException
can be fired for reasons other than HTTP error codes including simple networking errors. Those have no such matching http error code.
Can you give us a bit more info on what you're trying to accomplish with that code. There may be a better way to get the information you need.
You'll need to compile it using:
g++ inputfile.cpp -o outputbinary
The file you are referring has a missing #include <cstdlib>
directive, if you also include that in your file, everything shall compile fine.
I know this is an oldish question but I found it whilst looking for the same solution. The solution above doesn't appear to work in Laravel 4, you can however use this now:
<a href="{{ URL::previous() }}">Go Back</a>
Hope this helps people who look for this feature in L4
(Source: https://github.com/laravel/framework/pull/501/commits)
An easy solution that works for me with Ubuntu 14.04.
react-native run-android
The emulator (already launched) will return: Unable to download JS Bundle; start again the JS server:
react-native start
Hit Reload JS on the emulator. It worked for me. Hope it will help
I sugges to use the Apache Commons CSV https://commons.apache.org/proper/commons-csv/
Here is one example:
Path currentRelativePath = Paths.get("");
String currentPath = currentRelativePath.toAbsolutePath().toString();
String csvFile = currentPath + "/pathInYourProject/test.csv";
Reader in;
Iterable<CSVRecord> records = null;
try
{
in = new FileReader(csvFile);
records = CSVFormat.EXCEL.withHeader().parse(in); // header will be ignored
}
catch (IOException e)
{
e.printStackTrace();
}
for (CSVRecord record : records) {
String line = "";
for ( int i=0; i < record.size(); i++)
{
if ( line == "" )
line = line.concat(record.get(i));
else
line = line.concat("," + record.get(i));
}
System.out.println("read line: " + line);
}
It automaticly recognize , and " but not ; (maybe it can be configured...).
My example file is:
col1,col2,col3
val1,"val2",val3
"val4",val5
val6;val7;"val8"
And output is:
read line: val1,val2,val3
read line: val4,val5
read line: val6;val7;"val8"
Last line is considered like one value.
Commands that I had to use to update package.json
for NPM 3.10.10
:
npm install -g npm-check-updates
ncu -a
npm install
Background:
I was using the latest command from @josh3736 but my package.json
was not updated. I then noticed the description text when running npm-check-updates -u
:
The following dependency is satisfied by its declared version range, but the installed version is behind. You can install the latest version without modifying your package file by using npm update. If you want to update the dependency in your package file anyway, run ncu -a.
Reading the documentation for npm-check-updates you can see the difference:
https://www.npmjs.com/package/npm-check-updates
-u, --upgrade: overwrite package file
-a, --upgradeAll: include even those dependencies whose latest version satisfies the declared semver dependency
ncu is an alias for npm-check-updates
as seen in the message when typing npm-check-updates -u
:
[INFO]: You can also use ncu as an alias
Here is one way of doing this with List< KeyValuePair< string, string > >
public class ListWithDuplicates : List<KeyValuePair<string, string>>
{
public void Add(string key, string value)
{
var element = new KeyValuePair<string, string>(key, value);
this.Add(element);
}
}
var list = new ListWithDuplicates();
list.Add("k1", "v1");
list.Add("k1", "v2");
list.Add("k1", "v3");
foreach(var item in list)
{
string x = string.format("{0}={1}, ", item.Key, item.Value);
}
Outputs k1=v1, k1=v2, k1=v3
I had a case where solution was hard to figure out. This is not exactly relevant to particular question, but might help someone looking to solve a case with same error message when strptime is fed with timezone information. In my case, the reason for throwing
ValueError: time data '2016-02-28T08:27:16.000-07:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'
was presence of last colon in the timezone part. While in some locales (Russian one, for example) code was able to execute well, in another (English one) it was failing. Removing the last colon helped remedy my situation.
For getting all post parameters there is Map which contains request param name as key and param value as key.
Map params = servReq.getParameterMap();
And to get parameters with known name normal
String userId=servReq.getParameter("user_id");
If you want to examine elements inside a dataframe you should not be using ls()
which only looks at the names of objects in the current workspace (or if used inside a function in the current environment). Rownames or elements inside such objects are not visible to ls()
(unless of course you add an environment argument to the ls(.)
-call). Try using grep()
which is the workhorse function for pattern matching of character vectors:
result <- a[ grep("blue", a$x) , ] # Note need to use `a$` to get at the `x`
If you want to use subset then consider the closely related function grepl()
which returns a vector of logicals can be used in the subset argument:
subset(a, grepl("blue", a$x))
x
2 blue1
3 blue2
Edit: Adding one "proper" use of glob2rx within subset():
result <- subset(a, grepl(glob2rx("blue*") , x) )
result
x
2 blue1
3 blue2
I don't think I actually understood glob2rx
until I came back to this question. (I did understand the scoping issues that were ar the root of the questioner's difficulties. Anybody reading this should now scroll down to Gavin's answer and upvote it.)
You can use perl to replace various characters, for example:
$ echo "Hello\ world" | perl -pe 's/\\/\\\\/g'
Hello\\ world
Depending on the nature of your escape, you can chain multiple calls to escape the proper characters.
As always when you ask about fastest: Measure! Using the Methods above (on a Mac using Clang):
Method | executable size | Time Taken (in sec) |
| -O0 | -O3 | -O0 | -O3 |
------------|---------|---------|-----------|----------|
1. memset | 17 kB | 8.6 kB | 0.125 | 0.124 |
2. fill | 19 kB | 8.6 kB | 13.4 | 0.124 |
3. manual | 19 kB | 8.6 kB | 14.5 | 0.124 |
4. assign | 24 kB | 9.0 kB | 1.9 | 0.591 |
using 100000 iterations on an vector of 10000 ints.
Edit: If changeing this numbers plausibly changes the resulting times you can have some confidence (not as good as inspecting the final assembly code) that the artificial benchmark has not been optimized away entirely. Of course it is best to messure the performance under real conditions. end Edit
for reference the used code:
#include <vector>
#define TEST_METHOD 1
const size_t TEST_ITERATIONS = 100000;
const size_t TEST_ARRAY_SIZE = 10000;
int main(int argc, char** argv) {
std::vector<int> v(TEST_ARRAY_SIZE, 0);
for(size_t i = 0; i < TEST_ITERATIONS; ++i) {
#if TEST_METHOD == 1
memset(&v[0], 0, v.size() * sizeof v[0]);
#elif TEST_METHOD == 2
std::fill(v.begin(), v.end(), 0);
#elif TEST_METHOD == 3
for (std::vector<int>::iterator it=v.begin(), end=v.end(); it!=end; ++it) {
*it = 0;
}
#elif TEST_METHOD == 4
v.assign(v.size(),0);
#endif
}
return EXIT_SUCCESS;
}
Conclusion: use std::fill
(because, as others have said its most idiomatic)!
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>
the code behind for the window:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModelBase();
}
}
The ViewModel:
public class ViewModelBase
{
private ICommand _clickCommand;
public ICommand ClickCommand
{
get
{
return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
}
}
public bool CanExecute
{
get
{
// check if executing is allowed, i.e., validate, check if a process is running, etc.
return true/false;
}
}
public void MyAction()
{
}
}
Command Handler:
public class CommandHandler : ICommand
{
private Action _action;
private Func<bool> _canExecute;
/// <summary>
/// Creates instance of the command handler
/// </summary>
/// <param name="action">Action to be executed by the command</param>
/// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
public CommandHandler(Action action, Func<bool> canExecute)
{
_action = action;
_canExecute = canExecute;
}
/// <summary>
/// Wires CanExecuteChanged event
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Forcess checking if execute is allowed
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return _canExecute.Invoke();
}
public void Execute(object parameter)
{
_action();
}
}
I hope this will give you the idea.
Douglas Crockford has some very good explanations of inheritance in JavaScript:
This is for Laravel 5.1 and I am not sure does it work for earlier versions but if somebody search on Google and lands here it might be handy in middleware handle function gets $request parameter:
$request->server->get('SERVER_NAME')
outside of middleware handle method you can access it by helper function request()
request()->server->get('SERVER_NAME')
Try to add this hotfix: hotfixv4.microsoft.com/Windows%207/Windows%20Server2008%20R2%20SP1/sp2/Fix362872/7600/free/427221_intl_i386_zip.exe
Kinda late to the party, but in case anyone else is struggling. None of the Google searches I've found for the past two days have come up with anything that works, but I came up with a concise and elegant solution that will always work no matter how many nested tags you have:
function cursor_position() {_x000D_
var sel = document.getSelection();_x000D_
sel.modify("extend", "backward", "paragraphboundary");_x000D_
var pos = sel.toString().length;_x000D_
if(sel.anchorNode != undefined) sel.collapseToEnd();_x000D_
_x000D_
return pos;_x000D_
}_x000D_
_x000D_
// Demo:_x000D_
var elm = document.querySelector('[contenteditable]');_x000D_
elm.addEventListener('click', printCaretPosition)_x000D_
elm.addEventListener('keydown', printCaretPosition)_x000D_
_x000D_
function printCaretPosition(){_x000D_
console.log( cursor_position(), 'length:', this.textContent.trim().length )_x000D_
}
_x000D_
<div contenteditable>some text here <i>italic text here</i> some other text here <b>bold text here</b> end of text</div>
_x000D_
It selects all the way back to the beginning of the paragraph and then counts the length of the string to get the current position and then undoes the selection to return the cursor to the current position. If you want to do this for an entire document (more than one paragraph), then change paragraphboundary
to documentboundary
or whatever granularity for your case. Check out the API for more details. Cheers! :)
1) To remove white space everywhere:
df.columns = df.columns.str.replace(' ', '')
2) To remove white space at the beginning of string:
df.columns = df.columns.str.lstrip()
3) To remove white space at the end of string:
df.columns = df.columns.str.rstrip()
4) To remove white space at both ends:
df.columns = df.columns.str.strip()
5) To replace white space everywhere
df.columns = df.columns.str.replace(' ', '_')
6) To replace white space at the beginning:
df.columns = df.columns.str.replace('^ +', '_')
7) To replace white space at the end:
df.columns = df.columns.str.replace(' +$', '_')
8) To replace white space at both ends:
df.columns = df.columns.str.replace('^ +| +$', '_')
All above applies to a specific column as well, assume you have a column named col
, then just do:
df[col] = df[col].str.strip() # or .replace as above
You can use jackson api for the conversion
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
add above maven dependency in your POM, In your main method create ObjectMapper
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
later we nee to add our POJO class to the mapper
String json = mapper.writeValueAsString(pojo);
By using Server.Transfer("YourCurrentPage.aspx"); we can easily acheive this and it is better than Response.Redirect(); coz Server.Transfer() will save you the round trip.
Its very easy to create procedure in Mysql. Here, in my example I am going to create a procedure which is responsible to fetch all data from student table according to supplied name.
DELIMITER //
CREATE PROCEDURE getStudentInfo(IN s_name VARCHAR(64))
BEGIN
SELECT * FROM student_database.student s where s.sname = s_name;
END//
DELIMITER;
In the above example ,database and table names are student_database and student respectively. Note: Instead of s_name, you can also pass @s_name as global variable.
How to call procedure? Well! its very easy, simply you can call procedure by hitting this command
$mysql> CAll getStudentInfo('pass_required_name');
In version +2.0 you specify the namespace/room/node you are querying against.
As with broadcasting, the default is all clients from the default namespace ('/'):
const io = require('socket.io')();
io.clients((error, clients) => {
if (error) throw error;
console.log(clients); // => [6em3d4TJP8Et9EMNAAAA, G5p55dHhGgUnLUctAAAB]
});
Gets a list of client IDs connected to specific namespace (across all nodes if applicable).
const io = require('socket.io')();
io.of('/chat').clients((error, clients) => {
if (error) throw error;
console.log(clients); // => [PZDoMHjiu8PYfRiKAAAF, Anw2LatarvGVVXEIAAAD]
});
An example to get all clients in namespace's room:
const io = require('socket.io')();
io.of('/chat').in('general').clients((error, clients) => {
if (error) throw error;
console.log(clients); // => [Anw2LatarvGVVXEIAAAD]
});
This is from the official documentation: Socket.IO Server-API
I know this is old, but I came here searching for the same thing, I found that Bootstrap has the help-block, very handy for these situations:
<div class="help-block"></div>
Consider two class-typed variables:
class Boo { ... };
Boo b0; // mutable object
const Boo b1; // non-mutable object
Now you are able to call any member function of Boo
on b0
, but only const
-qualified member functions on b1
.
This awnser solved my problem. Below is a copy of it:
Make sure to start you JVM with -Dfile.encoding=UTF-8. You JVM defaults to the operating system charset
This is a JVM argument which could be added, for example, either to JBoss standalone or JBoss running from Eclipse.
In my case, this problem happened isolatelly on only one of my team people's computer. All the others was working without this problem.
If you happen to be using PyTorch already, you should go with their CosineSimilarity implementation.
Suppose you have two n
-dimensional numpy.ndarray
s, v1
and v2
, i.e. their shapes are both (n,)
. Here's how you get their cosine similarity:
import torch
import torch.nn as nn
cos = nn.CosineSimilarity()
cos(torch.tensor([v1]), torch.tensor([v2])).item()
Or suppose you have two numpy.ndarray
s w1
and w2
, whose shapes are both (m, n)
. The following gets you a list of cosine similarities, each being the cosine similarity between a row in w1
and the corresponding row in w2
:
cos(torch.tensor(w1), torch.tensor(w2)).tolist()
Those of us using Python 3.x should do this:
python -c "import sys; print(sys.path)"
overflow:hidden
(as mentioned by @Mikael S) doesn't work in every situation, but it should work in most situations.
Another option is to use the :after
trick:
<div class="wrapper">
<div class="col"></div>
<div class="col"></div>
</div>
.wrapper {
min-height: 1px; /* Required for IE7 */
}
.wrapper:after {
clear: both;
display: block;
height: 0;
overflow: hidden;
visibility: hidden;
content: ".";
font-size: 0;
}
.col {
display: inline;
float: left;
}
And for IE6:
.wrapper { height: 1px; }
I would advise against changing the default behaviour of a key. I do as much as possible without touching a mouse, so if you make my tab key not move to the next field on a form I will be very aggravated.
A shortcut key could be useful however, especially with large code blocks and nesting. Shift-TAB is a bad option because that normally takes me to the previous field on a form. Maybe a new button on the WMD editor to insert a code-TAB, with a shortcut key, would be possible?
Here's my Python 2/3 compatible version. Since the translate api has changed.
def remove(str_, chars):
"""Removes each char in `chars` from `str_`.
Args:
str_: String to remove characters from
chars: String of to-be removed characters
Returns:
A copy of str_ with `chars` removed
Example:
remove("What?!?: darn;", " ?.!:;") => 'Whatdarn'
"""
try:
# Python2.x
return str_.translate(None, chars)
except TypeError:
# Python 3.x
table = {ord(char): None for char in chars}
return str_.translate(table)
I know it's old question but it still in first 10 links in google.
It is not very efficient to save rows one-by-one because it cause database call in the loop and you better avoid that, especially when you need to insert huge portions of data.
It's better (and significantly faster) to use batch insert.
INSERT INTO `mouldings` (suppliers_code, name, cost)
VALUES
('s1', 'supplier1', 1.111),
('s2', 'supplier2', '2.222')
You can build such a query manually and than do Model.connection.execute(RAW SQL STRING)
(not recomended)
or use gem activerecord-import
(it was first released on 11 Aug 2010) in this case just put data in array rows
and call Model.import rows
The dialog on this seems to be the antithesis of the conversation on naming interface
and abstract
classes. I find this alarming, and think that the decision runs much deeper than simply choosing one naming convention and using it always with static final
.
When naming interfaces and abstract classes, the accepted convention has evolved into not prefixing or suffixing your abstract class
or interface
with any identifying information that would indicate it is anything other than a class.
public interface Reader {}
public abstract class FileReader implements Reader {}
public class XmlFileReader extends FileReader {}
The developer is said not to need to know that the above classes are abstract
or an interface
.
My personal preference and belief is that we should follow similar logic when referring to static final
variables. Instead, we evaluate its usage when determining how to name it. It seems the all uppercase argument is something that has been somewhat blindly adopted from the C and C++ languages. In my estimation, that is not justification to continue the tradition in Java.
We should ask ourselves what is the function of static final
in our own context. Here are three examples of how static final
may be used in different contexts:
public class ChatMessage {
//Used like a private variable
private static final Logger logger = LoggerFactory.getLogger(XmlFileReader.class);
//Used like an Enum
public class Error {
public static final int Success = 0;
public static final int TooLong = 1;
public static final int IllegalCharacters = 2;
}
//Used to define some static, constant, publicly visible property
public static final int MAX_SIZE = Integer.MAX_VALUE;
}
Could you use all uppercase in all three scenarios? Absolutely, but I think it can be argued that it would detract from the purpose of each. So, let's examine each case individually.
In the case of the Logger
example above, the logger is declared as private, and will only be used within the class, or possibly an inner class. Even if it were declared at protected
or , its usage is the same:package
visibility
public void send(final String message) {
logger.info("Sending the following message: '" + message + "'.");
//Send the message
}
Here, we don't care that logger
is a static final
member variable. It could simply be a final
instance variable. We don't know. We don't need to know. All we need to know is that we are logging the message to the logger that the class instance has provided.
public class ChatMessage {
private final Logger logger = LoggerFactory.getLogger(getClass());
}
You wouldn't name it LOGGER
in this scenario, so why should you name it all uppercase if it was static final
? Its context, or intention, is the same in both circumstances.
Note: I reversed my position on package
visibility because it is more like a form of public
access, restricted to package
level.
Now you might say, why are you using static final
integers as an enum
? That is a discussion that is still evolving and I'd even say semi-controversial, so I'll try not to derail this discussion for long by venturing into it. However, it would be suggested that you could implement the following accepted enum pattern:
public enum Error {
Success(0),
TooLong(1),
IllegalCharacters(2);
private final int value;
private Error(final int value) {
this.value = value;
}
public int value() {
return value;
}
public static Error fromValue(final int value) {
switch (value) {
case 0:
return Error.Success;
case 1:
return Error.TooLong;
case 2:
return Error.IllegalCharacters;
default:
throw new IllegalArgumentException("Unknown Error value.");
}
}
}
There are variations of the above that achieve the same purpose of allowing explicit conversion of an enum->int
and int->enum
. In the scope of streaming this information over a network, native Java serialization is simply too verbose. A simple int
, short
, or byte
could save tremendous bandwidth. I could delve into a long winded compare and contrast about the pros and cons of enum
vs static final int
involving type safety, readability, maintainability, etc.; fortunately, that lies outside the scope of this discussion.
The bottom line is this, sometimes
static final int
will be used as anenum
style structure.
If you can bring yourself to accept that the above statement is true, we can follow that up with a discussion of style. When declaring an enum
, the accepted style says that we don't do the following:
public enum Error {
SUCCESS(0),
TOOLONG(1),
ILLEGALCHARACTERS(2);
}
Instead, we do the following:
public enum Error {
Success(0),
TooLong(1),
IllegalCharacters(2);
}
If your static final
block of integers serves as a loose enum
, then why should you use a different naming convention for it? Its context, or intention, is the same in both circumstances.
This usage case is perhaps the most cloudy and debatable of all. The static constant size usage example is where this is most often encountered. Java removes the need for sizeof()
, but there are times when it is important to know how many bytes a data structure will occupy.
For example, consider you are writing or reading a list of data structures to a binary file, and the format of that binary file requires that the total size of the data chunk be inserted before the actual data. This is common so that a reader knows when the data stops in the scenario that there is more, unrelated, data that follows. Consider the following made up file format:
File Format: MyFormat (MYFM) for example purposes only
[int filetype: MYFM]
[int version: 0] //0 - Version of MyFormat file format
[int dataSize: 325] //The data section occupies the next 325 bytes
[int checksumSize: 400] //The checksum section occupies 400 bytes after the data section (16 bytes each)
[byte[] data]
[byte[] checksum]
This file contains a list of MyObject
objects serialized into a byte stream and written to this file. This file has 325 bytes of MyObject
objects, but without knowing the size of each MyObject
you have no way of knowing which bytes belong to each MyObject
. So, you define the size of MyObject
on MyObject
:
public class MyObject {
private final long id; //It has a 64bit identifier (+8 bytes)
private final int value; //It has a 32bit integer value (+4 bytes)
private final boolean special; //Is it special? (+1 byte)
public static final int SIZE = 13; //8 + 4 + 1 = 13 bytes
}
The MyObject
data structure will occupy 13 bytes when written to the file as defined above. Knowing this, when reading our binary file, we can figure out dynamically how many MyObject
objects follow in the file:
int dataSize = buffer.getInt();
int totalObjects = dataSize / MyObject.SIZE;
This seems to be the typical usage case and argument for all uppercase static final
constants, and I agree that in this context, all uppercase makes sense. Here's why:
Java doesn't have a struct
class like the C language, but a struct
is simply a class with all public members and no constructor. It's simply a data struct
ure. So, you can declare a class
in struct
like fashion:
public class MyFile {
public static final int MYFM = 0x4D59464D; //'MYFM' another use of all uppercase!
//The struct
public static class MyFileHeader {
public int fileType = MYFM;
public int version = 0;
public int dataSize = 0;
public int checksumSize = 0;
}
}
Let me preface this example by stating I personally wouldn't parse in this manner. I'd suggest an immutable class instead that handles the parsing internally by accepting a ByteBuffer
or all 4 variables as constructor arguments. That said, accessing (setting in this case) this struct
s members would look something like:
MyFileHeader header = new MyFileHeader();
header.fileType = buffer.getInt();
header.version = buffer.getInt();
header.dataSize = buffer.getInt();
header.checksumSize = buffer.getInt();
These aren't static
or final
, yet they are publicly exposed members that can be directly set. For this reason, I think that when a static final
member is exposed publicly, it makes sense to uppercase it entirely. This is the one time when it is important to distinguish it from public, non-static variables.
Note: Even in this case, if a developer attempted to set a final
variable, they would be met with either an IDE or compiler error.
In conclusion, the convention you choose for static final
variables is going to be your preference, but I strongly believe that the context of use should heavily weigh on your design decision. My personal recommendation would be to follow one of the two methodologies:
[highly subjective; logical]
private
variable that should be indistinguishable from a private
instance variable, then name them the same. all lowercaseenum
style block of static
values, then name it as you would an enum
. pascal case: initial-cap each word[objective; logical]
Methodology 2 basically condenses its context into visibility, and leaves no room for interpretation.
private
or protected
then it should be all lowercase.public
or package
then it should be all uppercase.This is how I view the naming convention of static final
variables. I don't think it is something that can or should be boxed into a single catch all. I believe that you should evaluate its intent before deciding how to name it.
However, the main objective should be to try and stay consistent throughout your project/package's scope. In the end, that is all you have control over.
(I do expect to be met with resistance, but also hope to gather some support from the community on this approach. Whatever your stance, please keep it civil when rebuking, critiquing, or acclaiming this style choice.)
class String
def black
return "\e[30m#{self}\e[0m"
end
def red
return "\e[31m#{self}\e[0m"
end
def light_green
return "\e[32m#{self}\e[0m"
end
def purple
return "\e[35m#{self}\e[0m"
end
def blue_dark
return "\e[34m#{self}\e[0m"
end
def blue_light
return "\e[36m#{self}\e[0m"
end
def white
return "\e[37m#{self}\e[0m"
end
def randColor
array_color = [
"\e[30m#{self}\e[0m",
"\e[31m#{self}\e[0m",
"\e[32m#{self}\e[0m",
"\e[35m#{self}\e[0m",
"\e[34m#{self}\e[0m",
"\e[36m#{self}\e[0m",
"\e[37m#{self}\e[0m" ]
return array_color[rand(0..array_color.size)]
end
end
puts "black".black
puts "red".red
puts "light_green".light_green
puts "purple".purple
puts "dark blue".blue_dark
puts "light blue".blue_light
puts "white".white
puts "random color".randColor
The Python name resolution only knows the following kinds of scope:
print
, int
, or zip
,def
block, lambda
expression or comprehension.def
block, lambda
expression or comprehension,class
block.Notably, other constructs such as if
, for
, or with
statements do not have their own scope.
The scoping TLDR: The lookup of a name begins at the scope in which the name is used, then any enclosing scopes (excluding class scopes), to the module globals, and finally the builtins – the first match in this search order is used.
The assignment to a scope is by default to the current scope – the special forms nonlocal
and global
must be used to assign to a name from an outer scope.
Finally, comprehensions and generator expressions as well as :=
asignment expressions have one special rule when combined.
These different scopes build a hierarchy, with builtins then global always forming the base, and closures, locals and class scope being nested as lexically defined. That is, only the nesting in the source code matters, not for example the call stack.
print("builtins are available without definition")
some_global = "1" # global variables are at module scope
def outer_function():
some_closure = "3.1" # locals and closure are defined the same, at function scope
some_local = "3.2" # a variable becomes a closure if a nested scope uses it
class InnerClass:
some_classvar = "3.3" # class variables exist *only* at class scope
def nested_function(self):
some_local = "3.2" # locals can replace outer names
print(some_closure) # closures are always readable
return InnerClass
Even though class
creates a scope and may have nested classes, functions and comprehensions, the names of the class
scope are not visible to enclosed scopes. This creates the following hierarchy:
? builtins [print, ...]
??? globals [some_global]
??? outer_function [some_local, some_closure]
??? InnerClass [some_classvar]
??? inner_function [some_local]
Name resolution always starts at the current scope in which a name is accessed, then goes up the hierarchy until a match is found. For example, looking up some_local
inside outer_function
and inner_function
starts at the respective function - and immediately finds the some_local
defined in outer_function
and inner_function
, respectively. When a name is not local, it is fetched from the nearest enclosing scope that defines it – looking up some_closure
and print
inside inner_function
searches until outer_function
and builtins, respectively.
By default, a name belongs to any scope in which it is bound to a value. Binding the same name again in an inner scope creates a new variable with the same name - for example, some_local
exists separately in both outer_function
and inner_function
. As far as scoping is concerned, binding includes any statement that sets the value of a name – assignment statements, but also the iteration variable of a for
loop, or the name of a with
context manager. Notably, del
also counts as name binding.
When a name must refer to an outer variable and be bound in an inner scope, the name must be declared as not local. Separate declarations exists for the different kinds of enclosing scopes: nonlocal
always refers to the nearest closure, and global
always refers to a global name. Notably, nonlocal
never refers to a global name and global
ignores all closures of the same name. There is no declaration to refer to the builtin scope.
some_global = "1"
def outer_function():
some_closure = "3.2"
some_global = "this is ignored by a nested global declaration"
def inner_function():
global some_global # declare variable from global scope
nonlocal some_closure # declare variable from enclosing scope
message = " bound by an inner scope"
some_global = some_global + message
some_closure = some_closure + message
return inner_function
Of note is that function local and nonlocal
are resolved at compile time. A nonlocal
name must exist in some outer scope. In contrast, a global
name can be defined dynamically and may be added or removed from the global scope at any time.
The scoping rules of list, set and dict comprehensions and generator expressions are almost the same as for functions. Likewise, the scoping rules for assignment expressions are almost the same as for regular name binding.
The scope of comprehensions and generator expressions is of the same kind as function scope. All names bound in the scope, namely the iteration variables, are locals or closures to the comprehensions/generator and nested scopes. All names, including iterables, are resolved using name resolution as applicable inside functions.
some_global = "global"
def outer_function():
some_closure = "closure"
return [ # new function-like scope started by comprehension
comp_local # names resolved using regular name resolution
for comp_local # iteration targets are local
in "iterable"
if comp_local in some_global and comp_local in some_global
]
An :=
assignment expression works on the nearest function, class or global scope. Notably, if the target of an assignment expression has been declared nonlocal
or global
in the nearest scope, the assignment expression honors this like a regular assignment.
print(some_global := "global")
def outer_function():
print(some_closure := "closure")
However, an assignment expression inside a comprehension/generator works on the nearest enclosing scope of the comprehension/generator, not the scope of the comprehension/generator itself. When several comprehensions/generators are nested, the nearest function or global scope is used. Since the comprehension/generator scope can read closures and global variables, the assignment variable is readable in the comprehension as well. Assigning from a comprehension to a class scope is not valid.
print(some_global := "global")
def outer_function():
print(some_closure := "closure")
steps = [
# v write to variable in containing scope
(some_closure := some_closure + comp_local)
# ^ read from variable in containing scope
for comp_local in some_global
]
return some_closure, steps
While the iteration variable is local to the comprehension in which it is bound, the target of the assignment expression does not create a local variable and is read from the outer scope:
? builtins [print, ...]
??? globals [some_global]
??? outer_function [some_closure]
??? <listcomp> [comp_local]
A solution that also works with both negative numbers and floats, and doesn't call any expensive String manipulation functions:
function getDigits(n) {
var a = Math.abs(n); // take care of the sign
var b = a << 0; // truncate the number
if(b - a !== 0) { // if the number is a float
return ("" + a).length - 1; // return the amount of digits & account for the dot
} else {
return ("" + a).length; // return the amount of digits
}
}
The time complexity of ArrayList.clear()
is O(n)
and of removeAll
is O(n^2)
.
So yes, ArrayList.clear
is much faster.
You can install maven using homebrew. The command is
$ brew install maven
If your computer can't find the IP address associated with SUBDOMAIN1.example.COM
, it will not find the site.
You need to either change your hosts
file (so you can at least test things - this will be a local change, only available to yourself), or update DNS so the name will resolve correctly (so the rest of the world can see it).
Dragging an object and placing in a different location is part of the standard of HTML5. All the objects can be draggable. But the Specifications of below web browser should be followed. API Chrome Internet Explorer Firefox Safari Opera Version 4.0 9.0 3.5 6.0 12.0
You can find example from below: https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop2
async function FileToString (file) {
try {
let res = await file.raw.text();
console.log(res);
} catch (err) {
throw err;
}
}
In C++ both struct
& class
are equal except struct's
default member access specifier is public
& class has private
.
The reason for having struct
in C++ is C++ is a superset of C and must have backward compatible with legacy C types
.
For example if the language user tries to include some C header file legacy-c.h
in his C++ code & it contains struct Test {int x,y};
. Members of struct Test
should be accessible as like C.
You can run the MySQL command SHOW FULL PROCESSLIST;
to see what queries are being processed at any given time, but that probably won't achieve what you're hoping for.
The best method to get a history without having to modify every application using the server is probably through triggers. You could set up triggers so that every query run results in the query being inserted into some sort of history table, and then create a separate page to access this information.
Do be aware that this will probably considerably slow down everything on the server though, with adding an extra INSERT
on top of every single query.
Edit: another alternative is the General Query Log, but having it written to a flat file would remove a lot of possibilities for flexibility of displaying, especially in real-time. If you just want a simple, easy-to-implement way to see what's going on though, enabling the GQL and then using running tail -f
on the logfile would do the trick.
I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=D:\test.xls " & _
";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
For i = 0 To rs.Fields.Count - 1
Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
strNaam = rs.Fields(0).Value
Next
rs.MoveNext
Loop
rs.Close
There are other ways, depending on what you want to do, such as GetString (GetString Method Description).
To those who are stuck wondering why a window flashes and goes away without doing anything, the problem may related to the RELATIVE path in your Python script. e.g. you used ".\". Even the Python script and Excel Workbook is in the same directory, the Current Directory may still be different. If you don't want to modify your code to change it to an absolute path. Just change your current Excel directory before you run the python script by:
ChDir ActiveWorkbook.Path
I'm just giving a example here. If the flash do appear, one of the first issues to check is the Current Working Directory.
I was also struggling with a similar issue dealing with exporting data into an Excel spreadsheet using C#. I tried many different methods working with external DLLs and had no luck.
For the export functionality you do not need to use anything dealing with the external DLLs. Instead, just maintain the header and content type of the response.
Here is an article that I found rather helpful. The article talks about how to export data to Excel spreadsheets using ASP.NET.
http://www.icodefor.net/2016/07/export-data-to-excel-sheet-in-asp-dot-net-c-sharp.html
From http://api.jquery.com/jQuery/
Selector Context By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function. For example, to do a search within an event handler, the search can be restricted like so:
$( "div.foo" ).click(function() {
$( "span", this ).addClass( "bar" );
});
When the search for the span selector is restricted to the context of this, only spans within the clicked element will get the additional class.
So for your example I would suggest something like:
$("div", ".container").each(function(){
//do whatever
});
It can also happen when drawing a new (other) table. I solved this by first removing the previous table:
$("#prod_tabel_ph").remove();
Create file - res / xml / network_security.xml
In network_security.xml ->
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">192.168.0.101</domain>
</domain-config>
</network-security-config>
Open AndroidManifests.xml :
android:usesCleartextTraffic="true" //Add this line in your manifests
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="@style/AppTheme">
<select v-model="challan.warehouse_id">
<option value="">Select Warehouse</option>
<option v-for="warehouse in warehouses" v-bind:value="warehouse.id" >
{{ warehouse.name }}
</option>
Here "challan.warehouse_id" come from "challan" object you get from:
editChallan: function() {
let that = this;
axios.post('/api/challan_list/get_challan_data', {
challan_id: that.challan_id
})
.then(function (response) {
that.challan = response.data;
})
.catch(function (error) {
that.errors = error;
});
}
From Standard docs., 3.6.1.2 Main Function,
It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:
int main() { / ... / }
and
int main(int argc, char* argv[]) { / ... / }
In the latter form
argc
shall be the number of arguments passed to the program from the environment in which the program is run.If argc is nonzero these arguments shall be supplied in argv[0] through argv[argc-1] as pointers to the initial characters of null-terminated multibyte strings.....
Hope that helps..
Twitter Bootstrap is incompatible with jQuery UI styles at the moment.
https://github.com/twitter/bootstrap/issues/156
This might help you https://github.com/sferik/rails_admin ( http://rails-admin-tb.herokuapp.com/admin/drafts/new )
I know this is old, but if anyone else wants to know why they get incomplete json like above is because the ampersand &
is a special character in URLs used to separate parameters.
In your data there is an ampersand in R&R
. So the acc parameter ends when it reaches the ampersand character.
That's why you are getting chopped data. The solution is either url encode the data or send as POST like the accepted solution suggests.
Just drop them:
nms.dropna(thresh=2)
this will drop all rows where there are at least two non-NaN
.
Then you could then drop where name is NaN
:
In [87]:
nms
Out[87]:
movie name rating
0 thg John 3
1 thg NaN 4
3 mol Graham NaN
4 lob NaN NaN
5 lob NaN NaN
[5 rows x 3 columns]
In [89]:
nms = nms.dropna(thresh=2)
In [90]:
nms[nms.name.notnull()]
Out[90]:
movie name rating
0 thg John 3
3 mol Graham NaN
[2 rows x 3 columns]
EDIT
Actually looking at what you originally want you can do just this without the dropna
call:
nms[nms.name.notnull()]
UPDATE
Looking at this question 3 years later, there is a mistake, firstly thresh
arg looks for at least n
non-NaN
values so in fact the output should be:
In [4]:
nms.dropna(thresh=2)
Out[4]:
movie name rating
0 thg John 3.0
1 thg NaN 4.0
3 mol Graham NaN
It's possible that I was either mistaken 3 years ago or that the version of pandas I was running had a bug, both scenarios are entirely possible.
Save to EPS and then convert to PDF:
saveas(gcf, 'nombre.eps', 'eps2c')
system('epstopdf nombre.eps') %Needs TeX Live (maybe it works with MiKTeX).
You will need some software that converts EPS to PDF.
Adding .
before \r\n
makes it work if the original string before \r\n
has no .
Other characters may work. I didn't try.
With or without the three lines including IsBodyHtml, not a matter.
From the Errata:
ModelState.AddRuleViolations(dinner.GetRuleViolations());
Should be:
ModelState.AddModelErrors(dinner.GetRuleViolations());
I agree with the use of instanceof
already mentioned.
An additional benefit of using instanceof
is that when used with a null
reference instanceof
of will return false
, while a.getClass()
would throw a NullPointerException
.
If you're rolling your own I'd highly recommend looking at http://effbot.org/zone/element-soap.htm.
Access Specifiers in Java: There are 4 access specifiers in java, namely private, package-private (default), protected and public in increasing access order.
Private: When you are developing some class and you want member of this class not to be exposed outside this class then you should declare it as private. private members can be accessed only in class where they are defined i.e. enclosing class. private members can be accessed on 'this' reference and also on other instances of class enclosing these members, but only within the definition of this class.
Package-private (default): This access specifier will provide access specified by private access specifier in addition to access described below.
When you are developing some package and hence some class (say Class1) within it, you may use default (need not be mentioned explicitly) access specifier, to expose member within class, to other classes within your (same) package. In these other classes (within same package), you can access these default members on instance of Class1. Also you can access these default members within subclasses of Class1, say Class2 (on this reference or on instance of Class1 or on instance of Class2).
Basically, within same package you can access default members on instance of class directly or on 'this' reference in subclasses.
protected: This access specifier will provide access specified by package-private access specifier in addition to access described below.
When you are developing some package and hence some class (say Class1) within it, then you should use protected access specifier for data member within Class1 if you don't want this member to be accessed outside your package (say in package of consumer of your package i.e. client who is using your APIs) in general, but you want to make an exception and allow access to this member only if client writes class say Class2 that extends Class1. So, in general, protected members will be accessible on 'this' reference in derived classes i.e. Class2 and also on explicit instances of Class2.
Please note:
So bottom line is, protected members can be accessed in other packages, only if some class from this other package, extends class enclosing this protected member and protected member is accessed on 'this' reference or explicit instances of extended class, within definition of extended class.
public: This access specifier will provide access specified by protected access specifier in addition to access described below.
When you are developing some package and hence some class (say Class1) within it, then you should use public access specifier for data member within Class1 if you want this member to be accessible in other packages on instance of Class1 created in some class of other package. Basically this access specifier should be used when you intent to expose your data member to world without any condition.
The below command worked for me
sudo service postgresql restart
The default Locale
is constructed statically at runtime for your application process from the system property settings, so it will represent the Locale
selected on that device when the application was launched. Typically, this is fine, but it does mean that if the user changes their Locale
in settings after your application process is running, the value of getDefaultLocale()
probably will not be immediately updated.
If you need to trap events like this for some reason in your application, you might instead try obtaining the Locale
available from the resource Configuration
object, i.e.
Locale current = getResources().getConfiguration().locale;
You may find that this value is updated more quickly after a settings change if that is necessary for your application.
Here is a simple and more update format of getting the data:
$now = new \DateTime('now');
$month = $now->format('m');
$year = $now->format('Y');
you can do this much easier with css only, for example : sass mode
.truncatedText {
font-size: 0.875em;
line-height: 1.2em;
height: 2.4em; // 2 lines * line-height
&:after {
content: " ...";
}
}
and you have ellipsis ;)
Since the deactivate
function created by sourcing ~/bin/activate
cannot be discovered by the usual means of looking for such a command in ~/bin
, you may wish to create one that just executes the function deactivate
.
The problem is that a script named deactivate
containing a single command deactivate
will cause an endless loop if accidentally executed while not in the venv. A common mistake.
This can be avoided by only executing deactivate
if the function exists (i.e. has been created by sourcing activate
).
#!/bin/bash
declare -Ff deactivate && deactivate
If you're using cyrus/sasl/imap on your mailserver, then one fast and efficient way to purge everything in a mailbox that is older then number of days specified is to use cyrus/imap ipurge command. For example, here is an example removing everything (be carefull!!), older then 30 days from user vleo. Notice, that you must be logged in as cyrus (imap mail administrator) user:
[cyrus@mailserver ~]$ /usr/lib/cyrus-imapd/ipurge -f -d 30 user.vleo
Working on user.vleo...
total messages 4
total bytes 113183
Deleted messages 0
Deleted bytes 0
Remaining messages 4
Remaining bytes 113183
The only thing that worked for me was creating a
.java-version
file with "oracle64-1.8.0.112" as the only entry ( use something that is 1.6+ )
Make sure you have dynamic web module facet turned on.
First ,you should install github in your PC; Second,you can download the tool 'Everything'; Third,open the tool everything ,type git.exe,then you will find the location and copy the location to PyCharm ,and Test,you will see successfully!
Data Warehouse vs Database: A data warehouse is specially designed for data analytics, which involves reading large amounts of data to understand relationships and trends across the data. A database is used to capture and store data, such as recording details of a transaction.
Data Warehouse: Suitable workloads - Analytics, reporting, big data. Data source - Data collected and normalized from many sources. Data capture - Bulk write operations typically on a predetermined batch schedule. Data normalization - Denormalized schemas, such as the Star schema or Snowflake schema. Data storage - Optimized for simplicity of access and high-speed query. performance using columnar storage. Data access - Optimized to minimize I/O and maximize data throughput.
Transactional Database: Suitable workloads - Transaction processing. Data source - Data captured as-is from a single source, such as a transactional system. Data capture - Optimized for continuous write operations as new data is available to maximize transaction throughput. Data normalization - Highly normalized, static schemas. Data storage - Optimized for high throughout write operations to a single row-oriented physical block. Data access - High volumes of small read operations.
just give and text style whatever you want like :D HTML:
<a href="javascript:;" class="fa fa-trash" style="color:#d9534f;">
<span style="color:black;">Text Name</span>
</a>
Select the text, right click on the selection, and select the option "command palette":
A new window opens. Search for "format" and select the option which has formatting as per the requirement.
Notice: Trying to get property of non-object in C:\wamp\www\phone\pages\init.php on line 22
@22 is
<?php echo $sidemenu->mname."<br />";?>
$sidemenu
is not an object, and you are trying to access one of its properties.
That is the reason for your error.
I think you can try to firstly select all the text in the field and then send the new sequence:
from selenium.webdriver.common.keys import Keys
element.sendKeys(Keys.chord(Keys.CONTROL, "a"), "55");
Also this is a cause too: If you built a jQuery collection (via .map() or something similar) then you shouldn't use this collection in .ajax()'s data. Because it's still a jQuery object, not plain JavaScript Array. You should use .get() at the and to get plain js array and should use it on the data setting on .ajax().
The simplest solution I've found is:
var text = atob(byteArray);
cp
has multiple usages:
$ cp --help
Usage: cp [OPTION]... [-T] SOURCE DEST
or: cp [OPTION]... SOURCE... DIRECTORY
or: cp [OPTION]... -t DIRECTORY SOURCE...
Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.
@AndyRoss's answer works for the
cp SOURCE DEST
style of cp
, but does the wrong thing if you use the
cp SOURCE... DIRECTORY/
style of cp
.
I think that "DEST" is ambiguous without a trailing slash in this usage (i.e. where the target directory doesn't yet exist), which is perhaps why cp
has never added an option for this.
So here's my version of this function which enforces a trailing slash on the dest dir:
cp-p() {
last=${@: -1}
if [[ $# -ge 2 && "$last" == */ ]] ; then
# cp SOURCE... DEST/
mkdir -p "$last" && cp "$@"
else
echo "cp-p: (copy, creating parent dirs)"
echo "cp-p: Usage: cp-p SOURCE... DEST/"
fi
}
You have a single quotes conflict, so use:
echo "A,B,C" | sed "s/,/','/g"
If using bash, you can do too (<<<
is a here-string
):
sed "s/,/','/g" <<< "A,B,C"
but not
sed "s/,/','/g" "A,B,C"
because sed
expect file(s) as argument(s)
EDIT:
if you use ksh or any other ones :
echo string | sed ...
There is no difference, under the hood it's all varlena
(variable length array).
Check this article from Depesz: http://www.depesz.com/index.php/2010/03/02/charx-vs-varcharx-vs-varchar-vs-text/
A couple of highlights:
To sum it all up:
- char(n) – takes too much space when dealing with values shorter than
n
(pads them ton
), and can lead to subtle errors because of adding trailing spaces, plus it is problematic to change the limit- varchar(n) – it's problematic to change the limit in live environment (requires exclusive lock while altering table)
- varchar – just like text
- text – for me a winner – over (n) data types because it lacks their problems, and over varchar – because it has distinct name
The article does detailed testing to show that the performance of inserts and selects for all 4 data types are similar. It also takes a detailed look at alternate ways on constraining the length when needed. Function based constraints or domains provide the advantage of instant increase of the length constraint, and on the basis that decreasing a string length constraint is rare, depesz concludes that one of them is usually the best choice for a length limit.
Use the random library:
import java.util.Random;
Then create a random generator:
Random rand = new Random();
As colours are separated into red green and blue, you can create a new random colour by creating random primary colours:
// Java 'Color' class takes 3 floats, from 0 to 1.
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
Then to finally create the colour, pass the primary colours into the constructor:
Color randomColor = new Color(r, g, b);
You can also create different random effects using this method, such as creating random colours with more emphasis on certain colours ... pass in less green and blue to produce a "pinker" random colour.
// Will produce a random colour with more red in it (usually "pink-ish")
float r = rand.nextFloat();
float g = rand.nextFloat() / 2f;
float b = rand.nextFloat() / 2f;
Or to ensure that only "light" colours are generated, you can generate colours that are always > 0.5 of each colour element:
// Will produce only bright / light colours:
float r = rand.nextFloat() / 2f + 0.5;
float g = rand.nextFloat() / 2f + 0.5;
float b = rand.nextFloat() / 2f + 0.5;
There are various other colour functions that can be used with the Color
class, such as making the colour brighter:
randomColor.brighter();
An overview of the Color
class can be read here: http://download.oracle.com/javase/6/docs/api/java/awt/Color.html
You can .append(element)
to the list, e.g.: s1.append(i)
. What you are currently trying to do is access an element (s1[i]
) that does not exist.
You can do that using FileInfo
class:
FileInfo fi = new FileInfo("path");
var created = fi.CreationTime;
var lastmodified = fi.LastWriteTime;
This was sort of tricky for me too, I did the following which worked pretty well.
chmod
the egg to be executable: chmod a+x [egg]
(ie, for Python 2.6, chmod a+x setuptools-0.6c9-py2.6.egg
)./[egg]
(ie, for Python 2.6, ./setuptools-0.6c9-py2.6.egg
)Not sure if you'll need to use sudo if you're just installing it for you current user. You'd definitely need it to install it for all users.
You need to first add using Microsoft.Win32;
to your code page.
Then you can begin to use the Registry
classes:
try
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
{
if (key != null)
{
Object o = key.GetValue("Version");
if (o != null)
{
Version version = new Version(o as String); //"as" because it's REG_SZ...otherwise ToString() might be safe(r)
//do what you like with version
}
}
}
}
catch (Exception ex) //just for demonstration...it's always best to handle specific exceptions
{
//react appropriately
}
BEWARE: unless you have administrator access, you are unlikely to be able to do much in LOCAL_MACHINE
. Sometimes even reading values can be a suspect operation without admin rights.
To check if a file doesn't exist, equivalent to Python's if not os.path.exists(filename)
:
if _, err := os.Stat("/path/to/whatever"); os.IsNotExist(err) {
// path/to/whatever does not exist
}
To check if a file exists, equivalent to Python's if os.path.exists(filename)
:
Edited: per recent comments
if _, err := os.Stat("/path/to/whatever"); err == nil {
// path/to/whatever exists
} else if os.IsNotExist(err) {
// path/to/whatever does *not* exist
} else {
// Schrodinger: file may or may not exist. See err for details.
// Therefore, do *NOT* use !os.IsNotExist(err) to test for file existence
}
See this; run
sudo update-java-alternatives --list
to list off all the Java installations on a machine by name and directory, and then run
sudo update-java-alternatives --set [JDK/JRE name e.g. java-8-oracle]
to choose which JRE/JDK to use.
If you want to use different JDKs/JREs for each Java task, you can run update-alternatives to configure one java executable at a time; you can run
sudo update-alternatives --config java[Tab]
to see the Java commands that can be configured (java, javac, javah, javaws, etc). And then
sudo update-alternatives --config [javac|java|javadoc|etc.]
will associate that Java task/command to a particular JDK/JRE.
You may also need to set JAVA_HOME for some applications: from this answer you can use
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")
for JREs, or
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:jre/bin/java::")
for JDKs.
SOLUTIONS
g++
. So install g++
first and then recreate your project. This worked for me.CMAKE_CXX_COMPILER:FILEPATH=/usr/bin/c++
Note the path to g++
depends on OS. I have used my fedora path obtained using which g++
often this is due to missing permissions. The windows account the local IIS Application Pool is running with may not have the permission to write to the applications directory. You could create a directory somewhere, give everyone permission to write in it and point your log4net config to that directory. If then a log file is created there, you can modify the permissions for your desired log directory so that the app pool can write to it.
Another reason could be an uninitialized log4net. In a winforms app, you usually configure log4net upon application start. In a web app, you can do this either dynamically (in your logging component, check if you can create a specific Ilog logger using its name, if not -> call configure()) or again upon application start in global.asax.cs.
<div class="container-fluid">
<div class="row">
<h3 class="one">Text</h3>
<button class="btn btn-secondary ml-auto">Button</button>
</div>
</div>
.ml-auto
is Bootstraph 4's non-flexbox way of aligning things.
There is comma missing in your tuple.
insert the comma between the tuples as shown:
pack_size = (('1', '1'),('3', '3'),(b, b),(h, h),(d, d), (e, e),(r, r))
Do the same for all
That's because abc
is undefined at the moment of the template rendering. You can use safe navigation operator (?
) to "protect" template until HTTP call is completed:
{{abc?.xyz?.name}}
You can read more about safe navigation operator here.
Update:
Safe navigation operator can't be used in arrays, you will have to take advantage of NgIf
directive to overcome this problem:
<div *ngIf="arr && arr.length > 0">
{{arr[0].name}}
</div>
Read more about NgIf
directive here.
Bootstrap provide events that you can hook into modal, like if you want to fire a event when the modal has finished being hidden from the user you can use hidden.bs.modal event like this
/* hidden.bs.modal event example */
$('#myModal').on('hidden.bs.modal', function () {
window.alert('hidden event fired!');
})
Check a working fiddle here read more about modal methods and events here in Documentation
You can check this just use table inside table like this
<!DOCTYPE html>
<html>
<head>
<style>
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
<body>
<table style="width:100%">
<tr>
<th>ABC</th>
<th>ABC</th>
<th>ABC</th>
<th>ABC</th>
</tr>
<tr>
<td>Item1</td>
<td>Item1</td>
<td>
<table style="width:100%">
<tr>
<td>name1</td>
<td>price1</td>
</tr>
<tr>
<td>name2</td>
<td>price2</td>
</tr>
<tr>
<td>name3</td>
<td>price3</td>
</tr>
</table>
</td>
<td>item1</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
<tr>
<td>E</td>
<td>F</td>
<td>G</td>
<td>H</td>
</tr>
<tr>
<td>E</td>
<td>R</td>
<td>T</td>
<td>T</td>
</tr>
</table>
</body>
</html>
_x000D_
You can use the Jquery UI for drag and drop with an additional library that translates mouse events into touch which is what you need, the library I recommend is https://github.com/furf/jquery-ui-touch-punch, with this your drag and drop from Jquery UI should work on touch devises
or you can use this code which I am using, it also converts mouse events into touch and it works like magic.
function touchHandler(event) {
var touch = event.changedTouches[0];
var simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent({
touchstart: "mousedown",
touchmove: "mousemove",
touchend: "mouseup"
}[event.type], true, true, window, 1,
touch.screenX, touch.screenY,
touch.clientX, touch.clientY, false,
false, false, false, 0, null);
touch.target.dispatchEvent(simulatedEvent);
event.preventDefault();
}
function init() {
document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);
}
And in your document.ready just call the init() function
code found from Here
I had this problem when trying to run 'npm install' in a Terminal window which had been opened before installing Node.js.
Opening a new Terminal window (i.e. bash session) worked. (Presumably this provided the correct environment variables for npm to run correctly.)
I ended up overriding Fragment.onResume()
and grabbing the attributes from the underlying dialog, then setting width/height params there. I set the outermost layout height/width to match_parent
. Note that this code seems to respect the margins I defined in the xml layout as well.
@Override
public void onResume() {
super.onResume();
ViewGroup.LayoutParams params = getDialog().getWindow().getAttributes();
params.width = LayoutParams.MATCH_PARENT;
params.height = LayoutParams.MATCH_PARENT;
getDialog().getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
}
Just a caveat to add about DateDiff, it counts the number of times you pass the boundary you specify as your units, so is subject to problems if you are looking for a precise timespan. e.g.
select datediff (m, '20100131', '20100201')
gives an answer of 1, because it crossed the boundary from January to February, so even though the span is 2 days, datediff would return a value of 1 - it crossed 1 date boundary.
select datediff(mi, '2010-01-22 15:29:55.090' , '2010-01-22 15:30:09.153')
Gives a value of 1, again, it passed the minute boundary once, so even though it is approx 14 seconds, it would be returned as a single minute when using Minutes as the units.
This is a nice tutorial:
http://android-developers.blogspot.de/2009/05/painless-threading.html
Or this for the UI thread:
http://developer.android.com/guide/faq/commontasks.html#threading
Or here a very practical one:
http://www.androidacademy.com/1-tutorials/43-hands-on/115-threading-with-android-part1
and another one about procceses and threads
http://developer.android.com/guide/components/processes-and-threads.html
You can avoid rolling your own Component subclass completely by using the JXImagePanel class from the free SwingX libraries.
login to your server via
ssh -X root@yourIP
edit /etc/ssh/sshd_config file, and add this line to it.
X11UseLocalhost no
Restart sshd. for CentOS (check your distribution)
/sbin/service sshd restart
check your DISPLAY
echo $DISPLAY
you should see this
yourIP:10.0
Enjoy
firefox
The same thing happened to me. In my case most of the worksheet was in protected mode (though the cells relevant to the macro were unlocked). When I disabled the protection on the worksheet, the macro worked fine...it seems VBA doesn't like locked cells even if they are not used by the macro.
for use sample touch listener just you need this code
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
view.startDrag(data, shadowBuilder, null, 0);
return true;
}
The short answer is you can't.
I don't know any PHP syntax, but what I can tell you is that PHP is executed on the server and JavaScript is executed on the client (on the browser).
You're doing a $_GET, which is used to retrieve form values:
The built-in $_GET function is used to collect values in a form with method="get".
In other words, if on your page you had:
<form method="get" action="blah.php">
<input name="test"></input>
</form>
Your $_GET call would retrieve the value in that input field.
So how to retrieve a value from JavaScript?
Well, you could stick the javascript value in a hidden form field...
<script type="text/javascript" charset="utf-8">
var test = "tester";
// find the 'test' input element and set its value to the above variable
document.getElementByID("test").value = test;
</script>
... elsewhere on your page ...
<form method="get" action="blah.php">
<input id="test" name="test" visibility="hidden"></input>
<input type="submit" value="Click me!"></input>
</form>
Then, when the user clicks your submit button, he/she will be issuing a "GET" request to blah.php, sending along the value in 'test'.
Delete %LocalAppData%\Microsoft\VisualStudio\14.0\ComponentModelCache
and restart Visual Studio.
Alternatively, use the Clear MEF Component Cache extension.
Try the following keystrokes:
gg=G
Explanation: gg
goes to the top of the file, =
is a command to fix the indentation and G
tells it to perform the operation to the end of the file.
I know this has been answered, but here's mine just because I think case is an under-appreciated tool. (Maybe because people think it is slow, but it's at least as fast as an if, sometimes faster.)
case "$1" in
0|1) xinput set-prop 12 "Device Enabled" $1 ;;
*) echo "This script requires a 1 or 0 as first parameter." ;;
esac
Be careful of difference between 'c'
and "c"
'c'
is a char suitable for formatting with %c
"c"
is a char* pointing to a memory block with a length of 2 (with the null terminator).
This is the code that worked for me:
jQuery('document').ready(function()
{
$(".navbar-header button").click(function(event) {
if ($(".navbar-collapse").hasClass('in'))
{ $(".navbar-collapse").slideUp(); }
});})