As of July 2019, the easiest method is to use: flutter doctor --android-licenses
in the command prompt.
It proceeds to display the unaccepted T&C of SDKs one by one and you're given option to choose 'y/n'. Choose y for all.
Alternately, when you run flutter doctor
, it will run Android toolchain diagnostics which displays how many licenses are not yet accepted, and suggests you to run it with the --android-licenses flag.
I found out that it also happens if you uninstalled some packages from your react-native project and there is still packages in your build gradle dependencies in the bottom of page like:
{
project(':react-native-sound-player')
}
<manifest xmlns:tools="http://schemas.android.com/tools" ... >
<uses-sdk tools:overrideLibrary="nl.innovalor.ocr, nl.innovalor.corelib" />
I was facing the issue of conflict between different min sdk versions. So this solution worked for me.
I have set up Volley as a separate Project. That way its not tied to any project and exist independently.
I also have a Nexus server (Internal repo) setup so I can access volley as
compile 'com.mycompany.volley:volley:1.0.4' in any project I need.
Any time I update Volley project, I just need to change the version number in other projects.
I feel very comfortable with this approach.
AndroidStudio is alpha version for now. So you have to edit gradle build script files by yourself. Add next lines to your build.gradle
android {
signingConfigs {
release {
storeFile file('android.keystore')
storePassword "pwd"
keyAlias "alias"
keyPassword "pwd"
}
}
buildTypes {
release {
signingConfig signingConfigs.release
}
}
}
To actually run your application at emulator or device run gradle installDebug
or gradle installRelease
.
You can create helloworld project from AndroidStudio wizard to see what structure of gradle files is needed. Or export gradle files from working eclipse project. Also this series of articles are helpfull http://blog.stylingandroid.com/archives/1872#more-1872
What solved my problem was just using the below two lines in ipython notebook at the top
%matplotib inline
%pylab inline
And it worked. I'm using Ubuntu16.04 and ipython-5.1
Use TRY_CAST function in exact same way of CAST function. TRY_CAST takes a string and tries to cast it to a data type specified after the AS keyword. If the conversion fails, TRY_CAST returns a NULL instead of failing.
Switching to a multibranch pipeline allowed me to access the branch name. A regular pipeline was not advised.
As a variation of @tangens answer: if you can't wait for the garbage collector to clean up your thread, cancel the timer at the end of your run method.
Timer t = new java.util.Timer();
t.schedule(
new java.util.TimerTask() {
@Override
public void run() {
// your code here
// close the thread
t.cancel();
}
},
5000
);
To expand on Jonathon Faust's and McDowell's answers: If you're on a *nix based system, you can use od
(one of the earliest Unix programs1 which should be available practically everywhere) to query the .class
file on a binary level:
od -An -j7 -N1 -t dC SomeClassFile.class
This will output the familiar integer values, e.g. 50
for Java 5
, 51
for Java 6
and so on.
1 Quote from https://en.wikipedia.org/wiki/Od_(Unix)
For mass assignment of values to an ActiveRecord model without saving, use either the assign_attributes
or attributes=
methods. These methods are available in Rails 3 and newer. However, there are minor differences and version-related gotchas to be aware of.
Both methods follow this usage:
@user.assign_attributes{ model: "Sierra", year: "2012", looks: "Sexy" }
@user.attributes = { model: "Sierra", year: "2012", looks: "Sexy" }
Note that neither method will perform validations or execute callbacks; callbacks and validation will happen when save
is called.
attributes=
differs slightly from assign_attributes
in Rails 3. attributes=
will check that the argument passed to it is a Hash, and returns immediately if it is not; assign_attributes
has no such Hash check. See the ActiveRecord Attribute Assignment API documentation for attributes=
.
The following invalid code will silently fail by simply returning without setting the attributes:
@user.attributes = [ { model: "Sierra" }, { year: "2012" }, { looks: "Sexy" } ]
attributes=
will silently behave as though the assignments were made successfully, when really, they were not.
This invalid code will raise an exception when assign_attributes
tries to stringify the hash keys of the enclosing array:
@user.assign_attributes([ { model: "Sierra" }, { year: "2012" }, { looks: "Sexy" } ])
assign_attributes
will raise a NoMethodError
exception for stringify_keys
, indicating that the first argument is not a Hash. The exception itself is not very informative about the actual cause, but the fact that an exception does occur is very important.
The only difference between these cases is the method used for mass assignment: attributes=
silently succeeds, and assign_attributes
raises an exception to inform that an error has occurred.
These examples may seem contrived, and they are to a degree, but this type of error can easily occur when converting data from an API, or even just using a series of data transformation and forgetting to Hash[]
the results of the final .map
. Maintain some code 50 lines above and 3 functions removed from your attribute assignment, and you've got a recipe for failure.
The lesson with Rails 3 is this: always use assign_attributes
instead of attributes=
.
In Rails 4, attributes=
is simply an alias to assign_attributes
. See the ActiveRecord Attribute Assignment API documentation for attributes=
.
With Rails 4, either method may be used interchangeably. Failure to pass a Hash as the first argument will result in a very helpful exception: ArgumentError: When assigning attributes, you must pass a hash as an argument.
If you're pre-flighting assignments in preparation to a save
, you might be interested in validating before save, as well. You can use the valid?
and invalid?
methods for this. Both return boolean values. valid?
returns true if the unsaved model passes all validations or false if it does not. invalid?
is simply the inverse of valid?
valid?
can be used like this:
@user.assign_attributes{ model: "Sierra", year: "2012", looks: "Sexy" }.valid?
This will give you the ability to handle any validations issues in advance of calling save
.
I think it is dangerous to use $.isEmptyObject from jquery to check whether the array is empty, as @jesenko mentioned. I just met that problem.
In the isEmptyObject doc, it mentions:
The argument should always be a plain JavaScript Object
which you can determine by $.isPlainObject
. The return of $.isPlainObject([])
is false.
I just ran into this and fixed it by doing 2 things:
Removing the SPNs that previously existed on the SQL Server computer account (as opposed to the service account) using
setspn -D MSSQLSvc/HOSTNAME.domain.name.com:1234 HOSTNAME
where 1234 was the port number used by the instance (mine was not a default instance).
See: http://www.html5-tutorials.org/tables/changing-column-width/
After the table tag, use the col element. you don't need a closing tag.
For example, if you had three columns:
<table>
<colgroup>
<col style="width:40%">
<col style="width:30%">
<col style="width:30%">
</colgroup>
<tbody>
...
</tbody>
</table>
As others have indicated, the raw_input
function has been renamed to input
in Python 3.0, and you really would be better served by a more up-to-date book, but I want to point out that there are better ways to see the output of your script.
From your description, I think you're using Windows, you've saved a .py
file and then you're double-clicking on it to run it. The terminal window that pops up closes as soon as your program ends, so you can't see what the result of your program was. To solve this, your book recommends adding a raw_input
/ input
statement to wait until the user presses enter. However, as you've seen, if something goes wrong, such as an error in your program, that statement won't be executed and the window will close without you being able to see what went wrong. You might find it easier to use a command-prompt or IDLE.
When you're looking at the folder window that contains your Python program, hold down shift and right-click anywhere in the white background area of the window. The menu that pops up should contain an entry "Open command window here". (I think this works on Windows Vista and Windows 7.) This will open a command-prompt window that looks something like this:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\Weeble\My Python Program>_
To run your program, type the following (substituting your script name):
python myscript.py
...and press enter. (If you get an error that "python" is not a recognized command, see http://showmedo.com/videotutorials/video?name=960000&fromSeriesID=96 ) When your program finishes running, whether it completes successfully or not, the window will remain open and the command-prompt will appear again for you to type another command. If you want to run your program again, you can press the up arrow to recall the previous command you entered and press enter to run it again, rather than having to type out the file name every time.
IDLE is a simple program editor that comes installed with Python. Among other features it can run your programs in a window. Right-click on your .py
file and choose "Edit in IDLE". When your program appears in the editor, press F5 or choose "Run module" from the "Run" menu. Your program will run in a window that stays open after your program ends, and in which you can enter Python commands to run immediately.
Is there a way to handle form post data in a Web Api controller?
The normal approach in ASP.NET Web API is to represent the form as a model so the media type formatter deserializes it. Alternative is to define the actions's parameter as NameValueCollection:
public void Post(NameValueCollection formData)
{
var value = formData["key"];
}
This is an alternative way of deleting records without leaving orphans.
Declare @user Table(keyValue int , someString varchar(10)) insert into @user values(1,'1 value') insert into @user values(2,'2 value') insert into @user values(3,'3 value') Declare @password Table( keyValue int , details varchar(10)) insert into @password values(1,'1 Password') insert into @password values(2,'2 Password') insert into @password values(3,'3 Password') --before deletion select * from @password a inner join @user b on a.keyvalue = b.keyvalue select * into #deletedID from @user where keyvalue=1 -- this works like the output example delete @user where keyvalue =1 delete @password where keyvalue in (select keyvalue from #deletedid) --After deletion-- select * from @password a inner join @user b on a.keyvalue = b.keyvalue
Assuming the current directory is not in the path, the syntax is ./[name of the program]
.
For example ./a.out
os._exit()
:
exit(0)
:
exit(1)
:
sys.exit()
:
quit()
:
Basically they all do the same thing, however, it also depends on what you are doing it for.
I don't think you left anything out and I would recommend getting used to quit()
or exit()
.
You would use sys.exit()
and os._exit()
mainly if you are using big files or are using python to control terminal.
Otherwise mainly use exit()
or quit()
.
Methods 1 and 2 work in Python 2 or 3, and they work on ragged, rectangular 2D lists. That means the inner lists do not need to have the same lengths as each other (ragged) or as the outer lists (rectangular). The other methods, well, it's complicated.
import itertools
import six
list_list = [[1,2,3], [4,5,6, 6.1, 6.2, 6.3], [7,8,9]]
map()
, zip_longest()
>>> list(map(list, six.moves.zip_longest(*list_list, fillvalue='-')))
[[1, 4, 7], [2, 5, 8], [3, 6, 9], ['-', 6.1, '-'], ['-', 6.2, '-'], ['-', 6.3, '-']]
six.moves.zip_longest()
becomes
itertools.izip_longest()
in Python 2itertools.zip_longest()
in Python 3The default fillvalue is None
. Thanks to @jena's answer, where map()
is changing the inner tuples to lists. Here it is turning iterators into lists. Thanks to @Oregano's and @badp's comments.
In Python 3, pass the result through list()
to get the same 2D list as method 2.
zip_longest()
>>> [list(row) for row in six.moves.zip_longest(*list_list, fillvalue='-')]
[[1, 4, 7], [2, 5, 8], [3, 6, 9], ['-', 6.1, '-'], ['-', 6.2, '-'], ['-', 6.3, '-']]
The @inspectorG4dget alternative.
map()
of map()
— broken in Python 3.6>>> map(list, map(None, *list_list))
[[1, 4, 7], [2, 5, 8], [3, 6, 9], [None, 6.1, None], [None, 6.2, None], [None, 6.3, None]]
This extraordinarily compact @SiggyF second alternative works with ragged 2D lists, unlike his first code which uses numpy to transpose and pass through ragged lists. But None has to be the fill value. (No, the None passed to the inner map() is not the fill value. It means there is no function to process each column. The columns are just passed through to the outer map() which converts them from tuples to lists.)
Somewhere in Python 3, map()
stopped putting up with all this abuse: the first parameter cannot be None, and ragged iterators are just truncated to the shortest. The other methods still work because this only applies to the inner map().
map()
of map()
revisited>>> list(map(list, map(lambda *args: args, *list_list)))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]] // Python 2.7
[[1, 4, 7], [2, 5, 8], [3, 6, 9], [None, 6.1, None], [None, 6.2, None], [None, 6.3, None]] // 3.6+
Alas the ragged rows do NOT become ragged columns in Python 3, they are just truncated. Boo hoo progress.
string firstdayofyear = new DateTime(DateTime.Now.Year, 1, 1).ToString("MM-dd-yyyy");
string lastdayofyear = new DateTime(DateTime.Now.Year, 12, 31).ToString("MM-dd-yyyy");
string firstdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("MM-dd-yyyy");
string lastdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1).ToString("MM-dd-yyyy");
Make sure you have a .babelrc file that declares what Babel is supposed to be transpiling. I spent like 30 minutes trying to figure this exact error. After I copied a bunch of files over to a new folder and found out I didn't copy the .babelrc file because it was hidden.
{
"presets": "es2015"
}
or something along those lines is what you are looking for inside your .babelrc file
#fullDiv {
height: 100%;
width: 100%;
left: 0;
top: 0;
overflow: hidden;
position: fixed;
}
In case if you want to implement your own Array.Copy method.
Static method which is of generic type.
static void MyCopy<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long destinationIndex, long copyNoOfElements)
{
long totaltraversal = sourceIndex + copyNoOfElements;
long sourceArrayLength = sourceArray.Length;
//to check all array's length and its indices properties before copying
CheckBoundaries(sourceArray, sourceIndex, destinationArray, copyNoOfElements, sourceArrayLength);
for (long i = sourceIndex; i < totaltraversal; i++)
{
destinationArray[destinationIndex++] = sourceArray[i];
}
}
Boundary method implementation.
private static void CheckBoundaries<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long copyNoOfElements, long sourceArrayLength)
{
if (sourceIndex >= sourceArray.Length)
{
throw new IndexOutOfRangeException();
}
if (copyNoOfElements > sourceArrayLength)
{
throw new IndexOutOfRangeException();
}
if (destinationArray.Length < copyNoOfElements)
{
throw new IndexOutOfRangeException();
}
}
A more general answer which accepts all the special characters including _
would be slightly different:
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[\W|\_])(?=\S+$).{8,}$
The difference (?=.*[\W|\_])
translates to "at least one of all the special characters including the underscore".
That error message means that there was not response OR the server could not be connected.
The following settings worked on my end:
'stream' => [
'ssl' => [
'allow_self_signed' => true,
'verify_peer' => false,
'verify_peer_name' => false,
],
]
Note that my SMTP settings are:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=[full gmail address]
MAIL_PASSWORD=[App Password obtained after two step verification]
MAIL_ENCRYPTION=ssl
If you want to give your user all read permissions, you could use:
EXEC sp_addrolemember N'db_datareader', N'your-user-name'
That adds the default db_datareader
role (read permission on all tables) to that user.
There's also a db_datawriter
role - which gives your user all WRITE permissions (INSERT, UPDATE, DELETE) on all tables:
EXEC sp_addrolemember N'db_datawriter', N'your-user-name'
If you need to be more granular, you can use the GRANT
command:
GRANT SELECT, INSERT, UPDATE ON dbo.YourTable TO YourUserName
GRANT SELECT, INSERT ON dbo.YourTable2 TO YourUserName
GRANT SELECT, DELETE ON dbo.YourTable3 TO YourUserName
and so forth - you can granularly give SELECT, INSERT, UPDATE, DELETE permission on specific tables.
This is all very well documented in the MSDN Books Online for SQL Server.
And yes, you can also do it graphically - in SSMS, go to your database, then Security > Users
, right-click on that user you want to give permissions to, then Properties
adn at the bottom you see "Database role memberships" where you can add the user to db roles.
For a more detailed answer on creating your own colormaps, I highly suggest visiting this page
If that answer is too much work, you can quickly make your own list of colors and pass them to the color
parameter. All the colormaps are in the cm
matplotlib module. Let's get a list of 30 RGB (plus alpha) color values from the reversed inferno colormap. To do so, first get the colormap and then pass it a sequence of values between 0 and 1. Here, we use np.linspace
to create 30 equally-spaced values between .4 and .8 that represent that portion of the colormap.
from matplotlib import cm
color = cm.inferno_r(np.linspace(.4, .8, 30))
color
array([[ 0.865006, 0.316822, 0.226055, 1. ],
[ 0.851384, 0.30226 , 0.239636, 1. ],
[ 0.832299, 0.283913, 0.257383, 1. ],
[ 0.817341, 0.270954, 0.27039 , 1. ],
[ 0.796607, 0.254728, 0.287264, 1. ],
[ 0.775059, 0.239667, 0.303526, 1. ],
[ 0.758422, 0.229097, 0.315266, 1. ],
[ 0.735683, 0.215906, 0.330245, 1. ],
.....
Then we can use this to plot, using the data from the original post:
import random
x = [{i: random.randint(1, 5)} for i in range(30)]
df = pd.DataFrame(x)
df.plot(kind='bar', stacked=True, color=color, legend=False, figsize=(12, 4))
Recent protocols prefer usage of RFC3339 per golang time package documentation.
In general RFC1123Z should be used instead of RFC1123 for servers that insist on that format, and RFC3339 should be preferred for new protocols. RFC822, RFC822Z, RFC1123, and RFC1123Z are useful for formatting; when used with time.Parse they do not accept all the time formats permitted by the RFCs.
cutOffTime, _ := time.Parse(time.RFC3339, "2017-08-30T13:35:00Z")
// POSTDATE is a date time field in DB (datastore)
query := datastore.NewQuery("db").Filter("POSTDATE >=", cutOffTime).
$(dialogElement).empty();
$(dialogElement).remove();
this fixes it for real
if you run node index.js
,Node will use 3000
If you run PORT=4444 node index.js
, Node will use process.env.PORT
which equals to 4444
in this example. Run with sudo
for ports below 1024.
For python3.5.3, pip3 is also installed when you install python. When you install it you may not select the add to path. Then you can find where the pip3 located and add it to path manually.
The closest I could make is
select * FROM( SELECT *, ROW_NUMBER() over (ORDER BY ID ) as ct from [db].[dbo].[table] ) sub where ct > fromNumber and ct <= toNumber
Which I guess similar to select * from [db].[dbo].[table] LIMIT 0, 10
You can retrieve the format strings from the CultureInfo
DateTimeFormat
property, which is a DateTimeFormatInfo
instance. This in turn has properties like ShortDatePattern
and ShortTimePattern
, containing the format strings:
CultureInfo us = new CultureInfo("en-US");
string shortUsDateFormatString = us.DateTimeFormat.ShortDatePattern;
string shortUsTimeFormatString = us.DateTimeFormat.ShortTimePattern;
CultureInfo uk = new CultureInfo("en-GB");
string shortUkDateFormatString = uk.DateTimeFormat.ShortDatePattern;
string shortUkTimeFormatString = uk.DateTimeFormat.ShortTimePattern;
If you simply want to format the date/time using the CultureInfo
, pass it in as your IFormatter
when converting the DateTime
to a string, using the ToString
method:
string us = myDate.ToString(new CultureInfo("en-US"));
string uk = myDate.ToString(new CultureInfo("en-GB"));
Do you mean
.*
.
any character, except newline character, with dotall mode it includes also the newline characters
*
any amount of the preceding expression, including 0 times
About efficiency, the virtual functions are slightly less efficient as the early-binding functions.
"This virtual call mechanism can be made almost as efficient as the "normal function call" mechanism (within 25%). Its space overhead is one pointer in each object of a class with virtual functions plus one vtbl for each such class" [A tour of C++ by Bjarne Stroustrup]
This code might work for non-.NET Core MVC controllers:
this.HttpContext.Response.StatusCode = 418; // I'm a teapot
return Json(new { status = "mer" }, JsonRequestBehavior.AllowGet);
What's even cooler is the fact that you can use an inline Table-Valued Function to select which (and how many via TOP
) row(s) to update. That is:
UPDATE MyTable
SET Column1=@Value1
FROM tvfSelectLatestRowOfMyTableMatchingCriteria(@Param1,@Param2,@Param3)
For the table valued function you have something interesting to select the row to update like:
CREATE FUNCTION tvfSelectLatestRowOfMyTableMatchingCriteria
(
@Param1 INT,
@Param2 INT,
@Param3 INT
)
RETURNS TABLE AS RETURN
(
SELECT TOP(1) MyTable.*
FROM MyTable
JOIN MyOtherTable
ON ...
JOIN WhoKnowsWhatElse
ON ...
WHERE MyTable.SomeColumn=@Param1 AND ...
ORDER BY MyTable.SomeDate DESC
)
..., and there lies (in my humble opinion) the true power of updating only top selected rows deterministically while at the same time simplifying the syntax of the UPDATE
statement.
You can also retrieve it from the environment variables, but that is probably not secure, so I would go with Andrew's answer.
printenv USER
If you need to retrieve it from an app, like Node, it's easier to get it from the environment variables, such as
process.env.USER
.
Procedural elements like loops are not part of the SQL language and can only be used inside the body of a procedural language function, procedure (Postgres 11 or later) or a DO
statement, where such additional elements are defined by the respective procedural language. The default is PL/pgSQL, but there are others.
Example with plpgsql:
DO
$do$
BEGIN
FOR i IN 1..25 LOOP
INSERT INTO playtime.meta_random_sample
(col_i, col_id) -- declare target columns!
SELECT i, id
FROM tbl
ORDER BY random()
LIMIT 15000;
END LOOP;
END
$do$;
For many tasks that can be solved with a loop, there is a shorter and faster set-based solution around the corner. Pure SQL equivalent for your example:
INSERT INTO playtime.meta_random_sample (col_i, col_id)
SELECT t.*
FROM generate_series(1,25) i
CROSS JOIN LATERAL (
SELECT i, id
FROM tbl
ORDER BY random()
LIMIT 15000
) t;
About generate_series()
:
About optimizing performance of random selections:
var var1 = 1, var2 = 1, var3 = 1;
In this case var
keyword is applicable to all the three variables.
var var1 = 1,
var2 = 1,
var3 = 1;
which is not equivalent to this:
var var1 = var2 = var3 = 1;
In this case behind the screens var
keyword is only applicable to var1
due to variable hoisting and rest of the expression is evaluated normally so the variables var2, var3
are becoming globals
Javascript treats this code in this order:
/*
var 1 is local to the particular scope because of var keyword
var2 and var3 will become globals because they've used without var keyword
*/
var var1; //only variable declarations will be hoisted.
var1= var2= var3 = 1;
Unofficial 64-bit installers for NumPy and SciPy are available at http://www.lfd.uci.edu/~gohlke/pythonlibs/
Make sure that you download & install the packages (aka. wheels) that match your CPython version and bitness (ie. cp35
= Python v3.5; win_amd64
= x86_64).
You'll want to install NumPy first; From a CMD prompt with administrator privileges for a system-wide (aka. Program Files) install:
C:\>pip install numpy-<version>+mkl-cp<ver-spec>-cp<ver-spec>m-<cpu-build>.whl
Or include the --user
flag to install to the current user's application folder (Typically %APPDATA%\Python
on Windows) from a non-admin CMD prompt:
C:\>pip install --user numpy-<version>+mkl-cp<ver-spec>-cp<ver-spec>m-<cpu-build>.whl
Then do the same for SciPy:
C:\>pip install [--user] scipy-<version>-cp<ver-spec>-cp<ver-spec>m-<cpu-build>.whl
Don't forget to replace <version>
, <ver-spec>
, and <cpu-build>
appropriately if you copy & paste any of these examples. And also that you must use the numpy & scipy packages from the ifd.uci.edu link above (or else you will get errors if you try to mix & match incompatible packages -- uninstall any conflicting packages first [ie. pip list
]).
You have to convert input x and y into int like below.
x=int(x)
y=int(y)
It stores an exact, versioned dependency tree rather than using starred versioning like package.json itself (e.g. 1.0.*). This means you can guarantee the dependencies for other developers or prod releases, etc. It also has a mechanism to lock the tree but generally will regenerate if package.json changes.
From the npm docs:
package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.
This file is intended to be committed into source repositories, and serves various purposes:
Describe a single representation of a dependency tree such that teammates, deployments, and continuous integration are guaranteed to install exactly the same dependencies.
Provide a facility for users to "time-travel" to previous states of node_modules without having to commit the directory itself.
To facilitate greater visibility of tree changes through readable source control diffs.
And optimize the installation process by allowing npm to skip repeated metadata resolutions for previously-installed packages."
To answer jrahhali's question below about just using the package.json with exact version numbers. Bear in mind that your package.json contains only your direct dependencies, not the dependencies of your dependencies (sometimes called nested dependencies). This means with the standard package.json you can't control the versions of those nested dependencies, referencing them directly or as peer dependencies won't help as you also don't control the version tolerance that your direct dependencies define for these nested dependencies.
Even if you lock down the versions of your direct dependencies you cannot 100% guarantee that your full dependency tree will be identical every time. Secondly you might want to allow non-breaking changes (based on semantic versioning) of your direct dependencies which gives you even less control of nested dependencies plus you again can't guarantee that your direct dependencies won't at some point break semantic versioning rules themselves.
The solution to all this is the lock file which as described above locks in the versions of the full dependency tree. This allows you to guarantee your dependency tree for other developers or for releases whilst still allowing testing of new dependency versions (direct or indirect) using your standard package.json.
NB. The previous shrink wrap json did pretty much the same thing but the lock file renames it so that it's function is clearer. If there's already a shrink wrap file in the project then this will be used instead of any lock file.
I know I'm late, but I've only ever had this error if my Response.Redirect
is in a Try...Catch
block.
Never put a Response.Redirect into a Try...Catch block. It's bad practice
As an alternative to putting the Response.Redirect into the Try...Catch block, I'd break up the method/function into two steps.
inside the Try...Catch block performs the requested actions and sets a "result" value to indicate success or failure of the actions.
outside of the Try...Catch block does the redirect (or doesn't) depending on what the "result" value is.
This code is far from perfect and probably should not be copied since I haven't tested it.
public void btnLogin_Click(UserLoginViewModel model)
{
bool ValidLogin = false; // this is our "result value"
try
{
using (Context Db = new Context)
{
User User = new User();
if (String.IsNullOrEmpty(model.EmailAddress))
ValidLogin = false; // no email address was entered
else
User = Db.FirstOrDefault(x => x.EmailAddress == model.EmailAddress);
if (User != null && User.PasswordHash == Hashing.CreateHash(model.Password))
ValidLogin = true; // login succeeded
}
}
catch (Exception ex)
{
throw ex; // something went wrong so throw an error
}
if (ValidLogin)
{
GenerateCookie(User);
Response.Redirect("~/Members/Default.aspx");
}
else
{
// do something to indicate that the login failed.
}
}
Another alternative is
dtColumns[index].visible = false/true;
To show or hide any column.
Removing with
rm -rf .*
may get you into trouble or some more errors.
If you have /path/to/folder, and would like to remove everything inside, but not that folder, just run:
rm -rf /path/to/folder/*
No. Extension methods require an instance variable (value) for an object. You can however, write a static wrapper around the ConfigurationManager
interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly.
public static class ConfigurationManagerWrapper
{
public static ConfigurationSection GetSection( string name )
{
return ConfigurationManager.GetSection( name );
}
.....
public static ConfigurationSection GetWidgetSection()
{
return GetSection( "widgets" );
}
}
try:
a # does a exist in the current namespace
except NameError:
a = 10 # nope
I checked some of the methods for speed performance and find that there is no difference! The only difference is that using some methods you must carefully check dimension.
Timing:
|------------|----------------|-------------------|
| | shape (10000) | shape (1,10000) |
|------------|----------------|-------------------|
| np.concat | 0.18280 | 0.17960 |
|------------|----------------|-------------------|
| np.stack | 0.21501 | 0.16465 |
|------------|----------------|-------------------|
| np.vstack | 0.21501 | 0.17181 |
|------------|----------------|-------------------|
| np.array | 0.21656 | 0.16833 |
|------------|----------------|-------------------|
As you can see I tried 2 experiments - using np.random.rand(10000)
and np.random.rand(1, 10000)
And if we use 2d arrays than np.stack
and np.array
create additional dimension - result.shape is (1,10000,10000) and (10000,1,10000) so they need additional actions to avoid this.
Code:
from time import perf_counter
from tqdm import tqdm_notebook
import numpy as np
l = []
for i in tqdm_notebook(range(10000)):
new_np = np.random.rand(10000)
l.append(new_np)
start = perf_counter()
stack = np.stack(l, axis=0 )
print(f'np.stack: {perf_counter() - start:.5f}')
start = perf_counter()
vstack = np.vstack(l)
print(f'np.vstack: {perf_counter() - start:.5f}')
start = perf_counter()
wrap = np.array(l)
print(f'np.array: {perf_counter() - start:.5f}')
start = perf_counter()
l = [el.reshape(1,-1) for el in l]
conc = np.concatenate(l, axis=0 )
print(f'np.concatenate: {perf_counter() - start:.5f}')
string cannot be the parameter to Nullable because string is not a value type. String is a reference type.
string s = null;
is a very valid statement and there is not need to make it nullable.
private string typeOfContract
{
get { return ViewState["typeOfContract"] as string; }
set { ViewState["typeOfContract"] = value; }
}
should work because of the as keyword.
The proper interval to get one second is 1000. The Interval
property is the time between ticks in milliseconds:
So, it's not the interval that you set that is wrong. Check the rest of your code for something like changing the interval of the timer, or binding the Tick
event multiple times.
In case you want to find other node besides "Alpha", the query should be something like this:
select Roles from MyTable where Roles.exist('(/*:root/*:role[contains(.,"Beta")])') = 1
I am using Xcode Version 11.4
In the attribute inspector, you can define the corner radius.
It won't show in the Storyboard but it will work fine when you run the project.
I found a solution
Depending on 3 traversals, you can decide who is the LCA. From LCA find distance of both nodes. Add these two distances, which is the answer.
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="number" />
I have tried every thing now try this one it shows other characters but you cant enter in the editText
edit.setRawInputType(Configuration.KEYBOARD_12KEY);
In my experience, the "I" convention applies to interfaces that are intended to provide a contract to a class, particularly when the interface itself is not an abstract notion of the class.
For example, in your case, I'd only expect to see IUser
if the only user you ever intend to have is User
. If you plan to have different types of users - NoviceUser
, ExpertUser
, etc. - I would expect to see a User
interface (and, perhaps, an AbstractUser
class that implements some common functionality, like get/setName()
).
I would also expect interfaces that define capabilities - Comparable
, Iterable
, etc. - to be named like that, and not like IComparable
or IIterable
.
If you use bootstrap, you might use this -
<img src="{{URL::asset('/image/propic.png')}}" alt="profile Pic" height="200" width="200">
note: inside public folder create a new folder named image then put your images there. Using URL::asset()
you can directly access to the public folder.
I was readying this solutions and this example may help.
My database have two tables (email and credit_card) with primary keys for their IDs. Another table (client) refers to this tables IDs as foreign keys. I have a reason to have the email apart from the client data.
First I insert the row data for the referenced tables (email, credit_card) then you get the ID for each, those IDs are needed in the third table (client).
If you don't insert first the rows in the referenced tables, MySQL wont be able to make the correspondences when you insert a new row in the third table that reference the foreign keys.
If you first insert the referenced rows for the referenced tables, then the row that refers to foreign keys, no error occurs.
Hope this helps.
Modals always load the content into an element on the page, which more often than not is a div
. Think of this div
as the iframe
equivalent when it comes to jQuery UI Dialogs. Now it depends on your requirements whether you want static content that resides within the page or you want to fetch the content from some other location. You may use this code and see if it works for you:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>test</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<link rel="stylesheet" type="text/css" media="screen" href="css/jquery-ui-1.8.23.custom.css"/>
</head>
<body>
<p>First open a modal <a href="http://ibm.com" class="example"> dialog</a></p>
<div id="dialog"></div>
</body>
<!--jQuery-->
<script src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script src="js/jquery-ui-1.8.23.custom.min.js"></script>
<script type="text/javascript">
$(function(){
//modal window start
$(".example").unbind('click');
$(".example").bind('click',function(){
showDialog();
var titletext=$(this).attr("title");
var openpage=$(this).attr("href");
$("#dialog").dialog( "option", "title", titletext );
$("#dialog").dialog( "option", "resizable", false );
$("#dialog").dialog( "option", "buttons", {
"Close": function() {
$(this).dialog("close");
$(this).dialog("destroy");
}
});
$("#dialog").load(openpage);
return false;
});
//modal window end
//Modal Window Initiation start
function showDialog(){
$("#dialog").dialog({
height: 400,
width: 500,
modal: true
}
</script>
</html>
There are, however, a few things which you should keep in mind. You will not be able to load remote URL's on your local system, you need to upload to a server if you want to load remote URL. Even then, you may only load URL's which belong to the same domain; e.g. if you upload this file to 'www.example.com' you may only access files hosted on 'www.example.com'. For loading external links this might help. All this information you will find in the link as suggested by @Robin.
I had the same problem. For some reason --initialize
did not work.
After about 5 hours of trial and error with different parameters, configs and commands I found out that the problem was caused by the file system.
I wanted to run a database on a large USB HDD drive. Drives larger than 2 TB are GPT partitioned! Here is a bug report with a solution:
https://bugs.mysql.com/bug.php?id=28913
In short words: Add the following line to your my.ini:
innodb_flush_method=normal
I had this problem with mysql 5.7 on Windows.
Similar to above solutions. But I always find myself looking for this chunk of code:
Date date=Calendar.getInstance().getTime();
System.out.println(date);
If you're using jQuery with rails, be wary of allowing entry to methods without verifying the authenticity token.
jquery-ujs can manage the tokens for you
You should have it already as part of the jquery-rails gem, but you might need to include it in application.js with
//= require jquery_ujs
That's all you need - your ajax call should now work
For more information, see: https://github.com/rails/jquery-ujs
For nodejs log file you can use winston and morgan and in place of your console.log() statement user winston.log() or other winston methods to log. For working with winston and morgan you need to install them using npm. Example: npm i -S winston npm i -S morgan
Then create a folder in your project with name winston and then create a config.js in that folder and copy this code given below.
const appRoot = require('app-root-path');
const winston = require('winston');
// define the custom settings for each transport (file, console)
const options = {
file: {
level: 'info',
filename: `${appRoot}/logs/app.log`,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: false,
},
console: {
level: 'debug',
handleExceptions: true,
json: false,
colorize: true,
},
};
// instantiate a new Winston Logger with the settings defined above
let logger;
if (process.env.logging === 'off') {
logger = winston.createLogger({
transports: [
new winston.transports.File(options.file),
],
exitOnError: false, // do not exit on handled exceptions
});
} else {
logger = winston.createLogger({
transports: [
new winston.transports.File(options.file),
new winston.transports.Console(options.console),
],
exitOnError: false, // do not exit on handled exceptions
});
}
// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
write(message) {
logger.info(message);
},
};
module.exports = logger;
After copying the above code make make a folder with name logs parallel to winston or wherever you want and create a file app.log in that logs folder. Go back to config.js and set the path in the 5th line "filename: ${appRoot}/logs/app.log
,
" to the respective app.log created by you.
After this go to your index.js and include the following code in it.
const morgan = require('morgan');
const winston = require('./winston/config');
const express = require('express');
const app = express();
app.use(morgan('combined', { stream: winston.stream }));
winston.info('You have successfully started working with winston and morgan');
$('.ui-icon-circle-triangle-w').text('<<');
You can use lsof
get the process that has bound to the required port.
Unfortunately the flags seem to be different depending on system, but on Mac OS X you can run
lsof -Pi | grep LISTEN
For example, on my machine I get something like:
mongod 8662 jacob 6u IPv4 0x17ceae4e0970fbe9 0t0 TCP localhost:27017 (LISTEN)
mongod 8662 jacob 7u IPv4 0x17ceae4e0f9c24b1 0t0 TCP localhost:28017 (LISTEN)
memcached 8680 jacob 17u IPv4 0x17ceae4e0971f7d1 0t0 TCP *:11211 (LISTEN)
memcached 8680 jacob 18u IPv6 0x17ceae4e0bdf6479 0t0 TCP *:11211 (LISTEN)
mysqld 9394 jacob 10u IPv4 0x17ceae4e080c4001 0t0 TCP *:3306 (LISTEN)
redis-ser 75429 jacob 4u IPv4 0x17ceae4e1ba8ea59 0t0 TCP localhost:6379 (LISTEN)
The second number is the PID and the port they're listening to is on the right before "(LISTEN)". Find the rogue PID and kill -9 $PID
to terminate with extreme prejudice.
Assuming such a query would return a single row, you could use either
select @EmpId = Id from dbo.Employee
Or
set @EmpId = (select Id from dbo.Employee)
You should append to the table and not the rows.
<script type="text/javascript">
$('a').click(function() {
$('#myTable').append('<tr class="child"><td>blahblah<\/td></tr>');
});
</script>
To set to default Excel type Date (defaulted to OS level locale /-> i.e. xlsx will look different when opened by a German or British person/ and flagged with an asterisk if you choose it in Excel's cell format chooser) you should:
CellStyle cellStyle = xssfWorkbook.createCellStyle();
cellStyle.setDataFormat((short)14);
cell.setCellStyle(cellStyle);
I did it with xlsx and it worked fine.
I created also a util/helper class (using jdk 8) which can format a string an replaces occurrences of variables.
For this purpose I used the Matchers "appendReplacement" method which does all the substitution and loops only over the affected parts of a format string.
The helper class isn't currently well javadoc documented. I will changes this in the future ;) Anyway I commented the most important lines (I hope).
public class FormatHelper {
//Prefix and suffix for the enclosing variable name in the format string.
//Replace the default values with any you need.
public static final String DEFAULT_PREFIX = "${";
public static final String DEFAULT_SUFFIX = "}";
//Define dynamic function what happens if a key is not found.
//Replace the defualt exception with any "unchecked" exception type you need or any other behavior.
public static final BiFunction<String, String, String> DEFAULT_NO_KEY_FUNCTION =
(fullMatch, variableName) -> {
throw new RuntimeException(String.format("Key: %s for variable %s not found.",
variableName,
fullMatch));
};
private final Pattern variablePattern;
private final Map<String, String> values;
private final BiFunction<String, String, String> noKeyFunction;
private final String prefix;
private final String suffix;
public FormatHelper(Map<String, String> values) {
this(DEFAULT_NO_KEY_FUNCTION, values);
}
public FormatHelper(
BiFunction<String, String, String> noKeyFunction, Map<String, String> values) {
this(DEFAULT_PREFIX, DEFAULT_SUFFIX, noKeyFunction, values);
}
public FormatHelper(String prefix, String suffix, Map<String, String> values) {
this(prefix, suffix, DEFAULT_NO_KEY_FUNCTION, values);
}
public FormatHelper(
String prefix,
String suffix,
BiFunction<String, String, String> noKeyFunction,
Map<String, String> values) {
this.prefix = prefix;
this.suffix = suffix;
this.values = values;
this.noKeyFunction = noKeyFunction;
//Create the Pattern and quote the prefix and suffix so that the regex don't interpret special chars.
//The variable name is a "\w+" in an extra capture group.
variablePattern = Pattern.compile(Pattern.quote(prefix) + "(\\w+)" + Pattern.quote(suffix));
}
public static String format(CharSequence format, Map<String, String> values) {
return new FormatHelper(values).format(format);
}
public static String format(
CharSequence format,
BiFunction<String, String, String> noKeyFunction,
Map<String, String> values) {
return new FormatHelper(noKeyFunction, values).format(format);
}
public static String format(
String prefix, String suffix, CharSequence format, Map<String, String> values) {
return new FormatHelper(prefix, suffix, values).format(format);
}
public static String format(
String prefix,
String suffix,
BiFunction<String, String, String> noKeyFunction,
CharSequence format,
Map<String, String> values) {
return new FormatHelper(prefix, suffix, noKeyFunction, values).format(format);
}
public String format(CharSequence format) {
//Create matcher based on the init pattern for variable names.
Matcher matcher = variablePattern.matcher(format);
//This buffer will hold all parts of the formatted finished string.
StringBuffer formatBuffer = new StringBuffer();
//loop while the matcher finds another variable (prefix -> name <- suffix) match
while (matcher.find()) {
//The root capture group with the full match e.g ${variableName}
String fullMatch = matcher.group();
//The capture group for the variable name resulting from "(\w+)" e.g. variableName
String variableName = matcher.group(1);
//Get the value in our Map so the Key is the used variable name in our "format" string. The associated value will replace the variable.
//If key is missing (absent) call the noKeyFunction with parameters "fullMatch" and "variableName" else return the value.
String value = values.computeIfAbsent(variableName, key -> noKeyFunction.apply(fullMatch, key));
//Escape the Map value because the "appendReplacement" method interprets the $ and \ as special chars.
String escapedValue = Matcher.quoteReplacement(value);
//The "appendReplacement" method replaces the current "full" match (e.g. ${variableName}) with the value from the "values" Map.
//The replaced part of the "format" string is appended to the StringBuffer "formatBuffer".
matcher.appendReplacement(formatBuffer, escapedValue);
}
//The "appendTail" method appends the last part of the "format" String which has no regex match.
//That means if e.g. our "format" string has no matches the whole untouched "format" string is appended to the StringBuffer "formatBuffer".
//Further more the method return the buffer.
return matcher.appendTail(formatBuffer)
.toString();
}
public String getPrefix() {
return prefix;
}
public String getSuffix() {
return suffix;
}
public Map<String, String> getValues() {
return values;
}
}
You can create a class instance for a specific Map with values (or suffix prefix or noKeyFunction) like:
Map<String, String> values = new HashMap<>();
values.put("firstName", "Peter");
values.put("lastName", "Parker");
FormatHelper formatHelper = new FormatHelper(values);
formatHelper.format("${firstName} ${lastName} is Spiderman!");
// Result: "Peter Parker is Spiderman!"
// Next format:
formatHelper.format("Does ${firstName} ${lastName} works as photographer?");
//Result: "Does Peter Parker works as photographer?"
Further more you can define what happens if a key in the values Map is missing (works in both ways e.g. wrong variable name in format string or missing key in Map). The default behavior is an thrown unchecked exception (unchecked because I use the default jdk8 Function which cant handle checked exceptions) like:
Map<String, String> map = new HashMap<>();
map.put("firstName", "Peter");
map.put("lastName", "Parker");
FormatHelper formatHelper = new FormatHelper(map);
formatHelper.format("${missingName} ${lastName} is Spiderman!");
//Result: RuntimeException: Key: missingName for variable ${missingName} not found.
You can define a custom behavior in the constructor call like:
Map<String, String> values = new HashMap<>();
values.put("firstName", "Peter");
values.put("lastName", "Parker");
FormatHelper formatHelper = new FormatHelper(fullMatch, variableName) -> variableName.equals("missingName") ? "John": "SOMETHING_WRONG", values);
formatHelper.format("${missingName} ${lastName} is Spiderman!");
// Result: "John Parker is Spiderman!"
or delegate it back to the default no key behavior:
...
FormatHelper formatHelper = new FormatHelper((fullMatch, variableName) -> variableName.equals("missingName") ? "John" :
FormatHelper.DEFAULT_NO_KEY_FUNCTION.apply(fullMatch,
variableName), map);
...
For better handling there are also static method representations like:
Map<String, String> values = new HashMap<>();
values.put("firstName", "Peter");
values.put("lastName", "Parker");
FormatHelper.format("${firstName} ${lastName} is Spiderman!", map);
// Result: "Peter Parker is Spiderman!"
You can use the --build-arg
option when you want to build using a Dockerfile.
From a link on https://github.com/docker/docker/issues/14634 , see the section "Build with --build-arg with multiple HTTP_PROXY":
[root@pppdc9prda2y java]# docker build
--build-arg https_proxy=$HTTP_PROXY --build-arg http_proxy=$HTTP_PROXY
--build-arg HTTP_PROXY=$HTTP_PROXY --build-arg HTTPS_PROXY=$HTTP_PROXY
--build-arg NO_PROXY=$NO_PROXY --build-arg no_proxy=$NO_PROXY -t java .
NOTE: On your own system, make sure you have set the HTTP_PROXY and NO_PROXY environment variables.
You can use a for statement too:
for (int y = 0; y < phrase.length(); y--){
char ch = phrase.charAt(y-1);
System.out.print(ch);
}
Yes. The same notation that works for non-empty dict/set works for empty ones.
Notice the difference between non-empty dict
and set
literals:
{1: 'a', 2: 'b', 3: 'c'}
-- a number of key-value pairs inside makes a dict
{'aaa', 'bbb', 'ccc'}
-- a tuple of values inside makes a set
So:
{}
== zero number of key-value pairs == empty dict
{*()}
== empty tuple of values == empty set
However the fact, that you can do it, doesn't mean you should. Unless you have some strong reasons, it's better to construct an empty set explicitly, like:
a = set()
Performance:
The literal is ~15% faster than the set-constructor (CPython-3.8, 2019 PC, Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz):
>>> %timeit ({*()} & {*()}) | {*()} 214 ns ± 1.26 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) >>> %timeit (set() & set()) | set() 252 ns ± 0.566 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
... and for completeness, Renato Garcia's
frozenset
proposal on the above expression is some 60% faster!>>> ? = frozenset() >>> %timeit (? & ?) | ? 100 ns ± 0.51 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
NB: As ctrueden noticed in comments, {()}
is not an empty set. It's a set with 1 element: empty tuple.
Bootstrap is an HTML, CSS, JS framework with many components that let you create beautiful and modern web sites or web applications very fast.
The following websites contain examples, elements and reusable components that you can integrate into your project using bootstrap framework
Do you have an activity set up the be the launched activity when the application starts?
This is done in your Manifest.xml file, something like:
<activity android:name=".Main" android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
$query= "INSERT INTO table ( " . implode(', ',array_keys($insData)) . ") VALUES (" . implode(', ',array_values($insData)) . ")";
Only need to write this line to insert an array into a database.
implode(', ',array_keys($insData))
: Gives you all keys as string format
implode(', ',array_values($insData))
: Gives you all values as string format
<a href="#" id="myAnchor">Click me</a>
<script type="text/javascript">
$(document).ready(function(){
$('#myAnchor').click(function(){
window.location.href = 'index.php';
});
})
</script>
Being the author of the response that you highlight in your question, and admittedly coming to this one a bit late, I'd have to say that among the many reasons that have been listed, the productivity of a professional developer is one of the most highly-regarded skills.
By productivity, I mean the ability to do your job efficiently with the best-possible results. IDEs enable this on many levels. I'm not an Emacs expert, but I doubt that it lacks any of the features of the major IDEs.
Design, documentation, tracking, developing, building, analyzing, deploying, and maintenance, key stepping stones in an enterprise application, can all be done within an IDE.
Why you wouldn't use something so powerful if you have the choice?
As an experiment, commit yourself to use an IDE for, say, 30 days, and see how you feel. I would love to read your thoughts on the experience.
A clean CSS-only solution this would be:
input[type="radio"]:read-only {
pointer-events: none;
}
This is an old question, and the answers already given all work, but there's also a new option which can be considered.
If you're using SourceTree to manage your git repositories, you can right-click on any commit and add a tag to it. With another mouseclick you can also send the tag straight to the branch on origin.
jQuery API documentation - datepicker
The minimum selectable date. When set to null
, there is no minimum.
Multiple types supported:
Date: A date object containing the minimum date.
Number: A number of days from today. For example 2
represents two days
from today and -1
represents yesterday
.
String: A string in the format defined by the dateFormat
option, or a relative date.
Relative dates must contain value and period pairs; valid periods are y
for years
, m
for months
, w
for weeks
, and d
for days
. For example, +1m +7d
represents one month and seven days
from today
.
In order not to display previous dates other than today
$('#datepicker').datepicker({minDate: 0});
Since the image is a linux, one thing to check is to make sure any shell scripts used in the container have unix line endings. If they have a ^M at the end then they are windows line endings. One way to fix them is with dos2unix on /usr/local/start-all.sh to convert them from windows to unix. Running the docker in interactive mode can help figure out other problems. You could have a file name typo or something. see https://en.wikipedia.org/wiki/Newline
Since you are asking about .NET, you should change the parameter from Long
to Integer
. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)
Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)
Really though, the managed method isn't difficult...
System.Threading.Thread.CurrentThread.Sleep(5000)
Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep
a good idea.
If you have a list of lists (tracked_output_sheet in my case), where you want to delete last element from each list, you can use the following code:
interim = []
for x in tracked_output_sheet:interim.append(x[:-1])
tracked_output_sheet= interim
If you just need to suspend for testing purpose you current thread execution try this:
function longExecFunc(callback, count) {
for (var j = 0; j < count; j++) {
for (var i = 1; i < (1 << 30); i++) {
var q = Math.sqrt(1 << 30);
}
}
callback();
}
longExecFunc(() => { console.log('done!')}, 5); //5, 6 ... whatever. Higher -- longer
I didn't see any answers that show users where we can find a Global Temp table. You can view Local and Global temp tables in the same location when navigating within SSMS. Screenshot below taken from this link.
Databases --> System Databases --> tempdb --> Temporary Tables
Your webapp has servletcontainer specific libraries like servlet-api.jar file in its /WEB-INF/lib. This is not right.
Remove them all.
The /WEB-INF/lib should contain only the libraries specific to the webapp, not to the servletcontainer. The servletcontainer (like Tomcat) is the one who should already provide the servletcontainer specific libraries.
If you supply libraries from an arbitrary servletcontainer of a different make/version, you'll run into this kind of problems because your webapp wouldn't be able to run on a servletcontainer of a different make/version than where those libraries are originated from.
How to solve: In Eclipse Right click on the project in eclipse Properties -> Java Build Path -> Add library -> Server Runtime Library -> Apache Tomcat
Im Maven Project:-
add follwing line in pom.xml file
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${default.javax.servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${default.javax.servlet.jsp.version}</version>
<scope>provided</scope>
</dependency>
Queue is in the multiprocessing module so:
from multiprocessing import Queue
>>> text=u'abcd'
>>> str(text)
'abcd'
If the string only contains ascii characters.
For anyone running a JDK on Ubuntu and want to upgrade to JDK11, I'd recommend installing via sdkman. SDKMAN is a tool for switching JVMs, removing and upgrading.
SDKMAN is a tool for managing parallel versions of multiple Software Development Kits on most Unix based systems. It provides a convenient Command Line Interface (CLI) and API for installing, switching, removing and listing Candidates.
Install SDKMAN
$ curl -s "https://get.sdkman.io" | bash
$ source "$HOME/.sdkman/bin/sdkman-init.sh"
$ sdk version
Install Java (11.0.3-zulu)
$ sdk install java
My solution was to use a short nickname (less than 31 characters) and then write the entire name in cell 0.
Just to extend KsaRs answer and provide a possibility to check xdebug from command line:
php -r "echo (extension_loaded('xdebug') ? '' : 'non '), 'exists';"
You can also use LocalDate.parse()
or LocalDateTime.parse()
on a String
without providing it with a pattern, if the String
is in ISO-8601 format.
for example,
String strDate = "2015-08-04";
LocalDate aLD = LocalDate.parse(strDate);
System.out.println("Date: " + aLD);
String strDatewithTime = "2015-08-04T10:11:30";
LocalDateTime aLDT = LocalDateTime.parse(strDatewithTime);
System.out.println("Date with Time: " + aLDT);
Output,
Date: 2015-08-04
Date with Time: 2015-08-04T10:11:30
and use DateTimeFormatter
only if you have to deal with other date patterns.
For instance, in the following example, dd MMM uuuu represents the day of the month (two digits), three letters of the name of the month (Jan, Feb, Mar,...), and a four-digit year:
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd MMM uuuu");
String anotherDate = "04 Aug 2015";
LocalDate lds = LocalDate.parse(anotherDate, dTF);
System.out.println(anotherDate + " parses to " + lds);
Output
04 Aug 2015 parses to 2015-08-04
also remember that the DateTimeFormatter
object is bidirectional; it can both parse input and format output.
String strDate = "2015-08-04";
LocalDate aLD = LocalDate.parse(strDate);
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd MMM uuuu");
System.out.println(aLD + " formats as " + dTF.format(aLD));
Output
2015-08-04 formats as 04 Aug 2015
(see complete list of Patterns for Formatting and Parsing DateFormatter)
Symbol Meaning Presentation Examples
------ ------- ------------ -------
G era text AD; Anno Domini; A
u year year 2004; 04
y year-of-era year 2004; 04
D day-of-year number 189
M/L month-of-year number/text 7; 07; Jul; July; J
d day-of-month number 10
Q/q quarter-of-year number/text 3; 03; Q3; 3rd quarter
Y week-based-year year 1996; 96
w week-of-week-based-year number 27
W week-of-month number 4
E day-of-week text Tue; Tuesday; T
e/c localized day-of-week number/text 2; 02; Tue; Tuesday; T
F week-of-month number 3
a am-pm-of-day text PM
h clock-hour-of-am-pm (1-12) number 12
K hour-of-am-pm (0-11) number 0
k clock-hour-of-am-pm (1-24) number 0
H hour-of-day (0-23) number 0
m minute-of-hour number 30
s second-of-minute number 55
S fraction-of-second fraction 978
A milli-of-day number 1234
n nano-of-second number 987654321
N nano-of-day number 1234000000
V time-zone ID zone-id America/Los_Angeles; Z; -08:30
z time-zone name zone-name Pacific Standard Time; PST
O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00;
X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15;
x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;
Z zone-offset offset-Z +0000; -0800; -08:00;
p pad next pad modifier 1
' escape for text delimiter
'' single quote literal '
[ optional section start
] optional section end
# reserved for future use
{ reserved for future use
} reserved for future use
How do they achieve internally that you are able to pass something like x > 5 into a method?
The short answer is that they don't.
Any sort of logical operation on a numpy array returns a boolean array. (i.e. __gt__
, __lt__
, etc all return boolean arrays where the given condition is true).
E.g.
x = np.arange(9).reshape(3,3)
print x > 5
yields:
array([[False, False, False],
[False, False, False],
[ True, True, True]], dtype=bool)
This is the same reason why something like if x > 5:
raises a ValueError if x
is a numpy array. It's an array of True/False values, not a single value.
Furthermore, numpy arrays can be indexed by boolean arrays. E.g. x[x>5]
yields [6 7 8]
, in this case.
Honestly, it's fairly rare that you actually need numpy.where
but it just returns the indicies where a boolean array is True
. Usually you can do what you need with simple boolean indexing.
In C, the integer(for 32 bit machine) is 32 bit and it ranges from -32768 to +32767.
Wrong. 32-bit signed integer in 2's complement representation has the range -231 to 231-1 which is equal to -2,147,483,648 to 2,147,483,647.
In CSS2.1, an element can only have at most one of any kind of pseudo-element at any time. (This means an element can have both a :before
and an :after
pseudo-element — it just cannot have more than one of each kind.)
As a result, when you have multiple :before
rules matching the same element, they will all cascade and apply to a single :before
pseudo-element, as with a normal element. In your example, the end result looks like this:
.circle.now:before {
content: "Now";
font-size: 19px;
color: black;
}
As you can see, only the content
declaration that has highest precedence (as mentioned, the one that comes last) will take effect — the rest of the declarations are discarded, as is the case with any other CSS property.
This behavior is described in the Selectors section of CSS2.1:
Pseudo-elements behave just like real elements in CSS with the exceptions described below and elsewhere.
This implies that selectors with pseudo-elements work just like selectors for normal elements. It also means the cascade should work the same way. Strangely, CSS2.1 appears to be the only reference; neither css3-selectors nor css3-cascade mention this at all, and it remains to be seen whether it will be clarified in a future specification.
If an element can match more than one selector with the same pseudo-element, and you want all of them to apply somehow, you will need to create additional CSS rules with combined selectors so that you can specify exactly what the browser should do in those cases. I can't provide a complete example including the content
property here, since it's not clear for instance whether the symbol or the text should come first. But the selector you need for this combined rule is either .circle.now:before
or .now.circle:before
— whichever selector you choose is personal preference as both selectors are equivalent, it's only the value of the content
property that you will need to define yourself.
If you still need a concrete example, see my answer to this similar question.
The legacy css3-content specification contains a section on inserting multiple ::before
and ::after
pseudo-elements using a notation that's compatible with the CSS2.1 cascade, but note that that particular document is obsolete — it hasn't been updated since 2003, and no one has implemented that feature in the past decade. The good news is that the abandoned document is actively undergoing a rewrite in the guise of css-content-3 and css-pseudo-4. The bad news is that the multiple pseudo-elements feature is nowhere to be found in either specification, presumably owing, again, to lack of implementer interest.
I investigate i knew that the jquery script need to load in order that why it not worked in your case. Because $ symbol mentioned in code not understand unless you load Jquery 1.9.1 at first. Load like follows
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/css/toastr.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/js/toastr.js"></script>
Then it will work fine
[...] How should Java Comparator class be declared to sort the arrays by their first elements in decreasing order [...]
Here's a complete example using Java 8:
import java.util.*;
public class Test {
public static void main(String args[]) {
int[][] twoDim = { {1, 2}, {3, 7}, {8, 9}, {4, 2}, {5, 3} };
Arrays.sort(twoDim, Comparator.comparingInt(a -> a[0])
.reversed());
System.out.println(Arrays.deepToString(twoDim));
}
}
Output:
[[8, 9], [5, 3], [4, 2], [3, 7], [1, 2]]
For Java 7 you can do:
Arrays.sort(twoDim, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[0], o1[0]);
}
});
If you unfortunate enough to work on Java 6 or older, you'd do:
Arrays.sort(twoDim, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return ((Integer) o2[0]).compareTo(o1[0]);
}
});
In case if you are using WPF application using PRISM framework then configuration should exist in your start up project (i.e. in the project where your bootstrapper resides.)
In short just remove it from the class library and put into a start up project.
can't you just subset the columns in either df first?
[i for i in df.columns if i not in df2.columns]
dfNew = merge(df **[i for i in df.columns if i not in df2.columns]**, df2, left_index=True, right_index=True, how='outer')
Here's a simple scraper I created in c# to get streaming quote data printed out to a console. It should be easily converted to java. Based on the following post:
http://blog.underdog-projects.net/2009/02/bringing-the-yahoo-finance-stream-to-the-shell/
Not too fancy (i.e. no regex etc), just a fast & dirty solution.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
namespace WebDataAddin
{
public class YahooConstants
{
public const string AskPrice = "a00";
public const string BidPrice = "b00";
public const string DayRangeLow = "g00";
public const string DayRangeHigh = "h00";
public const string MarketCap = "j10";
public const string Volume = "v00";
public const string AskSize = "a50";
public const string BidSize = "b60";
public const string EcnBid = "b30";
public const string EcnBidSize = "o50";
public const string EcnExtHrBid = "z03";
public const string EcnExtHrBidSize = "z04";
public const string EcnAsk = "b20";
public const string EcnAskSize = "o40";
public const string EcnExtHrAsk = "z05";
public const string EcnExtHrAskSize = "z07";
public const string EcnDayHigh = "h01";
public const string EcnDayLow = "g01";
public const string EcnExtHrDayHigh = "h02";
public const string EcnExtHrDayLow = "g11";
public const string LastTradeTimeUnixEpochformat = "t10";
public const string EcnQuoteLastTime = "t50";
public const string EcnExtHourTime = "t51";
public const string RtQuoteLastTime = "t53";
public const string RtExtHourQuoteLastTime = "t54";
public const string LastTrade = "l10";
public const string EcnQuoteLastValue = "l90";
public const string EcnExtHourPrice = "l91";
public const string RtQuoteLastValue = "l84";
public const string RtExtHourQuoteLastValue = "l86";
public const string QuoteChangeAbsolute = "c10";
public const string EcnQuoteAfterHourChangeAbsolute = "c81";
public const string EcnQuoteChangeAbsolute = "c60";
public const string EcnExtHourChange1 = "z02";
public const string EcnExtHourChange2 = "z08";
public const string RtQuoteChangeAbsolute = "c63";
public const string RtExtHourQuoteAfterHourChangeAbsolute = "c85";
public const string RtExtHourQuoteChangeAbsolute = "c64";
public const string QuoteChangePercent = "p20";
public const string EcnQuoteAfterHourChangePercent = "c82";
public const string EcnQuoteChangePercent = "p40";
public const string EcnExtHourPercentChange1 = "p41";
public const string EcnExtHourPercentChange2 = "z09";
public const string RtQuoteChangePercent = "p43";
public const string RtExtHourQuoteAfterHourChangePercent = "c86";
public const string RtExtHourQuoteChangePercent = "p44";
public static readonly IDictionary<string, string> CodeMap = typeof(YahooConstants).GetFields().
Where(field => field.FieldType == typeof(string)).
ToDictionary(field => ((string)field.GetValue(null)).ToUpper(), field => field.Name);
}
public static class StringBuilderExtensions
{
public static bool HasPrefix(this StringBuilder builder, string prefix)
{
return ContainsAtIndex(builder, prefix, 0);
}
public static bool HasSuffix(this StringBuilder builder, string suffix)
{
return ContainsAtIndex(builder, suffix, builder.Length - suffix.Length);
}
private static bool ContainsAtIndex(this StringBuilder builder, string str, int index)
{
if (builder != null && !string.IsNullOrEmpty(str) && index >= 0
&& builder.Length >= str.Length + index)
{
return !str.Where((t, i) => builder[index + i] != t).Any();
}
return false;
}
}
public class WebDataAddin
{
public const string ScriptStart = "<script>";
public const string ScriptEnd = "</script>";
public const string MessageStart = "try{parent.yfs_";
public const string MessageEnd = ");}catch(e){}";
public const string DataMessage = "u1f(";
public const string InfoMessage = "mktmcb(";
protected static T ParseJson<T>(string json)
{
// parse json - max acceptable value retrieved from
//http://forums.asp.net/t/1343461.aspx
var deserializer = new JavaScriptSerializer { MaxJsonLength = 2147483647 };
return deserializer.Deserialize<T>(json);
}
public static void Main()
{
const string symbols = "GBPUSD=X,SPY,MSFT,BAC,QQQ,GOOG";
// these are constants in the YahooConstants enum above
const string attrs = "b00,b60,a00,a50";
const string url = "http://streamerapi.finance.yahoo.com/streamer/1.0?s={0}&k={1}&r=0&callback=parent.yfs_u1f&mktmcb=parent.yfs_mktmcb&gencallback=parent.yfs_gencb®ion=US&lang=en-US&localize=0&mu=1";
var req = WebRequest.Create(string.Format(url, symbols, attrs));
req.Proxy.Credentials = CredentialCache.DefaultCredentials;
var missingCodes = new HashSet<string>();
var response = req.GetResponse();
if(response != null)
{
var stream = response.GetResponseStream();
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
var builder = new StringBuilder();
var initialPayloadReceived = false;
while (!reader.EndOfStream)
{
var c = (char)reader.Read();
builder.Append(c);
if(!initialPayloadReceived)
{
if (builder.HasSuffix(ScriptStart))
{
// chop off the first part, and re-append the
// script tag (this is all we care about)
builder.Clear();
builder.Append(ScriptStart);
initialPayloadReceived = true;
}
}
else
{
// check if we have a fully formed message
// (check suffix first to avoid re-checking
// the prefix over and over)
if (builder.HasSuffix(ScriptEnd) &&
builder.HasPrefix(ScriptStart))
{
var chop = ScriptStart.Length + MessageStart.Length;
var javascript = builder.ToString(chop,
builder.Length - ScriptEnd.Length - MessageEnd.Length - chop);
if (javascript.StartsWith(DataMessage))
{
var json = ParseJson<Dictionary<string, object>>(
javascript.Substring(DataMessage.Length));
// parse out the data. key should be the symbol
foreach(var symbol in json)
{
Console.WriteLine("Symbol: {0}", symbol.Key);
var symbolData = (Dictionary<string, object>) symbol.Value;
foreach(var dataAttr in symbolData)
{
var codeKey = dataAttr.Key.ToUpper();
if (YahooConstants.CodeMap.ContainsKey(codeKey))
{
Console.WriteLine("\t{0}: {1}", YahooConstants.
CodeMap[codeKey], dataAttr.Value);
} else
{
missingCodes.Add(codeKey);
Console.WriteLine("\t{0}: {1} (Warning! No Code Mapping Found)",
codeKey, dataAttr.Value);
}
}
Console.WriteLine();
}
} else if(javascript.StartsWith(InfoMessage))
{
var json = ParseJson<Dictionary<string, object>>(
javascript.Substring(InfoMessage.Length));
foreach (var dataAttr in json)
{
Console.WriteLine("\t{0}: {1}", dataAttr.Key, dataAttr.Value);
}
Console.WriteLine();
} else
{
throw new Exception("Cannot recognize the message type");
}
builder.Clear();
}
}
}
}
}
}
}
}
}
Another option could be using an Attribute Selector:
[class^="your-class-name"]{
//your style here
}
Whereas every class starting with "your-class-name" uses this style.
So in your case, you could do it like so:
[class^="class"]{
display: inline-block;
//some other properties
&:hover{
color: darken(#FFFFFF, 10%);
}
}
.class-b{
//specifically for class b
width: 100px;
&:hover{
color: darken(#FFFFFF, 20%);
}
}
More about Attribute Selectors on w3Schools
Enumerator
includes Enumerable
. Since 2.1
, Enumerable
also has a method #to_h
. That's why, we can write :-
a = ["item 1", "item 2", "item 3", "item 4"]
a.each_slice(2).to_h
# => {"item 1"=>"item 2", "item 3"=>"item 4"}
Because #each_slice
without block gives us Enumerator
, and as per the above explanation, we can call the #to_h
method on the Enumerator
object.
SELECT *, 1 AS sort_order
FROM table1
EXCEPT
SELECT *, 1 AS sort_order
FROM table2
UNION
SELECT *, 1 AS sort_order
FROM table1
INTERSECT
SELECT *, 1 AS sort_order
FROM table2
UNION
SELECT *, 2 AS sort_order
FROM table2
EXCEPT
SELECT *, 2 AS sort_order
FROM table1
ORDER BY sort_order;
But the real answer is: other than the ORDER BY
clause, the sort order will by arbitrary and not guaranteed.
Error:Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon. For example, an unrecognized JVM option is used.
Please refer to the user guide chapter on the daemon at https://docs.gradle.org/3.3/userguide/gradle_daemon.html
Use find for name "a" and execute rm to remove those named according to your wishes, as follows:
find . -name a -exec rm -rf {} \;
Test it first using ls to list:
find . -name a -exec ls {} \;
To ensure this only removes directories and not plain files, use the "-type d" arg (as suggested in the comments):
find . -name a -type d -exec rm -rf {} \;
The "{}" is a substitution for each file "a" found - the exec command is executed against each by substitution.
It could be a good idea to be careful with the Locale upon which c.getTime().toString();
depends.
One idea is to store the time in seconds (e.g. UNIX time). As an int
you can easily compare it, and then you just convert it to string when displaying it to the user.
select command denied to user ''@'' for table ''
This problem is a basically generated after join condition are wrong database name in your join query. So please check the your select query in join table name after database.
Then solve it for example its correct ans ware
string g = " SELECT `emptable`.`image` , `applyleave`.`id` , `applyleave`.`empid` , `applyleave`.`empname` , `applyleave`.`dateapply` , `applyleave`.`leavename` , `applyleave`.`fromdate` , `applyleave`.`todate` , `applyleave`.`resion` , `applyleave`.`contact` , `applyleave`.`leavestatus` , `applyleave`.`username` , `applyleave`.`noday` FROM `DataEMP_ems`.`applyleave` INNER JOIN `DataEMP_ems`.`emptable` ON ( `applyleave`.`empid` = `emptable`.`empid` ) WHERE ( `applyleave`.`leavestatus` = 'panding' ) ";
The join table is imputable
and applyleave
on the same database but online database name is diffrent then given error on this problem.
Unfortunately there is no hung state for a process. Now hung can be deadlock. This is block state. The threads in the process are blocked. The other things could be live lock where the process is running but doing the same thing again and again. This process is in running state. So as you can see there is no definite hung state. As suggested you can use the top command to see if the process is using 100% CPU or lot of memory.
If you want to see the array as an array, you can say
alert(JSON.stringify(aCustomers));
instead of all those document.write
s.
However, if you want to display them cleanly, one per line, in your popup, do this:
alert(aCustomers.join("\n"));
npm install typescript@">=3.1.1 <3.3.0" --save-dev --save-exact
rm -rf node_modules
npm install
Based on the official documentation:
dummies = pd.get_dummies(df['Category']).rename(columns=lambda x: 'Category_' + str(x))
df = pd.concat([df, dummies], axis=1)
df = df.drop(['Category'], inplace=True, axis=1)
There is also a nice post in the FastML blog.
I would like to answer your question, as there are various methods - here I’ll talk about the code that is widely used.
So, for hiding the sheet:
Sub try()
Worksheets("Sheet1").Visible = xlSheetHidden
End Sub
There are other methods also if you want to learn all Methods Click here
The answer above with spark-csv is correct but there is an issue - the library creates several files based on the data frame partitioning. And this is not what we usually need. So, you can combine all partitions to one:
df.coalesce(1).
write.
format("com.databricks.spark.csv").
option("header", "true").
save("myfile.csv")
and rename the output of the lib (name "part-00000") to a desire filename.
This blog post provides more details: https://fullstackml.com/2015/12/21/how-to-export-data-frame-from-apache-spark/
hmm.. just found the answer. it's easier then i thought. it just needs a bunch more stuff:
@echo off
if not exist log.txt GOTO :write
echo Date/Time last login:
type log.txt
del log.txt
:write
echo %date%, %time%. >> log.txt
@pause
exit
So it first reads the log.txt file and deletes it. After that it just get a new file (log.txt) with the date & time!
I hope this helps other people!
(the only prob is that the first time it does not work, but then just enter in random value at log.txt.) (This problem is solved and edited.)
In any web application, there will be a web.xml
in the WEB-INF/
folder.
If you dont have one in your web app, as it seems to be the case in your folder structure, the default Tomcat web.xml
is under TOMCAT_HOME/conf/web.xml
Either way, the relevant lines of the web.xml are
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
so any file matching this pattern when found will be shown as the home page.
In Tomcat, a web.xml setting within your web app will override the default, if present.
Further Reading
Shortest version to prettify existing JSON: (edit: using JSON.net)
JToken.Parse("mystring").ToString()
Input:
{"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }}
Output:
{
"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{
"value": "New",
"onclick": "CreateNewDoc()"
},
{
"value": "Open",
"onclick": "OpenDoc()"
},
{
"value": "Close",
"onclick": "CloseDoc()"
}
]
}
}
}
To pretty-print an object:
JToken.FromObject(myObject).ToString()
You should also keep in mind that when using like
, some sql flavors will ignore indexes, and that will kill performance. This is especially true if you don't use the "starts with" pattern like your example.
You should really look at the execution plan for the query and see what it's doing, guess as little as possible.
This being said, the "starts with" pattern can and is optimized in sql server. It will use the table index. EF 4.0 switched to like
for StartsWith
for this very reason.
My class for show DatePicker
. I can use for EditText
, TextView
or Button
import android.app.DatePickerDialog;
import android.content.Context;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class TextViewDatePicker
implements View.OnClickListener, DatePickerDialog.OnDateSetListener {
public static final String DATE_SERVER_PATTERN = "yyyy-MM-dd";
private DatePickerDialog mDatePickerDialog;
private TextView mView;
private Context mContext;
private long mMinDate;
private long mMaxDate;
public TextViewDatePicker(Context context, TextView view) {
this(context, view, 0, 0);
}
public TextViewDatePicker(Context context, TextView view, long minDate, long maxDate) {
mView = view;
mView.setOnClickListener(this);
mView.setFocusable(false);
mContext = context;
mMinDate = minDate;
mMaxDate = maxDate;
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, monthOfYear);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
Date date = calendar.getTime();
SimpleDateFormat formatter = new SimpleDateFormat(DATE_SERVER_PATTERN);
mView.setText(formatter.format(date));
}
@Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
mDatePickerDialog = new DatePickerDialog(mContext, this, calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
if (mMinDate != 0) {
mDatePickerDialog.getDatePicker().setMinDate(mMinDate);
}
if (mMaxDate != 0) {
mDatePickerDialog.getDatePicker().setMaxDate(mMaxDate);
}
mDatePickerDialog.show();
}
public DatePickerDialog getDatePickerDialog() {
return mDatePickerDialog;
}
public void setMinDate(long minDate) {
mMinDate = minDate;
}
public void setMaxDate(long maxDate) {
mMaxDate = maxDate;
}
}
Using
EditText myEditText = findViewById(R.id.myEditText);
TextViewDatePicker editTextDatePicker = new TextViewDatePicker(context, myEditText, minDate, maxDate);
//TextViewDatePicker editTextDatePicker = new TextViewDatePicker(context, myEditText); //without min date, max date
This is not possible to do with a textarea
. What you are looking for is an content editable div, which is very easily done:
<div contenteditable="true"></div>
div.editable {_x000D_
width: 300px;_x000D_
height: 200px;_x000D_
border: 1px solid #ccc;_x000D_
padding: 5px;_x000D_
}_x000D_
_x000D_
strong {_x000D_
font-weight: bold;_x000D_
}
_x000D_
<div contenteditable="true">This is the first line.<br>_x000D_
See, how the text fits here, also if<br>there is a <strong>linebreak</strong> at the end?_x000D_
<br>It works nicely._x000D_
<br>_x000D_
<br><span style="color: lightgreen">Great</span>._x000D_
</div>
_x000D_
I was having this issue for the following reason.
TLDR: Check if you are sending a GET
request that should be sending the parameters on the url instead of on the NSURLRequest's HTTBody
property.
==================================================
I had mounted a network abstraction on my app, and it was working pretty well for all my requests.
I added a new request to another web service (not my own) and it started throwing me this error.
I went to a playground and started from the ground up building a barebones request, and it worked. So I started moving closer to my abstraction until I found the cause.
My abstraction implementation had a bug:
I was sending a request that was supposed to send parameters encoded in the url and I was also filling the NSURLRequest's HTTBody
property with the query parameters as well.
As soon as I removed the HTTPBody
it worked.
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
Its not possible thats the whole point of hashing. You can however bruteforce by going through all possibilities (using all possible digits characters in every possible order) and hashing them and checking for a collision.
for more information on hashing and MD5 etc see: http://en.wikipedia.org/wiki/MD5 , http://en.wikipedia.org/wiki/Hash_function , http://en.wikipedia.org/wiki/Cryptographic_hash_function and http://onin.com/hhh/hhhexpl.html
I myself created my own app to do this, its open source you can check the link: http://sourceforge.net/projects/jpassrecovery/ and of course the source. Here is the source for easy access it has a basic implementation in the comments:
Bruter.java:
import java.util.ArrayList;
public class Bruter {
public ArrayList<String> characters = new ArrayList<>();
public boolean found = false;
public int maxLength;
public int minLength;
public int count;
long starttime, endtime;
public int minutes, seconds, hours, days;
public char[] specialCharacters = {'~', '`', '!', '@', '#', '$', '%', '^',
'&', '*', '(', ')', '_', '-', '+', '=', '{', '}', '[', ']', '|', '\\',
';', ':', '\'', '"', '<', '.', ',', '>', '/', '?', ' '};
public boolean done = false;
public boolean paused = false;
public boolean isFound() {
return found;
}
public void setPaused(boolean paused) {
this.paused = paused;
}
public boolean isPaused() {
return paused;
}
public void setFound(boolean found) {
this.found = found;
}
public synchronized void setEndtime(long endtime) {
this.endtime = endtime;
}
public int getCounter() {
return count;
}
public long getRemainder() {
return getNumberOfPossibilities() - count;
}
public long getNumberOfPossibilities() {
long possibilities = 0;
for (int i = minLength; i <= maxLength; i++) {
possibilities += (long) Math.pow(characters.size(), i);
}
return possibilities;
}
public void addExtendedSet() {
for (char c = (char) 0; c <= (char) 31; c++) {
characters.add(String.valueOf(c));
}
}
public void addStandardCharacterSet() {
for (char c = (char) 32; c <= (char) 127; c++) {
characters.add(String.valueOf(c));
}
}
public void addLowerCaseLetters() {
for (char c = 'a'; c <= 'z'; c++) {
characters.add(String.valueOf(c));
}
}
public void addDigits() {
for (int c = 0; c <= 9; c++) {
characters.add(String.valueOf(c));
}
}
public void addUpperCaseLetters() {
for (char c = 'A'; c <= 'Z'; c++) {
characters.add(String.valueOf(c));
}
}
public void addSpecialCharacters() {
for (char c : specialCharacters) {
characters.add(String.valueOf(c));
}
}
public void setMaxLength(int i) {
maxLength = i;
}
public void setMinLength(int i) {
minLength = i;
}
public int getPerSecond() {
int i;
try {
i = (int) (getCounter() / calculateTimeDifference());
} catch (Exception ex) {
return 0;
}
return i;
}
public String calculateTimeElapsed() {
long timeTaken = calculateTimeDifference();
seconds = (int) timeTaken;
if (seconds > 60) {
minutes = (int) (seconds / 60);
if (minutes * 60 > seconds) {
minutes = minutes - 1;
}
if (minutes > 60) {
hours = (int) minutes / 60;
if (hours * 60 > minutes) {
hours = hours - 1;
}
}
if (hours > 24) {
days = (int) hours / 24;
if (days * 24 > hours) {
days = days - 1;
}
}
seconds -= (minutes * 60);
minutes -= (hours * 60);
hours -= (days * 24);
days -= (hours * 24);
}
return "Time elapsed: " + days + "days " + hours + "h " + minutes + "min " + seconds + "s";
}
private long calculateTimeDifference() {
long timeTaken = (long) ((endtime - starttime) * (1 * Math.pow(10, -9)));
return timeTaken;
}
public boolean excludeChars(String s) {
char[] arrayChars = s.toCharArray();
for (int i = 0; i < arrayChars.length; i++) {
characters.remove(arrayChars[i] + "");
}
if (characters.size() < maxLength) {
return false;
} else {
return true;
}
}
public int getMaxLength() {
return maxLength;
}
public int getMinLength() {
return minLength;
}
public void setIsDone(Boolean b) {
done = b;
}
public boolean isDone() {
return done;
}
}
HashBruter.java:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import javax.swing.JOptionPane;
public class HashBruter extends Bruter {
/*
* public static void main(String[] args) {
*
* final HashBruter hb = new HashBruter();
*
* hb.setMaxLength(5); hb.setMinLength(1);
*
* hb.addSpecialCharacters(); hb.addUpperCaseLetters();
* hb.addLowerCaseLetters(); hb.addDigits();
*
* hb.setType("sha-512");
*
* hb.setHash("282154720ABD4FA76AD7CD5F8806AA8A19AEFB6D10042B0D57A311B86087DE4DE3186A92019D6EE51035106EE088DC6007BEB7BE46994D1463999968FBE9760E");
*
* Thread thread = new Thread(new Runnable() {
*
* @Override public void run() { hb.tryBruteForce(); } });
*
* thread.start();
*
* while (!hb.isFound()) { System.out.println("Hash: " +
* hb.getGeneratedHash()); System.out.println("Number of Possibilities: " +
* hb.getNumberOfPossibilities()); System.out.println("Checked hashes: " +
* hb.getCounter()); System.out.println("Estimated hashes left: " +
* hb.getRemainder()); }
*
* System.out.println("Found " + hb.getType() + " hash collision: " +
* hb.getGeneratedHash() + " password is: " + hb.getPassword());
*
* }
*/
public String hash, generatedHash, password;
public String type;
public String getType() {
return type;
}
public String getPassword() {
return password;
}
public void setHash(String p) {
hash = p;
}
public void setType(String digestType) {
type = digestType;
}
public String getGeneratedHash() {
return generatedHash;
}
public void tryBruteForce() {
starttime = System.nanoTime();
for (int size = minLength; size <= maxLength; size++) {
if (found == true || done == true) {
break;
} else {
while (paused) {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
generateAllPossibleCombinations("", size);
}
}
done = true;
}
private void generateAllPossibleCombinations(String baseString, int length) {
while (paused) {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
if (found == false || done == false) {
if (baseString.length() == length) {
if(type.equalsIgnoreCase("crc32")) {
generatedHash = generateCRC32(baseString);
} else if(type.equalsIgnoreCase("adler32")) {
generatedHash = generateAdler32(baseString);
} else if(type.equalsIgnoreCase("crc16")) {
generatedHash=generateCRC16(baseString);
} else if(type.equalsIgnoreCase("crc64")) {
generatedHash=generateCRC64(baseString.getBytes());
}
else {
generatedHash = generateHash(baseString.toCharArray());
}
password = baseString;
if (hash.equals(generatedHash)) {
password = baseString;
found = true;
done = true;
}
count++;
} else if (baseString.length() < length) {
for (int n = 0; n < characters.size(); n++) {
generateAllPossibleCombinations(baseString + characters.get(n), length);
}
}
}
}
private String generateHash(char[] passwordChar) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance(type);
} catch (NoSuchAlgorithmException e1) {
JOptionPane.showMessageDialog(null, "No such algorithm for hashes exists", "Error", JOptionPane.ERROR_MESSAGE);
}
String passwordString = new String(passwordChar);
byte[] passwordByte = passwordString.getBytes();
md.update(passwordByte, 0, passwordByte.length);
byte[] encodedPassword = md.digest();
String encodedPasswordInString = toHexString(encodedPassword);
return encodedPasswordInString;
}
private void byte2hex(byte b, StringBuffer buf) {
char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F'};
int high = ((b & 0xf0) >> 4);
int low = (b & 0x0f);
buf.append(hexChars[high]);
buf.append(hexChars[low]);
}
private String toHexString(byte[] block) {
StringBuffer buf = new StringBuffer();
int len = block.length;
for (int i = 0; i < len; i++) {
byte2hex(block[i], buf);
}
return buf.toString();
}
private String generateCRC32(String baseString) {
//Convert string to bytes
byte bytes[] = baseString.getBytes();
Checksum checksum = new CRC32();
/*
* To compute the CRC32 checksum for byte array, use
*
* void update(bytes[] b, int start, int length)
* method of CRC32 class.
*/
checksum.update(bytes,0,bytes.length);
/*
* Get the generated checksum using
* getValue method of CRC32 class.
*/
return String.valueOf(checksum.getValue());
}
private String generateAdler32(String baseString) {
//Convert string to bytes
byte bytes[] = baseString.getBytes();
Checksum checksum = new Adler32();
/*
* To compute the CRC32 checksum for byte array, use
*
* void update(bytes[] b, int start, int length)
* method of CRC32 class.
*/
checksum.update(bytes,0,bytes.length);
/*
* Get the generated checksum using
* getValue method of CRC32 class.
*/
return String.valueOf(checksum.getValue());
}
/*************************************************************************
* Compilation: javac CRC16.java
* Execution: java CRC16 s
*
* Reads in a string s as a command-line argument, and prints out
* its 16-bit Cyclic Redundancy Check (CRC16). Uses a lookup table.
*
* Reference: http://www.gelato.unsw.edu.au/lxr/source/lib/crc16.c
*
* % java CRC16 123456789
* CRC16 = bb3d
*
* Uses irreducible polynomial: 1 + x^2 + x^15 + x^16
*
*
*************************************************************************/
private String generateCRC16(String baseString) {
int[] table = {
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040,
};
byte[] bytes = baseString.getBytes();
int crc = 0x0000;
for (byte b : bytes) {
crc = (crc >>> 8) ^ table[(crc ^ b) & 0xff];
}
return Integer.toHexString(crc);
}
/*******************************************************************************
* Copyright (c) 2009, 2012 Mountainminds GmbH & Co. KG and Contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Marc R. Hoffmann - initial API and implementation
*
*******************************************************************************/
/**
* CRC64 checksum calculator based on the polynom specified in ISO 3309. The
* implementation is based on the following publications:
*
* <ul>
* <li>http://en.wikipedia.org/wiki/Cyclic_redundancy_check</li>
* <li>http://www.geocities.com/SiliconValley/Pines/8659/crc.htm</li>
* </ul>
*/
private static final long POLY64REV = 0xd800000000000000L;
private static final long[] LOOKUPTABLE;
static {
LOOKUPTABLE = new long[0x100];
for (int i = 0; i < 0x100; i++) {
long v = i;
for (int j = 0; j < 8; j++) {
if ((v & 1) == 1) {
v = (v >>> 1) ^ POLY64REV;
} else {
v = (v >>> 1);
}
}
LOOKUPTABLE[i] = v;
}
}
/**
* Calculates the CRC64 checksum for the given data array.
*
* @param data
* data to calculate checksum for
* @return checksum value
*/
public static String generateCRC64(final byte[] data) {
long sum = 0;
for (int i = 0; i < data.length; i++) {
final int lookupidx = ((int) sum ^ data[i]) & 0xff;
sum = (sum >>> 8) ^ LOOKUPTABLE[lookupidx];
}
return String.valueOf(sum);
}
}
you would use it like:
final HashBruter hb = new HashBruter();
hb.setMaxLength(5); hb.setMinLength(1);
hb.addSpecialCharacters(); hb.addUpperCaseLetters();
hb.addLowerCaseLetters(); hb.addDigits();
hb.setType("sha-512");
hb.setHash("282154720ABD4FA76AD7CD5F8806AA8A19AEFB6D10042B0D57A311B86087DE4DE3186A92019D6EE51035106EE088DC6007BEB7BE46994D1463999968FBE9760E");
Thread thread = new Thread(new Runnable() {
@Override public void run() { hb.tryBruteForce(); } });
thread.start();
while (!hb.isFound()) { System.out.println("Hash: " +
hb.getGeneratedHash()); System.out.println("Number of Possibilities: " +
hb.getNumberOfPossibilities()); System.out.println("Checked hashes: " +
hb.getCounter()); System.out.println("Estimated hashes left: " +
hb.getRemainder()); }
System.out.println("Found " + hb.getType() + " hash collision: " +
hb.getGeneratedHash() + " password is: " + hb.getPassword());
You have 3 options to edit commits in Mercurial:
hg strip --keep --rev -1
undo the last (1) commit(s), so you can do it again (see this answer for more information).
Using the MQ extension, which is shipped with Mercurial
Even if it isn't shipped with Mercurial, the Histedit extension is worth mentioning
You can also have a look on the Editing History page of the Mercurial wiki.
In short, editing history is really hard and discouraged. And if you've already pushed your changes, there's barely nothing you can do, except if you have total control of all the other clones.
I'm not really familiar with the git commit --amend
command, but AFAIK, Histedit is what seems to be the closest approach, but sadly it isn't shipped with Mercurial. MQ is really complicated to use, but you can do nearly anything with it.
Since the .Rows result is marked as consisting of rows, you can "For Each" it to deal with each row individually, like this:
Function Attendance(rng As Range) As Long
Attendance = 0
For Each rRow In rng.Rows
If WorksheetFunction.Sum(rRow) > 0 Then
Attendance = Attendance + 1
End If
Next
End Function
I use this to check attendance in any of a few categories (different columns) for a list of people (different rows).
(And of course you could use .Columns to do a "For Each" over the columns in the range.)
Would it not make sense to use msbuild directly? If you are doing this with every build, then you can add a msbuild task at the end? If you would just like to see if you can’t find another macro value that is not showed on the Visual Studio IDE, you could switch on the msbuild options to diagnostic and that will show you all of the variables that you could use, as well as their current value.
To switch this on in visual studio, go to Tools/Options then scroll down the tree view to the section called Projects and Solutions, expand that and click on Build and Run, at the right their is a drop down that specify the build output verbosity, setting that to diagnostic, will show you what other macro values you could use.
Because I don’t quite know to what level you would like to go, and how complex you want your build to be, this might give you some idea. I have recently been doing build scripts, that even execute SQL code as part of the build. If you would like some more help or even some sample build scripts, let me know, but if it is just a small process you want to run at the end of the build, the perhaps going the full msbuild script is a bit of over kill.
Hope it helps Rihan
Check Base64 or normal string
public bool IsBase64Encoded(String str)
{
try
{
// If no exception is caught, then it is possibly a base64 encoded string
byte[] data = Convert.FromBase64String(str);
// The part that checks if the string was properly padded to the
// correct length was borrowed from d@anish's solution
return (str.Replace(" ","").Length % 4 == 0);
}
catch
{
// If exception is caught, then it is not a base64 encoded string
return false;
}
}
A Table can have a Composite Primary Key which is a primary key made from two or more columns. For example:
CREATE TABLE userdata (
userid INT,
userdataid INT,
info char(200),
primary key (userid, userdataid)
);
Update: Here is a link with a more detailed description of composite primary keys.
There is one difference - you can't use String
without using System;
beforehand.
The %s
specifier converts the object using str()
, and %r
converts it using repr()
.
For some objects such as integers, they yield the same result, but repr()
is special in that (for types where this is possible) it conventionally returns a result that is valid Python syntax, which could be used to unambiguously recreate the object it represents.
Here's an example, using a date:
>>> import datetime
>>> d = datetime.date.today()
>>> str(d)
'2011-05-14'
>>> repr(d)
'datetime.date(2011, 5, 14)'
Types for which repr()
doesn't produce Python syntax include those that point to external resources such as a file
, which you can't guarantee to recreate in a different context.
Very late answer, but I think my answer is more straight forward for specific use cases where users want to simply insert (copy) data from table A into table B:
INSERT INTO table_b (col1, col2, col3, col4, col5, col6)
SELECT col1, 'str_val', int_val, col4, col5, col6
FROM table_a
There are a lot of good answers to this question already but another way to take a look at it is the cloud (ala Amazon's AWS) is good for interactive use cases and the grid (ala High Performance Computing) is good for batch use cases.
Cloud is interactive in that you can get resources on demand via self service. The code you run on VMs in the cloud, such as the Apache web server, can server clients interactively.
Grid is batch in that you submit jobs to a job queue after obtaining the credentials from some HPC authority to do so. The code you run on the grid waits in that queue until there are sufficient resources to execute it.
There are good use cases for both styles of computing.
Here (http://www.dotnetperls.com/picturebox) there 3 ways to do this:
Using ImageLocation property of the PictureBox like:
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pb1 = new PictureBox();
pb1.ImageLocation = "../SamuderaJayaMotor.png";
pb1.SizeMode = PictureBoxSizeMode.AutoSize;
}
Using an image from the web like:
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pb1 = new PictureBox();
pb1.ImageLocation = "http://www.dotnetperls.com/favicon.ico";
pb1.SizeMode = PictureBoxSizeMode.AutoSize;
}
And please, be sure that "../SamuderaJayaMotor.png" is the correct path of the image that you are using.
This question is tagged python-2.x
so it didn't seem right to tamper with the original question, or the accepted answer. However, Python 2 is now unsupported, and this question still has good google juice for "python csv urllib", so here's an updated Python 3 solution.
It's now necessary to decode urlopen
's response (in bytes) into a valid local encoding, so the accepted answer has to be modified slightly:
import csv, urllib.request
url = 'http://winterolympicsmedals.com/medals.csv'
response = urllib.request.urlopen(url)
lines = [l.decode('utf-8') for l in response.readlines()]
cr = csv.reader(lines)
for row in cr:
print(row)
Note the extra line beginning with lines =
, the fact that urlopen
is now in the urllib.request
module, and print
of course requires parentheses.
It's hardly advertised, but yes, csv.reader
can read from a list of strings.
And since someone else mentioned pandas, here's a one-liner to display the CSV in a console-friendly output:
python3 -c 'import pandas
df = pandas.read_csv("http://winterolympicsmedals.com/medals.csv")
print(df.to_string())'
(Yes, it's three lines, but you can copy-paste it as one command. ;)
I think you will have to loop over the "inserted" table, which contains all rows that were updated. You can use a WHERE loop, or a WITH statement if your primary key is a GUID. This is the simpler (for me) to write, so here is my example. We use this approach, so I know for a fact it works fine.
ALTER TRIGGER [dbo].[RA2Newsletter] ON [dbo].[Reiseagent]
AFTER INSERT
AS
-- This is your primary key. I assume INT, but initialize
-- to minimum value for the type you are using.
DECLARE @rAgent_ID INT = 0
-- Looping variable.
DECLARE @i INT = 0
-- Count of rows affected for looping over
DECLARE @count INT
-- These are your old variables.
DECLARE @rAgent_Name NVARCHAR(50)
DECLARE @rAgent_Email NVARCHAR(50)
DECLARE @rAgent_IP NVARCHAR(50)
DECLARE @hotelID INT
DECLARE @retval INT
BEGIN
SET NOCOUNT ON ;
-- Get count of affected rows
SELECT @Count = Count(rAgent_ID)
FROM inserted
-- Loop over rows affected
WHILE @i < @count
BEGIN
-- Get the next rAgent_ID
SELECT TOP 1
@rAgent_ID = rAgent_ID
FROM inserted
WHERE rAgent_ID > @rAgent_ID
ORDER BY rAgent_ID ASC
-- Populate values for the current row
SELECT @rAgent_Name = rAgent_Name,
@rAgent_Email = rAgent_Email,
@rAgent_IP = rAgent_IP,
@hotelID = hotelID
FROM Inserted
WHERE rAgent_ID = @rAgent_ID
-- Run your stored procedure
EXEC insert2Newsletter '', '', @rAgent_Name, @rAgent_Email,
@rAgent_IP, @hotelID, 'RA', @retval
-- Set up next iteration
SET @i = @i + 1
END
END
GO
I sure hope this helps you out. Cheers!
The following regex matches a '+' followed by n digits
var mobileNumber = "+18005551212";
var regex = new RegExp("^\\+[0-9]*$");
var OK = regex.test(mobileNumber);
if (OK) {
console.log("is a phone number");
} else {
console.log("is NOT a phone number");
}
I am using Debian 8 live off a USB. I was locked out of the system after 10 min of inactivity. The password that was required to log back in to the system for the user was:
login : Debian Live User
password : live
I hope this helps
I just encountered this problem. I tried a few things, but settled on using JSoup. The jar is about 132k, which is a bit big, but if you download the source and take out some of the methods you will not be using, then it is not as big.
=> Good thing about it is that it will handle badly formed HTML
Here's a good example from their site.
File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");
//http://jsoup.org/cookbook/input/load-document-from-url
//Document doc = Jsoup.connect("http://example.com/").get();
Element content = doc.getElementById("content");
Elements links = content.getElementsByTag("a");
for (Element link : links) {
String linkHref = link.attr("href");
String linkText = link.text();
}
If you are not going to use the NumPy library, you can use the nested list. This is code to implement the dynamic nested list (2-dimensional lists).
Let r
is the number of rows
let r=3
m=[]
for i in range(r):
m.append([int(x) for x in raw_input().split()])
Any time you can append a row using
m.append([int(x) for x in raw_input().split()])
Above, you have to enter the matrix row-wise. To insert a column:
for i in m:
i.append(x) # x is the value to be added in column
To print the matrix:
print m # all in single row
for i in m:
print i # each row in a different line
In my case it was the problem of building the extension, I was pointing at an extension src (with manifest and everything) but without a build.
If you run into this scenario run
npm i
then
npm build
Use Object.assign()
Example:
var a = {some: object};
var b = new Object;
Object.assign(b, a);
// b now equals a, but not by association.
A cleaner example that does the same thing:
var a = {some: object};
var b = Object.assign({}, a);
// Once again, b now equals a.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
At first you need to have enabled curl
extension in PHP. Then you can use this function:
function file_get_contents_ssl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3000); // 3 sec.
curl_setopt($ch, CURLOPT_TIMEOUT, 10000); // 10 sec.
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
It works similar to function file_get_contents(..).
Example:
echo file_get_contents_ssl("https://www.example.com/");
Output:
<!doctype html>
<html>
<head>
<title>Example Domain</title>
...
ThreadLocal
variables are typically implemented as private static
.
In this way, they are not bound to the class and each thread has its own reference to its own "ThreadLocal" object.
Adding to Cheeken's answer, This is how you sort a list of tuples by the 2nd item in descending order.
sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)],key=lambda x: x[1], reverse=True)
simple / elegant / how I do it:
Preview:
XML:
<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/btn_dropdown"
android:spinnerMode="dropdown"/>
spinnerMode
set to dropdown
is androids way to make a dropdown. (https://developer.android.com/reference/android/widget/Spinner#attr_android:spinnerMode)
Java:
//get the spinner from the xml.
Spinner dropdown = findViewById(R.id.spinner1);
//create a list of items for the spinner.
String[] items = new String[]{"1", "2", "three"};
//create an adapter to describe how the items are displayed, adapters are used in several places in android.
//There are multiple variations of this, but this is the basic variant.
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
//set the spinners adapter to the previously created one.
dropdown.setAdapter(adapter);
Documentation:
This is the basics but there is more to be self taught with experimentation. https://developer.android.com/guide/topics/ui/controls/spinner.html
--create a user that you want to use the database as:
create role neil;
--create the user for the web server to connect as:
create role webgui noinherit login password 's3cr3t';
--let webgui set role to neil:
grant neil to webgui; --this looks backwards but is correct.
webgui
is now in the neil
group, so webgui
can call set role neil
. However, webgui
did not inherit neil
's permissions.
Later, login as webgui:
psql -d some_database -U webgui
(enter s3cr3t as password)
set role neil;
webgui
does not need superuser
permission for this.
You want to set role
at the beginning of a database session and reset it at the end of the session. In a web app, this corresponds to getting a connection from your database connection pool and releasing it, respectively. Here's an example using Tomcat's connection pool and Spring Security:
public class SetRoleJdbcInterceptor extends JdbcInterceptor {
@Override
public void reset(ConnectionPool connectionPool, PooledConnection pooledConnection) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication != null) {
try {
/*
use OWASP's ESAPI to encode the username to avoid SQL Injection. Can't use parameters with SET ROLE. Need to write PG codec.
Or use a whitelist-map approach
*/
String username = ESAPI.encoder().encodeForSQL(MY_CODEC, authentication.getName());
Statement statement = pooledConnection.getConnection().createStatement();
statement.execute("set role \"" + username + "\"");
statement.close();
} catch(SQLException exp){
throw new RuntimeException(exp);
}
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("close".equals(method.getName())){
Statement statement = ((Connection)proxy).createStatement();
statement.execute("reset role");
statement.close();
}
return super.invoke(proxy, method, args);
}
}
def _create_type(meta, name, attrs):
type_name = f'{name}Type'
type_attrs = {}
for k, v in attrs.items():
if type(v) is _ClassPropertyDescriptor:
type_attrs[k] = v
return type(type_name, (meta,), type_attrs)
class ClassPropertyType(type):
def __new__(meta, name, bases, attrs):
Type = _create_type(meta, name, attrs)
cls = super().__new__(meta, name, bases, attrs)
cls.__class__ = Type
return cls
class _ClassPropertyDescriptor(object):
def __init__(self, fget, fset=None):
self.fget = fget
self.fset = fset
def __get__(self, obj, owner):
if self in obj.__dict__.values():
return self.fget(obj)
return self.fget(owner)
def __set__(self, obj, value):
if not self.fset:
raise AttributeError("can't set attribute")
return self.fset(obj, value)
def setter(self, func):
self.fset = func
return self
def classproperty(func):
return _ClassPropertyDescriptor(func)
class Bar(metaclass=ClassPropertyType):
__bar = 1
@classproperty
def bar(cls):
return cls.__bar
@bar.setter
def bar(cls, value):
cls.__bar = value
bar = Bar()
assert Bar.bar==1
Bar.bar=2
assert bar.bar==2
nbar = Bar()
assert nbar.bar==2
.mouseover()
.hover()
Bind one or two handlers
to the matched elements, to be executed when the mouse pointer
enters and leaves the elements.
Calling $(selector).hover(handlerIn, handlerOut)
is shorthand for:
$(selector).mouseenter(handlerIn).mouseleave(handlerOut);
Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.
mouseover
fires when the pointer moves into the child element as
well, while mouseenter
fires only when the pointer moves into the
bound element.
Because of this, .mouseover()
is not the same as .hover()
, for the same reason .mouseover()
is not the same as .mouseenter()
.
$('selector').mouseover(over_function) // may fire multiple times
// enter and exit functions only called once per element per entry and exit
$('selector').hover(enter_function, exit_function)
I had the same problem, and found the answer. If you use node.js with express, you need to give it its own function in order for the js file to be reached. For example:
const script = path.join(__dirname, 'script.js');
const server = express().get('/', (req, res) => res.sendFile(script))
Hi not an expert in streaming but my understanding is that it is included in th Java Media Framework JMF http://java.sun.com/javase/technologies/desktop/media/jmf/2.1.1/support-rtsp.html
If you simply want to squash all commits into a single, initial commit, just reset the repository and amend the first commit:
git reset hash-of-first-commit
git add -A
git commit --amend
Git reset will leave the working tree intact, so everything is still there. So just add the files using git add commands, and amend the first commit with these changes. Compared to rebase -i you'll lose the ability to merge the git comments though.
By using the -Xmx
command line parameter when you invoke java.
See http://download.oracle.com/javase/6/docs/technotes/tools/windows/java.html
Another option based on this answer: https://stackoverflow.com/a/29269316/451710
This allows you to execute multiple commands (e.g cd
) in the same process.
import subprocess
commands = '''
pwd
cd some-directory
pwd
cd another-directory
pwd
'''
process = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = process.communicate(commands.encode('utf-8'))
print(out.decode('utf-8'))
You can use \centering
with your parbox to do this.
(Sorry for the Google cached link; the original one I had doesn't work anymore.)
Normally, that is not an error per se; it is a warning that the first file it found that matches the -lPI-Http
argument to the compiler/linker is not valid. The error occurs when no other library can be found with the right content.
So, you need to look to see whether /dvlpmnt/libPI-Http.a
is a library of 32-bit object files or of 64-bit object files - it will likely be 64-bit if you are compiling with the -m32
option. Then you need to establish whether there is an alternative libPI-Http.a
or libPI-Http.so
file somewhere else that is 32-bit. If so, ensure that the directory that contains it is listed in a -L/some/where
argument to the linker. If not, then you will need to obtain or build a 32-bit version of the library from somewhere.
To establish what is in that library, you may need to do:
mkdir junk
cd junk
ar x /dvlpmnt/libPI-Http.a
file *.o
cd ..
rm -fr junk
The 'file
' step tells you what type of object files are in the archive. The rest just makes sure you don't make a mess that can't be easily cleaned up.
You should not make an ajax call, just put the src of the img element as the url of the image.
This would be useful if you use GET instead of POST
<script type="text/javascript" >
$(document).ready( function() {
$('.div_imagetranscrits').html('<img src="get_image_probes_via_ajax.pl?id_project=xxx" />')
} );
</script>
If you want to POST to that image and do it the way you do (trying to parse the contents of the image on the client side, you could try something like this: http://en.wikipedia.org/wiki/Data_URI_scheme
You'll need to encode the data
to base64, then you could put data:[<MIME-type>][;charset=<encoding>][;base64],<data>
into the img src
as example:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot img" />
To encode to base64:
This seems to be a recent regression or some strange behavior in typescript. If you have the code:
const result = []
Usually it would be treated as if you wrote:
const result:any[] = []
however, if you have both noImplicitAny
FALSE, AND strictNullChecks
TRUE in your tsconfig, it is treated as:
const result:never[] = []
This behavior defies all logic, IMHO. Turning on null checks changes the entry types of an array?? And then turning on noImplicitAny
actually restores the use of any
without any warnings??
When you truly have an array of any
, you shouldn't need to indicate it with extra code.
Here is an awesome and precise explanation I found.
TIMESTAMP used to track changes of records, and update every time when the record is changed. DATETIME used to store specific and static value which is not affected by any changes in records.
TIMESTAMP also affected by different TIME ZONE related setting. DATETIME is constant.
TIMESTAMP internally converted a current time zone to UTC for storage, and during retrieval convert the back to the current time zone. DATETIME can not do this.
TIMESTAMP is 4 bytes and DATETIME is 8 bytes.
TIMESTAMP supported range: ‘1970-01-01 00:00:01' UTC to ‘2038-01-19 03:14:07' UTC DATETIME supported range: ‘1000-01-01 00:00:00' to ‘9999-12-31 23:59:59'
Also...
Using numpy, you can do:
y = x.astype(int)
If you were using a non-numpy array, you could use a list comprehension:
y = [int(val) for val in x]
Getting last nth months data retrieve
SELECT * FROM TABLE_NAME
WHERE DATE_COLUMN BETWEEN '&STARTDATE' AND '&ENDDATE';
I used this
:top
cls
type G:\empty.txt
type I:\empty.txt
timeout /T 500
goto top
Check that (for jUnit - 4.12 and Eclipse surefire plugin)
I wrote a ES2015 solution ( use only with Webpack ).
class logger {
static isEnabled = true;
static enable () {
if(this.constructor.isEnabled === true){ return; }
this.constructor.isEnabled = true;
}
static disable () {
if(this.constructor.isEnabled === false){ return; }
this.constructor.isEnabled = false;
}
static log () {
if(this.constructor.isEnabled === false ) { return; }
const copy = [].slice.call(arguments);
window['console']['log'].apply(this, copy);
}
static warn () {
if(this.constructor.isEnabled === false ) { return; }
const copy = [].slice.call(arguments);
window['console']['warn'].apply(this, copy);
}
static error () {
if(this.constructor.isEnabled === false ) { return; }
const copy = [].slice.call(arguments);
window['console']['error'].apply(this, copy);
}
}
Description:
logger.disable()
- disable all console messageslogger.enable()
- enable all console messageslogger.log('message1', 'message2')
- works exactly like console.log.logger.warn('message1', 'message2')
- works exactly like console.warn.logger.error('message1', 'message2')
- works exactly like console.error.
Happy coding..Looks like this bug has been around for quite a while! Here are some bug references you may find helpful (and may want to subscribe to / vote up, hint, hint...):
Debian bug #85123 ("sudo: SECURE_PATH still can't be overridden") (from 2001!)
It seems that Bug#20996 is still present in this version of sudo. The changelog says that it can be overridden at runtime but I haven't yet discovered how.
They mention putting something like this in your sudoers file:
Defaults secure_path="/bin:/usr/bin:/usr/local/bin"
but when I do that in Ubuntu 8.10 at least, it gives me this error:
visudo: unknown defaults entry `secure_path' referenced near line 10
Ubuntu bug #50797 ("sudo built with --with-secure-path is problematic")
Worse still, as far as I can tell, it is impossible to respecify secure_path in the sudoers file. So if, for example, you want to offer your users easy access to something under /opt, you must recompile sudo.
Yes. There needs to be a way to override this "feature" without having to recompile. Nothing worse then security bigots telling you what's best for your environment and then not giving you a way to turn it off.
This is really annoying. It might be wise to keep current behavior by default for security reasons, but there should be a way of overriding it other than recompiling from source code! Many people ARE in need of PATH inheritance. I wonder why no maintainers look into it, which seems easy to come up with an acceptable solution.
I worked around it like this:
mv /usr/bin/sudo /usr/bin/sudo.orig
then create a file /usr/bin/sudo containing the following:
#!/bin/bash /usr/bin/sudo.orig env PATH=$PATH "$@"
then your regular sudo works just like the non secure-path sudo
Ubuntu bug #192651 ("sudo path is always reset")
Given that a duplicate of this bug was originally filed in July 2006, I'm not clear how long an ineffectual env_keep has been in operation. Whatever the merits of forcing users to employ tricks such as that listed above, surely the man pages for sudo and sudoers should reflect the fact that options to modify the PATH are effectively redundant.
Modifying documentation to reflect actual execution is non destabilising and very helpful.
Ubuntu bug #226595 ("impossible to retain/specify PATH")
I need to be able to run sudo with additional non-std binary folders in the PATH. Having already added my requirements to /etc/environment I was surprised when I got errors about missing commands when running them under sudo.....
I tried the following to fix this without sucess:
Using the "
sudo -E
" option - did not work. My existing PATH was still reset by sudoChanging "
Defaults env_reset
" to "Defaults !env_reset
" in /etc/sudoers -- also did not work (even when combined with sudo -E)Uncommenting
env_reset
(e.g. "#Defaults env_reset
") in /etc/sudoers -- also did not work.Adding '
Defaults env_keep += "PATH"
' to /etc/sudoers -- also did not work.Clearly - despite the man documentation - sudo is completely hardcoded regarding PATH and does not allow any flexibility regarding retaining the users PATH. Very annoying as I can't run non-default software under root permissions using sudo.
In my project I managed to use GridLayout and results are very stable, with no flickering and with a perfectly working vertical scrollbar.
First I created a JPanel for the settings; in my case it is a grid with a row for each parameter and two columns: left column is for labels and right column is for components. I believe your case is similar.
JPanel yourSettingsPanel = new JPanel();
yourSettingsPanel.setLayout(new GridLayout(numberOfParams, 2));
I then populate this panel by iterating on my parameters and alternating between adding a JLabel and adding a component.
for (int i = 0; i < numberOfParams; ++i) {
yourSettingsPanel.add(labels[i]);
yourSettingsPanel.add(components[i]);
}
To prevent yourSettingsPanel from extending to the entire container I first wrap it in the north region of a dummy panel, that I called northOnlyPanel.
JPanel northOnlyPanel = new JPanel();
northOnlyPanel.setLayout(new BorderLayout());
northOnlyPanel.add(yourSettingsPanel, BorderLayout.NORTH);
Finally I wrap the northOnlyPanel in a JScrollPane, which should behave nicely pretty much anywhere.
JScrollPane scroll = new JScrollPane(northOnlyPanel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
Most likely you want to display this JScrollPane extended inside a JFrame; you can add it to a BorderLayout JFrame, in the CENTER region:
window.add(scroll, BorderLayout.CENTER);
In my case I put it on the left column of a GridLayout(1, 2) panel, and I use the right column to display contextual help for each parameter.
JTextArea help = new JTextArea();
help.setLineWrap(true);
help.setWrapStyleWord(true);
help.setEditable(false);
JPanel split = new JPanel();
split.setLayout(new GridLayout(1, 2));
split.add(scroll);
split.add(help);
Just use the Json.NET library. It lets you parse Json format strings very easily:
JObject o = JObject.Parse(@"
{
""something"":""value"",
""jagged"":
{
""someother"":""value2""
}
}");
string something = (string)o["something"];
Documentation: Parsing JSON Object using JObject.Parse
One could use the Buffer
s that are provided as part of the java.nio
package to perform the conversion.
Here, the source byte[]
array has a of length 8, which is the size that corresponds with a long
value.
First, the byte[]
array is wrapped in a ByteBuffer
, and then the ByteBuffer.getLong
method is called to obtain the long
value:
ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 0, 0, 0, 0, 4});
long l = bb.getLong();
System.out.println(l);
Result
4
I'd like to thank dfa for pointing out the ByteBuffer.getLong
method in the comments.
Although it may not be applicable in this situation, the beauty of the Buffer
s come with looking at an array with multiple values.
For example, if we had a 8 byte array, and we wanted to view it as two int
values, we could wrap the byte[]
array in an ByteBuffer
, which is viewed as a IntBuffer
and obtain the values by IntBuffer.get
:
ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 1, 0, 0, 0, 4});
IntBuffer ib = bb.asIntBuffer();
int i0 = ib.get(0);
int i1 = ib.get(1);
System.out.println(i0);
System.out.println(i1);
Result:
1
4
Also add this bit of code to your form to allow it to be draggable still.
Just add it right before the constructor (the method that calls InitializeComponent()
private const int WM_NCHITTEST = 0x84;
private const int HTCLIENT = 0x1;
private const int HTCAPTION = 0x2;
///
/// Handling the window messages
///
protected override void WndProc(ref Message message)
{
base.WndProc(ref message);
if (message.Msg == WM_NCHITTEST && (int)message.Result == HTCLIENT)
message.Result = (IntPtr)HTCAPTION;
}
That code is from: https://jachman.wordpress.com/2006/06/08/enhanced-drag-and-move-winforms-without-having-a-titlebar/
Now to get rid of the title bar but still have a border combine the code from the other response:
this.ControlBox = false;
this.Text = String.Empty;
with this line:
this.FormBorderStyle = FormBorderStyle.FixedSingle;
Put those 3 lines of code into the form's OnLoad event and you should have a nice 'floating' form that is draggable with a thin border (use FormBorderStyle.None if you want no border).
Sometimes I think we can overcomplicate the solution just to avoid repeating one line of code. This is the reason I landed on this question in the first place.
After thinking about it for a bit I came to the conclusion that the simplest solution is to repeat the ReadLine
before and inside the loop.
using (var stringReader = new StringReader(input))
{
var line = await stringReader.ReadLineAsync();
while (line != null)
{
// do something
line = await stringReader.ReadLineAsync();
}
}
I realize this might be considered to not follow the DRY principle, but I think it's worth considering given the simplicity.
The reason why your X-axis plots frequencies only till 500 Hz is your command statement 'f = Fs/2*linspace(0,1,NFFT/2+1);'. Your Fs is 1000. So when you divide it by 2 & then multiply by values ranging from 0 to 1, it returns a vector of length NFFT/2+1. This vector consists of equally spaced frequency values, ranging from 0 to Fs/2 (i.e. 500 Hz). Since you plot using 'plot(f,2*abs(Y(1:NFFT/2+1)))' command, your X-axis limit is 500 Hz.
To add to the above correct answer :-
For my case in shell, this code worked (working on sqoop
)
ROOT_PATH="path/to/the/folder"
--options-file $ROOT_PATH/query.txt
This should do the trick:
<?php
$product_meta = get_post_meta($post_id);
echo wp_get_attachment_image( $product_meta['_thumbnail_id'][0], 'full' );
?>
You can change the parameters according to your needs.
Iframe
<iframe id="fred" style="border:1px solid #666CCC" title="PDF in an i-Frame" src="PDFData.pdf" frameborder="1" scrolling="auto" height="1100" width="850" ></iframe>
Object
<object data="your_url_to_pdf" type="application/pdf">
<embed src="your_url_to_pdf" type="application/pdf" />
</object>
Assuming there is no problem doing a lookup on localhost (to 127.0.0.1), you need to make sure your server is listening to 127.0.0.1.
netstat works in both windows an UNIX. You probably need "netstat -a
" to display listeners.
Your file has syntax error, so your file was not interpreted, so settings was not changed and you have blank page.
You can separate your file to two.
index.php
<?php
ini_set("display_errors", "1");
error_reporting(E_ALL);
include 'error.php';
error.php
<?
echo('catch this -> ' ;. $thisdoesnotexist);
With Laravel 5.6, if you want pass multiple emails with names, you need to pass array of associative arrays. Example pushing multiple recipients into the $to
array:
$to[] = array('email' => $email, 'name' => $name);
Fixed two recipients:
$to = [['email' => '[email protected]', 'name' => 'User One'],
['email' => '[email protected]', 'name' => 'User Two']];
The 'name' key is not mandatory. You can set it to 'name' => NULL
or do not add to the associative array, then only 'email'
will be used.
Unless you need an actual clone of every single object inside your List<T>
, the best way to clone a list is to create a new list with the old list as the collection parameter.
List<T> myList = ...;
List<T> cloneOfMyList = new List<T>(myList);
Changes to myList
such as insert or remove will not affect cloneOfMyList
and vice versa.
The actual objects the two Lists contain are still the same however.
The subtle difference is that 3NF makes a distinction between key and non-key attributes (also called non-prime attributes) whereas BCNF does not.
This is best explained using Zaniolo's definition of 3NF, which is equivalent to Codd's:
A relation, R, is in 3NF iff for every nontrivial FD (X->A) satisfied by R at least ONE of the following conditions is true:
(a) X is a superkey for R, or
(b) A is a key attribute for R
BCNF requires (a) but doesn't treat (b) as a special case of its own. In other words BCNF requires that every nontrivial determinant is a superkey even its dependent attributes happen to be part of a key.
A relation, R, is in BCNF iff for every nontrivial FD (X->A) satisfied by R the following condition is true:
(a) X is a superkey for R
BCNF is therefore more strict.
The difference is so subtle that what many people informally describe as 3NF is actually BCNF. For example, you stated here that 3NF means "data depends on the key[s]... and nothing but the key[s]", but that is really an informal description of BCNF and not 3NF. 3NF could more accurately be described as "non-key data depends on the keys... and nothing but the keys".
You also stated:
the 3NF quote explicitly says "nothing but the key" meaning that all attributes depend solely on the primary key.
That's an oversimplification. 3NF and BCNF and all the Normal Forms are concerned with all candidate keys and/or superkeys, not just one "primary" key.
If you plan to write the next line, ESCGo will do the carriage return and put you in insert mode on the next line (at the end of the file), saving a couple more keystrokes.
You should be able to paste the following into a bash terminal window.
Display ANSI colour palette:
e="\033["
for f in 0 7 `seq 6`; do
no="" bo=""
for b in n 7 0 `seq 6`; do
co="3$f"; p=" "
[ $b = n ] || { co="$co;4$b";p=""; }
no="${no}${e}${co}m ${p}${co} ${e}0m"
bo="${bo}${e}1;${co}m ${p}1;${co} ${e}0m"
done
echo -e "$no\n$bo"
done
256 colour demo:
yes "$(seq 232 255;seq 254 -1 233)" |
while read i; do printf "\x1b[48;5;${i}m\n"; sleep .01; done
For windows, @shoaly parameters didn't completely work for me. I was getting this error:
NCAT DEBUG: Proxy returned status code 501.
Ncat: Proxy returned status code 501.
ssh_exchange_identification: Connection closed by remote host
I wanted to ssh to a REMOTESERVER and the SSH port had been closed in my network. I found two solutions but the second is better.
To solve the problem using Ncat:
ncat.exe
into the current directory.SSH using Ncat as ProxyCommand in Git Bash with addition --proxy-type socks4
parameter:
ssh -o "ProxyCommand=./ncat --proxy-type socks4 --proxy 127.0.0.1:9150 %h %p" USERNAME@REMOTESERVER
Note that this implementation of Ncat does not support socks5.
THE BETTER SOLUTION:
SSH using connect.c as ProxyCommand in Git Bash:
ssh -o "ProxyCommand=connect -a none -S 127.0.0.1:9150 %h %p"
Note that connect.c supports socks version 4/4a/5.
To use the proxy in git
commands using ssh (for example while using GitHub) -- assuming you installed Git Bash in C:\Program Files\Git\
-- open ~/.ssh/config
and add this entry:
host github.com
user git
hostname github.com
port 22
proxycommand "/c/Program Files/Git/mingw64/bin/connect.exe" -a none -S 127.0.0.1:9150 %h %p
Just to add to these Anniversary Update
issues (thanks Microsoft) if the file you are missing is cgi.dll
, ie your Event Viewer
has
The Module DLL C:\WINDOWS\System32\inetsrv\cgi.dll failed to load. The data is the error.
Then to fix this:
IIS Manager
Connections
panel (typically your PC name)Management
, you should have Web Platform Installer
Products
cgi
then hit <Enter>
IIS: CGI
then click Add
on the right and finally Install
on the bottomWhy not just check which element was clicked? If you click on something, window.event.target
is assigned to the element which was clicked, and the clicked element can also be passed as an argument.
If the target and element aren't equal, it was an event that propagated up.
function myfunc(el){
if (window.event.target === el){
// perform action
}
}
<div onclick="myfunc(this)" />
My shape xml :
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@android:color/transparent" />
<stroke android:width="0.5dp" android:color="@android:color/holo_green_dark"/>
</shape>
My activity xml :
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="cn.easydone.test.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
<TextView
android:id="@+id/test_text"
android:background="@drawable/bg_stroke_dynamic_color"
android:padding="20dp"
android:text="asdasdasdasd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:clipToPadding="false"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
My activity java :
TextView testText = (TextView) findViewById(R.id.test_text);
((GradientDrawable)testText.getBackground()).setStroke(10,Color.BLACK);
Result picture : result
One common example is the __call__
in functools.partial
, here is a simplified version (with Python >= 3.5):
class partial:
"""New function with partial application of the given arguments and keywords."""
def __new__(cls, func, *args, **kwargs):
if not callable(func):
raise TypeError("the first argument must be callable")
self = super().__new__(cls)
self.func = func
self.args = args
self.kwargs = kwargs
return self
def __call__(self, *args, **kwargs):
return self.func(*self.args, *args, **self.kwargs, **kwargs)
Usage:
def add(x, y):
return x + y
inc = partial(add, y=1)
print(inc(41)) # 42
By default, package-lock.json
is updated whenever you run npm install
. However, this can be disabled globally by setting package-lock=false
in ~/.npmrc
.
When the global package-lock=false
setting is active, you can still force a project’s package-lock.json
file to be updated by running:
npm install --package-lock
This command is the only surefire way of forcing a package-lock.json
update.
You can use below code snippet
import shlex
import subprocess
import json
def call_curl(curl):
args = shlex.split(curl)
process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
return json.loads(stdout.decode('utf-8'))
if __name__ == '__main__':
curl = '''curl - X
POST - d
'{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}'
http: // localhost: 8080 / firewall / rules / 0000000000000001 '''
output = call_curl(curl)
print(output)
You should use val
instead of value
.
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('input[name="testing"]').val('Work!');
});
</script>
The proper way to fully uninstall conda (Anaconda / Miniconda):
Remove all conda-related files and directories using the Anaconda-Clean package
conda activate your_conda_env_name
conda install anaconda-clean
anaconda-clean # add `--yes` to avoid being prompted to delete each one
Remove your entire conda directory
rm -rf ~/miniconda3
Remove the line which adds the conda path to the PATH
environment variable
vi ~/.bashrc
# -> Search for conda and delete the lines containing it
# -> If you're not sure if the line belongs to conda, comment it instead of deleting it just to be safe
source ~/.bashrc
Remove the backup folder created by the the Anaconda-Clean package NOTE: Think twice before doing this, because after that you won't be able to restore anything from your old conda installation!
rm -rf ~/.anaconda_backup
Reference: Official conda documentation
INSERT IGNORE INTO `mytable`
SET `field0` = '2',
`field1` = 12345,
`field2` = 12678;
Here the mysql query, that insert records if not exist and will ignore existing similar records.
----Untested----
There are multiple php config files, but THIS is the one you need to edit:
/etc/php(version)?/fpm/pool.d/www.conf
uncomment the line that says:
catch_workers_output
That will allow PHPs stderr to go to php-fpm's error log instead of /dev/null.
SELECT
CASE
WHEN xyz.something = 1 THEN 'SOMETEXT'
WHEN xyz.somethingelse = 1 THEN 'SOMEOTHERTEXT'
WHEN xyz.somethingelseagain = 2 THEN 'SOMEOTHERTEXTGOESHERE'
ELSE 'SOMETHING UNKNOWN'
END AS ColumnName;
The only way I have 100% consistently been able to avoid this flex-direction column bug is to use a min-width media query to assign a max-width to the child element on desktop sized screens.
.parent {
display: flex;
flex-direction: column;
}
//a media query targeting desktop sort of sized screens
@media screen and (min-width: 980px) {
.child {
display: block;
max-width: 500px;//maximimum width of the element on a desktop sized screen
}
}
You will need to set naturally inline child elements (eg. <span>
or <a>
) to something other than inline (mainly display:block or display:inline-block) for the fix to work.
If your local directory has git initialized and you have not committed the changes that include the delete, you can use git checkout -f
to throw away local changes.
int[][] myNums = { {1, 2, 3, 4, 5, 6, 7}, {5, 6, 7, 8, 9, 10, 11} };
for (int x = 0; x < myNums.length; ++x) {
for(int y = 0; y < myNums[i].length; ++y) {
System.out.print(myNums[x][y]);
}
}
Output
1 2 3 4 5 6 7 5 6 7 8 9 10 11
Get the number of text fields from the user and assign it to a variable.
var no = document.getElementById("idname").value
To create input fields, use createElement
method and specify element name i.e. "input" as parameter like below and assign it to a variable.
var textfield = document.createElement("input");
Then assign necessary attributes to the variable.
textfield.type = "text";
textfield.value = "";
At last append variable to the form element using appendChild
method. so that the input element will be created in the form element itself.
document.getElementById('form').appendChild(textfield);
Loop the 2,3 and 4 step to create desired number of input elements given by the user inside the form element.
for(var i=0;i<no;i++) {
var textfield = document.createElement("input");
textfield.type = "text"; textfield.value = "";
document.getElementById('form').appendChild(textfield);
}
Here's the complete code
function fun() {
/*Getting the number of text fields*/
var no = document.getElementById("idname").value;
/*Generating text fields dynamically in the same form itself*/
for(var i=0;i<no;i++) {
var textfield = document.createElement("input");
textfield.type = "text";
textfield.value = "";
document.getElementById('form').appendChild(textfield);
}
}
_x000D_
<form id="form">
<input type="type" id="idname" oninput="fun()" value="">
</form>
_x000D_
If you use a Language Resource file to set the labels in your application you need to set the its value:
CultureInfo customCulture = new CultureInfo("en-US");
Languages.Culture = customCulture;
Simple Html 'required' tag is useful.
<form>
<input type="text" name="test" id="test" required>
<input type="submit" value="enter">
</form>
It specifies that an input field must be filled out before submitting the form or press the button submit. Here is example
Assuming you already know lists are of equal size, the following will guarantee True if and only if two vectors are exactly the same (including order)
functools.reduce(lambda b1,b2: b1 and b2, map(lambda e1,e2: e1==e2, listA, ListB), True)
Example:
>>> from functools import reduce
>>> def compvecs(a,b):
... return reduce(lambda b1,b2: b1 and b2, map(lambda e1,e2: e1==e2, a, b), True)
...
>>> compvecs(a=[1,2,3,4], b=[1,2,4,3])
False
>>> compvecs(a=[1,2,3,4], b=[1,2,3,4])
True
>>> compvecs(a=[1,2,3,4], b=[1,2,4,3])
False
>>> compare_vectors(a=[1,2,3,4], b=[1,2,2,4])
False
>>>
I had the same issue, but I simply solved it by adding -lm after the command that runs my code. Example. gcc code.c -lm
In my case I had to add the boundary to the header like the following:
const form = new FormData();
form.append(item.name, fs.createReadStream(pathToFile));
const response = await axios({
method: 'post',
url: 'http://www.yourserver.com/upload',
data: form,
headers: {
'Content-Type': `multipart/form-data; boundary=${form._boundary}`,
},
});
This solution is also useful if you're working with React Native.