Coming from the hardware development world. . .
Simulation tests functionality. 2+2 = 4 etc
Emulation tests the functionality on the specific environment (64-bit, 16-bit, fingers and toes).
Here is a food example:
You have two pieces of bread, one knife, peanut butter and jelly and will be giving them to a kindergartner. You write instructions on how to make a sandwich.
In simulation, you would act out the process, pretend you opened the jars, pretend spreading the peanut butter etc.
If at the end of the instructions your are left with only jelly and not peanut butter then you failed the simulation and you need to fix your instructions. On the other hand if you have a complete "sandwich" then the instructions should be valid
In emulation, you would use close representations of the actual parts (same bread, knife peanut butter etc). What happens if you gave your kindergartner a cheap plastic knife and really really thick peanut butter?? The knife would break in emulation and the instructions would need to be clarified or fixed to accommodate this problem. In this case you might suggest warming up the peanut butter in the microwave.
In practice: Consider a 64-bit system that you are programming in and a 32bit system that will actually be running the code. You add two very very large numbers and print the result. In simulation everything works (you managed to get the code right to add two numbers) In emulation however you find that you get the wrong answer. What happened? The emulation of the 32-bit system was unable to handle the large numbers. This is an example of correct functionality (i.e. simulation) but not proper support for your runtime environment (emulation)
Simple Explanation.
If you want to convert your PC (running Windows) into Mac, you can do either of these:
(1) You can simply install a Mac theme on your Windows. So, your PC feels more like Mac, but you can't actually run any Mac programs.
(SIMULATION)
(or)
(2) You can program your PC to run like Mac (I'm not sure if this is possible :P ). Now you can even run Mac programs successfully and expect the same output as on Mac.
(EMULATION)
In the first case, you can experience Mac, but you can't expect the same output as on Mac.
In the second case, you can expect the same output as on Mac, but still the fact remains that it is only a PC.
We have purchased 12 years of intraday data from Kibot.com and are pretty satisfied with the quality.
As for storage requirements: 12 years of 1-minute data for all USA equities (more than 8000 symbols) is about 100GB.
With tick-by-tick data situation is little different. If you record time and sales only, that would be about 30GB of data per month for all USA equities. If you want to store bid / ask changes together with transactions, you can expect about 150GB per month.
I hope this helps. Please let me know if there is anything else I can assist you with.
The newest camera2 apis work fine w/ an emulator that has camera support enabled.
Example for using the newer API:
Of course ios7 prohibits creating fake locations on real device.
For testing purpose there are two approches:
1) while device is connected to xcode, use the simulator and let it play a gpx track.
2) for real world testing, not connected to simu, one possibility is that your app, has a special modus built in, where you set it to "playback" mode. In that mode the app has to create the locations itself, using a timer of 1s, and creating a new CLLocation object.
3) A third possibility is described here: https://blackpixel.com/writing/2013/05/simulating-locations-with-xcode.html
If multiple clock are generated with different frequencies, then clock generation can be simplified if a procedure is called as concurrent procedure call. The time resolution issue, mentioned by Martin Thompson, may be mitigated a little by using different high and low time in the procedure. The test bench with procedure for clock generation is:
library ieee;
use ieee.std_logic_1164.all;
entity tb is
end entity;
architecture sim of tb is
-- Procedure for clock generation
procedure clk_gen(signal clk : out std_logic; constant FREQ : real) is
constant PERIOD : time := 1 sec / FREQ; -- Full period
constant HIGH_TIME : time := PERIOD / 2; -- High time
constant LOW_TIME : time := PERIOD - HIGH_TIME; -- Low time; always >= HIGH_TIME
begin
-- Check the arguments
assert (HIGH_TIME /= 0 fs) report "clk_plain: High time is zero; time resolution to large for frequency" severity FAILURE;
-- Generate a clock cycle
loop
clk <= '1';
wait for HIGH_TIME;
clk <= '0';
wait for LOW_TIME;
end loop;
end procedure;
-- Clock frequency and signal
signal clk_166 : std_logic;
signal clk_125 : std_logic;
begin
-- Clock generation with concurrent procedure call
clk_gen(clk_166, 166.667E6); -- 166.667 MHz clock
clk_gen(clk_125, 125.000E6); -- 125.000 MHz clock
-- Time resolution show
assert FALSE report "Time resolution: " & time'image(time'succ(0 fs)) severity NOTE;
end architecture;
The time resolution is printed on the terminal for information, using the concurrent assert last in the test bench.
If the clk_gen
procedure is placed in a separate package, then reuse from test bench to test bench becomes straight forward.
Waveform for clocks are shown in figure below.
An more advanced clock generator can also be created in the procedure, which can adjust the period over time to match the requested frequency despite the limitation by time resolution. This is shown here:
-- Advanced procedure for clock generation, with period adjust to match frequency over time, and run control by signal
procedure clk_gen(signal clk : out std_logic; constant FREQ : real; PHASE : time := 0 fs; signal run : std_logic) is
constant HIGH_TIME : time := 0.5 sec / FREQ; -- High time as fixed value
variable low_time_v : time; -- Low time calculated per cycle; always >= HIGH_TIME
variable cycles_v : real := 0.0; -- Number of cycles
variable freq_time_v : time := 0 fs; -- Time used for generation of cycles
begin
-- Check the arguments
assert (HIGH_TIME /= 0 fs) report "clk_gen: High time is zero; time resolution to large for frequency" severity FAILURE;
-- Initial phase shift
clk <= '0';
wait for PHASE;
-- Generate cycles
loop
-- Only high pulse if run is '1' or 'H'
if (run = '1') or (run = 'H') then
clk <= run;
end if;
wait for HIGH_TIME;
-- Low part of cycle
clk <= '0';
low_time_v := 1 sec * ((cycles_v + 1.0) / FREQ) - freq_time_v - HIGH_TIME; -- + 1.0 for cycle after current
wait for low_time_v;
-- Cycle counter and time passed update
cycles_v := cycles_v + 1.0;
freq_time_v := freq_time_v + HIGH_TIME + low_time_v;
end loop;
end procedure;
Again reuse through a package will be nice.
The error is a stack overflow. That should ring a bell on this site, right? It occurs because a call to poruszanie
results in another call to poruszanie
, incrementing the recursion depth by 1. The second call results in another call to the same function. That happens over and over again, each time incrementing the recursion depth.
Now, the usable resources of a program are limited. Each function call takes a certain amount of space on top of what is called the stack. If the maximum stack height is reached, you get a stack overflow error.
I am working on a MVC5/Web API project and needed to be able to get authorization for the Web Api methods. When my index view is first loaded I make a call to the 'token' Web API method which I believe is created automatically.
The client side code (CoffeeScript) to get the token is:
getAuthenticationToken = (username, password) ->
dataToSend = "username=" + username + "&password=" + password
dataToSend += "&grant_type=password"
$.post("/token", dataToSend).success saveAccessToken
If successful the following is called, which saves the authentication token locally:
saveAccessToken = (response) ->
window.authenticationToken = response.access_token
Then if I need to make an Ajax call to a Web API method that has the [Authorize] tag I simply add the following header to my Ajax call:
{ "Authorization": "Bearer " + window.authenticationToken }
One option is to use lapply
and class
. For example:
> foo <- data.frame(c("a", "b"), c(1, 2))
> names(foo) <- c("SomeFactor", "SomeNumeric")
> lapply(foo, class)
$SomeFactor
[1] "factor"
$SomeNumeric
[1] "numeric"
Another option is str
:
> str(foo)
'data.frame': 2 obs. of 2 variables:
$ SomeFactor : Factor w/ 2 levels "a","b": 1 2
$ SomeNumeric: num 1 2
this is in pure javascript
document.addEventListener('keypress', function (e) {_x000D_
if (e.keyCode === 13 || e.which === 13) {_x000D_
e.preventDefault();_x000D_
return false;_x000D_
}_x000D_
_x000D_
});
_x000D_
Make sure that novalidate attribute is not set to your form tag
you can reverse your array and push the data , at the end again reverse it:
var arr=[2,3,4,5,6];
var arr2=1;
arr.reverse();
//[6,5,4,3,2]
arr.push(arr2);
My explanation is in the code. :)
DECLARE @TestConvert VARCHAR(MAX) = '123456789.1234567'
BEGIN TRY
SELECT CAST(@TestConvert AS DECIMAL(10, 4))
END TRY
BEGIN CATCH
SELECT 'The reason you get the message "' + ERROR_MESSAGE() + '" is because DECIMAL(10, 4) only allows for 4 numbers after the decimal.'
END CATCH
-- Here's one way to truncate the string to a castable value.
SELECT CAST(LEFT(@TestConvert, (CHARINDEX('.', @TestConvert, 1) + 4)) AS DECIMAL(14, 4))
-- If you noticed, I changed it to DECIMAL(14, 4) instead of DECIMAL(10, 4) That's because this number has 14 digits, as proven below.
-- Read this for a better explanation as to what precision, scale and length mean: http://msdn.microsoft.com/en-us/library/ms190476(v=sql.105).aspx
SELECT LEN(LEFT(@TestConvert, (CHARINDEX('.', @TestConvert, 1) + 4)))
You should use a hidden input as a refresh indicator, with a value of "no":
<input type="hidden" id="refresh" value="no">
Now using jQuery, you can check its value:
$(document).ready(function(e) {
var $input = $('#refresh');
$input.val() == 'yes' ? location.reload(true) : $input.val('yes');
});
When you click on the back button, the values in hidden fields retain the same value as when you originally left the page.
So the first time you load the page, the input's value would be "no". When you return to the page, it'll be "yes" and your JavaScript code will trigger a refresh.
var ListByOwner = list.GroupBy(l => l.Owner)
.Select(lg =>
new {
Owner = lg.Key,
Boxes = lg.Count(),
TotalWeight = lg.Sum(w => w.Weight),
TotalVolume = lg.Sum(w => w.Volume)
});
One-liner solution
import pandas as pd
dict = {row[0] : row[1] for _, row in pd.read_csv("file.csv").iterrows()}
openssl pkcs12 -in YOUR_CERTIFICATE.p12 -out YOUR_CERTIFICATE.pem -nodes -clcerts
<system.webServer>
<staticContent>
<remove fileExtension=".woff"/>
<mimeMap fileExtension=".woff" mimeType="application/font-woff" />
<mimeMap fileExtension=".woff2" mimeType="font/woff2" />
</staticContent>
</system.webServer>
You can use the String split
method to get the single numbers as an array of strings. Then convert them to numbers with the unary plus operator, the Number
function or parseInt
, and add them to your array:
var arr = [1,2,3],
strVale = "130,235,342,124 ";
var strings = strVale.split(",");
for (var i=0; i<strVale.length; i++)
arr.push( + strings[i] );
Or, in one step, using Array map
to convert them and applying them to one single push
:
arr.push.apply(arr, strVale.split(",").map(Number));
As per latest api docs:
$(document).ready(function() {
$('#example').dataTable({
"order": []
});
});
While @nickf's answer works. If you don't care for older browsers, you can use this pure Javascript version. Works in IE9+, and others
var rect = el.getBoundingClientRect();
var position = {
top: rect.top + window.pageYOffset,
left: rect.left + window.pageXOffset
};
.set_title('') can be used to add title to Seaborn Plot
import seaborn as sb
sb.boxplot().set_title('Title')
Like it's written up there, you forget to type #include <sstream>
#include <sstream>
using namespace std;
QString Stats_Manager::convertInt(int num)
{
stringstream ss;
ss << num;
return ss.str();
}
You can also use some other ways to convert int
to string
, like
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;
check this!
To specify a directory to search for (binary) libraries, you just use -L
:
-L/data[...]/lib
To specify the actual library name, you use -l
:
-lfoo # (links libfoo.a or libfoo.so)
To specify a directory to search for include files (different from libraries!) you use -I
:
-I/data[...]/lib
So I think what you want is something like
g++ -g -Wall -I/data[...]/lib testing.cpp fileparameters.cpp main.cpp -o test
These compiler flags (amongst others) can also be found at the GNU GCC Command Options manual:
Here's a nice answer from the FAQ on the scipy.org website:
What advantages do NumPy arrays offer over (nested) Python lists?
Python’s lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python’s list comprehensions make them easy to construct and manipulate. However, they have certain limitations: they don’t support “vectorized” operations like elementwise addition and multiplication, and the fact that they can contain objects of differing types mean that Python must store type information for every element, and must execute type dispatching code when operating on each element. This also means that very few list operations can be carried out by efficient C loops – each iteration would require type checks and other Python API bookkeeping.
While moopasta's answer works, it doesn't appear to allow wildcards and there is another (potentially better) option. The Chromium project has some HTTP authentication documentation that is useful but incomplete.
Specifically the option that I found best is to whitelist sites that you would like to allow Chrome to pass authentication information to, you can do this by:
auth-server-whitelist
command line switch. e.g. --auth-server-whitelist="*example.com,*foobar.com,*baz"
. Downfall to this approach is that opening links from other programs will launch Chrome without the command line switch.AuthServerWhitelist
/"Authentication server whitelist" Group Policy or Local Group Policy. This seems like the most stable option but takes more work to setup. You can set this up locally, no need to have this remotely deployed.Those looking to set this up for an enterprise can likely follow the directions for using Group Policy or the Admin console to configure the AuthServerWhitelist
policy. Those looking to set this up for one machine only can also follow the Group Policy instructions:
Start > Run > gpedit.msc
Local Computer Policy > Computer Configuration > Administrative Templates
Administrative Templates
, and select Add/Remove Templates
windows\adm\en-US\chrome.adm
template via the dialogComputer Configuration > Administrative Templates > Classic Administrative Templates > Google > Google Chrome > Policies for HTTP Authentication
enable and configure Authentication server whitelist
chrome://policy
to view active policiesSometimes ! be careful with property depth of the image ! and name for image
exemple : ic_xxxxx_xxxx - Copie
In win7, if you want to set the correct timezone as a parameter in JRE, you have to edit the file deployment.properties
stored in path c:\users\%username%\appdata\locallow\sun\java\deployment
adding the string deployment.javaws.jre.1.args=-Duser.timezone\=
my_time_zone
Setting:
request.Referer = @"http://www.somesite.com/";
and adding cookies
than worked for me
write this code, it works perfectly..
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
cout<<"Hello World!";
return 0;
}
When creating a new project - Maven - Java application in Netbeans the IDE is not recognizing the Main class on 1st class entry. (in Step 8 below we see no classes).
When first a generic class is created and then the Main class is created Netbeans is registering the Main class and the app could be run and debugged.
Steps that worked for me:
Hope this works for others as well.
I assume you want the PDF to display in the browser, rather than forcing a download. If that is the case, try setting the Content-Disposition
header with a value of inline
.
Also remember that this will also be affected by browser settings - some browsers may be configured to always download PDF files or open them in a different application (e.g. Adobe Reader)
you can return 2 or more values to a function in VBA or any other visual basic stuff but you need to use the pointer method called Byref. See my example below. I will make a function to add and subtract 2 values say 5,6
sub Macro1
' now you call the function this way
dim o1 as integer, o2 as integer
AddSubtract 5, 6, o1, o2
msgbox o2
msgbox o1
end sub
function AddSubtract(a as integer, b as integer, ByRef sum as integer, ByRef dif as integer)
sum = a + b
dif = b - 1
end function
You can use .change
for what you want
$("input[@name='lom']").change(function(){
// Do something interesting here
});
as of jQuery 1.3
you no longer need the '@'. Correct way to select is:
$("input[name='lom']")
try this
function global_func(...args){
for(let i of args){
console.log(i)
}
}
global_func('task_name', 'action', [{x: 'x'},{x: 'x'}], {x: 'x'}, ['x1','x2'], 1, null, undefined, false, true)
//task_name
//action
//(2) [{...},
// {...}]
// {
// x:"x"
// }
//(2) [
// "x1",
// "x2"
// ]
//1
//null
//undefined
//false
//true
//func
I want to make sure this is out there, because it's so hard to get right:
using System.Runtime.InteropServices; //GuidAttribute
using System.Reflection; //Assembly
using System.Threading; //Mutex
using System.Security.AccessControl; //MutexAccessRule
using System.Security.Principal; //SecurityIdentifier
static void Main(string[] args)
{
// get application GUID as defined in AssemblyInfo.cs
string appGuid =
((GuidAttribute)Assembly.GetExecutingAssembly().
GetCustomAttributes(typeof(GuidAttribute), false).
GetValue(0)).Value.ToString();
// unique id for global mutex - Global prefix means it is global to the machine
string mutexId = string.Format( "Global\\{{{0}}}", appGuid );
// Need a place to store a return value in Mutex() constructor call
bool createdNew;
// edited by Jeremy Wiebe to add example of setting up security for multi-user usage
// edited by 'Marc' to work also on localized systems (don't use just "Everyone")
var allowEveryoneRule =
new MutexAccessRule( new SecurityIdentifier( WellKnownSidType.WorldSid
, null)
, MutexRights.FullControl
, AccessControlType.Allow
);
var securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
// edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen
using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings))
{
// edited by acidzombie24
var hasHandle = false;
try
{
try
{
// note, you may want to time out here instead of waiting forever
// edited by acidzombie24
// mutex.WaitOne(Timeout.Infinite, false);
hasHandle = mutex.WaitOne(5000, false);
if (hasHandle == false)
throw new TimeoutException("Timeout waiting for exclusive access");
}
catch (AbandonedMutexException)
{
// Log the fact that the mutex was abandoned in another process,
// it will still get acquired
hasHandle = true;
}
// Perform your work here.
}
finally
{
// edited by acidzombie24, added if statement
if(hasHandle)
mutex.ReleaseMutex();
}
}
}
I read the following and think it makes sense too:
Taking Care of Business
Remember, one of the most important OO rules is that an object is responsible for itself. This means that issues regarding the life cycle of a class should be handled in the class, not delegated to language constructs like static, and so on.
from the book Objected-Oriented Thought Process 4th Ed.
NSUnderlineStyleAttributeName which takes an NSNumber (where 0 is no underline) can be added to an attribute dictionary. I don't know if this is any easier. But, it was easier for my purposes.
NSDictionary *attributes;
attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName: style, NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:1]};
[text drawInRect:CGRectMake(self.contentRect.origin.x, currentY, maximumSize.width, textRect.size.height) withAttributes:attributes];
=IIF(Fields!Column.Value = "Approved", "Green", "No Color")
if you use isset like the answer posted already by singles, just make sure there is a bracket at the end like so:
$query_age = (isset($_GET['query_age']) ? $_GET['query_age'] : null);
For TensorFlow version < 0.11.0RC1:
The checkpoints that are saved contain values for the Variable
s in your model, not the model/graph itself, which means that the graph should be the same when you restore the checkpoint.
Here's an example for a linear regression where there's a training loop that saves variable checkpoints and an evaluation section that will restore variables saved in a prior run and compute predictions. Of course, you can also restore variables and continue training if you'd like.
x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
w = tf.Variable(tf.zeros([1, 1], dtype=tf.float32))
b = tf.Variable(tf.ones([1, 1], dtype=tf.float32))
y_hat = tf.add(b, tf.matmul(x, w))
...more setup for optimization and what not...
saver = tf.train.Saver() # defaults to saving all variables - in this case w and b
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
if FLAGS.train:
for i in xrange(FLAGS.training_steps):
...training loop...
if (i + 1) % FLAGS.checkpoint_steps == 0:
saver.save(sess, FLAGS.checkpoint_dir + 'model.ckpt',
global_step=i+1)
else:
# Here's where you're restoring the variables w and b.
# Note that the graph is exactly as it was when the variables were
# saved in a prior training run.
ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
else:
...no checkpoint found...
# Now you can run the model to get predictions
batch_x = ...load some data...
predictions = sess.run(y_hat, feed_dict={x: batch_x})
Here are the docs for Variable
s, which cover saving and restoring. And here are the docs for the Saver
.
Here is a simple function which does exactly this :
#include <windows.h>
#include <string>
bool dirExists(const std::string& dirName_in)
{
DWORD ftyp = GetFileAttributesA(dirName_in.c_str());
if (ftyp == INVALID_FILE_ATTRIBUTES)
return false; //something is wrong with your path!
if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
return true; // this is a directory!
return false; // this is not a directory!
}
If you have not too much data, you can definitely do pagination by just storing all the data in the browser and filtering what's visible at a certain time.
Here's a simple pagination example: http://jsfiddle.net/2ZzZB/56/
That example was on the list of fiddles on the angular.js github wiki, which should be helpful: https://github.com/angular/angular.js/wiki/JsFiddle-Examples
EDIT: http://jsfiddle.net/2ZzZB/16/ to http://jsfiddle.net/2ZzZB/56/ (won't show "1/4.5" if there is 45 results)
From the Java tutorial, you need to create a new font and register it in the graphics environment:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));
After this step is done, the font is available in calls to getAvailableFontFamilyNames()
and can be used in font constructors.
How much a stack can grow?
You can use a VM option named ss
to adjust the maximum stack size. A VM option is usually passed using -X{option}. So you can use java -Xss1M
to set the maximum of stack size to 1M.
Each thread has at least one stack. Some Java Virtual Machines(JVM) put Java stack(Java method calls) and native stack(Native method calls in VM) into one stack, and perform stack unwinding using a Managed to Native Frame, known as M2NFrame. Some JVMs keep two stacks separately. The Xss
set the size of the Java Stack in most cases.
For many JVMs, they put different default values for stack size on different platforms.
Can we limit this growth?
When a method call occurs, a new stack frame will be created on the stack of that thread. The stack will contain local variables, parameters, return address, etc. In java, you can never put an object on stack, only object reference can be stored on stack. Since array is also an object in java, arrays are also not stored on stack. So, if you reduce the amount of your local primitive variables, parameters by grouping them into objects, you can reduce the space on stack. Actually, the fact that we cannot explicitly put objects on java stack affects the performance some time(cache miss).
Does stack has some default minimum value or default maximum value?
As I said before, different VMs are different, and may change over versions. See here.
how does garbage collection work on stack?
Garbage collections in Java is a hot topic. Garbage collection aims to collect unreachable objects in the heap. So that needs a definition of 'reachable.' Everything on the stack constitutes part of the root set references in GC. Everything that is reachable from every stack of every thread should be considered as live. There are some other root set references, like Thread objects and some class objects.
This is only a very vague use of stack on GC. Currently most JVMs are using a generational GC. This article gives brief introduction about Java GC. And recently I read a very good article talking about the GC on .net. The GC on oracle jvm is quite similar so I think that might also help you.
This regex can help you to check your email-address according to all the criteria which gmail.com used.
var re = /^\w+([-+.'][^\s]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
var emailFormat = re.test($("#email").val()); // This return result in Boolean type
if (emailFormat) {}
Here is a useful article by Michael J. Swart on the matter, which covers different patterns and antipatterns for implementing UPSERT
in SQL Server:
https://michaeljswart.com/2017/07/sql-server-upsert-patterns-and-antipatterns/
It addresses associated concurrency issues (primary key violations, deadlocks) - all of the answers provided here yet are considered antipatterns in the article (except for the @Bridge solution using triggers, which is not covered there).
Here is an extract from the article with the solution preferred by the author:
Inside a serializable transaction with lock hints:
CREATE PROCEDURE s_AccountDetails_Upsert ( @Email nvarchar(4000), @Etc nvarchar(max) )
AS
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRAN
IF EXISTS ( SELECT * FROM dbo.AccountDetails WITH (UPDLOCK) WHERE Email = @Email )
UPDATE dbo.AccountDetails
SET Etc = @Etc
WHERE Email = @Email;
ELSE
INSERT dbo.AccountDetails ( Email, Etc )
VALUES ( @Email, @Etc );
COMMIT
There is also related question with answers here on stackoverflow: Insert Update stored proc on SQL Server
Seems like var ctx = $('#myChart');
is returning a list of elements. You would need to reference the first by using ctx[0]
.
Also height is a property, not a function.
I did it this way in my code:
var ctx = document.getElementById("myChart");
ctx.height = 500;
Asynchronous version :
<script type="text/javascript">
function initialize() {
var locations = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' +
'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
</script>
the warning or error of kind IMPLICIT DECLARATION is that the compiler is expecting a Function Declaration/Prototype..
It might either be a header file or your own function Declaration..
Just by looking at the image from the help pages, it makes a lot of sense.
So you have the blue boxes compileClasspath
and runtimeClassPath
.
The compileClasspath
is what is required to make a successful build when running gradle build
. The libraries that will be present on the classpath when compiling will be all libraries that are configured in your gradle build using either compileOnly
or implementation
.
Then we have the runtimeClasspath
and those are all packages that you added using either implementation
or runtimeOnly
. All those libraries will be added to the final build file (jar) that you deploy on the server.
As you also see in the image, if you want a library to be both used for compilation but you also want it added to the build file, then implementation
should be used.
An example of runtimeOnly
can be a database driver.
An example of compileOnly
can be servlet-api.
An example of implementation
can be spring-core.
You can always use Sharepoint Solution Generator to create a project and edit in VS2008.
You can find the Generator along with Sharepoint Developer tools.
When i need to copy data from filtered table i use range.SpecialCells(xlCellTypeVisible).copy. Where the range is range of all data (without a filter).
Example:
Sub copy()
'source worksheet
dim ws as Worksheet
set ws = Application.Worksheets("Data")' set you source worksheet here
dim data_end_row_number as Integer
data_end_row_number = ws.Range("B3").End(XlDown).Row.Number
'enable filter
ws.Range("B2:F2").AutoFilter Field:=2, Criteria1:="hockey", VisibleDropDown:=True
ws.Range("B3:F" & data_end_row_number).SpecialCells(xlCellTypeVisible).Copy
Application.Worksheets("Hoky").Range("B3").Paste
'You have to add headers to Hoky worksheet
end sub
This is why you should always import the base datetime
module: import datetime
, rather than the datetime
class within that module: from datetime import datetime
.
The other mistake you have made is to actually call the function in the default, with the ()
. This means that all models will get the date at the time the class is first defined - so if your server stays up for days or weeks without restarting Apache, all elements will get same the initial date.
So the field should be:
import datetime
date = models.DateField(_("Date"), default=datetime.date.today)
Just iterate over DataFrame.columns
, now this is an example in which you will end up with a list of column names that match:
import pandas as pd
data = {'spike-2': [1,2,3], 'hey spke': [4,5,6], 'spiked-in': [7,8,9], 'no': [10,11,12]}
df = pd.DataFrame(data)
spike_cols = [col for col in df.columns if 'spike' in col]
print(list(df.columns))
print(spike_cols)
Output:
['hey spke', 'no', 'spike-2', 'spiked-in']
['spike-2', 'spiked-in']
Explanation:
df.columns
returns a list of column names[col for col in df.columns if 'spike' in col]
iterates over the list df.columns
with the variable col
and adds it to the resulting list if col
contains 'spike'
. This syntax is list comprehension. If you only want the resulting data set with the columns that match you can do this:
df2 = df.filter(regex='spike')
print(df2)
Output:
spike-2 spiked-in
0 1 7
1 2 8
2 3 9
As it is already explained in other answers, const
in C merely means that a variable is read-only. It is still a run-time value. However, you can use an enum
as a real constant in C:
enum { NUM_TYPES = 4 };
static int types[NUM_TYPES] = {
1, 2, 3, 4
};
Try following int git bash
1.git add -u :/
2.git commit -m "your commit message"
git push -u origin master
Note:if you have not initialized your repo.
First of all
git init
and follow above mentioned steps in order. This worked for me
A "Broken Pipe" error occurs when you try to write to a pipe that has been closed on the other end. Since the code you've shown doesn't involve any pipes directly, I suspect you're doing something outside of Python to redirect the standard output of the Python interpreter to somewhere else. This could happen if you're running a script like this:
python foo.py | someothercommand
The issue you have is that someothercommand
is exiting without reading everything available on its standard input. This causes your write (via print
) to fail at some point.
I was able to reproduce the error with the following command on a Linux system:
python -c 'for i in range(1000): print i' | less
If I close the less
pager without scrolling through all of its input (1000 lines), Python exits with the same IOError
you have reported.
The Best Way I Can Use My Project.Use hasOwnProperty
in Tricky Way!.
var arr = []; (or) arr = new Array();
var obj = {}; (or) arr = new Object();
arr.constructor.prototype.hasOwnProperty('push') //true (This is an Array)
obj.constructor.prototype.hasOwnProperty('push') // false (This is an Object)
$a="some text =keep this,but not this"
$a.split('=')[1].split(',')[0]
returns
keep this
I'm not sure about the syntax of your specific commands (e.g., vagrant, etc), but in general...
Just register Ansible's (not-normally-shown) JSON output to a variable, then display each variable's stdout_lines
attribute:
- name: Generate SSH keys for vagrant user
user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048
register: vagrant
- debug: var=vagrant.stdout_lines
- name: Show SSH public key
command: /bin/cat $home_directory/.ssh/id_rsa.pub
register: cat
- debug: var=cat.stdout_lines
- name: Wait for user to copy SSH public key
pause: prompt="Please add the SSH public key above to your GitHub account"
register: pause
- debug: var=pause.stdout_lines
Here is a simple reliable way...
Put the following code in your Activity, and the tick() method will be called every second in the UI thread while your activity is in the "resumed" state. Of course, you can change the tick() method to do what you want, or to be called more or less frequently.
@Override
public void onPause() {
_handler = null;
super.onPause();
}
private Handler _handler;
@Override
public void onResume() {
super.onResume();
_handler = new Handler();
Runnable r = new Runnable() {
public void run() {
if (_handler == _h0) {
tick();
_handler.postDelayed(this, 1000);
}
}
private final Handler _h0 = _handler;
};
r.run();
}
private void tick() {
System.out.println("Tick " + System.currentTimeMillis());
}
For those interested, the "_h0=_handler" code is necessary to avoid two timers running simultaneously if your activity is paused and resumed within the tick period.
And if you want Generate a Black Shadow in the background, you can use the following:
background:linear-gradient( rgba(0, 0, 0, 0.5) 100%, rgba(0, 0, 0, 0.5)100%),url("logo/header-background.png");
The -m
switch of PuTTY takes a path to a script file as an argument, not a command.
Reference: https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-m
So you have to save your command (command_run
) to a plain text file (e.g. c:\path\command.txt
) and pass that to PuTTY:
putty.exe -ssh user@host -pw password -m c:\path\command.txt
Though note that you should use Plink (a command-line connection tool from PuTTY suite). It's a console application, so you can redirect its output to a file (what you cannot do with PuTTY).
A command-line syntax is identical, an output redirection added:
plink.exe -ssh user@host -pw password -m c:\path\command.txt > output.txt
See Using the command-line connection tool Plink.
And with Plink, you can actually provide the command directly on its command-line:
plink.exe -ssh user@host -pw password command > output.txt
Similar questions:
Automating running command on Linux from Windows using PuTTY
Executing command in Plink from a batch file
Comparing the O(n) time solution with the "constant time" O(1) solution provided in other answers goes to show that if the O(n) algorithm is fast enough, n may have to get very large before it is slower than a slow O(1).
The strings version is approx. 60% faster than the "maths" version for numbers of 20 or fewer digits. They become closer only when then number of digits approaches 200 digits
# the "maths" version
import math
def first_n_digits1(num, n):
return num // 10 ** (int(math.log(num, 10)) - n + 1)
%timeit first_n_digits1(34523452452, 2)
1.21 µs ± 75 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit first_n_digits1(34523452452, 8)
1.24 µs ± 47.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# 22 digits
%timeit first_n_digits1(3423234239472523452452, 2)
1.33 µs ± 59.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit first_n_digits1(3423234239472523452452, 15)
1.23 µs ± 61.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# 196 digits
%timeit first_n_digits1(3423234239472523409283475908723908723409872390871243908172340987123409871234012089172340987734507612340981344509873123401234670350981234098123140987314509812734091823509871345109871234098172340987125988123452452, 39)
1.86 µs ± 21.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# The "string" verions
def first_n_digits2(num, n):
return int(str(num)[:n])
%timeit first_n_digits2(34523452452, 2)
744 ns ± 28.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit first_n_digits2(34523452452, 8)
768 ns ± 42.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# 22 digits
%timeit first_n_digits2(3423234239472523452452, 2)
767 ns ± 33.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit first_n_digits2(3423234239472523452452, 15)
830 ns ± 55.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# 196 digits
%timeit first_n_digits2(3423234239472523409283475908723908723409872390871243908098712340987123401208917234098773450761234098134450987312340123467035098123409812314098734091823509871345109871234098172340987125988123452452, 39)
1.87 µs ± 140 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
You could use a C function getaddrinfo() to get the numerical address - both ipv4 and ipv6. See the example code here
Just wanted to show that there is no performance difference between the 2 main ways of doing it:
df = pd.DataFrame(np.random.randint(0,10,size=(100, 4)), columns=list('ABCD'))
def loc():
df1.loc[df1["A"] == 2] = 5
%timeit loc
19.9 ns ± 0.0873 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
def replace():
df2['A'].replace(
to_replace=2,
value=5,
inplace=True
)
%timeit replace
19.6 ns ± 0.509 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
What is in the link doesn't answer your question directly, but it's trivial to extend it to look like:
static void Main()
{
Action body = () => { ...your code... };
body.Catch<InvalidOperationException>()
.Catch<BadCodeException>()
.Catch<AnotherException>(ex => { ...handler... })();
}
(Basically provide another empty Catch
overload which returns itself)
The bigger question to this is why. I do not think the cost outweighs the gain here :)
Here's an alternate solution that actually adds your certificate to the built in list of default certificates: Trusting all certificates using HttpClient over HTTPS
However, it will only work for your application. There's no way to programmatically do it for all applications on a user's device, since that would be a security risk.
In case you are already using jQuery:
var $body = $('body');
$body.on('mousedown', function (evt) {
$body.on('mouseup mousemove', function handler(evt) {
if (evt.type === 'mouseup') {
// click
} else {
// drag
}
$body.off('mouseup mousemove', handler);
});
});
Use astype
In [31]: df
Out[31]:
a time
0 1 2013-01-01
1 2 2013-01-02
2 3 2013-01-03
In [32]: df['time'] = df['time'].astype('datetime64[ns]')
In [33]: df
Out[33]:
a time
0 1 2013-01-01 00:00:00
1 2 2013-01-02 00:00:00
2 3 2013-01-03 00:00:00
Two Scoops of Django: Best Practices for Django 1.5 suggests using version control for your settings files and storing the files in a separate directory:
project/
app1/
app2/
project/
__init__.py
settings/
__init__.py
base.py
local.py
production.py
manage.py
The base.py
file contains common settings (such as MEDIA_ROOT or ADMIN), while local.py
and production.py
have site-specific settings:
In the base file settings/base.py
:
INSTALLED_APPS = (
# common apps...
)
In the local development settings file settings/local.py
:
from project.settings.base import *
DEBUG = True
INSTALLED_APPS += (
'debug_toolbar', # and other apps for local development
)
In the file production settings file settings/production.py
:
from project.settings.base import *
DEBUG = False
INSTALLED_APPS += (
# other apps for production site
)
Then when you run django, you add the --settings
option:
# Running django for local development
$ ./manage.py runserver 0:8000 --settings=project.settings.local
# Running django shell on the production site
$ ./manage.py shell --settings=project.settings.production
The authors of the book have also put up a sample project layout template on Github.
The code from Alex works great. Just note that when you use request.getParameter you must use a request dispatcher
//Pass results back to the client
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("TestPages/ServiceServlet.jsp");
dispatcher.forward(request, response);
A couple ways this can be done:
This will make it a square
ul
{
list-style-type: square;
}
This will make it green
li
{
color: #0F0;
}
This will prevent the text from being green
li p
{
color: #000;
}
However that will require that all text within lists be in paragraphs so that the color is not overridden.
A better way is to make an image of a green square and use:
ul
{
list-style: url(green-square.png);
}
maybe you want to take a look java.util.Stack
class.
it has push, pop methods. and implemented List interface.
for shift/unshift, you can reference @Jon's answer.
however, something of ArrayList you may want to care about , arrayList is not synchronized. but Stack is. (sub-class of Vector). If you have thread-safe requirement, Stack may be better than ArrayList.
Wouldn't setting a css rule for all tables, and then a subsequent one for tables where class="dojoxGrid" work? Or am I missing something?
If we need only one column to be numeric
yyz$b <- as.numeric(as.character(yyz$b))
But, if all the columns needs to changed to numeric
, use lapply
to loop over the columns and convert to numeric
by first converting it to character
class as the columns were factor
.
yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))
Both the columns in the OP's post are factor
because of the string "n/a"
. This could be easily avoided while reading the file using na.strings = "n/a"
in the read.table/read.csv
or if we are using data.frame
, we can have character
columns with stringsAsFactors=FALSE
(the default is stringsAsFactors=TRUE
)
Regarding the usage of apply
, it converts the dataset to matrix
and matrix
can hold only a single class. To check the class
, we need
lapply(yyz, class)
Or
sapply(yyz, class)
Or check
str(yyz)
When you create more than one instance of MyClass , you will still only have only one instance of publicMethod in memory but in case of privilegedMethod you will end up creating lots of instances and staticMethod has no relationship with an object instance.
That's why prototypes save memory.
Also, if you change the parent object's properties, is the child's corresponding property hasn't been changed, it'll be updated.
Better to use sys also-
print dir(sys._getframe())
print dir(sys._getframe().f_lineno)
print sys._getframe().f_lineno
The output is:
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'f_back', 'f_builtins', 'f_code', 'f_exc_traceback', 'f_exc_type', 'f_exc_value', 'f_globals', 'f_lasti', 'f_lineno', 'f_locals', 'f_restricted', 'f_trace']
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
14
You can join to the same table on the fields that would be duplicated and then anti-join on the id field. Select the id field from the first table alias (tn1) and then use the array_agg function on the id field of the second table alias. Finally, for the array_agg function to work properly, you will group the results by the tn1.id field. This will produce a result set that contains the the id of a record and an array of all the id's that fit the join conditions.
select tn1.id,
array_agg(tn2.id) as duplicate_entries,
from table_name tn1 join table_name tn2 on
tn1.year = tn2.year
and tn1.sid = tn2.sid
and tn1.user_id = tn2.user_id
and tn1.cid = tn2.cid
and tn1.id <> tn2.id
group by tn1.id;
Obviously, id's that will be in the duplicate_entries array for one id, will also have their own entries in the result set. You will have to use this result set to decide which id you want to become the source of 'truth.' The one record that shouldn't get deleted. Maybe you could do something like this:
with dupe_set as (
select tn1.id,
array_agg(tn2.id) as duplicate_entries,
from table_name tn1 join table_name tn2 on
tn1.year = tn2.year
and tn1.sid = tn2.sid
and tn1.user_id = tn2.user_id
and tn1.cid = tn2.cid
and tn1.id <> tn2.id
group by tn1.id
order by tn1.id asc)
select ds.id from dupe_set ds where not exists
(select de from unnest(ds.duplicate_entries) as de where de < ds.id)
Selects the lowest number ID's that have duplicates (assuming the ID is increasing int PK). These would be the ID's that you would keep around.
I think its better to to do text-align center for div and let image take care of the height. Just specify a top and bottom padding for div to have space between image and div. Look at this example: http://jsfiddle.net/Tv9mG/
I tried and found time difference using the following scripts.
import time
start_time = time.perf_counter()
[main code here]
print (time.perf_counter() - start_time, "seconds")
Parent container has to have this:
position: relative;
Button itself has to have this:
position: relative;
bottom: 20px;
right: 20px;
or whatever you like
Object AccountObject = _dbContext.Accounts
.Join(_dbContext.Users, acc => acc.AccountId, usr => usr.AccountId, (acc, usr) => new { acc, usr })
.Where(x => x.usr.EmailAddress == key1)
.Where(x => x.usr.Hash == key2)
.Select(x => new { AccountId = x.acc.AccountId, Name = x.acc.Name })
.SingleOrDefault();
Fast and easy way to drop the duplicated columns by their values:
df = df.T.drop_duplicates().T
More info: Pandas DataFrame drop_duplicates manual .
there is no CSS selector for selecting a parent of a selected child.
you could do it with JavaScript
I think your EmpID
column is string and you forget to use ' '
in your value.
Because when you write EmpID=" + id.Text
, your command looks like EmpID = 12345
instead of EmpID = '12345'
Change your SqlCommand
to
SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID='" + id.Text +"'", con);
Or as a better way you can (and should) always use parameterized queries
. This kind of string concatenations are open for SQL Injection
attacks.
SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con);
cmd.Parameters.AddWithValue("@id", id.Text);
I think your EmpID
column keeps your employee id's, so it's type should some numerical type instead of character.
-> it works like pointer u don't have to use *
for( list<student>::iterator iter= data.begin(); iter != data.end(); iter++ )
cout<<iter->name; //'iter' not 'it'
On iOS 9.0.2, I'm getting the "register push notification alert" every time I delete the app and reinstall it. This is true for both AppStore production downloads and adhoc mode.
UPDATE: It is confirmed this is working for iOS 9.x
all zeros would probably be the most obvious that it wasn't a real SSN.
I read comments on answer set as Okay. Most of the user are asking that the button and some links click should be allowed. Here one more line is added to the existing code that will work.
<script type="text/javascript">
var hook = true;
window.onbeforeunload = function() {
if (hook) {
return "Did you save your stuff?"
}
}
function unhook() {
hook=false;
}
Call unhook() onClick for button and links which you want to allow. E.g.
<a href="#" onClick="unhook()">This link will allow navigation</a>
You could also try to add a key mapping witch auto select all the code in file and indent it:
'atom-text-editor':
'ctrl-alt-l': 'auto-indent:apply'
The unwanted side effects of simple folder delete or installing over existing installation have been removed by a script written by Kyle Fuller - deintegrate and here is the proper workflow:
Install clean:
$ sudo gem install cocoapods-clean
Run deintegrate in the folder of the project:
$ pod deintegrate
Clean (this tool is no longer available):
$ pod clean
Modify your podfile (delete the lines with the pods you don't want to use anymore) and run:
$ pod install
Done.
I think what you are looking for is:
startDate.setDate(startDate.getDate() + 1);
Also, you can have a look at Moment.js
A javascript date library for parsing, validating, manipulating, and formatting dates.
You can use the ejb3-persistence.jar that's bundled with hibernate. This jar only includes the javax.persistence package.
In a word - speed. An index for up to a million rows fits in a 32-bit word, so it can be used efficiently on 32-bit processors. Function arguments that fit in a CPU register are extremely efficient, while ones that are larger require accessing memory on each function call, a far slower operation. Updating a spreadsheet can be an intensive operation involving many cell references, so speed is important. Besides, the Excel team expects that anyone dealing with more than a million rows will be using a database rather than a spreadsheet.
change p:suffix=".jsp" value acordingly otherwise we can develope custom view resolver
I found 2 quick options to fix this:
Happy coding!
Most likely your sushosin updated, which changed the default of suhosin.memory_limit from disabled to 0 (which won't allow any updates to memory_limit).
On Debian, change /etc/php5/conf.d/suhosin.ini
;suhosin.memory_limit = 0
to
suhosin.memory_limit = 2G
Or whichever value you are comfortable with. You can find the changelog of Sushosin at http://www.hardened-php.net/hphp/changelog.html, which says:
Changed the way the memory_limit protection is implemented
1.Get supplier numbers and names for suppliers of parts supplied to at least two different projects.
SELECT S.SID, S.NAME
FROM SUPPLIES SP
JOIN SUPPLIER S
ON SP.SID = S.SID
WHERE PID IN
(SELECT PID FROM SUPPPLIES GROUP BY PID, JID HAVING COUNT(*) >= 2)
I am not slear about your second question
If You are looking list of methods which respond by an instance (in your case @current_user). According to ruby documentation methods
Returns a list of the names of public and protected methods of obj. This will include all the methods accessible in obj's ancestors. If the optional parameter is false, it returns an array of obj's public and protected singleton methods, the array will not include methods in modules included in obj.
@current_user.methods
@current_user.methods(false) #only public and protected singleton methods and also array will not include methods in modules included in @current_user class or parent of it.
Alternatively, You can also check that a method is callable on an object or not?.
@current_user.respond_to?:your_method_name
If you don't want parent class methods then just subtract the parent class methods from it.
@current_user.methods - @current_user.class.superclass.new.methods #methods that are available to @current_user instance.
results.show(20, false)
will not truncate. Check the source
20
is the default number of rows displayed when show()
is called without any arguments.
Accept attribute was introduced in the RFC 1867, intending to enable file-type filtering based on MIME type for the file-select control. But as of 2008, most, if not all, browsers make no use of this attribute. Using client-side scripting, you can make a sort of extension based validation, for submit data of correct type (extension).
Other solutions for advanced file uploading require Flash movies like SWFUpload or Java Applets like JUpload.
Single line comment
Ctrl + 1
Multi-line comment select the lines to be commented
Ctrl + 4
Unblock Multi-line comment
Ctrl + 5
If you can use repeated letters, you can use the *
operator:
>>> 'a'*5
'aaaaa'
Update: I noticed that my answer was just a poor duplicate of a well explained question on https://unix.stackexchange.com/... by BryKKan
Here is an extract from it:
openssl pkcs12 -in <filename.pfx> -nocerts -nodes | sed -ne '/-BEGIN PRIVATE KEY-/,/-END PRIVATE KEY-/p' > <clientcert.key>
openssl pkcs12 -in <filename.pfx> -clcerts -nokeys | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > <clientcert.cer>
openssl pkcs12 -in <filename.pfx> -cacerts -nokeys -chain | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > <cacerts.cer>
Concurrency: If two or more problems are solved by a single processor.
Parallelism: If one problem is solved by multiple processors.
Try using the BackgroundWorker class. You give it delegates for what to run, and to be notified when work has finished. There is an example on the MSDN page that I linked to.
This worked for me:
mv xyz.war ./tmp
cd tmp
jar -xvf xyz.war
rm -rf WEB-INF/lib/zookeeper-3.4.10.jar
rm -rf xyz.war
jar -cvf xyz.war *
mv xyz.war ../
cd ..
For me, the problem was caused by the hosting company (Godaddy) treating POST operations which had substantial response data (anything more than tens of kilobytes) as some sort of security threat. If more than 6 of these occurred in one minute, the host refused to execute the PHP code that responded to the POST request during the next minute. I'm not entirely sure what the host did instead, but I did see, with tcpdump, a TCP reset packet coming as the response to a POST request from the browser. This caused the http status code returned in a jqXHR object to be 0.
Changing the operations from POST to GET fixed the problem. It's not clear why Godaddy impose this limit, but changing the code was easier than changing the host.
When you create an App, a file called styles.xml will be created in your res/values folder. If you change the styles, you can change the background, text color, etc for all your layouts. That way you don’t have to go into each individual layout and change the it manually.
styles.xml:
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="Theme.AppBaseTheme" parent="@android:style/Theme.Light">
<item name="android:editTextColor">#295055</item>
<item name="android:textColorPrimary">#295055</item>
<item name="android:textColorSecondary">#295055</item>
<item name="android:textColorTertiary">#295055</item>
<item name="android:textColorPrimaryInverse">#295055</item>
<item name="android:textColorSecondaryInverse">#295055</item>
<item name="android:textColorTertiaryInverse">#295055</item>
<item name="android:windowBackground">@drawable/custom_background</item>
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
parent="@android:style/Theme.Light"
is Google’s native colors. Here is a reference of what the native styles are:
https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/res/res/values/themes.xml
The default Android style is also called “Theme”. So you calling it Theme probably confused the program.
name="Theme.AppBaseTheme"
means that you are creating a style that inherits all the styles from parent="@android:style/Theme.Light"
.
This part you can ignore unless you want to inherit from AppBaseTheme again. = <style name="AppTheme" parent="AppBaseTheme">
@drawable/custom_background is a custom image I put in the drawable’s folder. It is a 300x300 png image.
#295055 is a dark blue color.
My code changes the background and text color. For Button text, please look through Google’s native stlyes (the link I gave u above).
Then in Android Manifest, remember to include the code:
<application
android:theme="@style/Theme.AppBaseTheme">
Always keep in mind that 'size' is variable if not explicitly specified so if you declare
int i = 10;
On some systems it may result in 16-bit integer by compiler and on some others it may result in 32-bit integer (or 64-bit integer on newer systems).
In embedded environments this may end up in weird results (especially while handling memory mapped I/O or may be consider a simple array situation), so it is highly recommended to specify fixed size variables. In legacy systems you may come across
typedef short INT16;
typedef int INT32;
typedef long INT64;
Starting from C99, the designers added stdint.h header file that essentially leverages similar typedefs.
On a windows based system, you may see entries in stdin.h header file as
typedef signed char int8_t;
typedef signed short int16_t;
typedef signed int int32_t;
typedef unsigned char uint8_t;
There is quite more to that like minimum width integer or exact width integer types, I think it is not a bad thing to explore stdint.h for a better understanding.
You can stop any IIS Express application or you can stop all application. Right click on IIS express icon , which is located at right bottom corner of task bar. Then Select Show All Application
Use Sum()
List<string> foo = new List<string>();
foo.Add("1");
foo.Add("2");
foo.Add("3");
foo.Add("4");
Console.Write(foo.Sum(x => Convert.ToInt32(x)));
Prints:
10
If you want all the bars to get the same color (fill
), you can easily add it inside geom_bar
.
ggplot(data=df, aes(x=c1+c2/2, y=c3)) +
geom_bar(stat="identity", width=c2, fill = "#FF6666")
Add fill = the_name_of_your_var
inside aes
to change the colors depending of the variable :
c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2)
Use scale_fill_manual()
if you want to manually the change of colors.
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2) +
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))
py2exe will make the EXE file you want, but you need to have the same version of MSVCR90.dll on the machine you're going to use your new EXE file.
See Tutorial for more information.
static object Lock = new object();
lock (Lock)
{
// do stuff
}
I've got some subprojects.
I solved this problem via adding xib file to Copy Bundle Resources build phase of main project.
Another slight modification to @Salvador Dali enables a list of columns to exclude:
df[[i for i in list(df.columns) if i not in [list_of_columns_to_exclude]]]
or
df.loc[:,[i for i in list(df.columns) if i not in [list_of_columns_to_exclude]]]
Enabling delayed variable expansion solves you problem, the script produces "hi":
setlocal EnableDelayedExpansion
set var1=A
set var2=B
set AB=hi
set newvar=!%var1%%var2%!
echo %newvar%
If you need to get that in a program with Python on a Linux system for reproducibility:
with open('/proc/driver/nvidia/version') as f:
version = f.read().strip()
print(version)
gives:
NVRM version: NVIDIA UNIX x86_64 Kernel Module 384.90 Tue Sep 19 19:17:35 PDT 2017
GCC version: gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.5)
You can use Lookback. It records your screen, face, voice and all gestures, and uploads them to your account on the web.
Here's a demo: https://lookback.io/watch/JK354d5jcEpA7CNkE
// The Current Unix Timestamp_x000D_
// 1443535752 seconds since Jan 01 1970. (UTC)_x000D_
_x000D_
// Current time in seconds_x000D_
console.log(Math.floor(new Date().valueOf() / 1000)); // 1443535752_x000D_
console.log(Math.floor(Date.now() / 1000)); // 1443535752_x000D_
console.log(Math.floor(new Date().getTime() / 1000)); // 1443535752
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
jQuery
console.log(Math.floor($.now() / 1000)); // 1443535752
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Building on @general03's answer, you can use Android's built-in style to customize the dialog quickly. You can find the dialog themes under android.R.style.Theme_DeviceDefault_Dialogxxx
.
For example:
builder = new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_Dialog_MinWidth);
builder = new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_Dialog_NoActionBar);
builder = new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_DialogWhenLarge);
They're not actually characters, they're hexadecimal digits.
It depends whether you ListBox object of the System.Windows.Forms.ListBox
class, which does have the ListBox.IndexFromPoint()
method. But if the ListBox object is from the System.Windows.Control.Listbox
class, the answer from @dark-knight (marked as correct answer) does not work.
Im running Win 10 (1903) and current versions of the .NET framework (4.8). This issue should not be version dependant though, only whether your Application is using WPF or Windows Form for the UI. See also: WPF vs Windows Form
Following is worked for me
File dir = new File("E:\\test");
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "Start","test.bat");
pb.directory(dir);
Process p = pb.start();
Python indexing starts at 0 (rather than 1), so your assignment "r[1,:] = r0" defines the second (i.e. index 1) element of r and leaves the first (index 0) element as a pair of zeros. The first value of i in your for loop is 0, so rr gets the square root of the dot product of the first entry in r with itself (which is 0), and the division by rr in the subsequent line throws the error.
I just turn off my windows firewall and it worked for me. You can also try different versions of npm.
here is a portion of a procedure I use on my system to find text....
DECLARE @Search varchar(255)
SET @Search='[10.10.100.50]'
SELECT DISTINCT
o.name AS Object_Name,o.type_desc
FROM sys.sql_modules m
INNER JOIN sys.objects o ON m.object_id=o.object_id
WHERE m.definition Like '%'+@Search+'%'
ORDER BY 2,1
Given you've set up a git daemon on <url>
and an empty repository:
cd <localdir>
git init
git add .
git commit -m 'message'
git remote add origin <url>
git push -u origin master
By this way, you hold a form by his ID and throw all his content. This technic is fastiest.
document.forms["id_form"].reset();
go to .project file in your project and change the name of the project in name tag
Tested with Angular2 RC2
I tried a code-snippet similar to yours and it works for me ;) see [(ngModel)] = "str" in my template If you push the button, the console logs the current content of the textarea-field. Hope it helps
textarea-component.ts
import {Component} from '@angular/core';
@Component({
selector: 'textarea-comp',
template: `
<textarea cols="30" rows="4" [(ngModel)] = "str"></textarea>
<p><button (click)="pushMe()">pushMeToLog</button></p>
`
})
export class TextAreaComponent {
str: string;
pushMe() {
console.log( "TextAreaComponent::str: " + this.str);
}
}
Try to write \ZIPARCHIVE
instead of ZIPARCHIVE
.
make a class for that button lets say :
`<input type="button" value="+" class="b1" onclick="addRow()">`
your js should look like this :
$(document).ready(function(){
$('.b1').click(function(){
$('div').append('<input type="text"..etc ');
});
});
I'd suggest using such extension method:
public static class DataColumnCollectionExtensions
{
public static IEnumerable<DataColumn> AsEnumerable(this DataColumnCollection source)
{
return source.Cast<DataColumn>();
}
}
And therefore:
string[] columnNames = dataTable.Columns.AsEnumerable().Select(column => column.Name).ToArray();
You may also implement one more extension method for DataTable
class to reduce code:
public static class DataTableExtensions
{
public static IEnumerable<DataColumn> GetColumns(this DataTable source)
{
return source.Columns.AsEnumerable();
}
}
And use it as follows:
string[] columnNames = dataTable.GetColumns().Select(column => column.Name).ToArray();
Here's how I did it (Angular 7):
In the component, add an input:
@Input() componentClass: string = '';
Then in the component's HTML template add something like:
<div [ngClass]="componentClass">...</div>
And finally in the HTML template where you instance the component:
<root componentClass="someclass someotherclass">...</root>
Disclaimer: I'm fairly new to Angular, so I might be just getting lucky here!
Using SQL Server Management Studio
To configure the default language option
English
.Using Transact-SQL
To configure the default language option
This example shows how to use sp_configure to configure the default language option to French
USE AdventureWorks2012 ;
GO
EXEC sp_configure 'default language', 2 ;
GO
RECONFIGURE ;
GO
The 33 languages of SQL Server
| LANGID | ALIAS |
|--------|---------------------|
| 0 | English |
| 1 | German |
| 2 | French |
| 3 | Japanese |
| 4 | Danish |
| 5 | Spanish |
| 6 | Italian |
| 7 | Dutch |
| 8 | Norwegian |
| 9 | Portuguese |
| 10 | Finnish |
| 11 | Swedish |
| 12 | Czech |
| 13 | Hungarian |
| 14 | Polish |
| 15 | Romanian |
| 16 | Croatian |
| 17 | Slovak |
| 18 | Slovenian |
| 19 | Greek |
| 20 | Bulgarian |
| 21 | Russian |
| 22 | Turkish |
| 23 | British English |
| 24 | Estonian |
| 25 | Latvian |
| 26 | Lithuanian |
| 27 | Brazilian |
| 28 | Traditional Chinese |
| 29 | Korean |
| 30 | Simplified Chinese |
| 31 | Arabic |
| 32 | Thai |
| 33 | Bokmål |
A quick example:
List<List<string>> myList = new List<List<string>>();
myList.Add(new List<string> { "a", "b" });
myList.Add(new List<string> { "c", "d", "e" });
myList.Add(new List<string> { "qwerty", "asdf", "zxcv" });
myList.Add(new List<string> { "a", "b" });
// To iterate over it.
foreach (List<string> subList in myList)
{
foreach (string item in subList)
{
Console.WriteLine(item);
}
}
Is that what you were looking for? Or are you trying to create a new class
that extends List<T>
that has a member that is a `List'?
I was using INSERT SELECT Before, for those who want to use new stuff i will put this solution that works similar but much shorter:
UPDATE table1 //table that's going to be updated
LEFT JOIN //type of join
table2 AS tb2 //second table and rename for easy
ON
tb2.filedToMatchTables = table1.fieldToMatchTables//fileds to connect both tables
SET
fieldFromTable1 = tb2.fieldFromTable2; //field to be updated on table1
field1FromTable1 = tb2.field1FromTable2, //This is in the case you need to
field1FromTable1 = tb2.field1FromTable2, //update more than one field
field1FromTable1 = tb2.field1FromTable2; //remember to put ; at the end
Note: the solution in this and other answers involves disabling safety measures that are there to fix arbitrary code execution vulnerabilities. See for instance this ghostscript-related and this ubuntu-related announcement. Only go forward with these solutions if the input to
convert
comes from a trusted source.
I use ImageMagick in php (v.7.1) to slice PDF file to images.
First I got errors like:
Exception type: ImagickException
Exception message: not authorized ..... @ error/constitute.c/ReadImage/412
After some changes in /etc/ImageMagick-6/policy.xml
I start getting erroes like:
Exception type: ImagickException
Exception message: unable to create temporary file ..... Permission denied @ error/pdf.c/ReadPDFImage/465
My fix:
In file /etc/ImageMagick-6/policy.xml
(or /etc/ImageMagick/policy.xml
)
comment line
<!-- <policy domain="coder" rights="none" pattern="MVG" /> -->
change line
<policy domain="coder" rights="none" pattern="PDF" />
to
<policy domain="coder" rights="read|write" pattern="PDF" />
add line
<policy domain="coder" rights="read|write" pattern="LABEL" />
Then restart your web server (nginx, apache).
myJavaUtilDate // The terrible `java.util.Date` class is now legacy. Use *java.time* instead.
.toInstant() // Convert this moment in UTC from the legacy class `Date` to the modern class `Instant`.
.atZone( ZoneId.of( "Africa/Tunis" ) ) // Adjust from UTC to the wall-clock time used by the people of a particular region (a time zone).
.toLocalDate() // Extract the date-only portion.
.atStartOfDay( ZoneId.of( "Africa/Tunis" ) ) // Determine the first moment of that date in that zone. The day does *not* always start at 00:00:00.
You are using terrible old date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310.
Date
? Instant
A java.util.Date
represent a moment in UTC. Its replacement is Instant
. Call the new conversion methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
Specify the time zone in which you want your new time-of-day to make sense.
Specify a proper time zone name in the format of Continent/Region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 2-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime
Apply the ZoneId
to the Instant
to get a ZonedDateTime
. Same moment, same point on the timeline, but different wall-clock time.
ZonedDateTime zdt = instant.atZone( z ) ;
You asked to change the time-of-day. Apply a LocalTime
to change all the time-of-day parts: hour, minute, second, fractional second. A new ZonedDateTime
is instantiated, with values based on the original. The java.time classes use this immutable objects pattern to provide thread-safety.
LocalTime lt = LocalTime.of( 15 , 30 ) ; // 3:30 PM.
ZonedDateTime zdtAtThreeThirty = zdt.with( lt ) ;
But you asked specifically for 00:00. So apparently you want the first moment of the day. Beware: some days in some zones do not start at 00:00:00. They may start at another time such as 01:00:00 because of anomalies such as Daylight Saving Time (DST).
Let java.time determine the first moment. Extract the date-only portion. Then pass the time zone to get first moment.
LocalDate ld = zdt.toLocalDate() ;
ZonedDateTime zdtFirstMomentOfDay = ld.atStartOfDay( z ) ;
If you need to go back to UTC, extract an Instant
.
Instant instant = zdtFirstMomentOfDay.toInstant() ;
Instant
? Date
If you need a java.util.Date
to interoperate with old code not yet updated to java.time, convert.
java.util.Date d = java.util.Date.from( instant ) ;
I did this and it works great
<?php if ( has_post_thumbnail() ) { ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail(); ?></a>
<?php } ?>
My use case is munging data prior to loading into a DB table:
df[col] = df[col].fillna(-1)
df[col] = df[col].astype(int)
df[col] = df[col].astype(str)
df[col] = df[col].replace('-1', np.nan)
Remove NaNs, convert to int, convert to str and then reinsert NANs.
It's not pretty but it gets the job done!
The CSS below stops users from being able to select text.
-webkit-user-select: none; /* Safari */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+/Edge */
user-select: none; /* Standard */
To target IE9 downwards the html attribute unselectable
must be used instead:
<p unselectable="on">Test Text</p>
Try this,
IFS=''
while read line
do
echo $line
done < file.txt
EDIT:
From man bash
IFS - The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with the read builtin command. The default value is
``<space><tab><newline>''
See https://docs.djangoproject.com/en/stable/ref/templates/builtins/#if : just use, to reproduce their example:
{% if athlete_list %}
Number of athletes: {{ athlete_list|length }}
{% else %}
No athletes.
{% endif %}
Type in "netstat -ano" into your command line. I saw that it was showing something for Local Address port 0.0.0.0:80.
My issue was because I had SQL Server Reporting Services on Port 80. So I followed these instructions and changed the port # from 80 to 81:
Here is a picture of my command line AFTER I changed the port number for SQL Server Reporting Services:
If you are still having the same issue, read this forum:
In Python, any immutable object (such as an integer, boolean, string, tuple) is hashable, meaning its value does not change during its lifetime. This allows Python to create a unique hash value to identify it, which can be used by dictionaries to track unique keys and sets to track unique values.
This is why Python requires us to use immutable datatypes for the keys in a dictionary.
with $.getJSON()) there is no any error callback only you can track succeed callback and there no standard setting supported like beforeSend, statusCode, mimeType etc, if you want it use $.ajax().
Basically ng-click
first checks the isDisabled
and based on its value it will decide whether the function should be called or not.
<span ng-click="(isDisabled) || clicked()">Do something</span>
OR read it as
<span ng-click="(if this value is true function clicked won't be called. and if it's false the clicked will be called) || clicked()">Do something</span>
I needed to demo something quickly today and came up with this. Thought I would place it here if someone needed something similar to the OP's request.
#!/bin/bash
status_code=$(curl --write-out %{http_code} --silent --output /dev/null www.bbc.co.uk/news)
if [[ "$status_code" -ne 200 ]] ; then
echo "Site status changed to $status_code" | mail -s "SITE STATUS CHECKER" "[email protected]" -r "STATUS_CHECKER"
else
exit 0
fi
This will send an email alert on every state change from 200, so it's dumb and potentially greedy. To improve this, I would look at looping through several status codes and performing different actions dependant on the result.
In order to calculate the difference you have to put the +
operator,
that way typescript
converts the dates to numbers.
+new Date()- +new Date("2013-02-20T12:01:04.753Z")
From there you can make a formula to convert the difference to minutes
or hours
.
We can add the parent pom as a dependency with type pom and make exclusion on that. Because anyhow parent pom is downloaded. This worked for me
<dependency>
<groupId>com.abc.boot</groupId>
<artifactId>abc-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<type>pom</type>
<exclusions>
<exclusion>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</exclusion>
</exclusions>
</dependency>
For all example below you need to import fs and path modules:
const fs = require('fs');
const path = require('path');
function readFiles(dir, processFile) {
// read directory
fs.readdir(dir, (error, fileNames) => {
if (error) throw error;
fileNames.forEach(filename => {
// get current file name
const name = path.parse(filename).name;
// get current file extension
const ext = path.parse(filename).ext;
// get current file path
const filepath = path.resolve(dir, filename);
// get information about the file
fs.stat(filepath, function(error, stat) {
if (error) throw error;
// check if the current path is a file or a folder
const isFile = stat.isFile();
// exclude folders
if (isFile) {
// callback, do something with the file
processFile(filepath, name, ext, stat);
}
});
});
});
}
Usage:
// use an absolute path to the folder where files are located
readFiles('absolute/path/to/directory/', (filepath, name, ext, stat) => {
console.log('file path:', filepath);
console.log('file name:', name);
console.log('file extension:', ext);
console.log('file information:', stat);
});
/**
* @description Read files synchronously from a folder, with natural sorting
* @param {String} dir Absolute path to directory
* @returns {Object[]} List of object, each object represent a file
* structured like so: `{ filepath, name, ext, stat }`
*/
function readFilesSync(dir) {
const files = [];
fs.readdirSync(dir).forEach(filename => {
const name = path.parse(filename).name;
const ext = path.parse(filename).ext;
const filepath = path.resolve(dir, filename);
const stat = fs.statSync(filepath);
const isFile = stat.isFile();
if (isFile) files.push({ filepath, name, ext, stat });
});
files.sort((a, b) => {
// natural sort alphanumeric strings
// https://stackoverflow.com/a/38641281
return a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' });
});
return files;
}
Usage:
// return an array list of objects
// each object represent a file
const files = readFilesSync('absolute/path/to/directory/');
More info on promisify in this article.
const { promisify } = require('util');
const readdir_promise = promisify(fs.readdir);
const stat_promise = promisify(fs.stat);
function readFilesAsync(dir) {
return readdir_promise(dir, { encoding: 'utf8' })
.then(filenames => {
const files = getFiles(dir, filenames);
return Promise.all(files);
})
.catch(err => console.error(err));
}
function getFiles(dir, filenames) {
return filenames.map(filename => {
const name = path.parse(filename).name;
const ext = path.parse(filename).ext;
const filepath = path.resolve(dir, filename);
return stat({ name, ext, filepath });
});
}
function stat({ name, ext, filepath }) {
return stat_promise(filepath)
.then(stat => {
const isFile = stat.isFile();
if (isFile) return { name, ext, filepath, stat };
})
.catch(err => console.error(err));
}
Usage:
readFiles('absolute/path/to/directory/')
// return an array list of objects
// each object is a file
// with those properties: { name, ext, filepath, stat }
.then(files => console.log(files))
.catch(err => console.log(err));
Note: return undefined
for folders, if you want you can filter them out:
readFiles('absolute/path/to/directory/')
.then(files => files.filter(file => file !== undefined))
.catch(err => console.log(err));
Peace quote of 2020:
Console.WriteLine("I {0} JavaScript!", ">:D<");
console.log(`I ${'>:D<'} C#`)
A great slide show on how to achieve the desired effect from Googles Nick Butcher (start at slide 20).
He uses the standard android @attr
to style the button and divider.
You could also use the iframe method, although this is not cross browser compatible (eg. not working in chromium or android and probably others -> instead prompts to download). It works with dataURL's and normal URLS, not sure if the other examples work with dataURLS (please let me know if the other examples work with dataURLS?)
<iframe class="page-icon preview-pane" frameborder="0" height="352" width="396" src="data:application/pdf;base64, ..DATAURLHERE!... "></iframe>
I think better to try with mimetype than checking extension. Because, sometimes files can be exist without it and those are working very well in linux and unix systems.
So, you can try something like this:
["image/jpeg", "image/png", "image/gif"].indexOf(file.type) > -1
window.onload = function(){ document.getElementById("loading").style.display = "none" }
_x000D_
#loading {width: 100%;height: 100%;top: 0px;left: 0px;position: fixed;display: block; z-index: 99}_x000D_
_x000D_
#loading-image {position: absolute;top: 40%;left: 45%;z-index: 100}
_x000D_
<div id="loading">_x000D_
<img id="loading-image" src="img/loading.gif" alt="Loading..." />_x000D_
</div>
_x000D_
Page loading image with simplest fadeout effect created in JS:
Anyone who is using pipenv (and you should!) can simply use these two commands — without having the venv activated:
rm -rf `pipenv --venv` # remove the broken venv
pipenv install --dev # reinstall the venv from pipfile
You should avoid setting LD_LIBRARY_PATH
in your .bashrc
. See "Why LD_LIBRARY_PATH is bad
" for more information.
Use the linker option -rpath while linking so that the dynamic linker knows where to find libsync.so
during runtime.
gcc ... -Wl,-rpath /path/to/library -L/path/to/library -lsync -o sync_test
Another way would be to use a wrapper like this
#!/bin/bash
LD_LIBRARY_PATH=/path/to/library sync_test "$@"
If sync_test
starts any other programs, they might end up using the libs in /path/to/library
which may or may not be intended.
I solve this issues looking for the name that I passed on my request
I was sending on body:
{thumbbail: <myimg>}
and I was expect to:
upload.single('thumbnail')
so, I fix the name that a send on request
Download the file and from the same directory run docker build -t nodebb .
This will give you an image on your local machine that's named nodebb that you can launch an container from with docker run -d nodebb
(you can change nodebb to your own name).
This page should help - http://www.zedwood.com/article/103/bash-send-mail-with-an-attachment
It includes a script to send e-mail with a MIME attachment, ie with a HTML page and images included.
A "BEFORE-INSERT"-trigger is the only way to realize same-table updates on an insert, and is only possible from MySQL 5.5+. However, the value of an auto-increment field is only available to an "AFTER-INSERT" trigger - it defaults to 0 in the BEFORE-case. Therefore the following example code which would set a previously-calculated surrogate key value based on the auto-increment value id
will compile, but not actually work since NEW.id will always be 0:
create table products(id int not null auto_increment, surrogatekey varchar(10), description text);
create trigger trgProductSurrogatekey before insert on product
for each row set NEW.surrogatekey =
(select surrogatekey from surrogatekeys where id = NEW.id);
You want this method:
boolean isList = List.class.isAssignableFrom(myClass);
where in general, List
(above) should be replaced with superclass
and myClass
should be replaced with subclass
From the JavaDoc:
Determines if the class or interface represented by this
Class
object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specifiedClass
parameter. It returnstrue
if so; otherwise it returnsfalse
. If thisClass
object represents a primitive type, this method returnstrue
if the specifiedClass
parameter is exactly thisClass
object; otherwise it returnsfalse
.
Reference:
Related:
a) Check if an Object is an instance of a Class or Interface (including subclasses) you know at compile time:
boolean isInstance = someObject instanceof SomeTypeOrInterface;
Example:
assertTrue(Arrays.asList("a", "b", "c") instanceof List<?>);
b) Check if an Object is an instance of a Class or Interface (including subclasses) you only know at runtime:
Class<?> typeOrInterface = // acquire class somehow
boolean isInstance = typeOrInterface.isInstance(someObject);
Example:
public boolean checkForType(Object candidate, Class<?> type){
return type.isInstance(candidate);
}
setLocationRelativeTo(null)
should be called after you either use setSize(x,y)
, or use pack()
.
Use strftime
in the standard POSIX
module. The arguments to strftime
in Perl’s binding were designed to align with the return values from localtime
and gmtime
. Compare
strftime(fmt, sec, min, hour, mday, mon, year, wday = -1, yday = -1, isdst = -1)
with
my ($sec,$min,$hour,$mday,$mon,$year,$wday, $yday, $isdst) = gmtime(time);
Example command-line use is
$ perl -MPOSIX -le 'print strftime "%F %T", localtime $^T'
or from a source file as in
use POSIX;
print strftime "%F %T", localtime time;
Some systems do not support the %F
and %T
shorthands, so you will have to be explicit with
print strftime "%Y-%m-%d %H:%M:%S", localtime time;
or
print strftime "%Y-%m-%d %H:%M:%S", gmtime time;
Note that time
returns the current time when called whereas $^T
is fixed to the time when your program started. With gmtime
, the return value is the current time in GMT. Retrieve time in your local timezone with localtime
.
The trick here is that the ToolTip control is an extender control, which means that it will extend the set of properties for other controls on the form. Behind the scenes this is achieved by generating code like in Svetlozar's answer. There are other controls working in the same manner (such as the HelpProvider
).
This problem usually happen if eclipse accidentally compile the main.xml incorrectly. The easiest solution is to delete R.java inside gen directory. Once we delete, than eclipse will generate the new R.java base on the latest main.xml
There is a good blog about this topic: http://www.baeldung.com/jackson-serialize-dates Use @JsonFormat looks the most simple way.
public class Event {
public String name;
@JsonFormat
(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
public Date eventDate;
}
In my case, my Android Studio version was 3.6.1 and i have modified the classpath like below;
classpath 'com.android.tools.build:gradle:3.6.1'
and that error was gone.
Removing the inputs with jQuery works for me:
$(".select2-search, .select2-focusser").remove();
You can try this:
SELECT EXTRACT(YEAR FROM field) FROM table WHERE id=1
I posted what I use to solve this very issue efficiently here using a quick Binary Search Algorithm: https://stackoverflow.com/a/52786742/1678210
I didn't want to copy the same answer. Someone else had asked it slightly differently but the answer is the same.
for n in range(6,0,-1):
print n
# prints [6, 5, 4, 3, 2, 1]
I think this should work,
a = numpy.arange(0,27.,3).reshape(3,3)
a /= a.sum(axis=1)[:,numpy.newaxis]
As for ERRORCODE 39, you can definately just delete the physical table files on the disk. the location depends on your OS distribution and setup. On Debian its typically under /var/lib/mysql/database_name/ So do a:
rm -f /var/lib/mysql/<database_name>/
And then drop the database from your tool of choice or using the command:
DROP DATABASE <database_name>
There are a few different ways to accomplish this, I'll outline my favourites.
Use a ToggleButton and apply a custom style to it. I suggest this because your required control is "like a toggle button" but just looks different from the default toggle button styling.
My preferred method is to define a graphic for the button in css:
.toggle-button {
-fx-graphic: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png');
}
.toggle-button:selected {
-fx-graphic: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png');
}
OR use the attached css to define a background image.
// file imagetogglebutton.css deployed in the same package as ToggleButtonImage.class
.toggle-button {
-fx-background-image: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png');
-fx-background-repeat: no-repeat;
-fx-background-position: center;
}
.toggle-button:selected {
-fx-background-image: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png');
}
I prefer the -fx-graphic specification over the -fx-background-* specifications as the rules for styling background images are tricky and setting the background does not automatically size the button to the image, whereas setting the graphic does.
And some sample code:
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.StackPaneBuilder;
import javafx.stage.Stage;
public class ToggleButtonImage extends Application {
public static void main(String[] args) throws Exception { launch(args); }
@Override public void start(final Stage stage) throws Exception {
final ToggleButton toggle = new ToggleButton();
toggle.getStylesheets().add(this.getClass().getResource(
"imagetogglebutton.css"
).toExternalForm());
toggle.setMinSize(148, 148); toggle.setMaxSize(148, 148);
stage.setScene(new Scene(
StackPaneBuilder.create()
.children(toggle)
.style("-fx-padding:10; -fx-background-color: cornsilk;")
.build()
));
stage.show();
}
}
Some advantages of doing this are:
An alternate is to not use css and still use a ToggleButton, but set the image graphic in code:
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.*;
import javafx.scene.control.ToggleButton;
import javafx.scene.image.*;
import javafx.scene.layout.StackPaneBuilder;
import javafx.stage.Stage;
public class ToggleButtonImageViaGraphic extends Application {
public static void main(String[] args) throws Exception { launch(args); }
@Override public void start(final Stage stage) throws Exception {
final ToggleButton toggle = new ToggleButton();
final Image unselected = new Image(
"http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png"
);
final Image selected = new Image(
"http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png"
);
final ImageView toggleImage = new ImageView();
toggle.setGraphic(toggleImage);
toggleImage.imageProperty().bind(Bindings
.when(toggle.selectedProperty())
.then(selected)
.otherwise(unselected)
);
stage.setScene(new Scene(
StackPaneBuilder.create()
.children(toggle)
.style("-fx-padding:10; -fx-background-color: cornsilk;")
.build()
));
stage.show();
}
}
The code based approach has the advantage that you don't have to use css if you are unfamilar with it.
For best performance and ease of porting to unsigned applet and webstart sandboxes, bundle the images with your app and reference them by relative path urls rather than downloading them off the net.
[email protected] # Minimum three characters
[email protected] # Accepts Caps as well.
[email protected] # Accepts . before @
<input type="email" pattern="[A-Za-z0-9._%+-]{3,}@[a-zA-Z]{3,}([.]{1}[a-zA-Z]{2,}|[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,})" />
If your whitespace is consistent you could use that as a delimiter, also instead of inserting \t
directly, you could set the output separator and it will be included automatically:
< file awk -v OFS='\t' -v FS='[/ ]' '{print $3, $5, $NF}'
Maybe it is the case that you have your path in couple of lines, you used enter to make it? If so, then part of you paths might look like that "/\nData/" instead of "/Data/", which causes the problem. Just set it to be in one line and issue is solved!
I prefer Click. It abstracts managing options and allows "(...) creating beautiful command line interfaces in a composable way with as little code as necessary".
Here's example usage:
import click
@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name',
help='The person to greet.')
def hello(count, name):
"""Simple program that greets NAME for a total of COUNT times."""
for x in range(count):
click.echo('Hello %s!' % name)
if __name__ == '__main__':
hello()
It also automatically generates nicely formatted help pages:
$ python hello.py --help
Usage: hello.py [OPTIONS]
Simple program that greets NAME for a total of COUNT times.
Options:
--count INTEGER Number of greetings.
--name TEXT The person to greet.
--help Show this message and exit.
http://php.net/session.gc-maxlifetime
session.gc_maxlifetime = 1440
(1440 seconds = 24 minutes)
Different web stacks do support different lengths of http-requests. I know from experience that the early stacks of Safari only supported 4000 characters and thus had difficulty handling ASP.net pages because of the USER-STATE. This is even for POST, so you would have to check the browser and see what the stack limit is. I think that you may reach a limit even on newer browsers. I cannot remember but one of them (IE6, I think) had a limit of 16-bit limit, 32,768 or something.
raw_input()
was renamed to input()
in Python 3.
In theory, yes, it's just a matter of plugging things in. Zipfile can give you a file-like object for a file in a zip archive, and image.load will accept a file-like object. So something like this should work:
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
try:
image = pygame.image.load(imgfile, 'img_01.png')
finally:
imgfile.close()
(tl;dr: The exact answer to your question is numpy.empty
or numpy.empty_like
, but you likely don't care and can get away with using myList = [None]*10000
.)
You can initialize your list to all the same element. Whether it semantically makes sense to use a non-numeric value (that will give an error later if you use it, which is a good thing) or something like 0 (unusual? maybe useful if you're writing a sparse matrix or the 'default' value should be 0 and you're not worried about bugs) is up to you:
>>> [None for _ in range(10)]
[None, None, None, None, None, None, None, None, None, None]
(Here _
is just a variable name, you could have used i
.)
You can also do so like this:
>>> [None]*10
[None, None, None, None, None, None, None, None, None, None]
You probably don't need to optimize this. You can also append to the array every time you need to:
>>> x = []
>>> for i in range(10):
>>> x.append(i)
Which is best?
>>> def initAndWrite_test():
... x = [None]*10000
... for i in range(10000):
... x[i] = i
...
>>> def initAndWrite2_test():
... x = [None for _ in range(10000)]
... for i in range(10000):
... x[i] = i
...
>>> def appendWrite_test():
... x = []
... for i in range(10000):
... x.append(i)
Results in python2.7:
>>> import timeit
>>> for f in [initAndWrite_test, initAndWrite2_test, appendWrite_test]:
... print('{} takes {} usec/loop'.format(f.__name__, timeit.timeit(f, number=1000)*1000))
...
initAndWrite_test takes 714.596033096 usec/loop
initAndWrite2_test takes 981.526136398 usec/loop
appendWrite_test takes 908.597946167 usec/loop
Results in python 3.2:
initAndWrite_test takes 641.3581371307373 usec/loop
initAndWrite2_test takes 1033.6499214172363 usec/loop
appendWrite_test takes 895.9040641784668 usec/loop
As we can see, it is likely better to do the idiom [None]*10000
in both python2 and python3. However, if one is doing anything more complicated than assignment (such as anything complicated to generate or process every element in the list), then the overhead becomes a meaninglessly small fraction of the cost. That is, such optimization is premature to worry about if you're doing anything reasonable with the elements of your list.
These are all however inefficient because they go through memory, writing something in the process. In C this is different: an uninitialized array is filled with random garbage memory (sidenote: that has been reallocated from the system, and can be a security risk when you allocate or fail to mlock and/or fail to delete memory when closing the program). This is a design choice, designed for speedup: the makers of the C language thought that it was better not to automatically initialize memory, and that was the correct choice.
This is not an asymptotic speedup (because it's O(N)
), but for example you wouldn't need to first initialize your entire memory block before you overwrite with stuff you actually care about. This, if it were possible, is equivalent to something like (pseudo-code) x = list(size=10000)
.
If you want something similar in python, you can use the numpy
numerical matrix/N-dimensional-array manipulation package. Specifically, numpy.empty
or numpy.empty_like
That is the real answer to your question.
I am loading html pages from Documents and if they have the same name of css file UIWebView
it seem it does not throw the previous css rules. Maybe because they have the same URL or something.
I tried this:
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
[sharedCache release];
I tried this :
[[NSURLCache sharedURLCache] removeAllCachedResponses];
I am loading the initial page with:
NSURLRequest *appReq = [NSURLRequest requestWithURL:appURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
It refuses to throw its cached data! Frustrating!
I am doing this inside a PhoneGap (Cordova) application. I have not tried it in isolated UIWebView.
Update1: I have found this.
Changing the html files, though seems very messy.
Thought I would give a more recent answer as this question still comes up pretty high on searches.
Checking CLi JAR Version:
Run the following on the CLi jar file:
unzip -p jenkins-cli.jar META-INF/MANIFEST.MF
Example Output:
Manifest-Version: 1.0
Built-By: kohsuke
Jenkins-CLI-Version: 2.210 <--- Jenkins CLI Version
Created-By: Apache Maven 3.6.1
Build-Jdk: 1.8.0_144
Main-Class: hudson.cli.CLI
The CLi version is listed above.
To get the Server Version, run the following:
java -jar ./jenkins-cli.jar -s https://<Server_URL> -auth <email>@<domain>.com:<API Token> version
(the above will vary based on your implementation of authentication, please change accordingly)
Example Output:
Dec 23, 2019 4:42:55 PM org.apache.sshd.common.util.security.AbstractSecurityProviderRegistrar getOrCreateProvider
INFO: getOrCreateProvider(EdDSA) created instance of net.i2p.crypto.eddsa.EdDSASecurityProvider
2.210 <-- Jenkins Server Version
php\php.ini
set your loadable php extensions path (eg. extension_dir = "C:\php\ext"
)
(https://drive.google.com/open?id=1DDZd06SLHSmoFrdmWkmZuXt4DMOPIi_A)php\php.ini
) check if extension=php_mysqli.dll
is uncommented
(https://drive.google.com/open?id=17DUt1oECwOdol8K5GaW3tdPWlVRSYfQ9)"C:\php"
) and php\ext folder (eg."C:\php\ext"
) as your runtime environment variable path
(https://drive.google.com/open?id=1zCRRjh1Jem_LymGsgMmYxFc8Z9dUamKK)NPM package libraries have a section in the package.json file named peerDependencies. For example; a library built in Angular 8, will usually list Angular 8 as a dependency. This is a true dependency for anyone running less than version 8. But for anyone running version 8, 9 or 10, it's questionable whether any concern should be pursued.
I have been safely ignoring these messages on Angular Updates, but then again we do have Unit and Cypress Tests!
I had this problem with Ubuntu 18.04 LTS and Mysql Server version 5.7.27-0ubuntu0.18.04.1 (Ubuntu).
My solution was (running as root with sudo -i
)
mysql <<-EOSQL
use mysql;
update user set plugin="mysql_native_password" where User='root';
FLUSH PRIVILEGES ;
EOSQL
mysqladmin -u root password new_pw
For me, it was really simple: I had a stale postmaster.pid
file.
Simply deleting and restarting postgres fixed it for me:
rm '/Users/<username>/Library/Application Support/Postgres/var-10/postmaster.pid'
Mates,
I stumbled upon this error today while testing a simple script. I am not using "class" function though so it take it with grain of salt. I was calling function before its definition & declaration ...something like this
try{
foo();
}
catch (exception $e)
{
echo "$e->getMessage()";
}
function foo(){
echo "blah blah blah";
}
so php was throwing me error "call to undefined function ".
This kinda seem classic programming error but may help someone in need of clue.
Use dot notation and/or bracket notation to access object properties and for
loops to iterate arrays:
var d, i;
for (i = 0; i < dictionary.data.length; i++) {
d = dictionary.data[i];
alert(d.id + ' ' + d.name);
}
You can also iterate arrays using for
..in
loops; however, properties added to Array.prototype
may show through, and you may not necessarily get array elements in their correct order, or even in any consistent order.
In Core 2.2 Razor pages this syntax works:
<button type="submit" name="Submit">Save</button>
<button type="submit" name="Cancel">Cancel</button>
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
return Page();
var sub = Request.Form["Submit"];
var can = Request.Form["Cancel"];
if (sub.Count > 0)
{
.......
I liked the (C#) code in the following which sets the registry settings for your app. Not sure if it will cut it after installation though if permissions are required. For me it solved an issue with WebSocket not being available inside a WebBrowser control in WPF.