Use the array module. With it you can store collections of the same type efficiently.
>>> import array
>>> import itertools
>>> a = array_of_signed_ints = array.array("i", itertools.repeat(0, 10))
For more information - e.g. different types, look at the documentation of the array module. For up to 1 million entries this should feel pretty snappy. For 10 million entries my local machine thinks for 1.5 seconds.
The second parameter to array.array is a generator, which constructs the defined sequence as it is read. This way, the array module can consume the zeros one-by-one, but the generator only uses constant memory. This generator does not get bigger (memory-wise) if the sequence gets longer. The array will grow of course, but that should be obvious.
You use it just like a list:
>>> a.append(1)
>>> a.extend([1, 2, 3])
>>> a[-4:]
array('i', [1, 1, 2, 3])
>>> len(a)
14
...or simply convert it to a list:
>>> l = list(a)
>>> len(l)
14
Surprisingly
>>> a = [0] * 10000000
is faster at construction than the array method. Go figure! :)
if(strtotime($row['database_date']) > strtotime('now')) echo $row['database_date'];
else echo date("d-m-Y");
No need to check the hours because if they are on the same day it will show the same date either way...
With ES6+ you can just do [${variable}
]
You need to open the Service.cs file in the designer, right click it and choose the menu-option "Add Installer".
It won't install right out of the box... you need to create the installer class first.
Some reference on service installer:
How to: Add Installers to Your Service Application
Quite old... but this is what I am talking about:
Windows Services in C#: Adding the Installer (part 3)
By doing this, a ProjectInstaller.cs
will be automaticaly created. Then you can double click this, enter the designer, and configure the components:
serviceInstaller1
has the properties of the service itself: Description
, DisplayName
, ServiceName
and StartType
are the most important.
serviceProcessInstaller1
has this important property: Account
that is the account in which the service will run.
For example:
this.serviceProcessInstaller1.Account = ServiceAccount.LocalSystem;
It's not possible to decrypt MD5
hash which created. You need all information to decrypt the MD5
value which was used during encryption.
You can use AES
algorithm to encrypt and decrypt
JavaScript AES encryption and decryption (Advanced Encryption Standard)
This is for windows environment:
I got the Initial Admin password under C:\Users\Deepak("MyUser").jenkins\secrets\initialAdminPassword
I was able to login with user "admin" and above password. Then under Jenkins> people I edited the password of the user and clicked on apply to reflect the changes.
You need to target the device by its User Agent, using some script. The user agent for the iPad is:
Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10
In fact, unsigned int on most modern processors (ARM, Intel/AMD, Alpha, SPARC, Itanium ,PowerPC) will have a range of 0 to 2^32 - 1 which is 4,294,967,295 = 0xffffffff because int (both signed and unsigned) will be 32 bits long and the largest one is as stated.
(unsigned short will have maximal value 2^16 - 1 = 65,535 )
(unsigned) long long int will have a length of 64 bits (long int will be enough under most 64 bit Linuxes, etc, but the standard promises 64 bits for long long int). Hence these have the range 0 to 2^64 - 1 = 18446744073709551615
SQL*Plus uses &1, &2... &n to access the parameters.
Suppose you have the following script test.sql
:
SET SERVEROUTPUT ON
SPOOL test.log
EXEC dbms_output.put_line('&1 &2');
SPOOL off
you could call this script like this for example:
$ sqlplus login/pw @test Hello World!
In a UNIX script you would usually call a SQL script like this:
sqlplus /nolog << EOF
connect user/password@db
@test.sql Hello World!
exit
EOF
so that your login/password won't be visible with another session's ps
To build on the solutions from Ffisegydd and amaliammr, here's an example where we make CSV representation for a custom colormap:
#! /usr/bin/env python3
import matplotlib
import numpy as np
vmin = 0.1
vmax = 1000
norm = matplotlib.colors.Normalize(np.log10(vmin), np.log10(vmax))
lognum = norm(np.log10([.5, 2., 10, 40, 150,1000]))
cdict = {
'red':
(
(0., 0, 0),
(lognum[0], 0, 0),
(lognum[1], 0, 0),
(lognum[2], 1, 1),
(lognum[3], 0.8, 0.8),
(lognum[4], .7, .7),
(lognum[5], .7, .7)
),
'green':
(
(0., .6, .6),
(lognum[0], 0.8, 0.8),
(lognum[1], 1, 1),
(lognum[2], 1, 1),
(lognum[3], 0, 0),
(lognum[4], 0, 0),
(lognum[5], 0, 0)
),
'blue':
(
(0., 0, 0),
(lognum[0], 0, 0),
(lognum[1], 0, 0),
(lognum[2], 0, 0),
(lognum[3], 0, 0),
(lognum[4], 0, 0),
(lognum[5], 1, 1)
)
}
mycmap = matplotlib.colors.LinearSegmentedColormap('my_colormap', cdict, 256)
norm = matplotlib.colors.LogNorm(vmin, vmax)
colors = {}
count = 0
step_size = 0.001
for value in np.arange(vmin, vmax+step_size, step_size):
count += 1
print("%d/%d %f%%" % (count, vmax*(1./step_size), 100.*count/(vmax*(1./step_size))))
rgba = mycmap(norm(value), bytes=True)
color = (rgba[0], rgba[1], rgba[2])
if color not in colors.values():
colors[value] = color
print ("value, red, green, blue")
for value in sorted(colors.keys()):
rgb = colors[value]
print("%s, %s, %s, %s" % (value, rgb[0], rgb[1], rgb[2]))
why is my java logging not working
provides a jar file that will help you work out why your logging in not working as expected. It gives you a complete dump of what loggers and handlers have been installed and what levels are set and at which level in the logging hierarchy.
on my android device, the problem was about the previous build versions of the application that I had installed on my phone before. the following steps solved my problem:
removing any previous build of the application, including debugging version and signed apk version
on the root directory of your project, run (on windows):
cd android
.\gradlew clean
cd ..
npm cache clean --force
reboot your android device
hope this help you too.
You can update your jquery typings version like so
npm install --save @types/jquery@latest
I had this same error and I've been at if for 5 days surfing the net for a solution.it worked for me and it should work for you
In some cases you may need a counter that may be provided by for-loop implementation. For that, LINQ provides ElementAt
which enables the following:
for (int index = 0; index < dictionary.Count; index++) {
var item = dictionary.ElementAt(index);
var itemKey = item.Key;
var itemValue = item.Value;
}
localStorage
is something that is kept on the client side. There is no data transmitted to the server side.
You can only get the data with JavaScript and you can send it to the server side with Ajax.
For those of you (like me) that wasted too much time from this error:
I had received the same error: "Could not find implementation of query Pattern for source type 'DbSet'" but the solution for me was fixing a mistake at the DbContext level.
When I created my context I had this:
public class ContactContext : DbContext
{
public ContactContext() : base() { }
public DbSet Contacts { get; set; }
}
And my Repository (I was following a Repository pattern in ASP.NET guide) looked like this:
public Contact FindById(int id)
{
var contact = from c in _db.Contacts where c.Id == id select c;
return contact;
}
My issue came from the initial setup of my DbContext, when I used DbSet as a generic instead of the type.
I changed public DbSet Contacts { get; set; }
to public DbSet<Contact> Contacts { get; set; }
and suddenly the query was recognized.
This is probably what k.m says in his answer, but since he mentioned IEnumerable<t>
and not DbSet<<YourDomainObject>>
I had to dig around in the code for a couple hours to find the line that caused this headache.
This expression
SELECT (((DATEPART(DW, @my_date_var) - 1 ) + @@DATEFIRST ) % 7)
will always return a number between 0 and 6 where
0 -> Sunday
1 -> Monday
2 -> Tuesday
3 -> Wednesday
4 -> Thursday
5 -> Friday
6 -> Saturday
Independently from @@DATEFIRST
So a weekend day is tested like this
SELECT (CASE
WHEN (((DATEPART(DW, @my_date_var) - 1 ) + @@DATEFIRST ) % 7) IN (0,6)
THEN 1
ELSE 0
END) AS is_weekend_day
I have found simpler solution:
$('#clickToCreate').live('click', function() {
$('#yourDialogId')
.dialog({
title: "Set the title to Create"
})
.dialog('open');
});
$('#clickToEdit').live('click', function() {
$('#yourDialogId')
.dialog({
title: "Set the title To Edit"
})
.dialog('open');
});
Hope that helps!
For methods which may fail, that is you specify boolean as return type, I would use the prefix try
:
if (tryCreateFreshSnapshot())
{
// ...
}
For all other cases use prefixes like is..
has..
was..
can..
allows..
..
strstr(request, "favicon") != NULL
This is what I ended up doing in a Freeswitch
bash startup script:
# Check if user exists
if ! id -u $FS_USER > /dev/null 2>&1; then
echo "The user does not exist; execute below commands to crate and try again:"
echo " root@sh1:~# adduser --home /usr/local/freeswitch/ --shell /bin/false --no-create-home --ingroup daemon --disabled-password --disabled-login $FS_USER"
echo " ..."
echo " root@sh1:~# chown freeswitch:daemon /usr/local/freeswitch/ -R"
exit 1
fi
Not sure why do you need w,h. If these values are actually required and mean that only specified number of rows and cols should be read than you can try the following:
output = []
with open(r'c:\file.txt', 'r') as f:
w, h = map(int, f.readline().split())
tmp = []
for i, line in enumerate(f):
if i == h:
break
tmp.append(map(int, line.split()[:w]))
output.append(tmp)
Ok, first e.preventDefault();
it's not a Jquery element, it's a method of javascript, now what it's true it's if you add this method you avoid the submit the event, now what you could do it's send the form by ajax something like this
$('#subscription_order_form').submit(function(e){
$.ajax({
url: $(this).attr('action'),
data : $(this).serialize(),
success : function (data){
}
});
e.preventDefault();
});
JavaScript code using ng-controller:
$scope.checkkey = function (event) {
alert(event.keyCode); //this will show the ASCII value of the key pressed
}
In HTML:
<input type="text" ng-keypress="checkkey($event)" />
You can now place your checks and other conditions using the keyCode method.
const arr= [1, 2, 3]
arr.forEach(function(element){
if(arr[arr.length-1] === element){
console.log("Last Element")
}
})
The libraries mentioned in other answers would be fine solutions, but if you already happen to be digging through real-world html in your project, the Jsoup
project has a lot more to offer than just managing "ampersand pound FFFF semicolon" things.
// textValue: <p>This is a sample. \"Granny\" Smith –.<\/p>\r\n
// becomes this: This is a sample. "Granny" Smith –.
// with one line of code:
// Jsoup.parse(textValue).getText(); // for older versions of Jsoup
Jsoup.parse(textValue).text();
// Another possibility may be the static unescapeEntities method:
boolean strictMode = true;
String unescapedString = org.jsoup.parser.Parser.unescapeEntities(textValue, strictMode);
And you also get the convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods. It's open source and MIT licence.
Yes, this means all the 1 keys with value are overwriten with the last added value and here you add "surely not one" so it will display only "surely not one".
Even if you are trying to display with a loop, it will also only display one key and value which have same key.
I know this question already has an accepted answer, but for me, a .NET beginner, there was a simple solution to what I was doing wrong and I thought I'd share.
I had been doing this:
@Html.HiddenFor(Model.Foo.Bar.ID)
What worked for me was changing to this:
@Html.HiddenFor(m => m.Foo.Bar.ID)
(where "m" is an arbitrary string to represent the model object)
These are automatic variables, like $null
, $true
, $false
etc.
about_Automatic_Variables
, see https://technet.microsoft.com/en-us/library/hh847768.aspx?f=255&MSPPError=-2147217396
$NULL
$null
is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.Windows PowerShell treats
$null
as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.For example, when
$null
is included in a collection, it is counted as one of the objects.C:\PS> $a = ".dir", $null, ".pdf" C:\PS> $a.count 3
If you pipe the
$null
variable to theForEach-Object
cmdlet, it generates a value for$null
, just as it does for the other objects.PS C:\ps-test> ".dir", $null, ".pdf" | Foreach {"Hello"} Hello Hello Hello
As a result, you cannot use
$null
to mean "no parameter value." A parameter value of$null
overrides the default parameter value.However, because Windows PowerShell treats the
$null
variable as a placeholder, you can use it scripts like the following one, which would not work if$null
were ignored.$calendar = @($null, $null, “Meeting”, $null, $null, “Team Lunch”, $null) $days = Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" $currentDay = 0 foreach($day in $calendar) { if($day –ne $null) { "Appointment on $($days[$currentDay]): $day" } $currentDay++ }
output:
Appointment on Tuesday: Meeting Appointment on Friday: Team lunch
There are two types in this parsing.
From a file, you can use the following
import json
json = json.loads(open('/path/to/file.json').read())
value = json['key']
print json['value']
This arcticle explains the full parsing and getting values using two scenarios.Parsing JSON using Python
This warning is about unsafe use of strcpy. Try IOBname[ii]='\0';
instead.
Add another button called "CancelButton" that sets a flag, and then check for that flag.
If you have long loops in the "stuff" then check for it there too and exit if it's set. Use DoEvents inside long loops to ensure that the UI works.
Bool Cancel
Private Sub CancelButton_OnClick()
Cancel=True
End Sub
...
Private Sub SomeVBASub
Cancel=False
DoStuff
If Cancel Then Exit Sub
DoAnotherStuff
If Cancel Then Exit Sub
AndFinallyDothis
End Sub
componentWillUnmount
setState
,Assuming that you mean "When using ajax" and "An HTTP Request header", then use the headers
property in the object you pass to ajax()
headers(added 1.5)
Default:
{}
A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.
Well, to precisely see the difference between border: 0
and border: none
we can make some experiments.
Lets create three divs, first one whose border can only be disabled by setting its width to zero, second one that can only be disabled by setting its style to none, and a third with a border that can only be "disabled" by setting its color to transparent. Then lets try the effect of:
border: 0;
border: none;
border: transparent
border-style: solid!important; border-color: red!important; border-width: 2px!important; border-color: red!important; border-width: 2px!important; border-style: solid!important;
var container = document.querySelector('#container');_x000D_
var btnSetZero = document.querySelector('#setZero');_x000D_
var btnSetNone = document.querySelector('#setNone');_x000D_
var btnSetTransparent = document.querySelector('#setTransparent');_x000D_
var btnReset = document.querySelector('#reset');_x000D_
btnSetZero.addEventListener('click', () => {_x000D_
container.className = "border-zero";_x000D_
});_x000D_
_x000D_
btnSetNone.addEventListener('click', () => {_x000D_
container.className = "border-none";_x000D_
});_x000D_
_x000D_
btnSetTransparent.addEventListener('click', () => {_x000D_
container.className = "border-transparent";_x000D_
});_x000D_
_x000D_
btnReset.addEventListener('click', () => {_x000D_
container.className = "";_x000D_
});
_x000D_
div div {_x000D_
border: 2px solid red;_x000D_
margin: 2px;_x000D_
font-family: monospace;_x000D_
white-space: nowrap;_x000D_
width: 250px;_x000D_
}_x000D_
_x000D_
div.border-zero div {_x000D_
border: 0;_x000D_
}_x000D_
div.border-none div {_x000D_
border: none;_x000D_
}_x000D_
div.border-transparent div {_x000D_
border: transparent;_x000D_
}
_x000D_
<div id="container">_x000D_
<div style="border-style: solid!important; border-color: red!important;">_x000D_
border-style: solid!important;<br>_x000D_
border-color: red!important;_x000D_
</div>_x000D_
<div style="border-width: 2px!important; border-color: red!important;">_x000D_
border-width: 2px!important;<br>_x000D_
border-color: red!important;_x000D_
</div>_x000D_
<div style="border-width: 2px!important; border-style: solid!important;">_x000D_
border-width: 2px!important;<br>_x000D_
border-style: solid!important;_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<button id="setZero">border: 0;</button>_x000D_
<button id="setNone">border: none;</button>_x000D_
<button id="setTransparent">border: transparent;</button>_x000D_
<button id="reset">reset</button>
_x000D_
My results were the same in both firefox and chrome:
border: 0;
Seems to set border-width to 0
and border-style to none
, but not change border-color;
border: none;
Seems to only change border-style (to none
);
border: transparent;
Seems to change border-color to transparent
and border-style to none
;
If you want to do it typed:
class Something {
areas: Area[][];
constructor() {
this.areas = new Array<Array<Area>>();
for (let y = 0; y <= 100; y++) {
let row:Area[] = new Array<Area>();
for (let x = 0; x <=100; x++){
row.push(new Area(x, y));
}
this.areas.push(row);
}
}
}
The simplest way is:
make foo=bar target
Then in your makefile you can refer to $(foo)
. Note that this won't propagate to sub-makes automatically.
If you are using sub-makes, see this article: Communicating Variables to a Sub-make
$name=array();
while($result=mysql_fetch_array($res)) {
$name[]=array('Id'=>$result['id']);
// here you want to fetch all
// records from table like this.
// then you should get the array
// from all rows into one array
}
I've found a solution for width: "100%", height: "auto" if you know the aspectRatio (width / height) of the image.
Here's the code:
import { Image, StyleSheet, View } from 'react-native';
const image = () => (
<View style={styles.imgContainer}>
<Image style={styles.image} source={require('assets/images/image.png')} />
</View>
);
const style = StyleSheet.create({
imgContainer: {
flexDirection: 'row'
},
image: {
resizeMode: 'contain',
flex: 1,
aspectRatio: 1 // Your aspect ratio
}
});
This is the most simplest way I could get it to work without using onLayout
or Dimension
calculations. You can even wrap it in a simple reusable component if needed. Give it a shot if anyone is looking for a simple implementation.
This is a minor update, but since Java 7, proxy connections can now be created programmatically rather than through system properties. This may be useful if:
Here's a contrived example in groovy:
// proxy configuration read from file resource under "proxyFileName"
String proxyFileName = "proxy.txt"
String proxyPort = "1234"
String url = "http://www.promised.land"
File testProxyFile = new File(proxyFileName)
URLConnection connection
if (!testProxyFile.exists()) {
logger.debug "proxyFileName doesn't exist. Bypassing connection via proxy."
connection = url.toURL().openConnection()
} else {
String proxyAddress = testProxyFile.text
connection = url.toURL().openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort)))
}
try {
connection.connect()
}
catch (Exception e) {
logger.error e.printStackTrace()
}
Full Reference: http://docs.oracle.com/javase/7/docs/technotes/guides/net/proxies.html
The .NET documentation says: State Property: A bitwise combination of the ConnectionState values
So I think you should check
!myConnection.State.HasFlag(ConnectionState.Open)
instead of
myConnection.State != ConnectionState.Open
because State can have multiple flags.
apnerve's answer was correct before HTML 5 came out, now it's a little more complicated.
For example, the script
element, according to the HTML 5 specification, has two global attributes which change how the src
attribute functions: async
and defer
. These change how the script (embedded inline or imported from external file) should be executed.
This means there are three possible modes that can be selected using these attributes:
async
attribute is present, then the script will be executed asynchronously, as soon as it is available. async
attribute is not present but the defer
attribute is present, then the script is executed when the page has finished parsing. For details please see HTML 5 recommendation
I just wanted to update with a new answer for whoever occasionally visits this topic. Some of the answers should be checked and archived by stackoverflow and every one of us.
There are two typical ways of declaring a function. I prefer the second approach.
function function_name {
command...
}
or
function_name () {
command...
}
To call a function with arguments:
function_name "$arg1" "$arg2"
The function refers to passed arguments by their position (not by name), that is $1
, $2
, and so forth. $0
is the name of the script itself.
Example:
function_name () {
echo "Parameter #1 is $1"
}
Also, you need to call your function after it is declared.
#!/usr/bin/env sh
foo 1 # this will fail because foo has not been declared yet.
foo() {
echo "Parameter #1 is $1"
}
foo 2 # this will work.
Output:
./myScript.sh: line 2: foo: command not found
Parameter #1 is 2
You may use:
FileSystems.getDefault().getPath(new String()).toAbsolutePath();
or
FileSystems.getDefault().getPath(new String("./")).toAbsolutePath().getParent()
This will give you the root folder path without using the name of the file. You can then drill down to where you want to go.
Example: /src/main/java...
Here is my understanding of it so far, in case it helps someone.
core.autocrlf=true
and core.safecrlf = true
You have a repository where all the line endings are the same, but you work on different platforms. Git will make sure your lines endings are converted to the default for your platform. Why does this matter? Let's say you create a new file. The text editor on your platform will use its default line endings. When you check it in, if you don't have core.autocrlf set to true, you've introduced a line ending inconsistency for someone on a platform that defaults to a different line ending. I always set safecrlf too because I would like to know that the crlf operation is reversible. With these two settings, git is modifying your files, but it verifies that the modifications are reversible.
core.autocrlf=false
You have a repository that already has mixed line endings checked in and fixing the incorrect line endings could break other things. Its best not to tell git to convert line endings in this case, because then it will exacerbate the problem it was designed to solve - making diffs easier to read and merges less painful. With this setting, git doesn't modify your files.
core.autocrlf=input
I don't use this because the reason for this is to cover a use case where you created a file that has CRLF line endings on a platform that defaults to LF line endings. I prefer instead to make my text editor always save new files with the platform's line ending defaults.
Just for someone who have the same problem I did. If you just want to make some insert just once you can do something like this.
Lets suppose you have a table with two columns
ID Identity (1,1) | Name Varchar
and want to insert a row with the ID = 4. So you Reseed it to 3 so the next one is 4
DBCC CHECKIDENT([YourTable], RESEED, 3)
Make the Insert
INSERT INTO [YourTable]
( Name )
VALUES ( 'Client' )
And get your seed back to the highest ID, lets suppose is 15
DBCC CHECKIDENT([YourTable], RESEED, 15)
Done!
I would prefer to use the strlen function as library functions are implemented in the best way.
So, I would write if(strlen(p)==0) //Empty string
Keep in mind that 0x80
= 80h
= 128
You can see here that INT
is just one of the many instructions (actually the Assembly Language representation (or should I say 'mnemonic') of it) that exists in the x86 instruction set. You can also find more information about this instruction in Intel's own manual found here.
To summarize from the PDF:
INT n/INTO/INT 3—Call to Interrupt Procedure
The INT n instruction generates a call to the interrupt or exception handler specified with the destination operand. The destination operand specifies a vector from 0 to 255, encoded as an 8-bit unsigned intermediate value. The INT n instruction is the general mnemonic for executing a software-generated call to an interrupt handler.
As you can see 0x80 is the destination operand in your question. At this point the CPU knows that it should execute some code that resides in the Kernel, but what code? That is determined by the Interrupt Vector in Linux.
One of the most useful DOS software interrupts was interrupt 0x21. By calling it with different parameters in the registers (mostly ah and al) you could access various IO operations, string output and more.
Most Unix systems and derivatives do not use software interrupts, with the exception of interrupt 0x80, used to make system calls. This is accomplished by entering a 32-bit value corresponding to a kernel function into the EAX register of the processor and then executing INT 0x80.
Take a look at this please where other available values in the interrupt handler tables are shown:
As you can see the table points the CPU to execute a system call. You can find the Linux System Call table here.
So by moving the value 0x1 to EAX register and calling the INT 0x80 in your program, you can make the process go execute the code in Kernel which will stop (exit) the current running process (on Linux, x86 Intel CPU).
A hardware interrupt must not be confused with a software interrupt. Here is a very good answer on this regard.
This also is good source.
Use target-attribute:
<a target="_parent" href="http://url.org">link</a>
The default Gson implementation of Map serialization uses toString()
on the key:
Gson gson = new GsonBuilder()
.setPrettyPrinting().create();
Map<Point, String> original = new HashMap<>();
original.put(new Point(1, 2), "a");
original.put(new Point(3, 4), "b");
System.out.println(gson.toJson(original));
Will give:
{
"java.awt.Point[x\u003d1,y\u003d2]": "a",
"java.awt.Point[x\u003d3,y\u003d4]": "b"
}
enableComplexMapKeySerialization
If you want the Map Key to be serialized according to default Gson rules you can use enableComplexMapKeySerialization. This will return an array of arrays of key-value pairs:
Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
.setPrettyPrinting().create();
Map<Point, String> original = new HashMap<>();
original.put(new Point(1, 2), "a");
original.put(new Point(3, 4), "b");
System.out.println(gson.toJson(original));
Will return:
[
[
{
"x": 1,
"y": 2
},
"a"
],
[
{
"x": 3,
"y": 4
},
"b"
]
]
More details can be found here.
Switch to Branch2
git checkout Branch2
Apply the current (Branch2) changes on top of the Branch1 changes, staying in Branch2:
git rebase Branch1
Which would leave you with the desired result in Branch2:
a -- b -- c <-- Master
\
d -- e <-- Branch1
\
d -- e -- f' -- g' <-- Branch2
You can delete Branch1.
request.data
will be empty if request.headers["Content-Type"]
is recognized as form data, which will be parsed into request.form
. To get the raw data regardless of content type, use request.get_data()
.
request.data
calls request.get_data(parse_form_data=True)
, which results in the different behavior for form data.
You can do your whole program in one line! Yes, that is right, one line!
Console.WriteLine(DateTime.Now.ToString("yyyy.MM.dd"));
You may notice that I did not use the same date format as you. That is because you should use the International Date Format as described in this W3C document. Every time you don't use it, somewhere a cute little animal dies.
There are several ways to do this:
$collection = Mage::getModel('...')
->getCollection()
->setPageSize(20)
->setCurPage(1);
Will get first 20 records.
Here is the alternative and maybe more readable way:
$collection = Mage::getModel('...')->getCollection();
$collection->getSelect()->limit(20);
This will call Zend Db limit. You can set offset as second parameter.
After trying to manually uninstall, and then downloading another copy of the VS 2015 community installer for use with the force uninstall command line argument (Original answer by Michael Schuchardt), I was still unable to modify the install directory.
After testing further, I found that Unity (which integrates with Visual Studio as of Unity 5.2) also had to be removed. At this point Visual Studio Uninstaller (link to latest release on Github) can be used for the final removal of remaining any remaining components.
You will now be able to run the Visual Studio Installer and select a directory or, alternatively, run the install from command line using the "/CustomInstallPath ..." argument.
Here's how i do it in CoffeeScript on Node.JS:
blobService.createBlockBlobFromText 'containerName', (path + '$$$.$$$'), '', (err, result)->
if err
console.log 'failed to create path', err
else
console.log 'created path', path, result
If like me, you got that message after installing jenv,
simply add netbeans_jdkhome="$JAVA_HOME"
to your [netbeans-installation-directory]/etc/netbeans.conf
file
All hidden-*-up
, hidden-*
classes doesn't work for me, so I'm adding self-made hidden
class before visible-*
(which works for current bootstrap version). It is very useful if you need to show div only for one screen, and hide for all others.
CSS:
.hidden {display:none;}
HTML:
<div class="col-xs-12 hidden visible-xs visible-sm">
<img src="photo.png" style="width:100%">
</div>
You can determine the mean of the signal, and just subtract that value from all the entries. That will give you a zero mean result.
To get unit variance, determine the standard deviation of the signal, and divide all entries by that value.
If you are using Facebook SDK, you don't need to bother yourself to enter anything for redirect URI on the app management page of facebook. Just setup a URL scheme for your iOS app. The URL scheme of your app should be a value "fbxxxxxxxxxxx" where xxxxxxxxxxx is your app id as identified on facebook. To setup URL scheme for your iOS app, go to info tab of your app settings and add URL Type.
You can also write it like this:
let elem: any;
elem = $("div.printArea");
elem.printArea();
You can also do Dictionary:
var list = new List<string> { "a", "b", "a", "c", "a", "b" };
var result = list.GroupBy(x => x)
.ToDictionary(y=>y.Key, y=>y.Count())
.OrderByDescending(z => z.Value);
foreach (var x in result)
{
Console.WriteLine("Value: " + x.Key + " Count: " + x.Value);
}
You need a dict
:
my_dict = {'cheese': 'cake'}
Example code (from the docs):
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
You can read more about dictionaries here.
v-bind
and v-on
are two frequently used directives in vuejs html template.
So they provided a shorthand notation for the both of them as follows:
You can replace v-on:
with @
v-on:click='someFunction'
as:
@click='someFunction'
Another example:
v-on:keyup='someKeyUpFunction'
as:
@keyup='someKeyUpFunction'
Similarly, v-bind
with :
v-bind:href='var1'
Can be written as:
:href='var1'
Hope it helps!
The web host is not really playing foul. It's not strictly according to the rules - but compared with some some of the amazing inventions intended to prevent spam, its not a particularly bad one.
If you really do want to send mail from '@gmail.com' why not just use the gmail SMTP service? If you can't reconfigure the server where PHP is running, then there are lots of email wrapper tools out there which allow you to specify a custom SMTP relay phpmailer springs to mind.
C.
if you really need System.out.println to work(eg. it's called from third party library). you can simply use reflection to change out field in System.class:
try{
Field outField = System.class.getDeclaredField("out");
Field modifiersField = Field.class.getDeclaredField("accessFlags");
modifiersField.setAccessible(true);
modifiersField.set(outField, outField.getModifiers() & ~Modifier.FINAL);
outField.setAccessible(true);
outField.set(null, new PrintStream(new RedirectLogOutputStream());
}catch(NoSuchFieldException e){
e.printStackTrace();
}catch(IllegalAccessException e){
e.printStackTrace();
}
RedirectLogOutputStream class:
public class RedirectLogOutputStream extends OutputStream{
private String mCache;
@Override
public void write(int b) throws IOException{
if(mCache == null) mCache = "";
if(((char) b) == '\n'){
Log.i("redirect from system.out", mCache);
mCache = "";
}else{
mCache += (char) b;
}
}
}
In my case I had forgotten to save changes to the file 'app/hero.ts', after saving and restarting ng serve the issue was resolved.
Date format is yyyy-mm-dd. So the above query is looking for records older than 12Apr2013
Suggest you do a quick check by setting the date string to '2013-04-30', if no sql error, date format is confirmed to yyyy-mm-dd.
As a rule of thumb, the safest bet towards making your document be treated properly by all web servers, proxies, and client browsers, is probably the following:
In terms of the RFC 3023 spec, which some browsers fail to implement properly, the major difference in the content types is in how clients are supposed to treat the character encoding, as follows:
For application/xml, application/xml-dtd, application/xml-external-parsed-entity, or any one of the subtypes of application/xml such as application/atom+xml, application/rss+xml or application/rdf+xml, the character encoding is determined in this order:
For text/xml, text/xml-external-parsed-entity, or a subtype like text/foo+xml, the encoding attribute of the XML declaration within the document is ignored, and the character encoding is:
Most parsers don't implement the spec; they ignore the HTTP Context-Type and just use the encoding in the document. With so many ill-formed documents out there, that's unlikely to change any time soon.
Well, the basic premise here is: no, it is not secure yet.
Basically, you can't run crypto in JavaScript: JavaScript Crypto Considered Harmful.
The problem is that you can't reliably get the crypto code into the browser, and even if you could, JS isn't designed to let you run it securely. So until browsers have a cryptographic container (which Encrypted Media Extensions provide, but are being rallied against for their DRM purposes), it will not be possible to do securely.
As far as a "Better way", there isn't one right now. Your only alternative is to store the data in plain text, and hope for the best. Or don't store the information at all. Either way.
Either that, or if you need that sort of security, and you need local storage, create a custom application...
Looks like the image is too big and the window simply doesn't fit the screen.
Create window with the cv2.WINDOW_NORMAL
flag, it will make it scalable. Then you can resize it to fit your screen like this:
from __future__ import division
import cv2
img = cv2.imread('1.jpg')
screen_res = 1280, 720
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)
cv2.namedWindow('dst_rt', cv2.WINDOW_NORMAL)
cv2.resizeWindow('dst_rt', window_width, window_height)
cv2.imshow('dst_rt', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
According to the OpenCV documentation CV_WINDOW_KEEPRATIO
flag should do the same, yet it doesn't and it's value not even presented in the python module.
You will need to use onkeyup
and onchange
for this. The onchange will prevent context-menu pasting, and the onkeyup will fire for every keystroke.
See my answer on How to impose maxlength on textArea for a code sample.
The extensions methods also provide a ToDictionary extension. It is fairly simple to use, the general usage is passing a lambda selector for the key and getting the object as the value, but you can pass a lambda selector for both key and value.
class SomeObject
{
public int ID { get; set; }
public string Name { get; set; }
}
SomeObject[] objects = new SomeObject[]
{
new SomeObject { ID = 1, Name = "Hello" },
new SomeObject { ID = 2, Name = "World" }
};
Dictionary<int, string> objectDictionary = objects.ToDictionary(o => o.ID, o => o.Name);
Then objectDictionary[1]
Would contain the value "Hello"
For Bootstrap v4.3.1. Try below:
$(document).ready(function() {
var pathname = window.location.pathname; //get the path of current page
$('.navbar-nav > li > a[href="'+pathname+'"]').parent().addClass('active');
})
Simply do the following in the script tags:
<!Doctype html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Circle Canvas</title>_x000D_
</head>_x000D_
<body>_x000D_
<canvas id="myCanvas" width="300" height="150" style="border:1px solid _x000D_
#d3d3d3;">_x000D_
<body>_x000D_
<script>_x000D_
var c = document.getElementById("myCanvas");_x000D_
var ctx = c.getContext("2d");_x000D_
ctx.beginPath();_x000D_
ctx.arc(100, 75, 50, 0, 2 * Math.PI);_x000D_
ctx.stroke();_x000D_
</script>_x000D_
</body>_x000D_
</body>_x000D_
</html>
_x000D_
And there you go you got your circle.
Numpy arrays do not have an append method. Use the Numpy append function instead:
import numpy as np
array_3 = np.append(array_1, array_2, axis=n)
# you can either specify an integer axis value n or remove the keyword argument completely
For example, if array_1 and array_2 have the following values:
array_1 = np.array([1, 2])
array_2 = np.array([3, 4])
If you call np.append without specifying an axis value, like so:
array_3 = np.append(array_1, array_2)
array_3 will have the following value:
array([1, 2, 3, 4])
Else, if you call np.append with an axis value of 0, like so:
array_3 = np.append(array_1, array_2, axis=0)
array_3 will have the following value:
array([[1, 2],
[3, 4]])
More information on the append function here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html
Finally I've solved it using JacksonJaxbJsonProvider
It requires few changes in your Spring context.xml
and Maven pom.xml
In your Spring context.xml
add JacksonJaxbJsonProvider
to the <jaxrs:server>
:
<jaxrs:server id="restService" address="/resource">
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider"/>
</jaxrs:providers>
</jaxrs:server>
In your Maven pom.xml add:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.0</version>
</dependency>
Go to operations tab for the selected database and click "Drop the database (DROP)" to delete it.
You could use
kubectl describe pod `hostname` | grep IP | sed -E 's/IP:[[:space:]]+//'
which is based on what @mibbit suggested.
This takes the following facts into account:
kubectl
was manually placed in the container (possibly when the image was built)/var/run/secrets/kubernetes.io/serviceaccount
in the containerUse entrySet
,
/**
*Output:
D: 99.22
A: 3434.34
C: 1378.0
B: 123.22
E: -19.08
B's new balance: 1123.22
*/
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MainClass {
public static void main(String args[]) {
HashMap<String, Double> hm = new HashMap<String, Double>();
hm.put("A", new Double(3434.34));
hm.put("B", new Double(123.22));
hm.put("C", new Double(1378.00));
hm.put("D", new Double(99.22));
hm.put("E", new Double(-19.08));
Set<Map.Entry<String, Double>> set = hm.entrySet();
for (Map.Entry<String, Double> me : set) {
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
double balance = hm.get("B");
hm.put("B", balance + 1000);
System.out.println("B's new balance: " + hm.get("B"));
}
}
see complete example here:
Agree with @J-Dizzle,
I am a beginner in web-development and had a hard time solving this today.
Had similar problems when I was creating a SpringBoot project in STS.
Tried most of the solutions mentioned but they didn't work.
Tried removing .metadata
folder and re-building my springboot project but still nothing worked.
NOTE : I had multiple workspace in STS and this error occurred after migrating a project from one workspace to another.
Solution : All you need to do is restart your eclipse/STS IDE and it will work just fine.
Why would you want to? You wrote the method, so anyone modifying it could always remove the final keyword from qwerty and reassign it. As for the method signature, same reasoning, although I'm not sure what it would do to subclasses of your class... they may inherit the final parameter and even if they override the method, be unable to de-finalize x. Try it and find out if it would work.
The only real benefit, then, is if you make the parameter immutable and it carries over to the children. Otherwise, you're just cluttering your code for no particularly good reason. If it won't force anyone to follow your rules, you're better off just leaving a good comment as you why you shouldn't change that parameter or variable instead of giving if the final modifier.
Edit
In response to a comment, I will add that if you are seeing performance issues, making your local variables and parameters final can allow the compiler to optimize your code better. However, from the perspective of immutability of your code, I stand by my original statement.
Even shorter than the :search command:
:%norm A*
This is what it means:
% = for every line
norm = type the following commands
A* = append '*' to the end of current line
File.ReadLines()
returns an object of type System.Collections.Generic.IEnumerable<String>
File.ReadAllLines()
returns an array of strings.
If you want to use an array of strings you need to call the correct function.
You could use Jim solution, just use ReadAllLines()
or you could change your return type.
This would also work:
System.Collections.Generic.IEnumerable<String> lines = File.ReadLines("c:\\file.txt");
You can use any generic collection which implements IEnumerable. IList for an example.
This works form me to scroll to when I click next
$('#myTable').on('draw.dt', function() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
});
Try using os.system
:
os.system("script2.py 1")
execfile
is different because it is designed to run a sequence of Python statements in the current execution context. That's why sys.argv
didn't change for you.
Q1:
Business logics can be considered in two categories:
Domain logics like controls on an email address (uniqueness, constraints, etc.), obtaining the price of a product for invoice, or, calculating the shoppingCart's total price based of its product objects.
More broad and complicated workflows which are called business processes, like controlling the registration process for the student (which usually includes several steps and needs different checks and has more complicated constraints).
The first category goes into model and the second one belongs to controller. This is because the cases in the second category are broad application logics and putting them in the model may mix the model's abstraction (for example, it is not clear if we need to put those decisions in one model class or another, since they are related to both!).
See this answer for a specific distinction between model and controller, this link for very exact definitions and also this link for a nice Android example.
The point is that the notes mentioned by "Mud" and "Frank" above both can be true as well as "Pete"'s (business logic can be put in model, or controller, according to the type of business logic).
Finally, note that MVC differs from context to context. For example, in Android applications, some alternative definitions are suggested that differs from web-based ones (see this post for example).
Q2:
Business logic is more general and (as "decyclone" mentioned above) we have the following relation between them:
business rules ? business logics
However, if your website does not have a security certificate, it's on a shared hosting environment, and you don't want to get the "warning" when your website is being requested through https, you can't redirect it using htaccess. The reason is that the warning message gets triggered before the request even goes through to the htaccess file, so you have to fix it on the server. Go to /etc/httpd/conf.d/ssl.conf and comment out the part about the virtual server 443. But the odds are that your hosting provider won't give you that much control. So you would have to either move to a different host or buy the SSL just so the warning does not trigger before your htaccess has a chance to redirect.
let firstname = "paresh"
let lastname = "hirpara"
let itsme = "\(firstname) \(lastname)"
Yet another way to execute it (this time without setting execute permissions):
bash /path/to/scriptname
An easier option may be to log the POST data before it gets to the server. For web applications, I use Burp Proxy and set Firefox to use it as an HTTP/S proxy, and then I can watch (and mangle) data 'on the wire' in real time.
For making API requests without a browser, SoapUI is very useful and may show similar info. I would bet that you could probably configure SoapUI to connect through Burp as well (just a guess though).
There are available Extension methods to parse them into other primitive types.
"10".toInt()
"10".toLong()
"true".toBoolean()
"10.0".toFloat()
"10.0".toDouble()
"10".toByte()
"10".toShort()
String num = "10";
Integer.parseInt(num );
The data series names are defined by the column headers. Add the names to the column headers that you would like to use as titles for each of your data series, select all of the data (including the headers), then re-generate your graph. The names in the headers should then appear as the names in the legend for each series.
You can not sort TreeMap on values.
A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used You will need to provide
comparator
forComparator<? super K>
so your comparator should compare on keys.
To provide sort on values you will need SortedSet. Use
SortedSet<Map.Entry<String, Double>> sortedset = new TreeSet<Map.Entry<String, Double>>(
new Comparator<Map.Entry<String, Double>>() {
@Override
public int compare(Map.Entry<String, Double> e1,
Map.Entry<String, Double> e2) {
return e1.getValue().compareTo(e2.getValue());
}
});
sortedset.addAll(myMap.entrySet());
To give you an example
SortedMap<String, Double> myMap = new TreeMap<String, Double>();
myMap.put("a", 10.0);
myMap.put("b", 9.0);
myMap.put("c", 11.0);
myMap.put("d", 2.0);
sortedset.addAll(myMap.entrySet());
System.out.println(sortedset);
Output:
[d=2.0, b=9.0, a=10.0, c=11.0]
(Windows 10 pro x64) Here have some ways!
Alt + click
Alt + Ctrl + up/down
Keybindings: Ctrl + click
(??? it doesn't work!)
This method opens a file in the private data area of the application. You cannot open any files in subdirectories in this area or from entirely other areas using this method. So use the constructor of the FileInputStream
directly to pass the path with a directory in it.
@RequestParam
is the HTTP GET
or POST
parameter sent by client, request mapping is a segment of URL which's variable:
http:/host/form_edit?param1=val1¶m2=val2
var1
& var2
are request params.
http:/host/form/{params}
{params}
is a request mapping. you could call your service like : http:/host/form/user
or http:/host/form/firm
where firm & user are used as Pathvariable
.
It is a pointer to a pointer, so yes, in a way it's a 2D character array. In the same way that a char*
could indicate an array of char
s, a char**
could indicate that it points to and array of char*
s.
I think that maybe it is because you are declaring a variable that you already declared:
var Name = new Array(6);
//...
var Name[0] = Name_cell.getValue(); // <-- Here's the issue: 'var'
I think this should be like this:
var Name = new Array(6);
//...
Name[0] = Name_cell.getValue();
Tell me if it works! ;)
Call myTextInputLayout.setError()
instead of myEditText.setError()
.
These container and containment have double functionality on setting errors. Functionality you need is container's one. But you could require minimal version of 23 for that.
In general, the key to avoiding an explicit loop would be to join (merge) 2 instances of the dataframe on rowindex-1==rowindex.
Then you would have a big dataframe containing rows of r and r-1, from where you could do a df.apply() function.
However the overhead of creating the large dataset may offset the benefits of parallel processing...
Timings for Python 3.6 for extracting the second element from a 2-tuple list.
Also, added numpy
array method, which is simpler to read (but arguably simpler than the list comprehension).
from operator import itemgetter
elements = [(1,1) for _ in range(100000)]
%timeit second = [x[1] for x in elements]
%timeit second = list(map(itemgetter(1), elements))
%timeit second = dict(elements).values()
%timeit second = list(zip(*elements))[1]
%timeit second = np.array(elements)[:,1]
and the timings:
list comprehension: 4.73 ms ± 206 µs per loop
list(map): 5.3 ms ± 167 µs per loop
dict: 2.25 ms ± 103 µs per loop
list(zip) 5.2 ms ± 252 µs per loop
numpy array: 28.7 ms ± 1.88 ms per loop
Note that map()
and zip()
do not return a list anymore, hence the explicit conversion.
HttpClient was deprecated in Android 5.1 and is removed from the Android SDK in Android 6.0. While there is a workaround to continue using HttpClient in Android 6.0 with Android Studio, you really need to move to something else. That "something else" could be:
HttpUrlConnection
Or, depending upon the nature of your HTTP work, you might choose a library that supports higher-order operations (e.g., Retrofit for Web service APIs).
In a pinch, you could enable the legacy APIs, by having useLibrary 'org.apache.http.legacy'
in your android
closure in your module's build.gradle
file. However, Google has been advising people for years to stop using Android's built-in HttpClient, and so at most, this should be a stop-gap move, while you work on a more permanent shift to another API.
func Ternary(statement bool, a, b interface{}) interface{} {
if statement {
return a
}
return b
}
func Abs(n int) int {
return Ternary(n >= 0, n, -n).(int)
}
This will not outperform if/else and requires cast but works. FYI:
BenchmarkAbsTernary-8 100000000 18.8 ns/op
BenchmarkAbsIfElse-8 2000000000 0.27 ns/op
Simple install with NVM...
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
. ~/.nvm/nvm.sh
nvm install node
To install a certain version (such as 12.16.3) of Node change the last line to
nvm install 12.16.3
For more information about how to use NVM visit the docs: https://github.com/nvm-sh/nvm
Put this in the HTML head section, setting the url
var to the URL of the file to be downloaded:
<script type="text/javascript">
function startDownload()
{
var url='http://server/folder/file.ext';
window.open(url, 'Download');
}
</script>
Then put this in the body, which will start the download automatically after 5 seconds:
<script type="text/javascript">
setTimeout('startDownload()', 5000); //starts download after 5 seconds
</script>
(From here.)
In your expected output, you've got the second last row sum incorrect, it should be 40 according to the data in your tables, but here is the query:
Select ChargeNum, CategoryId, Sum(Hours)
From (
Select ChargeNum, CategoryId, Hours
From KnownHours
Union
Select ChargeNum, 'Unknown' As CategoryId, Hours
From UnknownHours
) As a
Group By ChargeNum, CategoryId
Order By ChargeNum, CategoryId
And here is the output:
ChargeNum CategoryId
---------- ---------- ----------------------
111111 1 40
111111 2 50
111111 Unknown 70
222222 1 40
222222 Unknown 25.5
Click on the Project in Visual Studio and then click on the button titled "Show all files" on the Solution Explorer toolbar. That will show files that aren't in the project. Now you'll see that image, right click in it, and select "Include in project" and that will add the image to the project!
The short answer is "you can't". What you'll need to do is either use a subquery or you could convert your existing stored procedure in to a table function. Creating it as function would depend on how "reusable" you would need it to be.
I received the same error when cloning an HTML element for use in a form.
(I have a partially complete form, which has a template injected into it, and then the template is modified)
The error was referencing the original field, and not the cloned version.
I couldn't find any methods that would force the form to re-evaluate itself (in the hope it would get rid of any references to the old fields that now don't exist) before running the validation.
In order to get around this issue, I removed the required attribute from the original element and dynamically added it to the cloned field before injecting it into the form. The form now validates the cloned and modified fields correctly.
In the completion handler with argument response
below I find the http status code is in response.response.statusCode
:
Alamofire.request(.POST, urlString, parameters: parameters)
.responseJSON(completionHandler: {response in
switch(response.result) {
case .Success(let JSON):
// Yeah! Hand response
case .Failure(let error):
let message : String
if let httpStatusCode = response.response?.statusCode {
switch(httpStatusCode) {
case 400:
message = "Username or password not provided."
case 401:
message = "Incorrect password for user '\(name)'."
...
}
} else {
message = error.localizedDescription
}
// display alert with error message
}
Use org.openide.util.Lookup and ClassLoader to dynamically load the Jar plugin, as shown here.
public LoadEngine() {
Lookup ocrengineLookup;
Collection<OCREngine> ocrengines;
Template ocrengineTemplate;
Result ocrengineResults;
try {
//ocrengineLookup = Lookup.getDefault(); this only load OCREngine in classpath of application
ocrengineLookup = Lookups.metaInfServices(getClassLoaderForExtraModule());//this load the OCREngine in the extra module as well
ocrengineTemplate = new Template(OCREngine.class);
ocrengineResults = ocrengineLookup.lookup(ocrengineTemplate);
ocrengines = ocrengineResults.allInstances();//all OCREngines must implement the defined interface in OCREngine. Reference to guideline of implement org.openide.util.Lookup for more information
} catch (Exception ex) {
}
}
public ClassLoader getClassLoaderForExtraModule() throws IOException {
List<URL> urls = new ArrayList<URL>(5);
//foreach( filepath: external file *.JAR) with each external file *.JAR, do as follows
File jar = new File(filepath);
JarFile jf = new JarFile(jar);
urls.add(jar.toURI().toURL());
Manifest mf = jf.getManifest(); // If the jar has a class-path in it's manifest add it's entries
if (mf
!= null) {
String cp =
mf.getMainAttributes().getValue("class-path");
if (cp
!= null) {
for (String cpe : cp.split("\\s+")) {
File lib =
new File(jar.getParentFile(), cpe);
urls.add(lib.toURI().toURL());
}
}
}
ClassLoader cl = ClassLoader.getSystemClassLoader();
if (urls.size() > 0) {
cl = new URLClassLoader(urls.toArray(new URL[urls.size()]), ClassLoader.getSystemClassLoader());
}
return cl;
}
This is what I did:
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
selectedEntry = [allEntries objectAtIndex:row];
}
The selectedEntry
is a NSString
and will hold the currently selected entry in the pickerview. I am new to objective C but I think this is much easier.
You need to set ulimit -c
. If you have 0 for this parameter a coredump file is not created. So do this: ulimit -c unlimited
and check if everything is correct ulimit -a
. The coredump file is created when an application has done for example something inappropriate. The name of the file on my system is core.<process-pid-here>
.
import json
def is_json(myjson):
try:
json_object = json.loads(myjson)
except ValueError as e:
return False
return True
Which prints:
print is_json("{}") #prints True
print is_json("{asdf}") #prints False
print is_json('{ "age":100}') #prints True
print is_json("{'age':100 }") #prints False
print is_json("{\"age\":100 }") #prints True
print is_json('{"age":100 }') #prints True
print is_json('{"foo":[5,6.8],"foo":"bar"}') #prints True
Convert a JSON string to a Python dictionary:
import json
mydict = json.loads('{"foo":"bar"}')
print(mydict['foo']) #prints bar
mylist = json.loads("[5,6,7]")
print(mylist)
[5, 6, 7]
Convert a python object to JSON string:
foo = {}
foo['gummy'] = 'bear'
print(json.dumps(foo)) #prints {"gummy": "bear"}
If you want access to low-level parsing, don't roll your own, use an existing library: http://www.json.org/
Great tutorial on python JSON module: https://pymotw.com/2/json/
sudo cpan JSON::XS
echo '{"foo":[5,6.8],"foo":"bar" bar}' > myjson.json
json_xs -t none < myjson.json
Prints:
, or } expected while parsing object/hash, at character offset 28 (before "bar}
at /usr/local/bin/json_xs line 183, <STDIN> line 1.
json_xs
is capable of syntax checking, parsing, prittifying, encoding, decoding and more:
The solution is:
Update-Database –TargetMigration 201609261919239_yourLastMigrationSucess
Depending on who you ask, some people report that executing select count(1) from random_table;
runs faster than select count(*) from random_table
. Others claim they are exactly the same.
This link claims that the speed difference between the 2 is due to a FULL TABLE SCAN vs FAST FULL SCAN.
If cars
is a sequence you can just do
for car in cars[1:-1]:
pass
Well, to simply run the code and show the output on the console you can create a task and execute it, pretty much as @canerbalci mentions.
The downside of this is that you will only get the output and thats it.
What I really like to do is to be able to debug the code, lets say Im trying to solve a small algorithm or trying a new ES6 feature, and I run it and there is something fishy with it, I can debug it inside VSC.
So, instead of creating a task for it, I modified the .vscode/launch.json file in this directory as follows:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "node",
"request": "launch",
"program": "${file}",
"stopOnEntry": true,
"args": [],
"cwd": "${fileDirname}",
"runtimeExecutable": null,
"runtimeArgs": [
"--nolazy"
],
"env": {
"NODE_ENV": "development"
},
"externalConsole": false,
"sourceMaps": false,
"outDir": null
}
]
}
What this does is that it will launch whichever file you are currently on, within the debugger of VSC. Its set to stop on start.
To launch it, press F5 key, in the file you want to debug.
Note that this behavior is the default (ANSI) behavior.
If you:
SET ANSI_NULLS OFF
http://msdn.microsoft.com/en-us/library/ms188048.aspx
You'll get different results.
SET ANSI_NULLS OFF
will apparently be going away in the future...
Yes, here is the process:
# Navigate to a directory and initiate a local repository
git init
# Add remote repository to be tracked for changes:
git remote add origin https://github.com/username/repository_name.git
# Track all changes made on above remote repository
# This will show files on remote repository not available on local repository
git fetch
# Add file present in staging area for checkout
git check origin/master -m /path/to/file
# NOTE: /path/to/file is a relative path from repository_name
git add /path/to/file
# Verify track of file(s) being committed to local repository
git status
# Commit to local repository
git commit -m "commit message"
# You may perform a final check of the staging area again with git status
This should resolve your problem: chmod go-w {/path/of/user}
Yes, assuming the account has appropriate permissions you can use:
SELECT <...>
FROM A.table1 t1 JOIN B.table2 t2 ON t2.column2 = t1.column1;
You just need to prefix the table reference with the name of the database it resides in.
If you would like a solution which:
Here is a utility function that I wrote:
public final <T extends Throwable> T expectException( Class<T> exceptionClass, Runnable runnable )
{
try
{
runnable.run();
}
catch( Throwable throwable )
{
if( throwable instanceof AssertionError && throwable.getCause() != null )
throwable = throwable.getCause(); //allows "assert x != null : new IllegalArgumentException();"
assert exceptionClass.isInstance( throwable ) : throwable; //exception of the wrong kind was thrown.
assert throwable.getClass() == exceptionClass : throwable; //exception thrown was a subclass, but not the exact class, expected.
@SuppressWarnings( "unchecked" )
T result = (T)throwable;
return result;
}
assert false; //expected exception was not thrown.
return null; //to keep the compiler happy.
}
Use it as follows:
@Test
public void testThrows()
{
RuntimeException e = expectException( RuntimeException.class, () ->
{
throw new RuntimeException( "fail!" );
} );
assert e.getMessage().equals( "fail!" );
}
Use mod_php7.c instead of mod_php5.c for PHP 7
Example
<IfModule mod_php7.c>
php_value max_execution_time 500
</IfModule>
The problem:
Microsoft Office 2010 products (or later) install updates that break compatibility of MSCOMCTL.ocx and COMCTL32.ocx. Unfortunately this affects many other programs such Visual Basic 6 SP6 and even Oracle Virtual Box v5. The actual problem is HKEY_CLASSES_ROOT\TypeLib\{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}\2.0
registry key. You can find detailed background information about this problem here.
Here is another working solution:
The solution assumes you have not damaged your registry by deleting, replacing and re-registering MSCOMCTL.ocx and COMCTL32.ocx without unregistering the Office patch files.
Create a batch file called fix.cmd and place the following commands in it:
regsvr32 /s /u %windir%\SysWOW64\comctl32.ocx
regsvr32 /s /u %windir%\SysWOW64\mscomctl.ocx
del /y %windir%\SysWOW64\comctl32.ocx
del /y %windir%\SysWOW64\mscomctl.ocx
msiexec /passive /norestart /i KB2708437.msi
msiexec /passive /a KB2708437.msi
regtlib %windir%\SysWOW64\msdatsrc.tlb
Download from Security update for Visual Basic 6.0 Service Pack 6: August 14, 2012 the msi file and rename it to KB2708437.msi.
Note: A direct link to the Service Pack 6 download is located HERE.
Run fix.cmd and the problem will be fixed!
What fix.cmd does is to properly unregister and then delete the current MSCOMCTL.ocx and COMCTL32.ocx files, and then apply the latest Visual Basic 6 SP6 rollup patch. In fact, the script enforces the patch to be installed and then re-installed by updating every file, regardless of version. Finally it registers msdatsrc.tlb type library.
Please let me know if this works for you.
======================================================================
Advanced Solution:
If however you have accidentally damaged your registry, you need to get as many versions of MSCOMCTL.ocx and COMCTL32.ocx you can find. Then you need to start from the newer version going back to the older and register and unregister the ocx files.
The latest version of MSCOMCTL.ocx is 6.1.98.39 (v2.1) of May 2012 which is more likely the one installed on your system and causing all your problems.
The oldest (legacy) version is that shipped with Visual Basic 6 on 1998 6.1.97.82 (v2.0), or the one shipped with an early service pack 6.1.97.86 on April 2005.
Example:
regsvr32 /s comctl32.6.0.98.34.ocx
regsvr32 /s /u comctl32.6.0.98.34.ocx
regsvr32 /s comctl32.6.0.81.6.ocx
regsvr32 /s /u comctl32.6.0.81.6.ocx
regsvr32 /s comctl32.6.0.81.5.ocx
regsvr32 /s /u comctl32.6.0.81.5.ocx
regsvr32 /s mscomctl.6.1.98.39.(2.1).ocx
regsvr32 /s /u mscomctl.6.1.98.39.(2.1).ocx
regsvr32 /s mscomctl.6.1.98.34.ocx
regsvr32 /s /u mscomctl.6.1.98.34.ocx
regsvr32 /s mscomctl.6.1.97.86.ocx
regsvr32 /s /u mscomctl.6.1.97.86.ocx
regsvr32 /s mscomctl.6.1.97.82.(2.0).ocx
regsvr32 /s /u mscomctl.6.1.97.82.(2.0).ocx
regsvr32 /s /u %windir%\SysWOW64\comctl32.ocx
regsvr32 /s /u %windir%\SysWOW64\mscomctl.ocx
del /q %windir%\SysWOW64\comctl32.ocx
del /q %windir%\SysWOW64\mscomctl.ocx
msiexec /passive /norestart /i KB2708437.msi
msiexec /passive /a KB2708437.msi
regtlib %windir%\SysWOW64\msdatsrc.tlb
WARNING:
Do not search the internet for those files. To find different version of the OCX files download and extract official Microsoft Installer packages such as the following:
2012 May - Microsoft KB2708437
It is also recommended to run CCleaner version 4.0 or later to fix any other ActiveX related problems on your computer.
You can do this by adding a div i.e. centerBlock. And give this property in CSS to center the image or any content. Here is the code:
<div class="container">
<div class="row">
<div class="col-sm-4 col-md-4 col-lg-4">
<div class="centerBlock">
<img class="img-responsive" src="img/some-image.png" title="This image needs to be centered">
</div>
</div>
<div class="col-sm-8 col-md-8 col-lg-8">
Some content not important at this moment
</div>
</div>
</div>
// CSS
.centerBlock {
display: table;
margin: auto;
}
ES6 version:
const flatten = (obj, path = '') => {
if (!(obj instanceof Object)) return {[path.replace(/\.$/g, '')]:obj};
return Object.keys(obj).reduce((output, key) => {
return obj instanceof Array ?
{...output, ...flatten(obj[key], path + '[' + key + '].')}:
{...output, ...flatten(obj[key], path + key + '.')};
}, {});
}
Example:
console.log(flatten({a:[{b:["c","d"]}]}));
console.log(flatten([1,[2,[3,4],5],6]));
A possible alternative for that:
Use an encoder (e.g. VLC or FFmpeg) into packetize your input stream to OGG format. For example, in this case I used VLC to packetize screen capture device with this code:
C:\Program Files\VideoLAN\VLC\vlc.exe -I dummy screen:// :screen-fps=16.000000 :screen-caching=100 :sout=#transcode{vcodec=theo,vb=800,scale=1,width=600,height=480,acodec=mp3}:http{mux=ogg,dst=127.0.0.1:8080/desktop.ogg} :no-sout-rtp-sap :no-sout-standard-sap :ttl=1 :sout-keep
Embed this code into a <video>
tag in your HTML page like that:
<video id="video" src="http://localhost:8080/desktop.ogg" autoplay="autoplay" />
This should do the trick. However it's kind of poor performance and AFAIK MP4 container type should have a better support among browsers than OGG.
Use include_once
instead.
This error means that you have already included this file.
include_once(LIB.'/class.php');
If you merged the branch, then reverted the merge using a pull request and merged that pull request to revert.
The easiest way I felt was to:
git revert -m 1 xxxxxx
(if the revert was merged using a branch) or using git revert xxxxxx
if it was a simple revertIf you know you will want all the matches, you could use the re.findall
function. It will return a list of all the matches. Then you can just do len(result)
for the number of matches.
Answer given by Abid Rahman K is not completely correct. I also tried it and found very helpful but got stuck.
This is how I copy image with a given mask.
x, y = np.where(mask!=0)
pts = zip(x, y)
# Assuming dst and src are of same sizes
for pt in pts:
dst[pt] = src[pt]
This is a bit slow but gives correct results.
EDIT:
Pythonic way.
idx = (mask!=0)
dst[idx] = src[idx]
Use .closest()
with a selector:
var $div = $('#divid').closest('div[class^="div-a"]');
Use: LOGGER.log(Level.INFO, "Got an exception.", e);
or LOGGER.info("Got an exception. " + e.getMessage())
;
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int num=sc.nextInt();
System.out.println("Enter a number (-1 to end):"+num);
int result=0;
int i=0;
while(true)
{
int n=num%10;
if(n==-1){
break;
}
i++;
System.out.println("Digit"+i+" = "+n);
result=result*10+n;
num=num/10;
if(num==0)
{
break;
}
}
}
}
# for each file on a directory, rename filename
file_list = os.listdir (r"D:\Dev\Python")
for file_name in file_list:
os.rename(file_name, re.sub(r'\d+','',file_name))
I've tried different solutions. First was:
a_df=np.unique(df[['col1','col2']], axis=0)
and it works well for not object data Another way to do this and to avoid error (for object columns type) is to apply drop_duplicates()
a_df=df.drop_duplicates(['col1','col2'])[['col1','col2']]
You can also use SQL to do this, but it worked very slow in my case:
from pandasql import sqldf
q="""SELECT DISTINCT col1, col2 FROM df;"""
pysqldf = lambda q: sqldf(q, globals())
a_df = pysqldf(q)
This is pretty much as close as you'll get if you want to use the ActionBar
APIs. I'm not sure you can place a colorstrip above the ActionBar
without doing some weird Window
hacking, it's not worth the trouble. As far as changing the MenuItems
goes, you can make those tighter via a style. It would be something like this, but I haven't tested it.
<style name="MyTheme" parent="android:Theme.Holo.Light">
<item name="actionButtonStyle">@style/MyActionButtonStyle</item>
</style>
<style name="MyActionButtonStyle" parent="Widget.ActionButton">
<item name="android:minWidth">28dip</item>
</style>
Here's how to inflate and add the custom layout to your ActionBar
.
// Inflate your custom layout
final ViewGroup actionBarLayout = (ViewGroup) getLayoutInflater().inflate(
R.layout.action_bar,
null);
// Set up your ActionBar
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(actionBarLayout);
// You customization
final int actionBarColor = getResources().getColor(R.color.action_bar);
actionBar.setBackgroundDrawable(new ColorDrawable(actionBarColor));
final Button actionBarTitle = (Button) findViewById(R.id.action_bar_title);
actionBarTitle.setText("Index(2)");
final Button actionBarSent = (Button) findViewById(R.id.action_bar_sent);
actionBarSent.setText("Sent");
final Button actionBarStaff = (Button) findViewById(R.id.action_bar_staff);
actionBarStaff.setText("Staff");
final Button actionBarLocations = (Button) findViewById(R.id.action_bar_locations);
actionBarLocations.setText("HIPPA Locations");
Here's the custom layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false"
android:orientation="horizontal"
android:paddingEnd="8dip" >
<Button
android:id="@+id/action_bar_title"
style="@style/ActionBarButtonWhite" />
<Button
android:id="@+id/action_bar_sent"
style="@style/ActionBarButtonOffWhite" />
<Button
android:id="@+id/action_bar_staff"
style="@style/ActionBarButtonOffWhite" />
<Button
android:id="@+id/action_bar_locations"
style="@style/ActionBarButtonOffWhite" />
</LinearLayout>
Here's the color strip layout: To use it, just use merge
in whatever layout you inflate in setContentView
.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/colorstrip"
android:background="@android:color/holo_blue_dark" />
Here are the Button
styles:
<style name="ActionBarButton">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:background">@null</item>
<item name="android:ellipsize">end</item>
<item name="android:singleLine">true</item>
<item name="android:textSize">@dimen/text_size_small</item>
</style>
<style name="ActionBarButtonWhite" parent="@style/ActionBarButton">
<item name="android:textColor">@color/white</item>
</style>
<style name="ActionBarButtonOffWhite" parent="@style/ActionBarButton">
<item name="android:textColor">@color/off_white</item>
</style>
Here are the colors and dimensions I used:
<color name="action_bar">#ff0d0d0d</color>
<color name="white">#ffffffff</color>
<color name="off_white">#99ffffff</color>
<!-- Text sizes -->
<dimen name="text_size_small">14.0sp</dimen>
<dimen name="text_size_medium">16.0sp</dimen>
<!-- ActionBar color strip -->
<dimen name="colorstrip">5dp</dimen>
If you want to customize it more than this, you may consider not using the ActionBar
at all, but I wouldn't recommend that. You may also consider reading through the Android Design Guidelines to get a better idea on how to design your ActionBar.
If you choose to forgo the ActionBar
and use your own layout instead, you should be sure to add action-able Toasts
when users long press your "MenuItems". This can be easily achieved using this Gist.
The fast-csv npm module can read data line-by-line from csv file.
Here is an example:
let csv= require('fast-csv');
var stream = fs.createReadStream("my.csv");
csv
.parseStream(stream, {headers : true})
.on("data", function(data){
console.log('I am one line of data', data);
})
.on("end", function(){
console.log("done");
});
I found a not-very-intuitive way to do this by using DUMP()
SELECT DUMP(A.NAME),
DUMP(A.surname),
DUMP(B.ordernum)
FROM customer A
JOIN orders B
ON A.id = B.id
It will return something like:
'Typ=1 Len=2: 0,48'
for each column.
Type=1
means VARCHAR2/NVARCHAR2
Type=2
means NUMBER/FLOAT
Type=12
means DATE
, etc.
You can refer to this oracle doc for information Datatype Code
or this for a simple mapping Oracle Type Code Mappings
I 2nd Chad Grant's answer and also submit this blog article [removed dead link] for your viewing pleasure.
... on a Mac, Preferences' is under the main 'Aptana Studio 3' menu rather than the 'Windows' menu as mentioned above.
Your problem is basically that you never specified the right path to the file.
Try instead, from your main script:
from folder.file import Klasa
Or, with from folder import file
:
from folder import file
k = file.Klasa()
Or again:
import folder.file as myModule
k = myModule.Klasa()
The recommended way is to let str.format
handle the casting (docs). Methods with %s
substitution may be deprecated eventually (see PEP3101).
>>> answer = True
>>> myvar = "the answer is {}".format(answer)
>>> print(myvar)
the answer is True
In Python 3.6+ you may use literal string interpolation:
>>> print(f"the answer is {answer}")
the answer is True
<gradient
android:centerColor="#c1c1c1"
android:endColor="#4f4f4f"
android:gradientRadius="400"
android:startColor="#c1c1c1"
android:type="radial" >
</gradient>
Invoking an empty time.Time
struct literal will return Go's zero date. Thus, for the following print statement:
fmt.Println(time.Time{})
The output is:
0001-01-01 00:00:00 +0000 UTC
For the sake of completeness, the official documentation explicitly states:
The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC.
like this?
<?php
$url_endpoint = get_permalink();
$url_endpoint = parse_url( $url_endpoint );
$url_endpoint = $url_endpoint['path'];
header('Location: http://linkhere.com/'. $url_endpoint);
?>
Adding to Brian Agnew's answer.
You can also do //div[@id='..' or @class='...]
and you can have parenthesized expressions inside //div[@id='..' and (@class='a' or @class='b')]
.
This should work.
if (rsData["usr.ursrdaystime"] != System.DBNull.Value))
{
strLevel = rsData["usr.ursrdaystime"].ToString();
}
also need to add using statement, like bellow:
using (var objConn = new SqlConnection(strConnection))
{
objConn.Open();
using (var objCmd = new SqlCommand(strSQL, objConn))
{
using (var rsData = objCmd.ExecuteReader())
{
while (rsData.Read())
{
if (rsData["usr.ursrdaystime"] != System.DBNull.Value)
{
strLevel = rsData["usr.ursrdaystime"].ToString();
}
}
}
}
}
this'll automaticly dispose (close) resources outside of block { .. }.
You can using the socket module to simply check if a port is open or not.
It would look something like this.
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('127.0.0.1',80))
if result == 0:
print "Port is open"
else:
print "Port is not open"
sock.close()
The nextInt()
method leaves the \n
(end line) symbol and is picked up immediately by nextLine()
, skipping over the next input. What you want to do is use nextLine()
for everything, and parse it later:
String nextIntString = keyboard.nextLine(); //get the number as a single line
int nextInt = Integer.parseInt(nextIntString); //convert the string to an int
This is by far the easiest way to avoid problems--don't mix your "next" methods. Use only nextLine()
and then parse int
s or separate words afterwards.
Also, make sure you use only one Scanner
if your are only using one terminal for input. That could be another reason for the exception.
Last note: compare a String
with the .equals()
function, not the ==
operator.
if (playAgain == "yes"); // Causes problems
if (playAgain.equals("yes")); // Works every time
if you want to do very quick plots with secondary Y-Axis then there is much easier way using Pandas wrapper function and just 2 lines of code. Just plot your first column then plot the second but with parameter secondary_y=True
, like this:
df.A.plot(label="Points", legend=True)
df.B.plot(secondary_y=True, label="Comments", legend=True)
This would look something like below:
You can do few more things as well. Take a look at Pandas plotting doc.
There is no options in javascript to find the height of a cross domain iframe height but you can done something like this with the help of some server side programming. I used PHP for this example
<code>
<?php
$output = file_get_contents('http://yourdomain.com');
?>
<div id='iframediv'>
<?php echo $output; ?>
</div>
<iframe style='display:none' id='iframe' src="http://yourdomain.com" width="100%" marginwidth="0" height="100%" marginheight="0" align="top" scrolling="auto" frameborder="0" hspace="0" vspace="0"> </iframe>
<script>
if(window.attachEvent) {
window.attachEvent('onload', iframeResizer);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function(evt) {
curronload(evt);
iframeResizer(evt);
};
window.onload = newonload;
} else {
window.onload = iframeResizer;
}
}
function iframeResizer(){
var result = document.getElementById("iframediv").offsetHeight;
document.getElementById("iframe").style.height = result;
document.getElementById("iframediv").style.display = 'none';
document.getElementById("iframe").style.display = 'inline';
}
</script>
</code>
Html::activeDropDownList($model, 'id', ArrayHelper::map(AttendanceLabel::find()->all(), 'id', 'label_name'), ['prompt'=>'Attendance Status'] );
So the simplest way is,
alter table table_name change column_name column_name int(11) NULL;
You could do this:
let thirtyMinutes = 30 * 60 * 1000; // convert 30 minutes to milliseconds_x000D_
let date1 = new Date();_x000D_
let date2 = new Date(date1.getTime() + thirtyMinutes);_x000D_
console.log(date1);_x000D_
console.log(date2);
_x000D_
For versions of data.table >= 1.9.8
, the following all just work:
library(data.table)
dt <- data.table(a = 1, b = 2, c = 3)
# select single column by index
dt[, 2]
# b
# 1: 2
# select multiple columns by index
dt[, 2:3]
# b c
# 1: 2 3
# select single column by name
dt[, "a"]
# a
# 1: 1
# select multiple columns by name
dt[, c("a", "b")]
# a b
# 1: 1 2
For versions of data.table < 1.9.8
(for which numerical column selection required the use of with = FALSE
), see this previous version of this answer. See also NEWS on v1.9.8, POTENTIALLY BREAKING CHANGES, point 3.
Many answers still use getNetworkType below 23 which is deprecated; use below code to check if the device has an internet connection.
public static boolean isNetworkConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
return capabilities != null && (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR));
} else {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnected();
}
}
return false;
}
..
And, do not forget to add this line in Manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Use the @RequestParam to pass a parameter to the controller handler method.
In the jsp your form should have an input field with name = "id"
like the following:
<input type="text" name="id" />
<input type="submit" />
Then in your controller, your handler method should be like the following:
@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
Person person = personService.getCurrentlyAuthenticatedUser();
model.addAttribute("person", new Person());
model.addAttribute("listPersons", this.personService.listPersons());
model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
return "note";
}
Please also refer to these answers and tutorial:
This gives us the names of columns in a list:
list(my_dataframe.columns)
Another function called tolist() can be used too:
my_dataframe.columns.tolist()
Solution in Android Java:
Start your EditText, the ID is come to your xml id.
EditText myText = (EditText)findViewById(R.id.my_text_id);
in your OnCreate Method, just set the text by the name defined.
String text = "here put the text that you want"
use setText method from your editText.
myText.setText(text); //variable from point 2
I've had success building iOS apps on linux using the iOS clang toolchain by cjacker. Basically it consists of the upstream clang and llvm tools from your linux distro, a linux port of apple's linker and some extra tools to help simplify the build process (such as converting xcode projects to Makefile format).
It does take a few steps to install, but you're a software developer so you'd be used to that. I posted an up to date howto for Debian 7 (Wheezy) online:
https://rogerkeays.com/how-to-build-an-ios-toolchain-for-linux-debian-7
Otherwise you want to go with the generic instructions which are a little older:
http://code.google.com/p/ios-toolchain-based-on-clang-for-linux/wiki/HowTo_en
Good luck.
Assuming WinForms, the ForeColor property allows to change all the text in the TextBox
(not just what you're about to add):
TextBox.ForeColor = Color.Red;
To only change the color of certain words, look at RichTextBox.
When you cherry-pick, it creates a new commit with a new SHA. If you do:
git cherry-pick -x <sha>
then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.
const getRandomNo = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
This function returns a random integer between the specified values. The value is no lower than min (or the next integer greater than min if min isn't an integer) and is less than (but not equal to) max. Example
console.log(`Random no between 0 and 10 ${getRandomNo(0,10)}`)
just declare the public
timestamps variable in your Model
to false
and everything will work great.
public $timestamps = false;
On Fedora, this works:
yum install lapack lapack-devel blas blas-devel
pip install numpy
pip install scipy
Remember to install 'lapack-devel' and 'blas-devel' in addition to 'blas' and 'lapack' otherwise you'll get the error you mentioned or the "numpy.distutils.system_info.LapackNotFoundError" error.
The crontab website gives the real time results display: https://crontab.guru/#5_8_*_*_0
Use DATE_FORMAT()
SELECT
DATE_FORMAT(NOW(), '%d %m %Y') AS your_date;
We need to put some kind of control that can wrap text like textblock/textbox
<Label Width="120" Height="100" >
<TextBlock TextWrapping="Wrap">
this is a very long text inside a textblock and this needs to be on multiline.
</TextBlock>
</Label>
I used this in my code:
<div class="sticky-top h-100">
<nav id="sidebar" class="vh-100">
....
this cause your sidebar height become 100% and fixed at top.
Simpler with the ANY
construct:
SELECT value_variable = ANY ('{1,2,3}'::int[])
The right operand of ANY
(between parentheses) can either be a set (result of a subquery, for instance) or an array. There are several ways to use it:
Important difference: Array operators (<@
, @>
, &&
et al.) expect array types as operands and support GIN or GiST indices in the standard distribution of PostgreSQL, while the ANY
construct expects an element type as left operand and does not support these indices. Example:
None of this works for NULL
elements. To test for NULL
:
Sure you know, but if its a constant then const MyVariable as Integer = 123
otherwise your out of luck; the variable must be assigned an initial value elsewhere.
You could:
public property get myIntegerThing() as integer
myIntegerThing= 123
end property
In a Class module then globally create it;
public cMyStuff as new MyStuffClass
So cMyStuff.myIntegerThing
is available immediately.
import csv
from sys import argv
d = open("mydata.csv", "r")
db = []
for line in csv.reader(d):
db.append(line)
# the rest of your code with 'db' filled with your list of lists as rows and columbs of your csv file.
I have a similar solution to the above and it works for opening, saving, file selecting. I paste it into its own module and use in all the Access DB's I create. As the code states it requires Microsoft Office 14.0 Object Library. Just another option I suppose:
Public Function Select_File(InitPath, ActionType, FileType)
' Requires reference to Microsoft Office 14.0 Object Library.
Dim fDialog As Office.FileDialog
Dim varFile As Variant
If ActionType = "FilePicker" Then
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
' Set up the File Dialog.
End If
If ActionType = "SaveAs" Then
Set fDialog = Application.FileDialog(msoFileDialogSaveAs)
End If
If ActionType = "Open" Then
Set fDialog = Application.FileDialog(msoFileDialogOpen)
End If
With fDialog
.AllowMultiSelect = False
' Disallow user to make multiple selections in dialog box
.Title = "Please specify the file to save/open..."
' Set the title of the dialog box.
If ActionType <> "SaveAs" Then
.Filters.Clear
' Clear out the current filters, and add our own.
.Filters.Add FileType, "*." & FileType
End If
.InitialFileName = InitPath
' Show the dialog box. If the .Show method returns True, the
' user picked a file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
'Loop through each file selected and add it to our list box.
For Each varFile In .SelectedItems
'return the subroutine value as the file path & name selected
Select_File = varFile
Next
End If
End With
End Function
If I have to do this, I will simply create a schema sql of current db, then drop & create db, then load db with schema sql.
Below are the steps involved:
1) Create Schema dump of database (--schema-only
)
pg_dump mydb -s > schema.sql
2) Drop database
drop database mydb;
3) Create Database
create database mydb;
4) Import Schema
psql mydb < schema.sql
Actually you can use,
BigInteger sum= new BigInteger("12345");
for creating object for BigInteger class.But the problem here is,you cannot give a variable in the double quotes.So we have to use the valueOf() method and we have to store the answer in that sum again.So we will write,
sum= sum.add(BigInteger.valueOf(i));
Have you tried this?
$('.myClass, .myOtherClass').removeClass('theclass');
In Safari, you can use synchronous requests to avoid the browser to display the popup. Of course, synchronous requests should only be used in this case to check user credentials... You can use a such request before sending the actual request which may cause a bad user experience if the content (sent or received) is quite heavy.
var xmlhttp=new XMLHttpRequest;
xmlhttp.withCredentials=true;
xmlhttp.open("POST",<YOUR UR>,false,username,password);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
In my case the problem was that ANDROID_HOME was pointing to ~/Library/Android/
for some reason.
The correct path is ~/Library/Android/sdk
That's because the response from chrome.runtime.sendMessage
is asynchronous; here's the order of operations:
var newDeals = [];
// (1) first chrome.runtime.sendMessage is called, and *registers a callback*
// so that when the data comes back *in the future*
// the function will be called
chrome.runtime.sendMessage({...}, function(deals) {
// (3) sometime in the future, this function runs,
// but it's too late
newDeals = deals;
});
// (2) this is called immediately, `newDeals` is an empty array
this.setState({ deals: newDeals });
When you pause the script with the debugger, you're giving the extension time to call the callback; by the time you continue, the data has arrived and it appears to work.
To fix, you want to do the setState
call after the data comes back from the Chrome extension:
var newDeals = [];
// (1) first chrome.runtime.sendMessage is called, and *registers a callback*
// so that when the data comes back *in the future*
// the function will be called
chrome.runtime.sendMessage({...}, function(deals) {
// (2) sometime in the future, this function runs
newDeals = deals;
// (3) now you can call `setState` with the data
this.setState({ deals: newDeals });
}.bind(this)); // Don't forget to bind(this) (or use an arrow function)
[Edit]
If this doesn't work for you, check out the other answers on this question, which explain other reasons your component might not be updating.
I've looked for different libraries like Jepp or Jython, but most seem to be very out of date.
Jython is not "a library"; it's an implementation of the Python language on top of the Java Virtual Machine. It is definitely not out of date; the most recent release was Feb. 24 of this year. It implements Python 2.5, which means you will be missing a couple of more recent features, but it is honestly not much different from 2.7.
Note: the actual communication between Java and Python is not a requirement of the aforementioned assignment, so this isn't doing my homework for me. This is, however, the only way I can think of to easily perform what needs to be done.
This seems extremely unlikely for a school assignment. Please tell us more about what you're really trying to do. Usually, school assignments specify exactly what languages you'll be using for what, and I've never heard of one that involved more than one language at all. If it did, they'd tell you if you needed to set up this kind of communication, and how they intended you to do it.
Chrome Developer Tools has an Audits tab which can show unused CSS selectors.
Run an audit, then, under Web Page Performance see Remove unused CSS rules
python 3.2
with open("d://test.txt") as f:
k=(((i.split("\n"))[0].rstrip()).split() for i in f.readlines())
d={}
for i,_,v in k:
d.setdefault(i,[]).append(v)
Select the Object -> Format -> Selection Pane -> Double click to change the name
DELETE FROM table1
where id IN
(SELECT id FROM table2..INNER JOIN..INNER JOIN WHERE etc)
Minimize use of DML queries with Joins. You should be able to do most of all DML queries with subqueries like above.
In general, joins should only be used when you need to SELECT or GROUP by columns in 2 or more tables. If you're only touching multiple tables to define a population, use subqueries. For DELETE queries, use correlated subquery.
Make sure you have enabled USB debugging on your device
Depending on the version of Android you're using, proceed as follows:
Return to the main Settings menu to find Developer options at the bottom. In the Developer options menu, scroll down and enable USB debugging.
I found the error because i was new to git you must check whether you have entered the correct syntax
i made a mistake and wrote
git commit
and got the same error
use
git commit -m 'some comment'
and you wont be seeing the page with
Here is an easy solution of customized Laravel pagination both server and client side code is included.
Assuming using Laravel 5.2 and the following included view:
@include('pagination.default', ['pager' => $data])
Features
default.blade.php
@if ($paginator->last_page > 1)
<ul class="pagination pg-blue">
<li class="page-item {{($paginator->current_page == 1)?'disabled':''}}">
<a class="page-link" tabindex="-1" href="{{ '/locate-vendor/'}}{{ substr($paginator->prev_page_url,7) }}">
Previous
</a>
</li>
<li class="page-item {{($paginator->current_page == 1)?'disabled':''}}">
<a class="page-link" tabindex="-1" href="{{ '/locate-vendor/1'}}">
First
</a>
</li>
@if ( $paginator->current_page > 5 )
<li class="page-item">
<a class="page-link" tabindex="-1">...</a>
</li>
@endif
@for ($i = 1; $i <= $paginator->last_page; $i++)
@if ( ($i > ($paginator->current_page - 5)) && ($i < ($paginator->current_page + 5)) )
<li class="page-item {{($paginator->current_page == $i)?'active':''}}">
<a class="page-link" href="{{'/locate-vendor/'}}{{$i}}">{{$i}}</a>
</li>
@endif
@endfor
@if ( $paginator->current_page < ($paginator->last_page - 4) )
<li class="page-item">
<a class="page-link" tabindex="-1">...</a>
</li>
@endif
<li class="page-item {{($paginator->current_page==$paginator->last_page)?'disabled':''}}">
<a class="page-link" href="{{'/locate-vendor/'}}{{$paginator->last_page}}">
Last
</a>
</li>
<li class="page-item {{($paginator->current_page==$paginator->last_page)?'disabled':''}}">
<a class="page-link" href="{{'/locate-vendor/'}}{{substr($paginator->next_page_url,7)}}">
Next
</a>
</li>
</ul>
@endif
Server Side Controller Function
public function getVendors (Request $request)
{
$inputs = $request->except('token');
$perPage = (isset($inputs['per_page']) && $inputs['per_page']>0)?$inputs['per_page']:$this->perPage;
$currentPage = (isset($inputs['page']) && $inputs['page']>0)?$inputs['page']:$this->page;
$slice_init = ($currentPage == 1)?0:(($currentPage*$perPage)-$perPage);
$totalVendors = DB::table('client_broker')
->whereIn('client_broker_type_id', [1, 2])
->where('status_id', '1')
->whereNotNull('client_broker_company_name')
->whereNotNull('client_broker_email')
->select('client_broker_id', 'client_broker_company_name','client_broker_email')
->distinct()
->count();
$vendors = DB::table('client_broker')
->whereIn('client_broker_type_id', [1, 2])
->where('status_id', '1')
->whereNotNull('client_broker_company_name')
->whereNotNull('client_broker_email')
->select('client_broker_id', 'client_broker_company_name','client_broker_email')
->distinct()
->skip($slice_init)
->take($perPage)
->get();
$vendors = new LengthAwarePaginator($vendors, $totalVendors, $perPage, $currentPage);
if ($totalVendors) {
$response = ['status' => 1, 'totalVendors' => $totalVendors, 'pageLimit'=>$perPage, 'data' => $vendors, 'Message' => 'Vendors Details Found.'];
} else {
$response = ['status' => 0, 'totalVendors' => 0, 'data' => [], 'pageLimit'=>'', 'Message' => 'Vendors Details not Found.'];
}
return response()->json($response, 200);
}
this way work properly and I used it in many projects! for example I get data of views the last 30 days:
$viewsData = DB::table('page_views')
->where('page_id', $page->id)
->whereDate('created_at', '>=', now()->subDays(30))
->select(DB::raw('DATE(created_at) as data'), DB::raw('count(*) as views'))
->groupBy('date')
->get();
If you want to get the number of views based on different IPs, you can use the DISTINCT
like below :
$viewsData = DB::table('page_views')
->where('page_id', $page->id)
->whereDate('created_at', '>=', now()->subDays(30))
->select(DB::raw('DATE(created_at) as data'), DB::raw('count(DISTINCT user_ip) as visitors'))
->groupBy('date')
->get();
You can easily customize it by manipulating the columns name
Today, 2020 year, I've solved this problem with Xcode 11.7, Xcode 12.0 and Xcode 12.1 following these steps:
If it's messed up then the "When using this certificate" is set to "Always Trust" along with the blue +
Problem should have gone away. If that didn't work then go back to Keychain and just double check and see if there are any other Apple certificates that are set to Always Trust and repeat the process.
If you want to remove a particular directory from the rule (meaning, you want to remove the directory foo) ,you can use :
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/foo/$
RewriteRule !index\.php$ /index.php [L]
The rewriteRule above will rewrite all requestes to /index.php excluding requests for /foo/ .
To exclude all existent directries, you will need to use the following condition above your rule :
RewriteCond %{REQUEST_FILENAME} !-d
the following rule
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !index\.php$ /index.php [L]
rewrites everything (except directries) to /index.php .
For scripting purposes, I've found that curl
command can do it, for example:
$ curl -s localhost:80 >/dev/null && echo Connected. || echo Fail.
Connected.
$ curl -s localhost:123 >/dev/null && echo Connected. || echo Fail.
Fail.
Possibly it may not won't work for all services, as curl
can return different error codes in some cases (as per comment), so adding the following condition could work in reliable way:
[ "$(curl -sm5 localhost:8080 >/dev/null; echo $?)" != 7 ] && echo OK || echo FAIL
Note: Added -m5
to set maximum connect timeout of 5 seconds.
If you would like to check also whether host is valid, you need to check for 6
exit code as well:
$ curl -m5 foo:123; [ $? != 6 -a $? != 7 ] && echo OK || echo FAIL
curl: (6) Could not resolve host: foo
FAIL
To troubleshoot the returned error code, simply run: curl host:port
, e.g.:
$ curl localhost:80
curl: (7) Failed to connect to localhost port 80: Connection refused
See: man curl
for full list of exit codes.