This code may help you:
double d = double.Parse(input_value);
string output= d.ToString("F2", CultureInfo.InvariantCulture) + "%";
More general sorted, where the key
keyword defines the sorting method, minus before numerical type indicates descending:
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> sorted(x.items(), key=lambda k: -k[1]) # Ascending
[('c', 7), ('a', 5), ('b', 3)]
I've always used .place()
for my tkinter widgets.
place syntax
You can specify the size of it just by changing the keyword arguments!
Of course, you will have to call .place()
again if you want to change it.
Works in python 3.8.2, if you're wondering.
1.this is my answer for your problem.
.ModalCarrot::before {
content:'';
background: url('blackCarrot.png'); /*url of image*/
height: 16px; /*height of image*/
width: 33px; /*width of image*/
position: absolute;
}
Chrome appears to have bug renegotiating the device authentication. You can try disabling USB Debugging and enabling it again. Sometimes you'll get a pop-up asking you to trust your computer key again.
Or you can go to your Android SDK and run adb devices
which will force a renegotiation.
After either (or both), Chrome should start working.
try this:
if($('input').attr('readonly') == undefined){
alert("foo");
}
if it is not there it will be undefined
in js
I faced the same issue. Our application running on four application servers and due to invalid schema location mentioned on one of the web service WSDL, hung threads are generated on the servers . The appliucations got down frequently. After corrected the schema Location , the issue got resolved.
Rather give names of the column on which you want to merge:
exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)
It occurred to me that you may have actually be asking how to implement the +
operator for dictionaries, the following seems to work:
>>> class Dict(dict):
... def __add__(self, other):
... copy = self.copy()
... copy.update(other)
... return copy
... def __radd__(self, other):
... copy = other.copy()
... copy.update(self)
... return copy
...
>>> default_data = Dict({'item1': 1, 'item2': 2})
>>> default_data + {'item3': 3}
{'item2': 2, 'item3': 3, 'item1': 1}
>>> {'test1': 1} + Dict(test2=2)
{'test1': 1, 'test2': 2}
Note that this is more overhead then using dict[key] = value
or dict.update()
, so I would recommend against using this solution unless you intend to create a new dictionary anyway.
As you noted, -Dmaven.test.skip=true
skips compiling the tests. More to the point, it skips building the test artifacts. A common practice for large projects is to have testing utilities and base classes shared among modules in the same project.
This is accomplished by having a module require a test-jar
of a previously built module:
<dependency>
<groupId>org.myproject.mygroup</groupId>
<artifactId>common</artifactId>
<version>1.0</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
If -Dmaven.test.skip=true
(or simply -Dmaven.test.skip
) is specified, the test-jar
s aren't built, and any module that relies on them will fail its build.
In contrast, when you use -DskipTests
, Maven does not run the tests, but it does compile them and build the test-jar, making it available for the subsequent modules.
This is by far the best method for most situations:
<pre><code>
code here, escape it yourself.
</code></pre>
I would have up voted the first person who suggested it but I don't have reputation. I felt compelled to say something though for the sake of people trying to find answers on the Internet.
It's not a problem. When you first design your application, you can use the test codes provided by AdMob. These codes work great on your emulators and on real devices. But as soon as you publish your application on Google Play, these codes stop working immediately. You need to make your test devices. https://developers.google.com/admob/android/test-ads
But you can use a life hack to continue using test codes for an already published application. Change the application ID in the build.gradle(android) file to a different name and everything will work. Do not forget to return the old name before publishing the application to the Market.
If you're using Python 3, or appropriate Python 2.x version with from __future__ import print_function
then:
data = [7, 7, 7, 7]
print(*data, sep='')
Otherwise, you'll need to convert to string and print:
print ''.join(map(str, data))
The value of a sticky broadcast is the value that was last broadcast and is currently held in the sticky cache. This is not the value of a broadcast that was received right now. I suppose you can say it is like a browser cookie that you can access at any time. The sticky broadcast is now deprecated, per the docs for sticky broadcast methods (e.g.):
This method was deprecated in API level 21. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.
You can try the following:
function parseBool(val)
{
if ((typeof val === 'string' && (val.toLowerCase() === 'true' || val.toLowerCase() === 'yes')) || val === 1)
return true;
else if ((typeof val === 'string' && (val.toLowerCase() === 'false' || val.toLowerCase() === 'no')) || val === 0)
return false;
return null;
}
If it's a valid value, it returns the equivalent bool value otherwise it returns null.
I would suggest going the lxml route and using xpath.
from lxml import etree
# data is the variable containing the html
data = etree.HTML(data)
anchor = data.xpath('//a[@class="title"]/text()')
I am days into the MVC4 world.
For what its worth, I have a SitesAPIController, and I needed a custom method, that could be called like:
http://localhost:9000/api/SitesAPI/Disposition/0
With different values for the last parameter to get record with different dispositions.
What Finally worked for me was:
The method in the SitesAPIController:
// GET api/SitesAPI/Disposition/1
[ActionName("Disposition")]
[HttpGet]
public Site Disposition(int disposition)
{
Site site = db.Sites.Where(s => s.Disposition == disposition).First();
return site;
}
And this in the WebApiConfig.cs
// this was already there
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// this i added
config.Routes.MapHttpRoute(
name: "Action",
routeTemplate: "api/{controller}/{action}/{disposition}"
);
For as long as I was naming the {disposition} as {id} i was encountering:
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:9000/api/SitesAPI/Disposition/0'.",
"MessageDetail": "No action was found on the controller 'SitesAPI' that matches the request."
}
When I renamed it to {disposition} it started working. So apparently the parameter name is matched with the value in the placeholder.
Feel free to edit this answer to make it more accurate/explanatory.
Try
SELECT * FROM table WHERE arr @> ARRAY['s']::varchar[]
If you want to modify the original array instead of returning a new array, use .push()
...
array1.push.apply(array1, array2);
array1.push.apply(array1, array3);
I used .apply
to push the individual members of arrays 2
and 3
at once.
or...
array1.push.apply(array1, array2.concat(array3));
To deal with large arrays, you can do this in batches.
for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
array1.push.apply(array1, to_add.slice(n, n+300));
}
If you do this a lot, create a method or function to handle it.
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
and use it like this:
array1.pushArrayMembers(array2, array3);
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
value: function() {_x000D_
for (var i = 0; i < arguments.length; i++) {_x000D_
var to_add = arguments[i];_x000D_
for (var n = 0; n < to_add.length; n+=300) {_x000D_
push_apply(this, slice_call(to_add, n, n+300));_x000D_
}_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
CMake 3.X offers a 'clean' target.
cmake --build C:/foo/build/ --target clean
From the CMake docs for 3.0.2:
--clean-first = Build target 'clean' first, then build.
(To clean only, use --target 'clean'.)
There is no cmake clean
in CMake version 2.X
I usually build the project in a single folder like "build". So if I want to make clean
, I can just rm -rf build
.
The "build" folder in the same directory as the root "CMakeLists.txt" is usually a good choice. To build your project, you simply give cmake the location of the CMakeLists.txt as an argument. For example: cd <location-of-cmakelists>/build && cmake ..
. (From @ComicSansMS)
It may be because I'm using Spring 3.1 (instead of Spring 3.0.5 as your question specified), but Steve Eastwood's answer didn't work for me. This solution works for Spring 3.1:
In your spring xml context:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper" ref="jacksonObjectMapper" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="jacksonObjectMapper" class="de.Company.backend.web.CompanyObjectMapper" />
You can use list ?? Enumerable.Empty<Friend>()
, or have FindFriends
return Enumerable.Empty<Friend>()
I checked quite some links for the solution, finally did the below mentioned steps to get it working. I am using Gradle 2.9.
Make the following changes in your build,gradle file :
Mention plugin:
apply plugin: 'eu.appsatori.fatjar'
Provide the Buildscript:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "eu.appsatori:gradle-fatjar-plugin:0.3"
}
}
Provide the Main Class:
fatJar {
classifier 'fat'
manifest {
attributes 'Main-Class': 'my.project.core.MyMainClass'
}
exclude 'META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/*.SF'
}
Create the fatjar:
./gradlew clean fatjar
Run the fatjar from /build/libs/ :
java -jar MyFatJar.jar
You could use simple regex:
var result = fileAsString.replace(/string to be replaced/g, 'replacement');
So...
var fs = require('fs')
fs.readFile(someFile, 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
var result = data.replace(/string to be replaced/g, 'replacement');
fs.writeFile(someFile, result, 'utf8', function (err) {
if (err) return console.log(err);
});
});
Datum = DateTime.Parse(DateTimePicker1.Value.ToString("dd/MM/yyyy"))
A "one liner" (on many line for easy read)) to be put directly into a variable:
var oneMonthAgo = new Date(
new Date().getFullYear(),
new Date().getMonth() - 1,
new Date().getDate()
);
Let Unreal do the job.
Close all, Right click your Project File (.uproject),
"Generate VisualStudio Project Files".
You have to free()
the allocated memory in exact reverse order of how it was allocated using malloc()
.
Note that You should free the memory only after you are done with your usage of the allocated pointers.
memory allocation for 1D arrays:
buffer = malloc(num_items*sizeof(double));
memory deallocation for 1D arrays:
free(buffer);
memory allocation for 2D arrays:
double **cross_norm=(double**)malloc(150 * sizeof(double *));
for(i=0; i<150;i++)
{
cross_norm[i]=(double*)malloc(num_items*sizeof(double));
}
memory deallocation for 2D arrays:
for(i=0; i<150;i++)
{
free(cross_norm[i]);
}
free(cross_norm);
updated() should be what you're looking for:
Called after a data change causes the virtual DOM to be re-rendered and patched.
The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here.
My assumption that this exception usually occurs when Tomcat is improperly closed and still holding the ports. Usually it is enough to kill any process listening to 1099 port. For Window 10:
netstat -aon | find "1099"
taskkill /F /PID $processId
Sure, you can use JS's foreach.
for (var k in result) {
something(result[k])
}
In SQL, this problem could be solved by several methods:
select * from df1 where exists (select * from df2 where df2.user_id = df1.user_id)
union all
select * from df2 where exists (select * from df1 where df1.user_id = df2.user_id)
or join and then unpivot (possible in SQL server)
select
df1.user_id,
c.rating
from df1
inner join df2 on df2.user_i = df1.user_id
outer apply (
select df1.rating union all
select df2.rating
) as c
Second one could be written in pandas with something like:
>>> df1 = pd.DataFrame({"user_id":[1,2,3], "rating":[10, 15, 20]})
>>> df2 = pd.DataFrame({"user_id":[3,4,5], "rating":[30, 35, 40]})
>>>
>>> df4 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df = pd.merge(df1, df2, on='user_id', suffixes=['_1', '_2'])
>>> df3 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df4 = df[['user_id', 'rating_2']].rename(columns={'rating_2':'rating'})
>>> pd.concat([df3, df4], axis=0)
user_id rating
0 3 20
0 3 30
strtok()
is a bad ideaDo not use strtok()
in normal code, strtok()
uses static
variables which have some problems. There are some use cases on embedded microcontrollers where static
variables make sense but avoid them in most other cases. strtok()
behaves unexpected when more than 1 thread uses it, when it is used in a interrupt or when there are some other circumstances where more than one input is processed between successive calls to strtok()
.
Consider this example:
#include <stdio.h>
#include <string.h>
//Splits the input by the / character and prints the content in between
//the / character. The input string will be changed
void printContent(char *input)
{
char *p = strtok(input, "/");
while(p)
{
printf("%s, ",p);
p = strtok(NULL, "/");
}
}
int main(void)
{
char buffer[] = "abc/def/ghi:ABC/DEF/GHI";
char *p = strtok(buffer, ":");
while(p)
{
printContent(p);
puts(""); //print newline
p = strtok(NULL, ":");
}
return 0;
}
You may expect the output:
abc, def, ghi,
ABC, DEF, GHI,
But you will get
abc, def, ghi,
This is because you call strtok()
in printContent()
resting the internal state of strtok()
generated in main()
. After returning, the content of strtok()
is empty and the next call to strtok()
returns NULL
.
You could use strtok_r()
when you use a POSIX system, this versions does not need static
variables. If your library does not provide strtok_r()
you can write your own version of it. This should not be hard and Stackoverflow is not a coding service, you can write it on your own.
Another technique that you can use to get the symbol from url gibberish is to open Chrome
console with F12 and just paste following javascript:
decodeURIComponent("%2c")
it will decode and return the symbol (or symbols).
Hope this saves you some time.
You can also deny access to a folder using RedirectMatch
Add the following line to htaccess
RedirectMatch 403 ^/folder/?$
This will return a 403 forbidden
error for the folder ie : http://example.com/folder/
but it doest block access to files and folders inside that folder, if you want to block everything inside the folder then just change the regex pattern to ^/folder/.*$
.
Another option is mod-rewrite
If url-rewrting-module
is enabled you can use something like the following in root/.htaccss
:
RewriteEngine on
RewriteRule ^folder/?$ - [F,L]
This will internally map a request for the folder
to forbidden
error page.
Your fns is a cellstr array. You need to index in to it with {} instead of () to get the single string out as char.
fns{i}
teststruct.(fns{i})
Indexing in to it with () returns a 1-long cellstr array, which isn't the same format as the char array that the ".(name)" dynamic field reference wants. The formatting, especially in the display output, can be confusing. To see the difference, try this.
name_as_char = 'a'
name_as_cellstr = {'a'}
You can try something like process.argv
, that is if you are using node.js
to run the program.
console.log(process.argv)
=> Would print an array containing
[
'/usr/bin/node',
'/home/user/path/filename.js',
'your_input'
]
You get the user provided input via array index, i.e., console.log(process.argv[3])
This should provide you with the input which you can store.
Example:
var somevariable = process.argv[3]; // input one
var somevariable2 = process.argv[4]; // input two
console.log(somevariable);
console.log(somevariable2);
If you are building a command-line program then the npm package yargs would be really helpful.
The standard dictionary includes the method setdefault() for retrieving a value and establishing a default if the value does not exist. By contrast, defaultdict lets the caller specify the default up front when the container is initialized.
import collections
def default_factory():
return 'default value'
d = collections.defaultdict(default_factory, foo='bar')
print 'd:', d
print 'foo =>', d['foo']
print 'bar =>', d['bar']
This works well as long as it is appropriate for all keys to have the same default. It can be especially useful if the default is a type used for aggregating or accumulating values, such as a list, set, or even int. The standard library documentation includes several examples of using defaultdict this way.
$ python collections_defaultdict.py
d: defaultdict(<function default_factory at 0x100468c80>, {'foo': 'bar'})
foo => bar
bar => default value
As of Rails 6, you can simply call redirect_to
followed by the path you wish to redirect to such as home_path
, and then pass is a hash of key-value pairs.
example:
redirect_to home_path(name: 'Jason', needs: 'help with rails', help: true)
After this, you will be able to retrieve these values from the params hash.
ex
params[:name]
to retrieve the string 'Jason'
The first line of every source file of your project must be the following:
#include <stdafx.h>
Visit here to understand Precompiled Headers
I'm posting this solution because I had a hard time finding what I needed. This post got me close enough (+1 for that thank you), and here is the final solution for rearranging column data before insert if the data matches a test.
Note: this is from a legacy project I inherited where:
rridprefix
+ rrid
on duplicate key
is less than ideal because the columns are too numerous and may changeAnyway, here is the trigger that puts any duplicate keys into a legacy column while allowing us to store the legacy, bad data (and not trigger the gaining tables composite, unique key).
BEGIN
-- prevent duplicate composite keys when merging in archive to main
SET @EXIST_COMPOSITE_KEY = (SELECT count(*) FROM patientrecords where rridprefix = NEW.rridprefix and rrid = NEW.rrid);
-- if the composite key to be introduced during merge exists, rearrange the data for insert
IF @EXIST_COMPOSITE_KEY > 0
THEN
-- set the incoming column data this way (if composite key exists)
-- the legacy duplicate rrid field will help us keep the bad data
SET NEW.legacyduperrid = NEW.rrid;
-- allow the following block to set the new rrid appropriately
SET NEW.rrid = null;
END IF;
-- legacy code tried set the rrid (race condition), now the db does it
SET NEW.rrid = (
SELECT if(NEW.rrid is null and NEW.legacyduperrid is null, IFNULL(MAX(rrid), 0) + 1, NEW.rrid)
FROM patientrecords
WHERE rridprefix = NEW.rridprefix
);
END
As Service is already a Context itself
you can even get it through:
Context mContext = this;
OR
Context mContext = [class name].this; //[] only specify the class name
// mContext = JobServiceSchedule.this;
OLD (pre v4):
Writing in es6 and using react 0.14.6 / react-router 2.0.0-rc5. I use this command to lookup the query params in my components:
this.props.location.query
It creates a hash of all available query params in the url.
UPDATE (React Router v4+):
this.props.location.query in React Router 4 has been removed (currently using v4.1.1) more about the issue here: https://github.com/ReactTraining/react-router/issues/4410
Looks like they want you to use your own method to parse the query params, currently using this library to fill the gap: https://github.com/sindresorhus/query-string
It is not necessary to use withRouter. This works for me:
In your parent page,
<BrowserRouter>
<Switch>
<Route path="/routeA" render={(props)=> (
<ComponentA {...props} propDummy={50} />
)} />
<Route path="/routeB" render={(props)=> (
<ComponentB {...props} propWhatever={100} />
)} />
</Switch>
</BrowserRouter>
Then in ComponentA or ComponentB you can access
this.props.history
object, including the this.props.history.push method.
I've tried all provided solutions with no luck and finally machine restart resolved the problem (as it pretty often happens with XCode issues..)
#if DEBUG
System.Diagnostics.Debugger.Break();
#endif
What's going on is that you're returning right after the first line of the file doesn't match the id you're looking for. You have to do this:
def query(id):
for line in file:
table = {}
(table["ID"],table["name"],table["city"]) = line.split(";")
if id == int(table["ID"]):
file.close()
return table
# ID not found; close file and return empty dict
file.close()
return {}
A jQuery solution: Add this button inside any element you want to be able to close:
<button type='button' class='close' onclick='$(this).parent().remove();'>×</button>
or to 'just' hide it:
<button type='button' class='close' onclick='$(this).parent().hide();'>×</button>
This exact error was related to a content block by Youtube when "playbacked on certain sites or applications". More specifically by WMG (Warner Music Group).
The error message did however suggest that a https iframe import to a http site was the issue, which it wasn't in this case.
IT returns number of objects are updated in table.
update_counts = ModelClass.objects.filter(name='bar').update(name="foo")
You can refer this link to get more information on bulk update and create. Bulk update and Create
I solve it in 2 queries. This is my Unity3D script using System.Data.SQLite.
IDbCommand command = dbConnection.CreateCommand();
command.CommandText = @"SELECT count(*) FROM pragma_table_info('Candidat') c WHERE c.name = 'BirthPlace'";
IDataReader reader = command.ExecuteReader();
while (reader.Read())
{
try
{
if (int.TryParse(reader[0].ToString(), out int result))
{
if (result == 0)
{
command = dbConnection.CreateCommand();
command.CommandText = @"ALTER TABLE Candidat ADD COLUMN BirthPlace VARCHAR";
command.ExecuteNonQuery();
command.Dispose();
}
}
}
catch { throw; }
}
IMHO the method UserForm_Initialize should remain private bacause it is event handler for Initialize event of the UserForm.
This event handler is called when new instance of the UserForm is created. In this even handler u can initialize the private members of UserForm1 class.
Example:
Standard module code:
Option Explicit
Public Sub Main()
Dim myUserForm As UserForm1
Set myUserForm = New UserForm1
myUserForm.Show
End Sub
User form code:
Option Explicit
Private m_initializationDate As Date
Private Sub UserForm_Initialize()
m_initializationDate = VBA.DateTime.Date
MsgBox "Hi from UserForm_Initialize event handler.", vbInformation
End Sub
EDIT: CAMP is no more maintained ; two forks are available:
CAMP is an MIT licensed library (formerly LGPL) that adds reflection to the C++ language. It doesn't require a specific preprocessing step in the compilation, but the binding has to be made manually.
The current Tegesoft library uses Boost, but there is also a fork using C++11 that no longer requires Boost.
# First we obtain de timezone info o some datatime variable
tz_info = your_timezone_aware_variable.tzinfo
# Now we can subtract two variables using the same time zone info
# For instance
# Lets obtain the Now() datetime but for the tz_info we got before
diff = datetime.datetime.now(tz_info)-your_timezone_aware_variable
Conclusion: You must mange your datetime variables with the same time info
du -aS /PATH/TO/folder | sort -rn | head -2 | tail -1
or
du -aS /PATH/TO/folder | sort -rn | awk 'NR==2'
I've used the jdbcsql project on Sourceforge.
On *nix systems, this will create a csv stream of results to standard out:
java -Djava.security.egd=file///dev/urandom -jar jdbcsql.jar -d oracledb_SID -h $host -p 1521 -U some_username -m oracle -P "$PW" -f excel -s "," "$1"
Note that adding the -Djava.security.egd=file///dev/urandom
increases performance greatly
Windows commands are similar: see http://jdbcsql.sourceforge.net/
var last = array.slice(-1)[0];
I find slice at -1 useful for getting the last element (especially of an array of unknown length) and the performance is much better than calculating the length less 1.
Performance of the various methods for selecting last array element
I could use the GetBody
from Request package.
Look this comment in source code from request.go in net/http:
GetBody defines an optional func to return a new copy of Body. It is used for client requests when a redirect requires reading the body more than once. Use of GetBody still requires setting Body. For server requests it is unused."
GetBody func() (io.ReadCloser, error)
This way you can get the body request without make it empty.
Sample:
getBody := request.GetBody
copyBody, err := getBody()
if err != nil {
// Do something return err
}
http.DefaultClient.Do(request)
okay it solved, here is my final code
if($(this).width() > $(this).height()) {
$(this).css('width',MaxPreviewDimension+'px');
$(this).css('height','auto');
} else {
$(this).css('height',MaxPreviewDimension+'px');
$(this).css('width','auto');
}
Thanks guys
This can be simplified by completely skipping the where object and the $users declaration. All you need is:
Code
get-content c:\scripts\users.txt | get-aduser -properties * | select displayname, office | export-csv c:\path\to\your.csv
The problem is that you're trying start the animation too early in the view controller's lifecycle. In viewDidLoad
, the view has just been created, and hasn't yet been added to the view hierarchy, so attempting to animate one of its subviews
at this point produces bad results.
What you really should be doing is continuing to set the alpha of the view in viewDidLoad
(or where you create your views), and then waiting for the viewDidAppear
: method to be called. At this point, you can start your animations without any issue.
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIView.animate(withDuration: 1.5) {
self.myFirstLabel.alpha = 1.0
self.myFirstButton.alpha = 1.0
self.mySecondButton.alpha = 1.0
}
}
The keyword super
doesn't "stick". Every method call is handled individually, so even if you got to SuperClass.method1()
by calling super
, that doesn't influence any other method call that you might make in the future.
That means there is no direct way to call SuperClass.method2()
from SuperClass.method1()
without going though SubClass.method2()
unless you're working with an actual instance of SuperClass
.
You can't even achieve the desired effect using Reflection (see the documentation of java.lang.reflect.Method.invoke(Object, Object...)
).
[EDIT] There still seems to be some confusion. Let me try a different explanation.
When you invoke foo()
, you actually invoke this.foo()
. Java simply lets you omit the this
. In the example in the question, the type of this
is SubClass
.
So when Java executes the code in SuperClass.method1()
, it eventually arrives at this.method2();
Using super
doesn't change the instance pointed to by this
. So the call goes to SubClass.method2()
since this
is of type SubClass
.
Maybe it's easier to understand when you imagine that Java passes this
as a hidden first parameter:
public class SuperClass
{
public void method1(SuperClass this)
{
System.out.println("superclass method1");
this.method2(this); // <--- this == mSubClass
}
public void method2(SuperClass this)
{
System.out.println("superclass method2");
}
}
public class SubClass extends SuperClass
{
@Override
public void method1(SubClass this)
{
System.out.println("subclass method1");
super.method1(this);
}
@Override
public void method2(SubClass this)
{
System.out.println("subclass method2");
}
}
public class Demo
{
public static void main(String[] args)
{
SubClass mSubClass = new SubClass();
mSubClass.method1(mSubClass);
}
}
If you follow the call stack, you can see that this
never changes, it's always the instance created in main()
.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim dt As New DataTable
Dim dc As DataColumn
dc = New DataColumn("Question", System.Type.GetType("System.String"))
dt.Columns.Add(dc)
dc = New DataColumn("Ans1", System.Type.GetType("System.String"))
dt.Columns.Add(dc)
dc = New DataColumn("Ans2", System.Type.GetType("System.String"))
dt.Columns.Add(dc)
dc = New DataColumn("Ans3", System.Type.GetType("System.String"))
dt.Columns.Add(dc)
dc = New DataColumn("Ans4", System.Type.GetType("System.String"))
dt.Columns.Add(dc)
dc = New DataColumn("AnsType", System.Type.GetType("System.String"))
dt.Columns.Add(dc)
Dim Dr As DataRow
Dr = dt.NewRow
Dr("Question") = "What is Your Name"
Dr("Ans1") = "Ravi"
Dr("Ans2") = "Mohan"
Dr("Ans3") = "Sohan"
Dr("Ans4") = "Gopal"
Dr("AnsType") = "Multi"
dt.Rows.Add(Dr)
Dr = dt.NewRow
Dr("Question") = "What is your father Name"
Dr("Ans1") = "Ravi22"
Dr("Ans2") = "Mohan2"
Dr("Ans3") = "Sohan2"
Dr("Ans4") = "Gopal2"
Dr("AnsType") = "Multi"
dt.Rows.Add(Dr)
Panel1.GrowStyle = TableLayoutPanelGrowStyle.AddRows
Panel1.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single
Panel1.BackColor = Color.Azure
Panel1.RowStyles.Insert(0, New RowStyle(SizeType.Absolute, 50))
Dim i As Integer = 0
For Each dri As DataRow In dt.Rows
Dim lab As New Label()
lab.Text = dri("Question")
lab.AutoSize = True
Panel1.Controls.Add(lab, 0, i)
Dim Ans1 As CheckBox
Ans1 = New CheckBox()
Ans1.Text = dri("Ans1")
Panel1.Controls.Add(Ans1, 1, i)
Dim Ans2 As RadioButton
Ans2 = New RadioButton()
Ans2.Text = dri("Ans2")
Panel1.Controls.Add(Ans2, 2, i)
i = i + 1
'Panel1.Controls.Add(Pan)
Next
To resize the existing volume mounted
sudo mount -t xfs /dev/sdf /opt/data/
mount: /opt/data: /dev/nvme1n1 already mounted on /opt/data.
sudo xfs_growfs /opt/data/
I had the same issue with weblogic 12c and maven I initially while deploying from eclipse (kepler) (deploying from the console gave no errors).
The other solutions given on this page didn't help.
I extracted the spring.tld spring-form.tld files of the spring-webmvc jar (which I found in my repository) in the web\WEB-INF folder of my war module;
I did a fresh build; deployed (from eclipse) into weblogic 12c, tested the application and the error was gone;
I removed the spring.tld spring-form.tld files again and after deleting; rebuilding and redeploying the application the error didn't show up again.
I double checked whether the files were gone in the war and they were indeed not present.
hope this helps others with a similar issue...
It can also be done with isinstance
as per Alex Hall's answer :
>>> NoneType = type(None)
>>> x = None
>>> type(x) == NoneType
True
>>> isinstance(x, NoneType)
True
isinstance
is also intuitive but there is the complication that it requires the line
NoneType = type(None)
which isn't needed for types like int
and float
.
OK, this question has been answered and answer accepted but someone asked me to put my answer so there you go.
First of all, it is not possible to say for sure. It is an internal implementation detail and not documented. However, based on the objects included in the other object. Now, how do we calculate the memory requirement for our cached objects?
I had previously touched this subject in this article:
Now, how do we calculate the memory requirement for our cached objects? Well, as most of you would know, Int32 and float are four bytes, double and DateTime 8 bytes, char is actually two bytes (not one byte), and so on. String is a bit more complex, 2*(n+1), where n is the length of the string. For objects, it will depend on their members: just sum up the memory requirement of all its members, remembering all object references are simply 4 byte pointers on a 32 bit box. Now, this is actually not quite true, we have not taken care of the overhead of each object in the heap. I am not sure if you need to be concerned about this, but I suppose, if you will be using lots of small objects, you would have to take the overhead into consideration. Each heap object costs as much as its primitive types, plus four bytes for object references (on a 32 bit machine, although BizTalk runs 32 bit on 64 bit machines as well), plus 4 bytes for the type object pointer, and I think 4 bytes for the sync block index. Why is this additional overhead important? Well, let’s imagine we have a class with two Int32 members; in this case, the memory requirement is 16 bytes and not 8.
this is your answer:
<div class="test">Hello</div>
<div class="one">World</div>
The following jQuery Won't work:
$(data).find('div.test');
as the divs are top level elements and data isn't an element but a string, to make it work you need to use .filter
$(data).filter('div.test');
Another same question: Use Jquery Selectors on $.AJAX loaded HTML?
I've solved using only @JsonIgnore
like @kryger has suggested.
So your getter will become:
@JsonIgnore
public String getEncryptedPwd() {
return this.encryptedPwd;
}
You can set @JsonIgnore
of course on field, setter or getter like described here.
And, if you want to protect encrypted password only on serialization side (e.g. when you need to login your users), add this @JsonProperty
annotation to your field:
@JsonProperty(access = Access.WRITE_ONLY)
private String encryptedPwd;
More info here.
It indeed sets the stack size on a JVM.
You should touch it in either of these two situations:
The latter usually comes when your Xss is set too large - then you need to balance it (testing!)
header("Location: route_to_main_page");
I've encountered this problem while having a custom 404 error handling file. Instead of throwing some html content it was suppose to redirect to the main page url. It worked well.
Then I used this as a skeleton for a next project, therefore not changing the "route_to_main_page" actually on the new project (different URL) became a "route_to_external_url" so any 404 errors within your code (missing css stylesheets, js libraries) would return the "Uncaught SyntaxError: Unexpected token <".
If a website's directory does NOT have an "index...." file, AND .htaccess has NOT been used to block access to the directory itself, then Apache will create an "index of" page for that directory. You can save that page, and its icons, using "Save page as..." along with the "Web page, complete" option (Firefox example). If you own the website, temporarily rename any "index...." file, and reference the directory locally. Then restore your "index...." file.
For your particular example, I would just do this, since you obviously don't care about actually having the browser get the redirect anyway (by virtue of accepting the answer you have already accepted):
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index() {
// obviously these values might come from somewhere non-trivial
return Index(2, "text");
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(int someValue, string anotherValue) {
// would probably do something non-trivial here with the param values
return View();
}
That works easily and there is no funny business really going on - this allows you to maintain the fact that the second one really only accepts HTTP POST requests (except in this instance, which is under your control anyway) and you don't have to use TempData either, which is what the link you posted in your answer is suggesting.
I would love to know what is "wrong" with this, if there is anything. Obviously, if you want to really have sent to the browser a redirect, this isn't going to work, but then you should ask why you would be trying to convert that regardless, since it seems odd to me.
Hope that helps.
Your reader
variable is an iterable, by looping over it you retrieve the rows.
To make it skip one item before your loop, simply call next(reader, None)
and ignore the return value.
You can also simplify your code a little; use the opened files as context managers to have them closed automatically:
with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
reader = csv.reader(infile)
next(reader, None) # skip the headers
writer = csv.writer(outfile)
for row in reader:
# process each row
writer.writerow(row)
# no need to close, the files are closed automatically when you get to this point.
If you wanted to write the header to the output file unprocessed, that's easy too, pass the output of next()
to writer.writerow()
:
headers = next(reader, None) # returns the headers or `None` if the input is empty
if headers:
writer.writerow(headers)
To avoid many if-else structures, let JavaScript do the trick automatically:
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
document.getElementById('name').value = "<?php echo $_GET['name'];?>";
</script>
<select name="location" id="location">
<option value="x">x</option>
<option value="y">y</option>
</select>
<script type="text/javascript">
document.getElementById('location').value = "<?php echo $_GET['location'];?>";
</script>
http://en.wikipedia.org/wiki/Stirling%27s_approximation Stirling approximation might help you. It is really helpful in dealing with problems on factorials related to huge numbers of the order of 10^10 and above.
I have faced the same problem and I have fixed. Please make sure some things as written bellow :
Mail::send('emails.auth.activate', array('link'=> URL::route('account-activate', $code),'username'=>$user->username),function($message) use ($user) {
$message->to($user->email , $user->username)->subject('Active your account !');
});
This should be your emails.activation
Hello {{ $username }} , <br> <br> <br>
We have created your account ! Awesome ! Please activate by clicking the following link <br> <br> <br>
----- <br>
{{ $link }} <br> <br> <br>
----
The answer to your why you can't call $email variable into your mail sending function. You need to call $user variable then you can write your desired variable as $user->variable
Thank You :)
If you're using Perl, download a module to parse the XML: XML::Simple, XML::Twig, or XML::LibXML. Don't re-invent the wheel.
Instructions here are a little complicated so I'm going to offer something more straightforward:
git reset HEAD --hard
Abandon all changes to the current branch
...
Perform intermediary work as necessary
git stash pop
Re-pop the stash again at a later date when you're ready
Although it is a bit strange, but the notifyDataSetChanged
does not really work without setting new values to adapter. So, you should do:
array = getNewItems();
((MyAdapter) mAdapter).setValues(array); // pass the new list to adapter !!!
mAdapter.notifyDataSetChanged();
This has worked for me.
select top 0 *
into #mytemptable
from myrealtable
Your first usage of Map
is inside a function in the combat
class. That happens before Map
is defined, hence the error.
A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map
is fully declared.
The solution is to follow the C++ pattern of the class declaration in a .h
file and the function bodies in a .cpp
. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.
Code example of ItemListener
implementation
class ItemChangeListener implements ItemListener{
@Override
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
Object item = event.getItem();
// do something with object
}
}
}
Now we will get only selected item.
Then just add listener to your JComboBox
addItemListener(new ItemChangeListener());
There is now an open-source extension in the Marketplace that seems to do what the OP was asking for:
If it doesn't do exactly what you want, the code is available, so you can modify it to suit your scenario.
HTH
SELECT
spid,
sp.[status],
loginame [Login],
hostname,
blocked BlkBy,
sd.name DBName,
cmd Command,
cpu CPUTime,
memusage Memory,
physical_io DiskIO,
lastwaittype LastWaitType,
[program_name] ProgramName,
last_batch LastBatch,
login_time LoginTime,
'kill ' + CAST(spid as varchar(10)) as 'Kill Command'
FROM master.dbo.sysprocesses sp
JOIN master.dbo.sysdatabases sd ON sp.dbid = sd.dbid
WHERE sd.name NOT IN ('master', 'model', 'msdb')
--AND sd.name = 'db_name'
--AND hostname like 'hostname1%'
--AND loginame like 'username1%'
ORDER BY spid
/* If a service connects continously. You can automatically execute kill process then run your script:
DECLARE @sqlcommand nvarchar (500)
SELECT @sqlcommand = 'kill ' + CAST(spid as varchar(10))
FROM master.dbo.sysprocesses sp
JOIN master.dbo.sysdatabases sd ON sp.dbid = sd.dbid
WHERE sd.name NOT IN ('master', 'model', 'msdb')
--AND sd.name = 'db_name'
--AND hostname like 'hostname1%'
--AND loginame like 'username1%'
--SELECT @sqlcommand
EXEC sp_executesql @sqlcommand
*/
The short answer:
Use the click
event, which won't fire until after the value has been updated, and fires when you want it to:
<label><input type='checkbox' onclick='handleClick(this);'>Checkbox</label>
function handleClick(cb) {
display("Clicked, new value = " + cb.checked);
}
The longer answer:
The change
event handler isn't called until the checked
state has been updated (live example | source), but because (as Tim Büthe points out in the comments) IE doesn't fire the change
event until the checkbox loses focus, you don't get the notification proactively. Worse, with IE if you click a label for the checkbox (rather than the checkbox itself) to update it, you can get the impression that you're getting the old value (try it with IE here by clicking the label: live example | source). This is because if the checkbox has focus, clicking the label takes the focus away from it, firing the change
event with the old value, and then the click
happens setting the new value and setting focus back on the checkbox. Very confusing.
But you can avoid all of that unpleasantness if you use click
instead.
I've used DOM0 handlers (onxyz
attributes) because that's what you asked about, but for the record, I would generally recommend hooking up handlers in code (DOM2's addEventListener
, or attachEvent
in older versions of IE) rather than using onxyz
attributes. That lets you attach multiple handlers to the same element and lets you avoid making all of your handlers global functions.
An earlier version of this answer used this code for handleClick
:
function handleClick(cb) {
setTimeout(function() {
display("Clicked, new value = " + cb.checked);
}, 0);
}
The goal seemed to be to allow the click to complete before looking at the value. As far as I'm aware, there's no reason to do that, and I have no idea why I did. The value is changed before the click
handler is called. In fact, the spec is quite clear about that. The version without setTimeout
works perfectly well in every browser I've tried (even IE6). I can only assume I was thinking about some other platform where the change isn't done until after the event. In any case, no reason to do that with HTML checkboxes.
This problem is probably from your /etc/apt/sources.list as others mentioned but there is chance that the problem is with your hard disk. I solved the same issue by cleaning up some space.
When you don't have enough space on your hard disk, updating your machine won't occur until you delete some files.
Install Mylyn connector for GitHub from this update site, it provides great integration: you can directly import your repositories using Import > Projects from Git > GitHub. You can set the default repository folder in Preferences > Git.
The answer above covers everything in great detail, apart from a couple of things.
First, if there are no styles, then the (Context context, AttributeSet attrs)
method signature will be used to instantiate the preference. In this case just use context.obtainStyledAttributes(attrs, R.styleable.MyCustomView)
to get the TypedArray.
Secondly it does not cover how to deal with plaurals resources (quantity strings). These cannot be dealt with using TypedArray. Here is a code snippet from my SeekBarPreference that sets the summary of the preference formatting its value according to the value of the preference. If the xml for the preference sets android:summary to a text string or a string resouce the value of the preference is formatted into the string (it should have %d in it, to pick up the value). If android:summary is set to a plaurals resource, then that is used to format the result.
// Use your own name space if not using an android resource.
final static private String ANDROID_NS =
"http://schemas.android.com/apk/res/android";
private int pluralResource;
private Resources resources;
private String summary;
public SeekBarPreference(Context context, AttributeSet attrs) {
// ...
TypedArray attributes = context.obtainStyledAttributes(
attrs, R.styleable.SeekBarPreference);
pluralResource = attrs.getAttributeResourceValue(ANDROID_NS, "summary", 0);
if (pluralResource != 0) {
if (! resources.getResourceTypeName(pluralResource).equals("plurals")) {
pluralResource = 0;
}
}
if (pluralResource == 0) {
summary = attributes.getString(
R.styleable.SeekBarPreference_android_summary);
}
attributes.recycle();
}
@Override
public CharSequence getSummary() {
int value = getPersistedInt(defaultValue);
if (pluralResource != 0) {
return resources.getQuantityString(pluralResource, value, value);
}
return (summary == null) ? null : String.format(summary, value);
}
notifyChanged()
in the preference's onDialogClosed
method.Here is a simple mail sending code with attachment
try
{
SmtpClient mailServer = new SmtpClient("smtp.gmail.com", 587);
mailServer.EnableSsl = true;
mailServer.Credentials = new System.Net.NetworkCredential("[email protected]", "mypassword");
string from = "[email protected]";
string to = "[email protected]";
MailMessage msg = new MailMessage(from, to);
msg.Subject = "Enter the subject here";
msg.Body = "The message goes here.";
msg.Attachments.Add(new Attachment("D:\\myfile.txt"));
mailServer.Send(msg);
}
catch (Exception ex)
{
Console.WriteLine("Unable to send email. Error : " + ex);
}
Read more Sending emails with attachment in C#
You first have to tell Gnuplot to use a style that uses points, e.g. with points
or with linespoints
. Try for example:
plot sin(x) with points
Output:
Now try:
plot sin(x) with points pointtype 5
Output:
You may also want to look at the output from the test
command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:
You need to wait for Javascript and jQuery to finish loading.
Execute Javascript to check if jQuery.active
is 0
and document.readyState
is complete
, which means the JS and jQuery load is complete.
public boolean waitForJStoLoad() {
WebDriverWait wait = new WebDriverWait(driver, 30);
// wait for jQuery to load
ExpectedCondition<Boolean> jQueryLoad = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
try {
return ((Long)executeJavaScript("return jQuery.active") == 0);
}
catch (Exception e) {
return true;
}
}
};
// wait for Javascript to load
ExpectedCondition<Boolean> jsLoad = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
return executeJavaScript("return document.readyState")
.toString().equals("complete");
}
};
return wait.until(jQueryLoad) && wait.until(jsLoad);
}
I've developed http://code.google.com/p/java-keyutil/ which imports PEM certificates straight into a Java keystore. Its primary purpose is to import a multi-part PEM Operating System certificate bundles such as ca-bundle.crt. These often includes headers which keytool cannot handle
</self promotion>
Check the PASSWORD_LOCK_TIME
parameter. If it is set to 1 then you won't be able to unlock the password for 1 day even after you issue the alter user unlock
command.
Here is one way to do it
_,_,rest = s.partition(start)
result,_,_ = rest.partition(end)
print result
Another way using regexp
import re
print re.findall(re.escape(start)+"(.*)"+re.escape(end),s)[0]
or
print re.search(re.escape(start)+"(.*)"+re.escape(end),s).group(1)
Using list comprehensions in python, you can collect an entire column of values into a list using just two lines:
df = sqlContext.sql("show tables in default")
tableList = [x["tableName"] for x in df.rdd.collect()]
In the above example, we return a list of tables in database 'default', but the same can be adapted by replacing the query used in sql().
Or more abbreviated:
tableList = [x["tableName"] for x in sqlContext.sql("show tables in default").rdd.collect()]
And for your example of three columns, we can create a list of dictionaries, and then iterate through them in a for loop.
sql_text = "select name, age, city from user"
tupleList = [{name:x["name"], age:x["age"], city:x["city"]}
for x in sqlContext.sql(sql_text).rdd.collect()]
for row in tupleList:
print("{} is a {} year old from {}".format(
row["name"],
row["age"],
row["city"]))
Well, you're going to have to check for null somewhere. You could do something like this:
from item in db.vw_Dropship_OrderItems
where (listStatus == null || listStatus.Contains(item.StatusCode))
&& (listMerchants == null || listMerchants.Contains(item.MerchantId))
select item;
The simplest way to modify all files of a project at once (batch) is through Line Endings Unify package:
OR (instead of 3.) copy:
{
"keys": ["ctrl+alt+l"],
"command": "line_endings_unify"
},
to the User array (right pane, after the opening [
) in Preferences -> KeyBindings + press Ctrl+Alt+L.
As mentioned in another answer:
The Carriage Return (CR) character (
0x0D
,\r
) [...] Early Macintosh operating systems (OS-9 and earlier).The Line Feed (LF) character (
0x0A
,\n
) [...] UNIX based systems (Linux, Mac OSX)The End of Line (EOL) sequence (
0x0D 0x0A
,\r\n
) [...] (non-Unix: Windows, Symbian OS).
If you have node_modules, build or other auto-generated folders, delete them before running the package.
When you run the package:
js,jsx
).\n
.<input onchange="readURL(this);" type="file" name="userfile" />
<img src="" id="blah"/>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(150).height(200);
};
reader.readAsDataURL(input.files[0]);
//console.log(reader);
//alert(reader.readAsDataURL(input.files[0]));
}
}
</script>
Since @KiritModi 's answer is from 2015, this is the Swift 3.0's version:
func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
let size = image.size
let widthRatio = targetSize.width / image.size.width
let heightRatio = targetSize.height / image.size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
string MyConString = "Data Source='mysql7.000webhost.com';" +
"Port=3306;" +
"Database='a455555_test';" +
"UID='a455555_me';" +
"PWD='something';";
Althought there are some good answers already here, most of them are focusing in browser navigation. I'm writing this in 2018 and probably someone wants to know about the security of mobile apps.
For mobile apps, if you control both ends of the application (server and app), as long as you use HTTPS you're secure. iOS or Android will verify the certificate and mitigate possible MiM attacks (that would be the only weak point in all this). You can send sensitive data through HTTPS connections that it will be encrypted during transport. Just your app and the server will know any parameters sent through https.
The only "maybe" here would be if client or server are infected with malicious software that can see the data before it is wrapped in https. But if someone is infected with this kind of software, they will have access to the data, no matter what you use to transport it.
Use the PHP function serialize()
to convert arrays to strings. These strings can easily be stored in MySQL database. Using unserialize()
they can be converted to arrays again if needed.
If you are using the batch conversion, in the window click "options" in the "Batch conversion settings-output format" and tick the two boxes "save transparent color" (one under "PNG" and the other under "ICO").
It's a matter of operator precedence.
||
has a higher precedence than or
.
So, in between the two you have other operators including ternary (? :
) and assignment (=
) so which one you choose can affect the outcome of statements.
Here's a ruby operator precedence table.
See this question for another example using and
/&&
.
Also, be aware of some nasty things that could happen:
a = false || true #=> true
a #=> true
a = false or true #=> true
a #=> false
Both of the previous two statements evaluate to true
, but the second sets a
to false
since =
precedence is lower than ||
but higher than or
.
I had the same problem. Solved it by using a javascript library called FileSaver
Just call
saveAs(file, 'filename');
Full http post request:
$http.post('apiUrl', myObject, { responseType: 'arraybuffer' })
.success(function(data) {
var file = new Blob([data], { type: 'application/pdf' });
saveAs(file, 'filename.pdf');
});
With this command:
dpkg -s mysql-server | grep Status
I was looking for a way to mimic the CTRL+Shift+End, so dotNET solution is great, except with my Excel 2010 I need to add a set
if I want to avoid an error:
Function GetLastCell(sh As Worksheet) As Range
Set GetLastCell = sh.Cells(1, 1).SpecialCells(xlLastCell)
End Function
and how to check this for yourself:
Sub test()
Dim ws As Worksheet, r As Range
Set ws = ActiveWorkbook.Sheets("Sheet1")
Set r = GetLastCell(ws)
MsgBox r.Column & "-" & r.Row
End Sub
Just in case above solutions didn't work:
Get the port your process is listening to:
$ ps ax | grep python
Kill the Process
$ kill PROCESS_NAME
I also ran into this issue - I was trying to pull in an object from a source and it was working in the test code but not the src code. To further test, I copied a block of code from the test and dropped it into the src code, then immediately removed the JUnit lines so I just had how the test was pulling in the object. Then suddenly my code wouldn't compile.
The issue was that when I dropped the code in, Eclipse helpfully resolved all the classes so I had JUnit calls coming from my src code, which was not proper. I should have noticed the warnings at the top about unused imports, but I neglected to see them.
Once I removed the unused JUnit imports in my src file, it all worked beautifully.
what happened to me is that I have multiple projects in my solution. I meant to debug project 1, however, the project 2 was set as the default starting project. I fixed this by, right click on the project and select "Set as startup project", then running debugging is fine.
I've successfully used int(x or 0) for this type of error, so long as None should equate to 0 in the logic. Note that this will also resolve to 0 in other cases where testing x returns False. e.g. empty list, set, dictionary or zero length string. Sorry, Kindall already gave this answer.
keep in mind that avoiding text scaling is the main reason responsive layouts exist. the entire logic behind responsive sites is to create functional layouts that effectively display your content so its easily readable and usable on multiple screen sizes.
Although It is necessary to scale text in some cases, be careful not to miniaturise your site and miss the point.
heres an example anyway.
@media(min-width:1200px){
h1 {font-size:34px}
}
@media(min-width:992px){
h1 {font-size:32px}
}
@media(min-width:768px){
h1 {font-size:28px}
}
@media(max-width:767px){
h1 {font-size:26px}
}
Also keep in mind the 480 viewport has been dropped in bootstrap 3.
Why :not just use two :not
:
input:not([type="radio"]):not([type="checkbox"])
Yes, it is intentional
You need to start creating the JAR at the root of the files.
So, for instance:
jar cvf program.jar -C path/to/classes .
That assumes that path/to/classes
contains the com
directory.
FYI, these days it is relatively uncommon for most people to use the jar
command directly, as they will use a build tool such as Ant or Maven to take care of that (and other aspects of the build). It is well worth the effort of allowing one of those tools to take care of all aspects of your build, and it's even easier with a good IDE to help write the build.xml
(Ant) or pom.xml
(Maven).
For maven projects add following dependancy :
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
For gradle projects:
dependencies {
providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.0.1'
}
or download javax.servlet.jar
and add to your project.
untested, but in my mind, this should work? cause it'll be 0x01 on little endian, and 0x00 on big endian?
bool runtimeIsLittleEndian(void)
{
volatile uint16_t i=1;
return ((uint8_t*)&i)[0]==0x01;//0x01=little, 0x00=big
}
Shortest way:
echo substr(uniqid(),-6); // result: 5ebf06
I was also facing a similar issue ("no runnable methods..") on running the simplest of simple piece of code (Using @Test, @Before etc.) and found the solution nowhere. I was using Junit4 and Eclipse SDK version 4.1.2. Resolved my problem by using the latest Eclipse SDK 4.2.2. I hope this helps people who are struggling with a somewhat similar issue.
You may also try standard sql un-pivoting method by using a sequence of logic with the following code.. The following code has 3 steps:
remove any null combinations ( if exists, table expression can be fully avoided if there are strictly no null values in base table)
select *
from
(
select name, subject,
case subject
when 'Maths' then maths
when 'Science' then science
when 'English' then english
end as Marks
from studentmarks
Cross Join (values('Maths'),('Science'),('English')) AS Subjct(Subject)
)as D
where marks is not null;
Edit:
There's either a bug with git pull
, or you can't do what you're trying to do with that command. You can however, do it with fetch and merge:
cd /X
git --git-dir=/X/Y/.git fetch
git --git-dir=/X/Y/.git --work-tree=/X/Y merge origin/master
Original answer:
Assuming you're running bash or similar, you can do (cd /X/Y; git pull)
.
The git man page specifies some variables (see "The git Repository") that seem like they should help, but I can't make them work right (with my repository in /tmp/ggg2):
GIT_WORK_TREE=/tmp/ggg2 GIT_DIR=/tmp/ggg2/.git git pull
fatal: /usr/lib/git-core/git-pull cannot be used without a working tree.
Running the command below while my cwd is /tmp updates that repo, but the updated file appears in /tmp instead of the working tree /tmp/ggg2:
GIT_DIR=/tmp/ggg2/.git git pull
See also this answer to a similar question, which demonstrates the --git-dir
and --work-tree
flags.
You either want to select an anonymous type:
var dataset2 = from recordset
in entities.processlists
where recordset.ProcessName == processname
select new
{
recordset.ServerName,
recordset.ProcessID,
recordset.Username
};
But you cannot cast that to another type, so I guess you want something like this:
var dataset2 = from recordset
in entities.processlists
where recordset.ProcessName == processname
// Select new concrete type
select new PInfo
{
ServerName = recordset.ServerName,
ProcessID = recordset.ProcessID,
Username = recordset.Username
};
RMDIR or RD if you are using the classic Command Prompt (cmd.exe):
rd /s /q "path"
RMDIR [/S] [/Q] [drive:]path
RD [/S] [/Q] [drive:]path
/S Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree.
/Q Quiet mode, do not ask if ok to remove a directory tree with /S
If you are using PowerShell you can use Remove-Item
(which is aliased to del
, erase
, rd
, ri
, rm
and rmdir
) and takes a -Recurse
argument that can be shorted to -r
rd -r "path"
The reason why nothing happens when you use 'alert()' is probably as explained by MDN: "The HTML specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event."
But there is also another reason why you might not see the warning at all, whether it calls alert() or not, also explained on the same site:
"... browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with"
That is what I see with current versions of Chrome and FireFox. I open my page which has beforeunload handler set up with this code:
window.addEventListener
('beforeunload'
, function (evt)
{ evt.preventDefault();
evt.returnValue = 'Hello';
return "hello 2222"
}
);
If I do not click on my page, in other words "do not interact" with it, and click the close-button, the window closes without warning.
But if I click on the page before trying to close the window or tab, I DO get the warning, and can cancel the closing of the window.
So these browsers are "smart" (and user-friendly) in that if you have not done anything with the page, it can not have any user-input that would need saving, so they will close the window without any warnings.
Consider that without this feature any site might selfishly ask you: "Do you really want to leave our site?", when you have already clearly indicated your intention to leave their site.
SEE: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
I've seen
anEvent.isPopupTrigger()
be used before. I'm fairly new to Java so I'm happy to hear thoughts about this approach :)
INSERTED
and DELETED
are virtual tables. They need to be used in a FROM
clause.
CREATE TRIGGER sampleTrigger
ON database1.dbo.table1
FOR DELETE
AS
IF EXISTS (SELECT foo
FROM database2.dbo.table2
WHERE id IN (SELECT deleted.id FROM deleted)
AND bar = 4)
Code To Get Today's date in any specific Format
You can define the desired format in SimpleDateFormat instance to get the date in that specific formate
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
String todaysdate = dateFormat.format(date);
System.out.println("Today's date : " + todaysdate);
Follow below links to see the valid date format combination.
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
CODE : To get x days ahead or Previous from Today's date, To get the past date or Future date.
For Example :
Today date : 11/27/2018
xdayFromTodaysDate = 2 to get date as 11/29/2018
xdayFromTodaysDate = -2 to get date as 11/25/2018
public String getAniversaryDate(int xdayFromTodaysDate ){
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH,xdayFromTodaysDate);
date = cal.getTime();
String aniversaryDate = dateFormat.format(date);
LOGGER.info("Today's date : " + todaysdate);
return aniversaryDate;
}
CODE : To get x days ahead or Previous from a Given date
public String getAniversaryDate(String givendate, int xdayFromTodaysDate ){
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
try {
Date date = dateFormat.parse(givendate);
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH,xdayFromTodaysDate);
date = cal.getTime();
String aniversaryDate = dateFormat.format(date);
LOGGER.info("aniversaryDate : " + aniversaryDate);
return aniversaryDate;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
You don't need to give local path. just give cdn link of bootstrap datetimepicker. and it works.
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class='col-sm-6'>_x000D_
<div class="form-group">_x000D_
<div class='input-group date' id='datetimepicker'>_x000D_
<input type='text' class="form-control" />_x000D_
<span class="input-group-addon">_x000D_
<span class="glyphicon glyphicon-calendar"></span>_x000D_
</span>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<script type="text/javascript">_x000D_
$(function () {_x000D_
$('#datetimepicker').datepicker();_x000D_
});_x000D_
</script>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Could you try this one:
create or replace
procedure point_triangle
IS
BEGIN
FOR thisteam in (select P.FIRSTNAME,P.LASTNAME, SUM(P.PTS) S from PLAYERREGULARSEASON P where P.TEAM = 'IND' group by P.FIRSTNAME, P.LASTNAME order by SUM(P.PTS) DESC)
LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.S);
END LOOP;
END;
The problem I had accessing the sqlite db file I created in my java (jersey) server had solely to due with path. Some of the docs say the jdbc connect url should look like "jdbc:sqlite://path-to-file/sample.db". I thought the double-slash was part of a htt protocol-style path and would map properly when deployed, but in actuality, it's an absolute or relative path. So, when I placed the file at the root of the WebContent folder (tomcat project), a uri like this worked "jdbc:sqlite:sample.db".
The one thing that was throwing me was that when I was stepping through the debugger, I received a message that said "opening db: ... permission denied". I thought it was a matter of file system permissions or perhaps sql user permissions. After finding out that SQLite doesn't have the concept of roles/permissions like MySQL, etc, I did eventually change the file permissions before I came to what I believe was the correct solution, but I think it was just a bad message (i.e. permission denied, instead of File not found).
Hope this helps someone.
Step.1
$ git submodule update
Step.2
To be commented out the dependences of classpass
The user/host combination may have been created without password.
I was assuming that when adding a new host for an existing user (using a GUI app), the existing password would also be used for the new user/host combination.
I could log in with
mysql -u username -p PASSWORD
locally, but not from IPADDRESS with
mysql -u --host=HOST -p PASSWORD
(I could actually log in from IPADDRESS without using a password)
mysql -u --host=HOST
Setting the password allowed access:
set password for '<USER>'@'<IPADDRESS>' = '<PASSWORD>';
So in the project were I had this exact same issue the problem wasn't in the foreach
or the .toList()
it was actually in the AutoFac configuration we used.
This created some weird situations were the above error was thrown but also a bunch of other equivalent errors were thrown.
This was our fix: Changed this:
container.RegisterType<DataContext>().As<DbContext>().InstancePerLifetimeScope();
container.RegisterType<DbFactory>().As<IDbFactory>().SingleInstance();
container.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerRequest();
To:
container.RegisterType<DataContext>().As<DbContext>().As<DbContext>();
container.RegisterType<DbFactory>().As<IDbFactory>().As<IDbFactory>().InstancePerLifetimeScope();
container.RegisterType<UnitOfWork>().As<IUnitOfWork>().As<IUnitOfWork>();//.InstancePerRequest();
I was using a KEY word for one of my columns and I solved it with brackets []
I already answered similar question on here Here is the Link
No both are different.
@Service annotation have use for other purpose and @Controller use for other. Actually Spring @Component, @Service, @Repository and @Controller annotations are used for automatic bean detection using classpath scan in Spring framework, but it doesn't ,mean that all functionalities are same. @Service: It indicates annotated class is a Service component in the business layer.
@Controller: Annotated class indicates that it is a controller components, and mainly used at presentation layer.
so just to make it a complete answer:
login(username, password) {
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('username', username);
urlSearchParams.append('password', password);
let body = urlSearchParams.toString()
return this.http.post('http://localHost:3000/users/login', body, {headers:headers})
.map((response: Response) => {
// login successful if there's a jwt token in the response
console.log(response);
var body = response.json();
console.log(body);
if (body.response){
let user = response.json();
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
}
else{
return body;
}
});
}
Any attribute that starts with data-
is the prefix for custom attributes used for some specific purpose (that purpose depends on the application). It was added as a semantic remedy to people's heavy use of rel
and other attributes for purposes other than their original intended purposes (rel
was often used to hold data for things like advanced tooltips).
In the case of Bootstrap, I'm not familiar with its inner workings, but judging from the name, I'd guess it's a hook to allow toggling of the visibility or perhaps a mode of the element it's attached to (such as the collapsable side bar on Octopress.org).
html5doctor has a good article on the data- attribute.
Cycle 2 is another example of extensive use of the data- attribute.
Use the Maven debug option, ie mvn -X
:
Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...
In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml
.
Check ASUI dialog which create at runtime. There is no need of hide and show logic. Simply service will create a component at runtime using AOT ASUI NPM
You can add nulls to the ArrayList
, and you will have to check for nulls in the loop:
for(Item i : itemList) {
if (i != null) {
}
}
itemsList.size();
would take the null
into account.
List<Integer> list = new ArrayList<Integer>();
list.add(null);
list.add (5);
System.out.println (list.size());
for (Integer value : list) {
if (value == null)
System.out.println ("null value");
else
System.out.println (value);
}
Output :
2
null value
5
First, one should check if the last character is a comma. If it exists, remove it.
if (str.indexOf(',', this.length - ','.length) !== -1) {
str = str.substring(0, str.length - 1);
}
NOTE str.indexOf(',', this.length - ','.length) can be simplified to str.indexOf(',', this.length - 1)
"Edit -> EOL Conversion". You can convert to Windows/Linux/Mac EOL there. The current format is displayed in the status bar.
Try autoplay="autoplay"
instead of the "true"
value. That's the documented way to enable autoplay. That sounds weirdly redundant, I know.
Clean up, check all check box => This work for me
Your logic is flawed... basically, you need to:
You're not doing step 2.
Here's the code you want:
Properties prop = new Properties();
prop.load(new FileInputStream("/displayCategerization.properties"));
for (Map.Entry<Object, Object> entry : prop.entrySet())
{
List<String> categoryList = categoryMap.get((String) entry.getKey());
if (categoryList == null)
{
categoryList = new ArrayList<String>();
LogDisplayService.categoryMap.put((String) entry.getKey(), categoryList);
}
categoryList.add((String) entry.getValue());
}
Note also the "correct" way to iterate over the entries of a map/properties - via its entrySet()
.
also check this out, for example we wanna count t
echo "test" | awk -v RS='t' 'END{print NR-1}'
or in python
python -c 'print "this is for test".count("t")'
or even better, we can make our script dynamic with awk
echo 'test' | awk '{for (i=1 ; i<=NF ; i++) array[$i]++ } END{ for (char in array) print char,array[char]}' FS=""
in this case output is like this :
e 1
s 1
t 2
The easiest way is to invite @get_id_bot in your chat and then type:
/my_id @get_id_bot
Inside your chat
yes there are some telltale signs for common CMSs like Drupal, Joomla, Pligg, and RoR etc .. .. ASP.NET stuff is easy to spot too .. but as the framework becomes more obscure it gets harder to deduce ..
What I usually is compare the site i am snooping with another site that I know is built using a particular tech. That sometimes works ..
Python lists are mutable objects and here:
plot_data = [[]] * len(positions)
you are repeating the same list len(positions)
times.
>>> plot_data = [[]] * 3
>>> plot_data
[[], [], []]
>>> plot_data[0].append(1)
>>> plot_data
[[1], [1], [1]]
>>>
Each list in your list is a reference to the same object. You modify one, you see the modification in all of them.
If you want different lists, you can do this way:
plot_data = [[] for _ in positions]
for example:
>>> pd = [[] for _ in range(3)]
>>> pd
[[], [], []]
>>> pd[0].append(1)
>>> pd
[[1], [], []]
This is working for me:
this.listCopy = Object.assign([], this.list);
You can use flexbox to center your text. By the way no need for extra containers because text is considered as anonymous flex item.
From flexbox specs:
Each in-flow child of a flex container becomes a flex item, and each contiguous run of text that is directly contained inside a flex container is wrapped in an anonymous flex item. However, an anonymous flex item that contains only white space (i.e. characters that can be affected by the
white-space
property) is not rendered (just as if it weredisplay:none
).
So just make grid items as flex containers (display: flex
), and add align-items: center
and justify-content: center
to center both vertically and horizontally.
Also performed optimization of HTML and CSS:
html,_x000D_
body {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
.container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-template-rows: 100vh;_x000D_
_x000D_
font-family: Raleway;_x000D_
font-size: large;_x000D_
}_x000D_
_x000D_
.left_bg,_x000D_
.right_bg {_x000D_
display: flex;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
}_x000D_
_x000D_
.left_bg {_x000D_
background-color: #3498db;_x000D_
}_x000D_
_x000D_
.right_bg {_x000D_
background-color: #ecf0f1;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="left_bg">Review my stuff</div>_x000D_
<div class="right_bg">Hire me!</div>_x000D_
</div>
_x000D_
int intLength(int i) {
int l=0;
for(;i;i/=10) l++;
return l==0 ? 1 : l;
}
Here's a tiny efficient one
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxImage.Checked)
{
groupBoxImage.Show();
}
else if (!checkBoxImage.Checked)
{
groupBoxImage.Hide();
}
}
You may need to run the cron job as a user with permissions to execute the PHP script. Try executing the cron job as root, using the command runuser
(man runuser
). Or create a system crontable and run the PHP script as an authorized user, as @Philip described.
I provide a detailed answer how to use cron in this stackoverflow post.
How to write a cron that will run a script every day at midnight?
This will work although when embedding PHP in HTML it is better practice to use the following form:
<table>
<?php foreach($array as $key=>$value): ?>
<tr>
<td><?= $key; ?></td>
</tr>
<?php endforeach; ?>
</table>
You can find the doc for the alternative syntax on PHP.net
Just about any error will throw an exceptions. The only errors I can think of that wouldn't work with the "pause on exceptions" option are syntax errors, which happen before any of the code gets executed, so there's no place to pause anyway and none of the code will run.
Apparently, Chrome won't pause on the exception if it's inside a try-catch block though. It only pauses on uncaught exceptions. I don't know of any way to change it.
If you just need to know what line the exception happened on (then you could set a breakpoint if the exception is reproducible), the Error
object given to the catch block has a stack
property that shows where the exception happened.
You could use printf()
with %f
:
double dexp = 12345678;
System.out.printf("dexp: %f\n", dexp);
This will print dexp: 12345678.000000
. If you don't want the fractional part, use
System.out.printf("dexp: %.0f\n", dexp);
0 in %.0f
means 0 places in fractional part i.e no fractional part. If you want to print fractional part with desired number of decimal places then instead of 0 just provide the number like this %.8f
. By default fractional part is printed up to 6 decimal places.
This uses the format specifier language explained in the documentation.
The default toString()
format used in your original code is spelled out here.
Without any problems, I imported directly from the command line.
mysql -uroot -hURLServer -p DBName< filename.sql
Haven't tested it, but that should alert the blobs data url:
var blob = event.clipboardData.items[0].getAsFile(),
form = new FormData(),
request = new XMLHttpRequest();
var reader = new FileReader();
reader.onload = function(event) {
alert(event.target.result); // <-- data url
};
reader.readAsDataURL(blob);
Check for the existence by retrieving its object_id:
if object_id('tempdb..##clients_keyword') is not null
drop table ##clients_keyword
@echo off
echo somethink
echo Press enter to exit
set /p input=
It's a SQL Compact database. You need to define what you mean by "Open". You can open it via code with the SqlCeConnection so you can write your own tool/app to access it.
Visual Studio can also open the files directly if was created with the right version of SQL Compact.
There are also some third-party tools for manipulating them.
...and don't forget what happens when you mix types:
x = 127;
x += " hours "
// x is now a string: "127 hours "
x += 1 === 0;
// x is still a string: "127 hours false"
The datasource is by default .\SQLEXPRESS (its the instance where databases are placed by default) or if u changed the name of the instance during installation of sql server so i advise you to do this :
connectionString="Data Source=.\\yourInstance(defaulT Data source is SQLEXPRESS);
Initial Catalog=databaseName;
User ID=theuser if u use it;
Password=thepassword if u use it;
integrated security=true(if u don t use user and pass; else change it false)"
Without to knowing your instance, I could help with this one. Hope it helped
Here, you could use cv2.bitwise_and
function if you already have the mask image.
For check the below code:
img = cv2.imread('lena.jpg')
mask = cv2.imread('mask.png',0)
res = cv2.bitwise_and(img,img,mask = mask)
The output will be as follows for a lena image, and for rectangular mask.
You care about two things when querying - accuracy and performance. With that in mind, I tested a few different approaches in MongoDB v3.0.14.
TL;DR db.doc.find({ nums: { $gt: -Infinity }})
is the fastest and most reliable (at least in the MongoDB version I tested).
EDIT: This no longer works in MongoDB v3.6! See the comments under this post for a potential solution.
I inserted 1k docs w/o a list field, 1k docs with an empty list, and 5 docs with a non-empty list.
for (var i = 0; i < 1000; i++) { db.doc.insert({}); }
for (var i = 0; i < 1000; i++) { db.doc.insert({ nums: [] }); }
for (var i = 0; i < 5; i++) { db.doc.insert({ nums: [1, 2, 3] }); }
db.doc.createIndex({ nums: 1 });
I recognize this isn't enough of a scale to take performance as seriously as I am in the tests below, but it's enough to present the correctness of various queries and behavior of chosen query plans.
db.doc.find({'nums': {'$exists': true}})
returns wrong results (for what we're trying to accomplish).
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': {'$exists': true}}).count()
1005
--
db.doc.find({'nums.0': {'$exists': true}})
returns correct results, but it's also slow using a full collection scan (notice COLLSCAN
stage in the explanation).
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums.0': {'$exists': true}}).count()
5
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums.0': {'$exists': true}}).explain()
{
"queryPlanner": {
"plannerVersion": 1,
"namespace": "test.doc",
"indexFilterSet": false,
"parsedQuery": {
"nums.0": {
"$exists": true
}
},
"winningPlan": {
"stage": "COLLSCAN",
"filter": {
"nums.0": {
"$exists": true
}
},
"direction": "forward"
},
"rejectedPlans": [ ]
},
"serverInfo": {
"host": "MacBook-Pro",
"port": 27017,
"version": "3.0.14",
"gitVersion": "08352afcca24bfc145240a0fac9d28b978ab77f3"
},
"ok": 1
}
--
db.doc.find({'nums': { $exists: true, $gt: { '$size': 0 }}})
returns wrong results. That's because of an invalid index scan advancing no documents. It will likely be accurate but slow without the index.
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $gt: { '$size': 0 }}}).count()
0
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $gt: { '$size': 0 }}}).explain('executionStats').executionStats.executionStages
{
"stage": "KEEP_MUTATIONS",
"nReturned": 0,
"executionTimeMillisEstimate": 0,
"works": 2,
"advanced": 0,
"needTime": 0,
"needFetch": 0,
"saveState": 0,
"restoreState": 0,
"isEOF": 1,
"invalidates": 0,
"inputStage": {
"stage": "FETCH",
"filter": {
"$and": [
{
"nums": {
"$gt": {
"$size": 0
}
}
},
{
"nums": {
"$exists": true
}
}
]
},
"nReturned": 0,
"executionTimeMillisEstimate": 0,
"works": 1,
"advanced": 0,
"needTime": 0,
"needFetch": 0,
"saveState": 0,
"restoreState": 0,
"isEOF": 1,
"invalidates": 0,
"docsExamined": 0,
"alreadyHasObj": 0,
"inputStage": {
"stage": "IXSCAN",
"nReturned": 0,
"executionTimeMillisEstimate": 0,
"works": 1,
"advanced": 0,
"needTime": 0,
"needFetch": 0,
"saveState": 0,
"restoreState": 0,
"isEOF": 1,
"invalidates": 0,
"keyPattern": {
"nums": 1
},
"indexName": "nums_1",
"isMultiKey": true,
"direction": "forward",
"indexBounds": {
"nums": [
"({ $size: 0.0 }, [])"
]
},
"keysExamined": 0,
"dupsTested": 0,
"dupsDropped": 0,
"seenInvalidated": 0,
"matchTested": 0
}
}
}
--
db.doc.find({'nums': { $exists: true, $not: { '$size': 0 }}})
returns correct results, but the performance is bad. It technically does an index scan, but then it still advances all the docs and then has to filter through them).
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $not: { '$size': 0 }}}).count()
5
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $not: { '$size': 0 }}}).explain('executionStats').executionStats.executionStages
{
"stage": "KEEP_MUTATIONS",
"nReturned": 5,
"executionTimeMillisEstimate": 0,
"works": 2016,
"advanced": 5,
"needTime": 2010,
"needFetch": 0,
"saveState": 15,
"restoreState": 15,
"isEOF": 1,
"invalidates": 0,
"inputStage": {
"stage": "FETCH",
"filter": {
"$and": [
{
"nums": {
"$exists": true
}
},
{
"$not": {
"nums": {
"$size": 0
}
}
}
]
},
"nReturned": 5,
"executionTimeMillisEstimate": 0,
"works": 2016,
"advanced": 5,
"needTime": 2010,
"needFetch": 0,
"saveState": 15,
"restoreState": 15,
"isEOF": 1,
"invalidates": 0,
"docsExamined": 2005,
"alreadyHasObj": 0,
"inputStage": {
"stage": "IXSCAN",
"nReturned": 2005,
"executionTimeMillisEstimate": 0,
"works": 2015,
"advanced": 2005,
"needTime": 10,
"needFetch": 0,
"saveState": 15,
"restoreState": 15,
"isEOF": 1,
"invalidates": 0,
"keyPattern": {
"nums": 1
},
"indexName": "nums_1",
"isMultiKey": true,
"direction": "forward",
"indexBounds": {
"nums": [
"[MinKey, MaxKey]"
]
},
"keysExamined": 2015,
"dupsTested": 2015,
"dupsDropped": 10,
"seenInvalidated": 0,
"matchTested": 0
}
}
}
--
db.doc.find({'nums': { $exists: true, $ne: [] }})
returns correct results and is slightly faster, but the performance is still not ideal. It uses IXSCAN which only advances docs with an existing list field, but then has to filter out the empty lists one by one.
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $ne: [] }}).count()
5
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $ne: [] }}).explain('executionStats').executionStats.executionStages
{
"stage": "KEEP_MUTATIONS",
"nReturned": 5,
"executionTimeMillisEstimate": 0,
"works": 1018,
"advanced": 5,
"needTime": 1011,
"needFetch": 0,
"saveState": 15,
"restoreState": 15,
"isEOF": 1,
"invalidates": 0,
"inputStage": {
"stage": "FETCH",
"filter": {
"$and": [
{
"$not": {
"nums": {
"$eq": [ ]
}
}
},
{
"nums": {
"$exists": true
}
}
]
},
"nReturned": 5,
"executionTimeMillisEstimate": 0,
"works": 1017,
"advanced": 5,
"needTime": 1011,
"needFetch": 0,
"saveState": 15,
"restoreState": 15,
"isEOF": 1,
"invalidates": 0,
"docsExamined": 1005,
"alreadyHasObj": 0,
"inputStage": {
"stage": "IXSCAN",
"nReturned": 1005,
"executionTimeMillisEstimate": 0,
"works": 1016,
"advanced": 1005,
"needTime": 11,
"needFetch": 0,
"saveState": 15,
"restoreState": 15,
"isEOF": 1,
"invalidates": 0,
"keyPattern": {
"nums": 1
},
"indexName": "nums_1",
"isMultiKey": true,
"direction": "forward",
"indexBounds": {
"nums": [
"[MinKey, undefined)",
"(undefined, [])",
"([], MaxKey]"
]
},
"keysExamined": 1016,
"dupsTested": 1015,
"dupsDropped": 10,
"seenInvalidated": 0,
"matchTested": 0
}
}
}
--
db.doc.find({'nums': { $gt: [] }})
IS DANGEROUS BECAUSE DEPENDING ON THE INDEX USED IT MIGHT GIVE UNEXPECTED RESULTS. That's because of an invalid index scan which advances no documents.
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $gt: [] }}).count()
0
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $gt: [] }}).hint({ nums: 1 }).count()
0
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $gt: [] }}).hint({ _id: 1 }).count()
5
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $gt: [] }}).explain('executionStats').executionStats.executionStages
{
"stage": "KEEP_MUTATIONS",
"nReturned": 0,
"executionTimeMillisEstimate": 0,
"works": 1,
"advanced": 0,
"needTime": 0,
"needFetch": 0,
"saveState": 0,
"restoreState": 0,
"isEOF": 1,
"invalidates": 0,
"inputStage": {
"stage": "FETCH",
"filter": {
"nums": {
"$gt": [ ]
}
},
"nReturned": 0,
"executionTimeMillisEstimate": 0,
"works": 1,
"advanced": 0,
"needTime": 0,
"needFetch": 0,
"saveState": 0,
"restoreState": 0,
"isEOF": 1,
"invalidates": 0,
"docsExamined": 0,
"alreadyHasObj": 0,
"inputStage": {
"stage": "IXSCAN",
"nReturned": 0,
"executionTimeMillisEstimate": 0,
"works": 1,
"advanced": 0,
"needTime": 0,
"needFetch": 0,
"saveState": 0,
"restoreState": 0,
"isEOF": 1,
"invalidates": 0,
"keyPattern": {
"nums": 1
},
"indexName": "nums_1",
"isMultiKey": true,
"direction": "forward",
"indexBounds": {
"nums": [
"([], BinData(0, ))"
]
},
"keysExamined": 0,
"dupsTested": 0,
"dupsDropped": 0,
"seenInvalidated": 0,
"matchTested": 0
}
}
}
--
db.doc.find({'nums.0’: { $gt: -Infinity }})
returns correct results, but has bad performance (uses a full collection scan).
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums.0': { $gt: -Infinity }}).count()
5
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums.0': { $gt: -Infinity }}).explain('executionStats').executionStats.executionStages
{
"stage": "COLLSCAN",
"filter": {
"nums.0": {
"$gt": -Infinity
}
},
"nReturned": 5,
"executionTimeMillisEstimate": 0,
"works": 2007,
"advanced": 5,
"needTime": 2001,
"needFetch": 0,
"saveState": 15,
"restoreState": 15,
"isEOF": 1,
"invalidates": 0,
"direction": "forward",
"docsExamined": 2005
}
--
db.doc.find({'nums': { $gt: -Infinity }})
surprisingly, this works very well! It gives the right results and it's fast, advancing 5 docs from the index scan phase.
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $gt: -Infinity }}).explain('executionStats').executionStats.executionStages
{
"stage": "FETCH",
"nReturned": 5,
"executionTimeMillisEstimate": 0,
"works": 16,
"advanced": 5,
"needTime": 10,
"needFetch": 0,
"saveState": 0,
"restoreState": 0,
"isEOF": 1,
"invalidates": 0,
"docsExamined": 5,
"alreadyHasObj": 0,
"inputStage": {
"stage": "IXSCAN",
"nReturned": 5,
"executionTimeMillisEstimate": 0,
"works": 15,
"advanced": 5,
"needTime": 10,
"needFetch": 0,
"saveState": 0,
"restoreState": 0,
"isEOF": 1,
"invalidates": 0,
"keyPattern": {
"nums": 1
},
"indexName": "nums_1",
"isMultiKey": true,
"direction": "forward",
"indexBounds": {
"nums": [
"(-inf.0, inf.0]"
]
},
"keysExamined": 15,
"dupsTested": 15,
"dupsDropped": 10,
"seenInvalidated": 0,
"matchTested": 0
}
}
Some fixes I've used for this problem:
Check if the connection you want to share is shareable.
a. Press Win-key + r and run ncpa.cpl
b. Right click on the connection you want to share and go to properties
c. Go to sharing tab and check if sharing is enabled
Run devmgmt.msc
from the run console.
a. Expand the network adapters list
b. Right click -> properties on the adapter of the connection you want to share
c. Go to power management tab and enable allow this computer to turn off this device to save power
. Restart your laptop if you've made changes.
Check if airplane mode is disabled. You can enable airplane mode and then turn on the wi-fi, you can never know. Do disable airplane mode if it is on.
Use admin command prompt to run this command.
Below grep with regex is also working,
>pwd | grep -o "\w*-*$"
If doing from scratch in Bootstrap 4
$enable-responsive-font-sizes
and turn it on.If the child is always going to be a specific tag then you could do it like this
function test(el)
{
var children = el.getElementsByTagName('div');// any tag could be used here..
for(var i = 0; i< children.length;i++)
{
if (children[i].getAttribute('id') == 'child') // any attribute could be used here
{
// do what ever you want with the element..
// children[i] holds the element at the moment..
}
}
}
There are several methods to accomplish this, each of which has advantages and disadvantages; First and foremost, you're going to need to have an instance of a Worksheet object, Application.ActiveSheet works if you just want the one the user is looking at.
The Worksheet object has three properties that can be used to access cell data (Cells, Rows, Columns) and a method that can be used to obtain a block of cell data, (get_Range).
Ranges can be resized and such, but you may need to use the properties mentioned above to find out where the boundaries of your data are. The advantage to a Range becomes apparent when you are working with large amounts of data because VSTO add-ins are hosted outside the boundaries of the Excel application itself, so all calls to Excel have to be passed through a layer with overhead; obtaining a Range allows you to get/set all of the data you want in one call which can have huge performance benefits, but it requires you to use explicit details rather than iterating through each entry.
This MSDN forum post shows a VB.Net developer asking a question about getting the results of a Range as an array
public class SecondHighInIntArray {
public static void main(String[] args) {
int[] intArray=new int[]{2,2,1};
//{2,2,1,12,3,7,9,-1,-5,7};
int secHigh=findSecHigh(intArray);
System.out.println(secHigh);
}
private static int findSecHigh(int[] intArray) {
int highest=Integer.MIN_VALUE;
int sechighest=Integer.MIN_VALUE;
int len=intArray.length;
for(int i=0;i<len;i++)
{
if(intArray[i]>highest)
{
sechighest=highest;
highest=intArray[i];
continue;
}
if(intArray[i]<highest && intArray[i]>sechighest)
{
sechighest=intArray[i];
continue;
}
}
return sechighest;
}
}
The Excel number for a modern date is most easily calculated as the number of days since 12/30/1899 on the Gregorian calendar.
Excel treats the mythical date 01/00/1900 (i.e., 12/31/1899) as corresponding to 0, and incorrectly treats year 1900 as a leap year. So for dates before 03/01/1900, the Excel number is effectively the number of days after 12/31/1899.
However, Excel will not format any number below 0 (-1 gives you ##########) and so this only matters for "01/00/1900" to 02/28/1900, making it easier to just use the 12/30/1899 date as a base.
A complete function in DB2 SQL that accounts for the leap year 1900 error:
SELECT
DAYS(INPUT_DATE)
- DAYS(DATE('1899-12-30'))
- CASE
WHEN INPUT_DATE < DATE('1900-03-01')
THEN 1
ELSE 0
END
The NetworkInfo
class is deprecated as of API level 29, along with the related access methods like ConnectivityManager#getNetworkInfo()
and ConnectivityManager#getActiveNetworkInfo()
.
The documentation now suggests people to use the ConnectivityManager.NetworkCallback
API for asynchronized callback monitoring, or use ConnectivityManager#getNetworkCapabilities
or ConnectivityManager#getLinkProperties
for synchronized access of network information
Callers should instead use the ConnectivityManager.NetworkCallback API to learn about connectivity changes, or switch to use ConnectivityManager#getNetworkCapabilities or ConnectivityManager#getLinkProperties to get information synchronously.
To check if WiFi is connected, here's the code that I use:
Kotlin:
val connMgr = applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
connMgr?: return false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val network: Network = connMgr.activeNetwork ?: return false
val capabilities = connMgr.getNetworkCapabilities(network)
return capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
} else {
val networkInfo = connMgr.activeNetworkInfo ?: return false
return networkInfo.isConnected && networkInfo.type == ConnectivityManager.TYPE_WIFI
}
Java:
ConnectivityManager connMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connMgr == null) {
return false;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network network = connMgr.getActiveNetwork();
if (network == null) return false;
NetworkCapabilities capabilities = connMgr.getNetworkCapabilities(network);
return capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
} else {
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
}
Remember to also add permission ACCESS_NETWORK_STATE
to your Manifest file.
In Visual Studio 2015 Update3 I have this feature.
Just by highlighting properties and then press Ctrl + . and then press Generate Constructor.
For example, if you've highlighted two properties it will suggest you to create a constructor with two parameters and if you've selected three it will suggest one with three parameters and so on.
It also works with Visual Studio 2017 and 2019.
JSONObject json = new JSONObject();
json.put("fromZIPCode","123456");
JSONObject json1 = new JSONObject();
json1.put("fromZIPCode","123456");
sList.add(json1);
sList.add(json);
System.out.println(sList);
Output will be
[{"fromZIPCode":"123456"},{"fromZIPCode":"123456"}]
3 easy steps to run your PHP program is:
The easiest way is to install MAMP!
Do a 2-minute setup of MAMP.
Open the localhost server in your browser at the created port to see your program up and runing!
Funny, I recently had to do this.
function padDigits(number, digits) {
return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}
Use like:
padDigits(9, 4); // "0009"
padDigits(10, 4); // "0010"
padDigits(15000, 4); // "15000"
Not beautiful, but effective.
If you pass the -v
flag to the ansible-playbook command, then ansible will show the output on your terminal.
For your use case, you may want to try using the fetch module to copy the public key from the server to your local machine. That way, it will only show a "changed" status when the file changes.
Try this:
def word(string, num)
string = 'Smith'
string[0..(num-1)]
end
I believe the problem is that codecs.BOM_UTF8
is a byte string, not a Unicode string. I suspect the file handler is trying to guess what you really mean based on "I'm meant to be writing Unicode as UTF-8-encoded text, but you've given me a byte string!"
Try writing the Unicode string for the byte order mark (i.e. Unicode U+FEFF) directly, so that the file just encodes that as UTF-8:
import codecs
file = codecs.open("lol", "w", "utf-8")
file.write(u'\ufeff')
file.close()
(That seems to give the right answer - a file with bytes EF BB BF.)
EDIT: S. Lott's suggestion of using "utf-8-sig" as the encoding is a better one than explicitly writing the BOM yourself, but I'll leave this answer here as it explains what was going wrong before.
By using reflection, private methods can be called from test classes. In this case,
//test method will be like this ...
public class TestA {
@Test
public void testMethod() {
A a= new A();
Method privateMethod = A.class.getDeclaredMethod("method1", null);
privateMethod.setAccessible(true);
// invoke the private method for test
privateMethod.invoke(A, null);
}
}
If the private method calls any other private method, then we need to spy the object and stub the another method.The test class will be like ...
//test method will be like this ...
public class TestA {
@Test
public void testMethod() {
A a= new A();
A spyA = spy(a);
Method privateMethod = A.class.getDeclaredMethod("method1", null);
privateMethod.setAccessible(true);
doReturn("Test").when(spyA, "method2"); // if private method2 is returning string data
// invoke the private method for test
privateMethod.invoke(spyA , null);
}
}
**The approach is to combine reflection and spying the object. **method1 and **method2 are private methods and method1 calls method2.
why not simply just give the input field where you want to jump to a id and do a simple focus
$("#newListField").focus();
You can always do increasing range and subtract from a variable in your case 100 - i
where i in range( 0, 101 )
.
for i in range( 0, 101 ):
print 100 - i
Math.round also returns an integer value, so you don't need to typecast.
int b = Math.round(float a);
This is an older post, however as the info is still relevant today an additional option may help others.
Define a constant for the file path per Stefan's answer. The definition can be placed at the top of the PHP page itself, or within an included/required external file such as config.php. (http://php.net/manual/en/function.include.php)
Echo the constant in PHP tags, then add the filename directly after.
That's it!
Works for other linked files such as JavaScript as well.
<?php define('CSS_PATH', 'template/css/'); //define CSS path define('JS_PATH', 'template/js/'); //define JavaScript path ?> <!-- Doctype should be declared, even in PHP file --> <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="<?php echo CSS_PATH; ?>main.css"> <script type="text/javascript" src="<?php echo JS_PATH; ?>main.js"></script> </head> <body> </body> </html>
If there is an interface anywhere in the ThreadProvider hierarchy try putting the name of the Interface as the type of your service provider, eg. if you have say this structure:
public class ThreadProvider implements CustomInterface{
...
}
Then in your controller try this:
@Controller
public class ChiusuraController {
@Autowired
private CustomInterface chiusuraProvider;
}
The reason why this is happening is, in your first case when you DID NOT have ChiusuraProvider
extend ThreadProvider
Spring probably was underlying creating a CGLIB based proxy for you(to handle the @Transaction).
When you DID extend from ThreadProvider
assuming that ThreadProvider extends some interface, Spring in that case creates a Java Dynamic Proxy based Proxy, which would appear to be an implementation of that interface instead of being of ChisuraProvider
type.
If you absolutely need to use ChisuraProvider
you can try AspectJ as an alternative or force CGLIB based proxy in the case with ThreadProvider also this way:
<aop:aspectj-autoproxy proxy-target-class="true"/>
Here is some more reference on this from the Spring Reference site: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/classic-aop-spring.html#classic-aop-pfb
The issue with most of the other answers is that they use Distinct
, GroupBy
or ToLookup
, which creates an extra Dictionary under the hood. Equally ToUpper creates extra string.
This is what I did, which is an almost an exact copy of Microsoft's code except for one change:
public static Dictionary<TKey, TSource> ToDictionaryIgnoreDup<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer = null) =>
source.ToDictionaryIgnoreDup(keySelector, i => i, comparer);
public static Dictionary<TKey, TElement> ToDictionaryIgnoreDup<TSource, TKey, TElement>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer = null)
{
if (keySelector == null)
throw new ArgumentNullException(nameof(keySelector));
if (elementSelector == null)
throw new ArgumentNullException(nameof(elementSelector));
var d = new Dictionary<TKey, TElement>(comparer ?? EqualityComparer<TKey>.Default);
foreach (var element in source)
d[keySelector(element)] = elementSelector(element);
return d;
}
Because a set on the indexer causes it to add the key, it will not throw, and will also do only one key lookup. You can also give it an IEqualityComparer
, for example StringComparer.OrdinalIgnoreCase
If you haven't yet pushed your changes, you can also do a soft reset:
git reset --soft HEAD^
This will revert the commit, but put the committed changes back into your index. Assuming the branches are relatively up-to-date with regard to each other, git will let you do a checkout into the other branch, whereupon you can simply commit:
git checkout branch
git commit
The disadvantage is that you need to re-enter your commit message.
ES6 style allows you to use new features, such as super
keyword. super
keyword it's all about parent class context, when you are using ES6 classes syntax. As a very simple example, checkout:
class Foo {
static classMethod() {
return 'hello';
}
}
class Bar extends Foo {
static classMethod() {
return super.classMethod() + ', too';
}
}
Bar.classMethod(); // 'hello, too'
Also, you can use super
to call parent constructor:
class Foo {}
class Bar extends Foo {
constructor(num) {
let tmp = num * 2; // OK
this.num = num; // ReferenceError
super();
this.num = num; // OK
}
}
And of course you can use it to access parent class properties super.prop
.
So, use ES6 and be happy.
How about SymPy? Their solver looks like what you need. Have a look at their source code if you want to build the library yourself…
You can use :nth-child(N) CSS selector like :
table td:first-child {} //1
table td:nth-child(2) {} //2
table td:nth-child(3) {} //3
table td:last-child {} //4
Here is my code to create procedure in MySQL :
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `procedureName`(IN comId int)
BEGIN
select * from tableName
(add joins OR sub query as per your requirement)
Where (where condition here)
END $$
DELIMITER ;
To call this procedure use this query :
call procedureName(); // without parameter
call procedureName(id,pid); // with parameter
Detail :
1) DEFINER : root is the user name and change it as per your username of mysql localhost is the host you can change it with ip address of the server if you are execute this query on hosting server.
Read here for more detail
Maybe you can filter rows by possible columns like this :
DataRow[] filteredRows =
datatable.Select(string.Format("{0} LIKE '%{1}%'", columnName, value));
There is an implicit call to super()
with no arguments for all classes that have a parent - which is every user defined class in Java - so calling it explicitly is usually not required. However, you may use the call to super()
with arguments if the parent's constructor takes parameters, and you wish to specify them. Moreover, if the parent's constructor takes parameters, and it has no default parameter-less constructor, you will need to call super()
with argument(s).
An example, where the explicit call to super()
gives you some extra control over the title of the frame:
class MyFrame extends JFrame
{
public MyFrame() {
super("My Window Title");
...
}
}
Begin with Turtle graphics in Python.
I would use the turtle graphics which comes standard with Python. It is visual, simple and you could use this environment to introduce many programming concepts like iteration and procedure calls before getting too far into syntax. Consider the following interactive session in python:
>>> from turtle import *
>>> setup()
>>> title("turtle test")
>>> clear()
>>>
>>> #DRAW A SQUARE
>>> down() #pen down
>>> forward(50) #move forward 50 units
>>> right(90) #turn right 90 degrees
>>> forward(50)
>>> right(90)
>>> forward(50)
>>> right(90)
>>> forward(50)
>>>
>>> #INTRODUCE ITERATION TO SIMPLIFY SQUARE CODE
>>> clear()
>>> for i in range(4):
forward(50)
right(90)
>>>
>>> #INTRODUCE PROCEDURES
>>> def square(length):
down()
for i in range(4):
forward(length)
right(90)
>>>
>>> #HAVE STUDENTS PREDICT WHAT THIS WILL DRAW
>>> for i in range(50):
up()
left(90)
forward(25)
square(i)
>>>
>>> #NOW HAVE THE STUDENTS WRITE CODE TO DRAW
>>> #A SQUARE 'TUNNEL' (I.E. CONCENTRIC SQUARES
>>> #GETTING SMALLER AND SMALLER).
>>>
>>> #AFTER THAT, MAKE THE TUNNEL ROTATE BY HAVING
>>> #EACH SUCCESSIVE SQUARE TILTED
In trying to accomplish the last two assignments, they will have many failed attempts, but the failures will be visually interesting and they'll learn quickly as they try to figure out why it didn't draw what they expected.
As an aside, I was in search to find the best way to implode an associative array but using my own seperators etc...
So I did this using PHP's array_walk() function to let me join an associative array into a list of parameters that could then be applied to a HTML tag....
// Create Params Array
$p = Array("id"=>"blar","class"=>"myclass","onclick"=>"myJavascriptFunc()");
// Join Params
array_walk($p, create_function('&$i,$k','$i=" $k=\"$i\"";'));
$p_string = implode($p,"");
// Now use $p_string for your html tag
Obviously, you could stick that in your own function somehow but it gives you an idea of how you can join an associative array using your own method. Hope that helps someone :)
The b denotes a byte string.
Bytes are the actual data. Strings are an abstraction.
If you had multi-character string object and you took a single character, it would be a string, and it might be more than 1 byte in size depending on encoding.
If took 1 byte with a byte string, you'd get a single 8-bit value from 0-255 and it might not represent a complete character if those characters due to encoding were > 1 byte.
TBH I'd use strings unless I had some specific low level reason to use bytes.
I wrote the following simple class as, effectively, a way to emulate a pointer in python:
class Parameter:
"""Syntactic sugar for getter/setter pair
Usage:
p = Parameter(getter, setter)
Set parameter value:
p(value)
p.val = value
p.set(value)
Retrieve parameter value:
p()
p.val
p.get()
"""
def __init__(self, getter, setter):
"""Create parameter
Required positional parameters:
getter: called with no arguments, retrieves the parameter value.
setter: called with value, sets the parameter.
"""
self._get = getter
self._set = setter
def __call__(self, val=None):
if val is not None:
self._set(val)
return self._get()
def get(self):
return self._get()
def set(self, val):
self._set(val)
@property
def val(self):
return self._get()
@val.setter
def val(self, val):
self._set(val)
Here's an example of use (from a jupyter notebook page):
l1 = list(range(10))
def l1_5_getter(lst=l1, number=5):
return lst[number]
def l1_5_setter(val, lst=l1, number=5):
lst[number] = val
[
l1_5_getter(),
l1_5_setter(12),
l1,
l1_5_getter()
]
Out = [5, None, [0, 1, 2, 3, 4, 12, 6, 7, 8, 9], 12]
p = Parameter(l1_5_getter, l1_5_setter)
print([
p(),
p.get(),
p.val,
p(13),
p(),
p.set(14),
p.get()
])
p.val = 15
print(p.val, l1)
[12, 12, 12, 13, 13, None, 14]
15 [0, 1, 2, 3, 4, 15, 6, 7, 8, 9]
Of course, it is also easy to make this work for dict items or attributes of an object. There is even a way to do what the OP asked for, using globals():
def setter(val, dict=globals(), key='a'):
dict[key] = val
def getter(dict=globals(), key='a'):
return dict[key]
pa = Parameter(getter, setter)
pa(2)
print(a)
pa(3)
print(a)
This will print out 2, followed by 3.
Messing with the global namespace in this way is kind of transparently a terrible idea, but it shows that it is possible (if inadvisable) to do what the OP asked for.
The example is, of course, fairly pointless. But I have found this class to be useful in the application for which I developed it: a mathematical model whose behavior is governed by numerous user-settable mathematical parameters, of diverse types (which, because they depend on command line arguments, are not known at compile time). And once access to something has been encapsulated in a Parameter object, all such objects can be manipulated in a uniform way.
Although it doesn't look much like a C or C++ pointer, this is solving a problem that I would have solved with pointers if I were writing in C++.