If you have a mixture of formats in your date, don't forget to set infer_datetime_format=True
to make life easier.
df['date'] = pd.to_datetime(df['date'], infer_datetime_format=True)
Source: pd.to_datetime
or if you want a customized approach:
def autoconvert_datetime(value):
formats = ['%m/%d/%Y', '%m-%d-%y'] # formats to try
result_format = '%d-%m-%Y' # output format
for dt_format in formats:
try:
dt_obj = datetime.strptime(value, dt_format)
return dt_obj.strftime(result_format)
except Exception as e: # throws exception when format doesn't match
pass
return value # let it be if it doesn't match
df['date'] = df['date'].apply(autoconvert_datetime)
I am using Python via Anaconda's Spyder software. Using the original code listed in the question of this thread by @Gshocked, the code does not work (the python won't read the mp4 file). So I downloaded OpenCV 3.2 and copied "opencv_ffmpeg320.dll" and "opencv_ffmpeg320_64.dll" from the "bin" folder. I pasted both of these dll files to Anaconda's "Dlls" folder.
Anaconda also has a "pckgs" folder...I copied and pasted the entire "OpenCV 3.2" folder that I downloaded to the Anaconda "pckgs" folder.
Finally, Anaconda has a "Library" folder which has a "bin" subfolder. I pasted the "opencv_ffmpeg320.dll" and "opencv_ffmpeg320_64.dll" files to that folder.
After closing and restarting Spyder, the code worked. I'm not sure which of the three methods worked, and I'm too lazy to go back and figure it out. But it works so, cheers!
Normaly you can GET and POST parameters in a servlet the same way:
request.getParameter("cmd");
But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.
If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:
BufferedReader reader = request.getReader();
Json post processing example (uses org.json package )
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
try {
JSONObject jsonObject = HTTP.toJSONObject(jb.toString());
} catch (JSONException e) {
// crash and burn
throw new IOException("Error parsing JSON request string");
}
// Work with the data using methods like...
// int someInt = jsonObject.getInt("intParamName");
// String someString = jsonObject.getString("stringParamName");
// JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
// JSONArray arr = jsonObject.getJSONArray("arrayParamName");
// etc...
}
MYSQL 8.0:
Search my.ini
in disk, we will find this folder:
C:\ProgramData\MySQL\MySQL Server 8.0
It'sProgramData
, notProgram file
Data is in sub-folder: \Data
.
Each database
owns a folder, each table
is file, each index
is 1+ files.
Why don't you try to grep the return of your command ? Something like :
adb devices -l | grep 123abc12
It should return only the line you want to.
There is no easy way to catch such exception unfortunately. What I do is either override the OnError method at the page level or the Application_Error in global.asax, then check if it was a Max Request failure and, if so, transfer to an error page.
protected override void OnError(EventArgs e) .....
private void Application_Error(object sender, EventArgs e)
{
if (GlobalHelper.IsMaxRequestExceededException(this.Server.GetLastError()))
{
this.Server.ClearError();
this.Server.Transfer("~/error/UploadTooLarge.aspx");
}
}
It's a hack but the code below works for me
const int TimedOutExceptionCode = -2147467259;
public static bool IsMaxRequestExceededException(Exception e)
{
// unhandled errors = caught at global.ascx level
// http exception = caught at page level
Exception main;
var unhandled = e as HttpUnhandledException;
if (unhandled != null && unhandled.ErrorCode == TimedOutExceptionCode)
{
main = unhandled.InnerException;
}
else
{
main = e;
}
var http = main as HttpException;
if (http != null && http.ErrorCode == TimedOutExceptionCode)
{
// hack: no real method of identifying if the error is max request exceeded as
// it is treated as a timeout exception
if (http.StackTrace.Contains("GetEntireRawContent"))
{
// MAX REQUEST HAS BEEN EXCEEDED
return true;
}
}
return false;
}
If you want to get single row and from the that row single column, one line code to get the value of the specific column is to use find()
method alongside specifying of the column that you want to retrieve it.
Here is sample code:
ModelName::find($id_of_the_record, ['column_name'])->toArray()['column_name'];
For my Node Application,
"facebook": {
"clientID" : "##############",
"clientSecret": "####################",
"callbackURL": "/auth/facebook/callback/"
}
put callback Url relative
My OAuth redirect URIs as follows
Make Sure "/" at the end of Facebook auth redirect URI
These setups worked for me.
So many complicated methods... Just find all "Titled" group and join its lower cased variant with underscore.
>>> import re
>>> def camel_to_snake(string):
... groups = re.findall('([A-z0-9][a-z]*)', string)
... return '_'.join([i.lower() for i in groups])
...
>>> camel_to_snake('ABCPingPongByTheWay2KWhereIsOurBorderlands3???')
'a_b_c_ping_pong_by_the_way_2_k_where_is_our_borderlands_3'
If you don't want make numbers like first character of group or separate group - you can use ([A-z][a-z0-9]*)
mask.
It's destroy
and destroy_all
methods, like
user.destroy
User.find(15).destroy
User.destroy(15)
User.where(age: 20).destroy_all
User.destroy_all(age: 20)
Alternatively you can use delete
and delete_all
which won't enforce :before_destroy
and :after_destroy
callbacks or any dependent association options.
User.delete_all(condition: 'value')
will allow you to delete records without a primary key
Note: from @hammady's comment, user.destroy
won't work if User model has no primary key.
Note 2: From @pavel-chuchuva's comment, destroy_all
with conditions and delete_all
with conditions has been deprecated in Rails 5.1 - see guides.rubyonrails.org/5_1_release_notes.html
Once I realized I was running an Oracle database, not MySQL, I found the answer
select * from v$database;
or
select ora_database_name from dual;
Try both. Credit and source goes to: http://www.perlmonks.org/?node_id=520376.
html_entity_decode('エ', 0, 'UTF-8');
This works too. However the json_decode() solution is a lot faster (around 50 times).
You can use the adb
command which comes in the tools dir of the SDK:
adb shell
It will give you a command line prompt where you can browse and access the filesystem. Or you can extract the files you want:
adb pull /sdcard/the_file_you_want.txt
Also, if you use eclipse with the ADT, there's a view to browse the file system (Window->Show View->Other... and choose Android->File Explorer)
Android Studio automatically creates a Gradle wrapper in the root of your project, which is how it invokes Gradle. The wrapper is basically a script that calls through to the actual Gradle binary and allows you to keep Gradle up to date, which makes using version control easier. To run a Gradle command, you can simply use the gradlew
script found in the root of your project (or gradlew.bat
on Windows) followed by the name of the task you want to run. For instance, to build a debug version of your Android application, you can run ./gradlew assembleDebug
from the root of your repository. In a default project setup, the resulting apk can then be found in app/build/outputs/apk/app-debug.apk
. On a *nix machine, you can also just run find . -name '*.apk'
to find it, if it's not there.
Another method could be to split the string by ":" and then pop off the end.
var newString = string.split(":").pop();
This will help
wget -m -np -c --level 0 --no-check-certificate -R"index.html*"http://www.your-websitepage.com/dir
One thing that took me a while to figure out, use 'http' to access the proxy, even if you're trying to proxy through to a https server. This works for me using Charles (osx protocol analyser):
var http = require('http');
http.get ({
host: '127.0.0.1',
port: 8888,
path: 'https://www.google.com/accounts/OAuthGetRequestToken'
}, function (response) {
console.log (response);
});
Use the in
keyword.
if 'apples' in d:
if d['apples'] == 20:
print('20 apples')
else:
print('Not 20 apples')
If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get
function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None
instead):
if d.get('apples', 0) == 20:
print('20 apples.')
else:
print('Not 20 apples.')
Why would we want to check if an array is empty
? Arrays don't grow or shrink in the same that lists do. Starting with a 'empty' array, and growing with np.append
is a frequent novice error.
Using a list in if alist:
hinges on its boolean value:
In [102]: bool([])
Out[102]: False
In [103]: bool([1])
Out[103]: True
But trying to do the same with an array produces (in version 1.18):
In [104]: bool(np.array([]))
/usr/local/bin/ipython3:1: DeprecationWarning: The truth value
of an empty array is ambiguous. Returning False, but in
future this will result in an error. Use `array.size > 0` to
check that an array is not empty.
#!/usr/bin/python3
Out[104]: False
In [105]: bool(np.array([1]))
Out[105]: True
and bool(np.array([1,2])
produces the infamous ambiguity error.
The accepted answer suggests size
:
In [11]: x = np.array([])
In [12]: x.size
Out[12]: 0
But I (and most others) check the shape
more than the size
:
In [13]: x.shape
Out[13]: (0,)
Another thing in its favor is that it 'maps' on to an empty
list:
In [14]: x.tolist()
Out[14]: []
But there are other other arrays with 0 size
, that aren't 'empty' in that last sense:
In [15]: x = np.array([[]])
In [16]: x.size
Out[16]: 0
In [17]: x.shape
Out[17]: (1, 0)
In [18]: x.tolist()
Out[18]: [[]]
In [19]: bool(x.tolist())
Out[19]: True
np.array([[],[]])
is also size 0, but shape (2,0) and len
2.
While the concept of an empty
list is well defined, an empty array
is not well defined. One empty list is equal to another. The same can't be said for a size 0
array.
The answer really depends on
If you need one single regex, try:
(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)
A short explanation:
(?=.*[a-z]) // use positive look ahead to see if at least one lower case letter exists
(?=.*[A-Z]) // use positive look ahead to see if at least one upper case letter exists
(?=.*\d) // use positive look ahead to see if at least one digit exists
(?=.*\W]) // use positive look ahead to see if at least one non-word character exists
And I agree with SilentGhost, \W
might be a bit broad. I'd replace it with a character set like this: [-+_!@#$%^&*.,?]
(feel free to add more of course!)
I believe, the 500ms run in the background, while the rest of the code continues to execute and empties the list.
Then after 500ms nothing happens, as no function-call is implemented in the after-callup (same as frame.after(500, function=None)
)
I had a similar problem but using IntelliJ IDEA rather than Eclipse. I already had the ARM EABI installed, but I still got the error.
For IntelliJ IDEA, it appears you also have to create an AVB first before running the emulator, so to do this you must just go into Android SDK Manager and create a new AVB. This should solve your problem... Please make sure you have followed the above answer to include the ARM before following these steps.
Just a note: In OS X Lion, overflow set to "scroll" behaves more like auto in that scrollbars will only show when being used. They will disappear when not in use. So if any the solutions above don't appear to be working that might be why.
This is what you'll need to fix it:
::-webkit-scrollbar {
-webkit-appearance: none;
width: 7px;
}
::-webkit-scrollbar-thumb {
border-radius: 4px;
background-color: rgba(0, 0, 0, .5);
-webkit-box-shadow: 0 0 1px rgba(255, 255, 255, .5);
}
You can style it accordingly.
As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:
MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();
It's easy enough to write the equivalent of CopyTo
in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream
.
For efficient purposes you could check whether the stream returned is already a MemoryStream
:
byte[] data;
using (Stream inputStream = model.File.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
data = memoryStream.ToArray();
}
Adding to DarVar's answer:
git for-each-ref --format='%(committerdate) %09 %(authorname) %09 %(refname)' | sort -k5n -k2M -k3n -k4n | awk '{print $7 $8}'
P.S.: We used AWK to pretty print the author and the remote branch.
You can use:
select VARCHAR_FORMAT(creationdate, 'MM/DD/YYYY') from table name
The reason to make an App with no activity or service could be making a Homescreen Widget app that doesn't need to be started.
Once you start a project don't create any activities. After you created the project just hit run. Android studio will say No default activity found
.
Click Edit Configuration (From the Run menu) and in the Launch option part set the Launch value to Nothing.
Then click ok and run the App.
(Since there is no launcher activity, No app will be show in the Apps menu.).
Here's a simple solution based on a combination of what dipali and Piyush Gupta posted:
public boolean dbHasData(String searchTable, String searchColumn, String searchKey) {
String query = "Select * from " + searchTable + " where " + searchColumn + " = ?";
return getReadableDatabase().rawQuery(query, new String[]{searchKey}).moveToFirst();
}
The result '\\&'
is only displayed - actually the string is \&
:
>>> str = '&'
>>> new_str = str.replace('&', '\&')
>>> new_str
'\\&'
>>> print new_str
\&
Try it in a shell.
Pass it in through the constructor:
const char* dat = "my string!";
std::string my_string( dat );
You can use the function string.c_str() to go the other way:
std::string my_string("testing!");
const char* dat = my_string.c_str();
Why not using jQuery.parseHTML() http://api.jquery.com/jquery.parsehtml/?
I am running a real case (in opposite to a synthetic benchmark)
if("=,<=,=>,<>,<,>,!=,==,".IndexOf(tmps)>=0) {
versus
if("=,<=,=>,<>,<,>,!=,==,".Contains(tmps)) {
It is a vital part of my system and it is executed 131,953 times (thanks DotTrace).
However shocking surprise, the result is the opposite that expected
:-/
net framework 4.0 (updated as for 13-02-2012)
I had a very related issue but for higher Java versions:
$ ./gradlew clean assemble
... <other normal Gradle output>
Could not target platform: 'Java SE 11' using tool chain: 'JDK 8 (1.8)'.
I noticed that the task succeeded when running using InteliJ. Adding a file (same level as build.gradle) called .java-version
solved my issue:
# .java-version
11.0.3
If you just want the column names, then
select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'tablename'
On MS SQL Server, for more information on the table such as the types of the columns, use
sp_help 'tablename'
The main difference is that the output of pip freeze
can be dumped into a requirements.txt file and used later to re-construct the "frozen" environment.
In other words you can run:
pip freeze > frozen-requirements.txt
on one machine and then later on a different machine or on a clean environment you can do:
pip install -r frozen-requirements.txt
and you'll get the an identical environment with the exact same dependencies installed as you had in the original environment where you generated the frozen-requirements.txt.
In layman terms: JDK is grandfather JRE is father and JVM is their son. [i.e. JDK > JRE > JVM ]
JDK = JRE + Development/debugging tools
JRE = JVM + Java Packages Classes(like util, math, lang, awt,swing etc)+runtime libraries.
JVM = Class loader system + runtime data area + Execution Engine.
In other words if you are a Java programmer you will need JDK in your system and this package will include JRE and JVM as well but if you are normal user who like to play online games then you will only need JRE and this package will not have JDK in it.
JVM :
The Java Virtual Machine (JVM) is the virtual machine that run the Java bytecodes. The JVM doesn't understand Java source code, that's why you compile your *.java files to obtain *.class files that contain the bytecodes understandable by the JVM. It's also the entity that allows Java to be a "portable language" (write once, run anywhere). Indeed there are specific implementations of the JVM for different systems (Windows, Linux, MacOS, see the wikipedia list..), the aim is that with the same bytecodes they all give the same results.
JDK and JRE
To explain the difference between JDK and JRE, the best is to read the Oracle documentation and consult the diagram :
Java Runtime Environment (JRE)
The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language. In addition, two key deployment technologies are part of the JRE: Java Plug-in, which enables applets to run in popular browsers; and Java Web Start, which deploys standalone applications over a network. It is also the foundation for the technologies in the Java 2 Platform, Enterprise Edition (J2EE) for enterprise software development and deployment. The JRE does not contain tools and utilities such as compilers or debuggers for developing applets and applications.
Java Development Kit (JDK)
The JDK is a superset of the JRE, and contains everything that is in the JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications.
Note that Oracle is not the only one to provide JDK.
okay, thx a lot now i use sth like this:
public static String[] removeElements(String[] input, String deleteMe) {
if (input != null) {
List<String> list = new ArrayList<String>(Arrays.asList(input));
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(deleteMe)) {
list.remove(i);
}
}
return list.toArray(new String[0]);
} else {
return new String[0];
}
}
CSS only
line-height: 1.5;
white-space: normal;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
here how I use it; This button inside my CameraActionActivity Activity class where I call camera
btn_frag_camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intenImatToSec = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(intenImatToSec, REQUEST_CODE_VIDEO);
//intenImatToSec.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
//intenImatToSec.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
//Toast.makeText(getActivity(), "Hello From Camera", Toast.LENGTH_SHORT).show();
}
});
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE_IMG) {
Bundle bundle = data.getExtras();
Bitmap bitmap = (Bitmap) bundle.get("data");
Intent intentBitMap = new Intent(getActivity(), DisplayImage.class);
// aldigimiz imagi burda yonlendirdigimiz sinifa iletiyoruz
ByteArrayOutputStream _bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, _bs);
intentBitMap.putExtra("byteArray", _bs.toByteArray());
startActivity(intentBitMap);
} else if (requestCode == REQUEST_CODE_VIDEO) {
Uri videoUrl = data.getData();
Intent intenToDisplayVideo = new Intent(getActivity(), DisplayVideo.class);
intenToDisplayVideo.putExtra("videoUri", videoUrl.toString());
startActivity(intenToDisplayVideo);
}
}
}
And my other DisplayVideo Activity Class
VideoView videoView = (VideoView) findViewById(R.id.videoview_display_video_actvity);
Bundle extras = getIntent().getExtras();
Uri myUri= Uri.parse(extras.getString("videoUri"));
videoView.setVideoURI(myUri);
exec is for statement and does not return anything. eval is for expression and returns value of expression.
expression means "something" while statement means "do something".
***LOGIN script that doesnt link to a database or external file. Good for a global password -
Place on Login form page - place this at the top of the login page - above everything else***
<?php
if(isset($_POST['Login'])){
if(strtolower($_POST["username"])=="ChangeThis" && $_POST["password"]=="ChangeThis"){
session_start();
$_SESSION['logged_in'] = TRUE;
header("Location: ./YourPageAfterLogin.php");
}else {
$error= "Login failed !";
}
}
//print"version3<br>";
//print"username=".$_POST["username"]."<br>";
//print"password=".$_POST["username"];
?>
*Login on following pages - Place this at the top of every page that needs to be protected by login. this checks the session and if a user name and password has *
<?php
session_start();
if(!isset($_SESSION['logged_in']) OR $_SESSION['logged_in'] != TRUE){
header("Location: ./YourLoginPage.php");
}
?>
Running IIS 7.5, I had luck adding permissions for the local computer user IUSR. The app pool user didn't work.
first, you need to find the toolbox that you need. There are many people developing 3rd party toolboxes for Matlab, so there isn't just one single place where you can find "the image processing toolbox". That said, a good place to start looking is the Matlab Central which is a Mathworks-run site for exchanging all kinds of Matlab-related material.
Once you find a toolbox you want, it will be in some compressed format, and its developers might have a "readme" file that details on how to install it. If it isn't the case, a generic way to attempt installation is to place the toolbox in any directory on your drive, and then add it to Matlab path, e.g., going to File -> Set Path... -> Add Folder or Add with Subfolders (I'm writing for memory but this is definitely close).
Otherwise, you can extract all .m files in your working directory, if you don't want to use downloaded toolbox in more than one project.
By using map function you can do that. Please refer below code.
var userDetails = [{
"_id":"5078c3a803ff4197dc81fbfb",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 1"
},{
"_id":"5078c3a803ff4197dc81fbfc",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 2"
}];
var formattedUserDetails = userDetails.map(({ _id:id, email, image, name }) => ({
id,
email,
image,
name
}));
console.log(formattedUserDetails);
You can overwrite the existing jenkins.war
file with the new one and then restart Jenkins.
This file is usually located in /usr/share/jenkins
.
If this is not the case for your system, in Manage Jenkins -> System Information
, it will display the path to the .war
file under executable-war
.
I had the same problem. I use hyphenat plus the following macro:
\RequirePackage{hyphenat}
\RequirePackage{expl3}
% The following defs make sure words that contain an explicit `-` (hyphen) are still hyphenated the normal way, and double- and triple hyphens keep working the way they should. Just don't use a `-` as the last token of your document. Also note that `-` is now a macro that is not fully expandable
\ExplSyntaxOn
% latex2e doesn't like commands starting with 'end', apparently expl3 doesn't have any problems with it
\cs_new:Npn \hyphenfix_emdash:c {---}
\cs_new:Npn \hyphenfix_endash:c {--}
\cs_new:Npn \hyphenfix_discardnext:NN #1#2{#1}
\catcode`\-=\active
\cs_new_protected:Npn -{
\futurelet\hyphenfix_nexttok\hyphenfix_i:w
}
\cs_new:Npn \hyphenfix_i:w {
\cs_if_eq:NNTF{\hyphenfix_nexttok}{-}{
%discard the next `-` token
\hyphenfix_discardnext:NN{\futurelet\hyphenfix_nexttok\hyphenfix_ii:w}
}{
% from package hyphenat
\hyp
}
}
\cs_new:Npn \hyphenfix_ii:w {
\cs_if_eq:NNTF{\hyphenfix_nexttok}{-}{
\hyphenfix_discardnext:NN{\hyphenfix_emdash:c}
}{
\hyphenfix_endash:c
}
}
\ExplSyntaxOff
Note that this uses the expl3 package from latex3.
It makes the -
an active character that scans forward to see if it is followed by more dashes. If so, it stays a -
, to make sure --
and ---
keep working. If not, it becomes the \hyp
command from hyphenat, enabling word breaks in the rest of the word. This is a generic solution that makes all words that contain explicit hyphens hyphenate normally.
Note that -
becomes a macro that is not fully expandable, so try to include this after loading other packages that may not expect -
to be a macro
Edit: This is my second version, the first version was less robust when a {
or }
followed a hyphen. This one is not, but unlike the first version the -
in this version is not fully expandable.
Power has more precedence than multiply, so:
2**2*3 = (2^2)*3
2*2*3 = 2*2*3
You could add another empty layout below that one and set them both to have the same layout weight. They should get 50% of the space each.
See http://api.jquery.com/jQuery.ajax/, there's mention of datatype and contentType there.
They are both used in the request to the server so the server knows what kind of data to receive/send.
Take a look at my answer here.
Answer to comment:
The FFT actually calculates the cross-correlation of the input signal with sine and cosine functions (basis functions) at a range of equally spaced frequencies. For a given FFT output, there is a corresponding frequency (F) as given by the answer I posted. The real part of the output sample is the cross-correlation of the input signal with cos(2*pi*F*t)
and the imaginary part is the cross-correlation of the input signal with sin(2*pi*F*t)
. The reason the input signal is correlated with sin
and cos
functions is to account for phase differences between the input signal and basis functions.
By taking the magnitude of the complex FFT output, you get a measure of how well the input signal correlates with sinusoids at a set of frequencies regardless of the input signal phase. If you are just analyzing frequency content of a signal, you will almost always take the magnitude or magnitude squared of the complex output of the FFT.
<?php
echo '<script type="text/javascript">document.write(\'Hello world\');</script>';
?>
Sometimes you can retreive the phonenumber with a USSD request to your operator. For example I can get my phonenumber by dialing *116# This can probably be done within an app, I guess, if the USSD responce somehow could be catched. Offcourse this is not a method I would recommend to use within an app that is to be distributed, the code may even differ between operators.
The error is explicit ...
Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion' has value '1.8', but '1.7' is required.
Error: could not find java.dll
Error: Could not find Java SE Runtime Environment.
... you are attempting to use the java.exe
1.7 executable while the HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment
> CurrentVersion
registry key has the value 1.8.
The recurring theme to proposed solutions is that the error is a configuration error. The error can be solved in various different manners (e.g. reconfiguration of the users environment or removal of java executables with fingers-crossed and hope that there exists another fallback java.exe
in the users %PATH%
and that the fallback java.exe
is the correct executable).
The correct solution depends on what you're trying to achieve: "are you trying to downgrade from jdk-8 to jdk-7? Are trying to upgrade to jdk-8? ..."
notes:
- the
java.exe
executable available in the users%PATH%
is installed inC:\Windows\System32
- the installation does not update the users
%PATH%
- the
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
>CurrentVersion
string registry entry is created (among others) with the value1.7
notes:
- the users
%PATH%
is updated to includeC:\Program Files (x86)\Common Files\Oracle\Java\javapath
as the first entry- the the
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
>CurrentVersion
string registry entries value is updated to1.8
update the users %PATH%
environment variable, remove C:\Program Files (x86)\Common Files\Oracle\Java\javapath
in a new command prompt java -version
Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion' has value '1.8', but '1.7' is required.
Error: could not find java.dll
Error: Could not find Java SE Runtime Environment.
OP's solution https://stackoverflow.com/a/29769311/1423507 is a "fingers-crossed and hope that there exists a fallback java.exe
in the users %PATH%
and that the fallback executable is correct" approach to the error. Given the reproduction steps, removing the java.exe
, javaw.exe
and javaws.exe
executables from C:\Windows\System32
(only in my case) will result in no longer having any java.exe
present in the users %PATH%
resulting in the error 'java' is not recognized as an internal or external command, operable program or batch file.
which is not so much of a solution.
answers https://stackoverflow.com/a/35775493/1423507 and https://stackoverflow.com/a/36516620/1423507 work however you're reverting to using java.exe
1.7 (e.g. update the CurrentVersion
registry key's value to match the java.exe
version found in the users %PATH%
).
make surejava.exe
1.8 is the first found in the users %PATH%
(how you do that is irrelevant) i.e.:
%PATH%
to include C:\Program Files (x86)\Common Files\Oracle\Java\javapath
first (ensure that the executables in that directory are correct)%PATH%
to include the absolute path of your java binaries first (set PATH="C:\Program Files\Java\jre1.8.0_191\bin;%PATH%"
)%PATH%
with them (set JAVA_HOME="C:\Program Files\Java"
; set JRE_HOME=%JAVA_HOME%\jre1.8.0_191
; set PATH=%JRE_HOME%\bin;%PATH%
)I know this thread is old now, but here is some decent documentation on Google Docs API. It was ridiculously hard to find, but useful, so maybe it will help you some. http://pythonhosted.org/gdata/docs/api.html.
I used gspread recently for a project to graph employee time data. I don't know how much it might help you, but here's a link to the code: https://github.com/lightcastle/employee-timecards
Gspread made things pretty easy for me. I was also able to add logic in to check for various conditions to create month-to-date and year-to-date results. But I just imported the whole dang spreadsheet and parsed it from there, so I'm not 100% sure that it is exactly what you're looking for. Best of luck.
This will convert to a numeric value without the need to cast or specify length or digits:
STRING_COL+0.0
If your column is an INT
, can leave off the .0
to avoid decimals:
STRING_COL+0
Try > workdirectory/filename.txt
This would:
You can consider it equivalent to:
rm -f workdirectory/filename.txt; touch workdirectory/filename.txt
You can use the onclick
attribute, just return false
if you don't want continue;
<script type="text/javascript">
function confirm_alert(node) {
return confirm("Please click on OK to continue.");
}
</script>
<a href="http://www.google.com" onclick="return confirm_alert(this);">Click Me</a>
This also works.
Javascript:
var app = angular.module('angularApp', []);
app.controller('MainCtrl', function($scope, name, id) {
$scope.id = id;
$scope.name = name;
// and more init
});
Html:
<!DOCTYPE html>
<html ng-app="angularApp">
<head lang="en">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<script src="app.js"></script>
<script>
app.value("name", "James").value("id", "007");
</script>
</head>
<body ng-controller="MainCtrl">
<h1>I am {{name}} {{id}}</h1>
</body>
</html>
Use a static AutoResetEvent in your spawned threads to call back to the main thread using the Set() method. This guy has a fairly good demo in SO on how to use it.
Note that "number of cores" might not be a particularly useful number, you might have to qualify it a bit more. How do you want to count multi-threaded CPUs such as Intel HT, IBM Power5 and Power6, and most famously, Sun's Niagara/UltraSparc T1 and T2? Or even more interesting, the MIPS 1004k with its two levels of hardware threading (supervisor AND user-level)... Not to mention what happens when you move into hypervisor-supported systems where the hardware might have tens of CPUs but your particular OS only sees a few.
The best you can hope for is to tell the number of logical processing units that you have in your local OS partition. Forget about seeing the true machine unless you are a hypervisor. The only exception to this rule today is in x86 land, but the end of non-virtual machines is coming fast...
SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = (Int32) comm .ExecuteScalar();
If you would like to use linq, so you can try following:
Dictionary<string, object> dict = new Dictionary<string, object>();
var arr = dict.Select(z => z.Value).ToArray();
I don't know which one is faster or better. Both work for me.
You can define a DB class as below. Also, as andrewf suggested, use a context manager for cursor access.I'd define it as a member function. This way it keeps the connection open across multiple transactions from the app code and saves unnecessary reconnections to the server.
import pyodbc
class MS_DB():
""" Collection of helper methods to query the MS SQL Server database.
"""
def __init__(self, username, password, host, port=1433, initial_db='dev_db'):
self.username = username
self._password = password
self.host = host
self.port = str(port)
self.db = initial_db
conn_str = 'DRIVER=DRIVER=ODBC Driver 13 for SQL Server;SERVER='+ \
self.host + ';PORT='+ self.port +';DATABASE='+ \
self.db +';UID='+ self.username +';PWD='+ \
self._password +';'
print('Connected to DB:', conn_str)
self._connection = pyodbc.connect(conn_str)
pyodbc.pooling = False
def __repr__(self):
return f"MS-SQLServer('{self.username}', <password hidden>, '{self.host}', '{self.port}', '{self.db}')"
def __str__(self):
return f"MS-SQLServer Module for STP on {self.host}"
def __del__(self):
self._connection.close()
print("Connection closed.")
@contextmanager
def cursor(self, commit: bool = False):
"""
A context manager style of using a DB cursor for database operations.
This function should be used for any database queries or operations that
need to be done.
:param commit:
A boolean value that says whether to commit any database changes to the database. Defaults to False.
:type commit: bool
"""
cursor = self._connection.cursor()
try:
yield cursor
except pyodbc.DatabaseError as err:
print("DatabaseError {} ".format(err))
cursor.rollback()
raise err
else:
if commit:
cursor.commit()
finally:
cursor.close()
ms_db = MS_DB(username='my_user', password='my_secret', host='hostname')
with ms_db.cursor() as cursor:
cursor.execute("SELECT @@version;")
print(cur.fetchall())
Note : Use it if calculating / adding days from current date.
Be aware: this answer has issues (see comments)
var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);
It should be like
var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));
Follow the below steps:
Select body > form-data and do same as shown in the image.
Now in your Django view.py
def post(self, request, *args, **kwargs): image = request.FILES["image"] data = json.loads(request.data['data']) ... return Response(...)
if myfile.closed == False:
print("File is still open ################")
This may be a new attribute for ngView, but I've been able to get it anchor hash links to work with angular-route
using the ngView autoscroll
attribute and 'double-hashes'.
(The following code was used with angular-strap)
<!-- use the autoscroll attribute to scroll to hash on $viewContentLoaded -->
<div ng-view="" autoscroll></div>
<!-- A.href link for bs-scrollspy from angular-strap -->
<!-- A.ngHref for autoscroll on current route without a location change -->
<ul class="nav bs-sidenav">
<li data-target="#main-html5"><a href="#main-html5" ng-href="##main-html5">HTML5</a></li>
<li data-target="#main-angular"><a href="#main-angular" ng-href="##main-angular" >Angular</a></li>
<li data-target="#main-karma"><a href="#main-karma" ng-href="##main-karma">Karma</a></li>
</ul>
If you need an algorithm, try this: Convert the color from RGB space to HSV space (Hue, Saturation, Value). If your UI framework can't do it, check this article: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
Hue is in [0,360). To find the "opposite" color (think colorwheel), just add 180 degrees:
h = (h + 180) % 360;
For saturation and value, invert them:
l = 1.0 - l;
v = 1.0 - v;
Convert back to RGB. This should always give you a high contrast even though most combinations will look ugly.
If you want to avoid the "ugly" part, build a table with several "good" combinations, find the one with the least difference
def q(x):
return x*x
def diff(col1, col2):
return math.sqrt(q(col1.r-col2.r) + q(col1.g-col2.g) + q(col1.b-col2.b))
and use that.
There is boolean data type in SQL Server. Its values can be TRUE
, FALSE
or UNKNOWN
. However, the boolean data type is only the result of a boolean expression containing some combination of comparison operators (e.g. =
, <>
, <
, >=
) or logical operators (e.g. AND
, OR
, IN
, EXISTS
). Boolean expressions are only allowed in a handful of places including the WHERE
clause, HAVING
clause, the WHEN
clause of a CASE
expression or the predicate of an IF
or WHILE
flow control statement.
For all other usages, including the data type of a column in a table, boolean is not allowed. For those other usages, the BIT
data type is preferred. It behaves like a narrowed-down INTEGER
which allows only the values 0
, 1
and NULL
, unless further restricted with a NOT NULL
column constraint or a CHECK
constraint.
To use a BIT
column in a boolean expression it needs to be compared using a comparison operator such as =
, <>
or IS NULL
. e.g.
SELECT
a.answer_body
FROM answers AS a
WHERE a.is_accepted = 0;
From a formatting perspective, a bit
value is typically displayed as 0
or 1
in client software. When a more user-friendly format is required, and it can't be handled at an application tier in front of the database, it can be converted "just-in-time" using a CASE
expression e.g.
SELECT
a.answer_body,
CASE a.is_accepted WHEN 1 THEN 'TRUE' ELSE 'FALSE' END AS is_accepted
FROM answers AS a;
Storing boolean values as a character data type like char(1)
or varchar(5)
is also possible, but that is much less clear, has more storage/network overhead, and requires CHECK
constraints on each column to restrict illegal values.
For reference, the schema of answers
table would be similar to:
CREATE TABLE answers (
...,
answer_body nvarchar(MAX) NOT NULL,
is_accepted bit NOT NULL DEFAULT (0)
);
On a Mac, you can use terminal to go to /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home
(or wherever your Android SDK is installed) and enter the following in the command prompt:
./java -version
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if (range.length==0) {
if ([text isEqualToString:@"\n"]) {
[txtView resignFirstResponder];
if(textView.returnKeyType== UIReturnKeyGo){
[self PreviewLatter];
return NO;
}
return NO;
}
} return YES;
}
The solution is much too big. Try this simple one. Please provide a 7+ character buffer, no check made.
char *i2str(int i, char *buf){
byte l=0;
if(i<0) buf[l++]='-';
boolean leadingZ=true;
for(int div=10000, mod=0; div>0; div/=10){
mod=i%div;
i/=div;
if(!leadingZ || i!=0){
leadingZ=false;
buf[l++]=i+'0';
}
i=mod;
}
buf[l]=0;
return buf;
}
Can be easily modified to give back end of buffer, if you discard index 'l' and increment the buffer directly.
You can do this easily. Go to menu File -> New -> Import Module...:
Browse for the directory which contains the module. Click Finish:
Go to Project Structure and add Module Dependency:
Note: If you receive an SDK error, update that one.
Just drop the option v
.
-v
is for verbose. If you don't use it then it won't display:
tar -zxf tmp.tar.gz -C ~/tmp1
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
application.statusBarHidden = YES;
return YES;
}
I had this issue as well and jaywhy13 answer was good but not enough.
I had to change a setting: Settings -> Gradle -> MyProject
There you need to check the "auto import" and select "use customizable gradle wrapper". After that it should refresh gradle and you can build again. If not try a reboot of Android Studio.
This was already a month ago, but oh well.
I could be wrong, but for your question I get the feeling that bind_param
isn't really the problem here. You always need to define some conditions, be it directly in the query string itself, of using bind_param
to set the ?
placeholders. That's not really an issue.
The problem I had using MySQLi SELECT *
queries is the bind_result
part. That's where it gets interesting. I came across this post from Jeffrey Way: http://jeff-way.com/2009/05/27/tricky-prepared-statements/(This link is no longer active). The script basically loops through the results and returns them as an array — no need to know how many columns there are, and you can still use prepared statements.
In this case it would look something like this:
$stmt = $mysqli->prepare(
'SELECT * FROM tablename WHERE field1 = ? AND field2 = ?');
$stmt->bind_param('ss', $value, $value2);
$stmt->execute();
Then use the snippet from the site:
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ($stmt->fetch()) {
foreach($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
And $results
now contains all the info from SELECT *
. So far I found this to be an ideal solution.
This is something i came up with based on Justin answer. It might require some optimization.
n=int(input())
a=[]
b=[]
def sieve(n):
np = n + 1
s = list(range(np))
s[1] = 0
sqrtn = int(n**0.5)
for i in range(2, sqrtn + 1):
if s[i]:
s[i*i: np: i] = [0] * len(range(i*i, np, i))
return filter(None, s)
k=list(sieve(n))
for i in range(len(k)):
if n%k[i]==0:
a.append(k[i])
a.sort()
for i in range(len(a)):
j=1
while n%(a[i]**j)==0:
j=j+1
b.append(j-1)
nod=1
for i in range(len(b)):
nod=nod*(b[i]+1)
print('no.of divisors of {} = {}'.format(n,nod))
don't use recursive approach (heap issues) :) use a queue
queue.add(param_dir)
while (queue is not empty){
directory= queue.pop
- get items from current directory
- if item is file add to a list (final list)
- if item is directory => queue.push
}
that was easy, enjoy!
In some special cases you may find this useful (e.g. rendering cell-content in MS Report )
example:
select * from
(
values
('use STAGING'),
('go'),
('EXEC sp_MSforeachtable
@command1=''select ''''?'''' as tablename,count(1) as anzahl from ? having count(1) = 0''')
) as t([Copy_and_execute_this_statement])
go
f.write(plaintext)
f.write("\n".encode("utf-8"))
Unique pointers are guaranteed to destroy the object they manage when they go out of scope. http://en.cppreference.com/w/cpp/memory/unique_ptr
In this case:
unique_ptr<double> uptr2 (pd);
pd
will be destroyed when uptr2
goes out of scope. This facilitates memory management by automatic deletion.
The case of unique_ptr<int> uptr (new int(3));
is not different, except that the raw pointer is not assigned to any variable here.
Does this do what you want?
print range(0, (m+1)*n, n)[1:]
For m=5, n=20
[20, 40, 60, 80, 100]
Or better yet,
>>> print range(n, (m+1)*n, n)
[20, 40, 60, 80, 100]
For Python3+
>>> print(list(range(n, (m+1)*n, n)))
[20, 40, 60, 80, 100]
Probably you've found how to do it, but you can call
ListView.setItemsCanFocus(true)
and now your buttons will catch focus
The following should do it:
$("input[type='checkbox']").click(function() {
var index = $(this).attr('name').substr(2);
$('table tr').each(function() {
$('td:eq(' + index + ')',this).toggle();
});
});
This is untested code, but the principle is that you choose the table cell in each row that corresponds to the chosen index extracted from the checkbox name. You could of course limit the selectors with a class or an ID.
In my case, along with Mekanik's suggestions, I was receiving this error in Windows Server 2012 and I had to tick "HTTP Activation" in "Add Role Services".
For 3d graphics applications the lwjgl.util vector implementation out-performed above mentioned jblas by a factor of about 3.
I have done 1 million matrix multiplications of a vec4 with a 4x4 matrix.
lwjgl finished in about 18ms, jblas required about 60ms.
(I assume, that the JNI approach is not very suitable for fast successive application of relatively small multiplications. Since the translation/mapping may take more time than the actual execution of the multiplication.)
You have to use HTML in your webView in this case. I solved this using following code
webView.loadDataWithBaseURL(null,
"<!DOCTYPE html><html><body style = \"text-align:center\"><img src= "
+ \"http://www.koenvangorp.be/photos/2005_09_16-moon_2000.jpg\"
+ " alt=\"pageNo\" width=\"100%\"></body></html>",
"text/html", "UTF-8", null);
So I have been lurking on stack for so many years. This is actually my first time posting on here.
Anyhow, this might seem insane but I came across this post while struggling with the same issue and came up with a dirty solution. I know there are more elegant ways to perhaps set this as a property value but:
if you look at lines 12880-12883 in tcpdf.php :
$fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][`110`])) / 2) * $this->k);
$fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
$popt['ap']['n'][$onvalue] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(`110`).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
$popt['ap']['n']['Off'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(`111`).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
and lines 13135-13138 :
$fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][`108`])) / 2) * $this->k);
$fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
$popt['ap']['n']['Yes'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(`108`).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
$popt['ap']['n']['Off'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(`109`).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
Those widgets are rendered from the zapfdingbats font set... just swap the character codes and voila... checks are radios and/or vice versa. This also opens up ideas to make a custom font set to use here and add some nice styling to your form elements.
Anyhow, just figured I would offer my two cents ... it worked awesome for me.
Yes, bool
. It's not exactly the same -- '0'
is True
, but None
, False
, []
, 0
, 0.0
, and ""
are all False
.
bool
is used implicitly when you evaluate an object in a condition like an if
or while
statement, conditional expression, or with a boolean operator.
If you wanted to handle strings containing numbers as PHP does, you could do something like:
def empty(value):
try:
value = float(value)
except ValueError:
pass
return bool(value)
In Laravel 5, there is a .env
file,
It looks like
APP_ENV=local
APP_DEBUG=true
APP_KEY=YOUR_API_KEY
DB_HOST=YOUR_HOST
DB_DATABASE=YOUR_DATABASE
DB_USERNAME=YOUR_USERNAME
DB_PASSWORD=YOUR_PASSWORD
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
Edit that .env There is .env.sample is there , try to create from that if no such .env file found.
EDIT: Use stej's answer below. My own (partially incorrect) one is still reproduced here for reference:
You can use
Get-Variable foo -Scope Global
and trap the error that is raised when the variable doesn't exist.
The example code below demonstrates this in detail.
<%@page import="java.sql.*, java.io.*,listresult"%> //import the required library
<%
String label = request.getParameter("label"); // retrieving a variable from a previous page
Connection dbc = null; //Make connection to the database
Class.forName("com.mysql.jdbc.Driver");
dbc = DriverManager.getConnection("jdbc:mysql://localhost:3306/works", "root", "root");
if (dbc != null)
{
System.out.println("Connection successful");
}
ResultSet rs = listresult.dbresult.func(dbc, label); //This function is in the end. The function is defined in another package- listresult
%>
<form name="demo form" method="post">
<table>
<tr>
<td>
Label Name:
</td>
<td>
<input type="text" name="label" value="<%=rs.getString("labelname")%>">
</td>
<td>
<select name="label">
<option value="">SELECT</option>
<% while (rs.next()) {%>
<option value="<%=rs.getString("lname")%>"><%=rs.getString("lname")%>
</option>
<%}%>
</select>
</td>
</tr>
</table>
</form>
//The function:
public static ResultSet func(Connection dbc, String x)
{
ResultSet rs = null;
String sql;
PreparedStatement pst;
try
{
sql = "select lname from demo where label like '" + x + "'";
pst = dbc.prepareStatement(sql);
rs = pst.executeQuery();
}
catch (Exception e)
{
e.printStackTrace();
String sqlMessage = e.getMessage();
}
return rs;
}
I have tried to make this example as detailed as possible. Do ask if you have any queries.
I would suggest you to test it firstly:
copy this train.csv
to the same directory as this jupyter script in and then change the path to train.csv
to test whether this can be loaded successfully.
If yes, that means the previous path input is a problem
If not, that means the file it self denied your access to it, or its real filename can be something else like: train.csv.<hidden extension>
Use Guava to normalize all your commas. Split the string up around the commas, throw out the empties, and connect it all back together. Two calls. No loops. Works the first time:
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
public class TestClass {
Splitter splitter = Splitter.on(',').omitEmptyStrings().trimResults();
Joiner joiner = Joiner.on(',').skipNulls();
public String cleanUpCommas(String string) {
return joiner.join(splitter.split(string));
}
}
public class TestMain {
public static void main(String[] args) {
TestClass testClass = new TestClass();
System.out.println(testClass.cleanUpCommas("a,b,c,d,e"));
System.out.println(testClass.cleanUpCommas("a,b,c,d,e,,,,,"));
System.out.println(testClass.cleanUpCommas("a,b,,, ,c,d, ,,e,,,,,"));
System.out.println(testClass.cleanUpCommas("a,b,c,d, e,,,,,"));
System.out.println(testClass.cleanUpCommas(",,, ,,,,a,b,c,d, e,,,,,"));
}
}
Output:
a,b,c,d,e
a,b,c,d,e
a,b,c,d,e
a,b,c,d,e
a,b,c,d,e
Personally, I hate futzing around with counting limits of substrings and all that nonsense.
A simple way is as follows:
def count_letters(word, char):
return word.count(char)
Or, there's another way count each element directly:
from collections import Counter
Counter('banana')
Of course, you can specify one element, e.g.
Counter('banana')['a']
Server Error in '/' Application.
The system cannot find the file specified
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ComponentModel.Win32Exception: The system cannot find the file specified
Source Error:
{ SqlCommand cmd = new SqlCommand("select * from tblemployee",con); con.Open(); GridView1.DataSource = cmd.ExecuteReader(); GridView1.DataBind();
Source File: d:\C# programs\kudvenkat\adobasics1\adobasics1\employeedata.aspx.cs Line: 23
if your error is same like mine..just do this
right click on your table in sqlserver object explorer,choose properties in lower left corner in general option there is a connection block with server and connection specification.in your web config for datasource=. or local choose name specified in server in properties..
In my case, the tomcat directory was owned by root, and I was not running eclipse as root.
So I had to
sudo chown -R $USER apache-tomcat-VERSION/
Open your settings.xml file ~/.m2/settings.xml
(create it if it doesn't exist). Add a section with the properties added. Then make sure the activeProfiles includes the new profile.
<settings>
<!-- ... other settings here ... -->
<profiles>
<profile>
<id>downloadSources</id>
<properties>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</properties>
</profile>
</profiles>
<activeProfiles>
<activeProfile>downloadSources</activeProfile>
</activeProfiles>
</settings>
public String getLocalIpAddress() {
try {
for (Enumeration < NetworkInterface > en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration < InetAddress > enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
There are four ways to build an iterative function:
__iter__
and __next__
(or next
in Python 2.x))__getitem__
)Examples:
# generator
def uc_gen(text):
for char in text.upper():
yield char
# generator expression
def uc_genexp(text):
return (char for char in text.upper())
# iterator protocol
class uc_iter():
def __init__(self, text):
self.text = text.upper()
self.index = 0
def __iter__(self):
return self
def __next__(self):
try:
result = self.text[self.index]
except IndexError:
raise StopIteration
self.index += 1
return result
# getitem method
class uc_getitem():
def __init__(self, text):
self.text = text.upper()
def __getitem__(self, index):
return self.text[index]
To see all four methods in action:
for iterator in uc_gen, uc_genexp, uc_iter, uc_getitem:
for ch in iterator('abcde'):
print(ch, end=' ')
print()
Which results in:
A B C D E
A B C D E
A B C D E
A B C D E
Note:
The two generator types (uc_gen
and uc_genexp
) cannot be reversed()
; the plain iterator (uc_iter
) would need the __reversed__
magic method (which, according to the docs, must return a new iterator, but returning self
works (at least in CPython)); and the getitem iteratable (uc_getitem
) must have the __len__
magic method:
# for uc_iter we add __reversed__ and update __next__
def __reversed__(self):
self.index = -1
return self
def __next__(self):
try:
result = self.text[self.index]
except IndexError:
raise StopIteration
self.index += -1 if self.index < 0 else +1
return result
# for uc_getitem
def __len__(self)
return len(self.text)
To answer Colonel Panic's secondary question about an infinite lazily evaluated iterator, here are those examples, using each of the four methods above:
# generator
def even_gen():
result = 0
while True:
yield result
result += 2
# generator expression
def even_genexp():
return (num for num in even_gen()) # or even_iter or even_getitem
# not much value under these circumstances
# iterator protocol
class even_iter():
def __init__(self):
self.value = 0
def __iter__(self):
return self
def __next__(self):
next_value = self.value
self.value += 2
return next_value
# getitem method
class even_getitem():
def __getitem__(self, index):
return index * 2
import random
for iterator in even_gen, even_genexp, even_iter, even_getitem:
limit = random.randint(15, 30)
count = 0
for even in iterator():
print even,
count += 1
if count >= limit:
break
print
Which results in (at least for my sample run):
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32
How to choose which one to use? This is mostly a matter of taste. The two methods I see most often are generators and the iterator protocol, as well as a hybrid (__iter__
returning a generator).
Generator expressions are useful for replacing list comprehensions (they are lazy and so can save on resources).
If one needs compatibility with earlier Python 2.x versions use __getitem__
.
This isn't easy, unless your regexp engine has special support for it. The easiest way would be to use a negative-match option, for example:
$var !~ /^foo$/
or die "too much foo";
If not, you have to do something evil:
$var =~ /^(($)|([^f].*)|(f[^o].*)|(fo[^o].*)|(foo.+))$/
or die "too much foo";
That one basically says "if it starts with non-f
, the rest can be anything; if it starts with f
, non-o
, the rest can be anything; otherwise, if it starts fo
, the next character had better not be another o
".
Since nobody has added the obvious solution yet which works fine for two comparisons, I'll offer it:
if (foobar === foo || foobar === bar) {
//do something
}
And, if you have lots of values (perhaps hundreds or thousands), then I'd suggest making a Set as this makes very clean and simple comparison code and it's fast at runtime:
// pre-construct the Set
var tSet = new Set(["foo", "bar", "test1", "test2", "test3", ...]);
// test the Set at runtime
if (tSet.has(foobar)) {
// do something
}
For pre-ES6, you can get a Set polyfill of which there are many. One is described in this other answer.
Check your enviroment:
echo $http_proxy
echo $https_proxy
echo $HTTPS_PROXY
echo $HTTP_PROXY
and delete with export http_proxy=
Or check https and http proxy
git config --global --unset https.proxy
git config --global --unset http.proxy
Or do you have the proxy in the local config?
git config --unset http.proxy
git config --unset https.proxy
In PHP, Encryption and Decryption of a string is possible using one of the Cryptography Extensions called OpenSSL function for encrypt and decrypt.
openssl_encrypt() Function: The openssl_encrypt() function is used to encrypt the data.
Syntax is as follows :
string openssl_encrypt( string $data, string $method, string $key, $options = 0, string $iv, string $tag= NULL, string $aad, int $tag_length = 16 )
Parameters are as follows :
$data: It holds the string or data which need to be encrypted.
$method: The cipher method is adopted using openssl_get_cipher_methods() function.
$key: It holds the encryption key.
$options: It holds the bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING.
$iv: It holds the initialization vector which is not NULL.
$tag: It holds the authentication tag which is passed by reference when using AEAD cipher mode (GCM or CCM).
$aad: It holds the additional authentication data.
$tag_length: It holds the length of the authentication tag. The length of authentication tag lies between 4 to 16 for GCM mode.
Return Value: It returns the encrypted string on success or FALSE on failure.
openssl_decrypt() Function The openssl_decrypt() function is used to decrypt the data.
Syntax is as follows :
string openssl_decrypt( string $data, string $method, string $key, int $options = 0, string $iv, string $tag, string $aad)
Parameters are as follows :
$data: It holds the string or data which need to be encrypted.
$method: The cipher method is adopted using openssl_get_cipher_methods() function.
$key: It holds the encryption key.
$options: It holds the bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING.
$iv: It holds the initialization vector which is not NULL.
$tag: It holds the authentication tag using AEAD cipher mode (GCM or CCM). When authentication fails openssl_decrypt() returns FALSE.
$aad: It holds the additional authentication data.
Return Value: It returns the decrypted string on success or FALSE on failure.
Approach: First declare a string and store it into variable and use openssl_encrypt() function to encrypt the given string and use openssl_decrypt() function to descrypt the given string.
You can find the examples at : https://www.geeksforgeeks.org/how-to-encrypt-and-decrypt-a-php-string/
Using parameter binding is definitely the way to go here. Not only is it very quick to write (just add [Parameter(Mandatory=$true)]
above your mandatory parameters), but it's also the only option that you won't hate yourself for later.
More below:
[Console]::ReadLine
is explicitly forbidden by the FxCop rules for PowerShell. Why? Because it only works in PowerShell.exe, not PowerShell ISE, PowerGUI, etc.
Read-Host is, quite simply, bad form. Read-Host uncontrollably stops the script to prompt the user, which means that you can never have another script that includes the script that uses Read-Host.
You're trying to ask for parameters.
You should use the [Parameter(Mandatory=$true)]
attribute, and correct typing, to ask for the parameters.
If you use this on a [SecureString]
, it will prompt for a password field. If you use this on a Credential type, ([Management.Automation.PSCredential]
), the credentials dialog will pop up, if the parameter isn't there. A string will just become a plain old text box. If you add a HelpMessage to the parameter attribute (that is, [Parameter(Mandatory = $true, HelpMessage = 'New User Credentials')]
) then it will become help text for the prompt.
Try this code. This does what you want.
LOGIC
""
with blanks and write to the new file at the same time.CODE (TRIED AND TESTED)
Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" _
(ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long
Private Const MAX_PATH As Long = 260
'~~> Change this where and how you want to save the file
Const FlName = "C:\Users\Siddharth Rout\Desktop\MyWorkbook.txt"
Sub Sample()
Dim tmpFile As String
Dim MyData As String, strData() As String
Dim entireline As String
Dim filesize As Integer
'~~> Create a Temp File
tmpFile = TempPath & Format(Now, "ddmmyyyyhhmmss") & ".txt"
ActiveWorkbook.SaveAs Filename:=tmpFile _
, FileFormat:=xlText, CreateBackup:=False
'~~> Read the entire file in 1 Go!
Open tmpFile For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
strData() = Split(MyData, vbCrLf)
'~~> Get a free file handle
filesize = FreeFile()
'~~> Open your file
Open FlName For Output As #filesize
For i = LBound(strData) To UBound(strData)
entireline = Replace(strData(i), """", "")
'~~> Export Text
Print #filesize, entireline
Next i
Close #filesize
MsgBox "Done"
End Sub
Function TempPath() As String
TempPath = String$(MAX_PATH, Chr$(0))
GetTempPath MAX_PATH, TempPath
TempPath = Replace(TempPath, Chr$(0), "")
End Function
SNAPSHOTS
Actual Workbook
After Saving
Use ThisWorkbook
which will refer to the original workbook which holds the code.
Alternatively at code start
Dim Wb As Workbook
Set Wb = ActiveWorkbook
sample code that activates all open books before returning to ThisWorkbook
Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
Wb2.Activate
Next
Wb.Activate
End Sub
Posting this since React.createClass
is deprecated from react version 16 and the new Javascript ES6 will give you more benefits.
Parent
import React, {Component} from 'react';
import Child from './Child';
export default class Parent extends Component {
es6Function = (value) => {
console.log(value)
}
simplifiedFunction (value) {
console.log(value)
}
render () {
return (
<div>
<Child
es6Function = {this.es6Function}
simplifiedFunction = {this.simplifiedFunction}
/>
</div>
)
}
}
Child
import React, {Component} from 'react';
export default class Child extends Component {
render () {
return (
<div>
<h1 onClick= { () =>
this.props.simplifiedFunction(<SomethingThatYouWantToPassIn>)
}
> Something</h1>
</div>
)
}
}
Simplified stateless child as ES6 constant
import React from 'react';
const Child = () => {
return (
<div>
<h1 onClick= { () =>
this.props.es6Function(<SomethingThatYouWantToPassIn>)
}
> Something</h1>
</div>
)
}
export default Child;
?(.*\n)+
With this you can get everything Even a new line
Well, there's always the low tech solution of adding logging of the size of your maps when you modify them, then search the logs for which maps are growing beyond a reasonable size.
From the Express site, define a NotFound exception and throw it whenever you want to have a 404 page OR redirect to /404 in the below case:
function NotFound(msg){
this.name = 'NotFound';
Error.call(this, msg);
Error.captureStackTrace(this, arguments.callee);
}
NotFound.prototype.__proto__ = Error.prototype;
app.get('/404', function(req, res){
throw new NotFound;
});
app.get('/500', function(req, res){
throw new Error('keyboard cat!');
});
count the carriage returns/line feeds. I believe in unicode they are still 0x000D and 0x000A respectively. that way you can be as efficient or as inefficient as you want, and decide if you have to deal with both characters or not
This seem to work for me in Bootstrap v5 alpha 3
_variables-overrides.scss
$primary: #00adef;
$theme-colors: (
"primary": $primary,
);
main.scss
// Overrides
@import "variables-overrides";
// Required - Configuration
@import "@/node_modules/bootstrap/scss/functions";
@import "@/node_modules/bootstrap/scss/variables";
@import "@/node_modules/bootstrap/scss/mixins";
@import "@/node_modules/bootstrap/scss/utilities";
// Optional - Layout & components
@import "@/node_modules/bootstrap/scss/root";
@import "@/node_modules/bootstrap/scss/reboot";
@import "@/node_modules/bootstrap/scss/type";
@import "@/node_modules/bootstrap/scss/images";
@import "@/node_modules/bootstrap/scss/containers";
@import "@/node_modules/bootstrap/scss/grid";
@import "@/node_modules/bootstrap/scss/tables";
@import "@/node_modules/bootstrap/scss/forms";
@import "@/node_modules/bootstrap/scss/buttons";
@import "@/node_modules/bootstrap/scss/transitions";
@import "@/node_modules/bootstrap/scss/dropdown";
@import "@/node_modules/bootstrap/scss/button-group";
@import "@/node_modules/bootstrap/scss/nav";
@import "@/node_modules/bootstrap/scss/navbar";
@import "@/node_modules/bootstrap/scss/card";
@import "@/node_modules/bootstrap/scss/accordion";
@import "@/node_modules/bootstrap/scss/breadcrumb";
@import "@/node_modules/bootstrap/scss/pagination";
@import "@/node_modules/bootstrap/scss/badge";
@import "@/node_modules/bootstrap/scss/alert";
@import "@/node_modules/bootstrap/scss/progress";
@import "@/node_modules/bootstrap/scss/list-group";
@import "@/node_modules/bootstrap/scss/close";
@import "@/node_modules/bootstrap/scss/toasts";
@import "@/node_modules/bootstrap/scss/modal";
@import "@/node_modules/bootstrap/scss/tooltip";
@import "@/node_modules/bootstrap/scss/popover";
@import "@/node_modules/bootstrap/scss/carousel";
@import "@/node_modules/bootstrap/scss/spinners";
// Helpers
@import "@/node_modules/bootstrap/scss/helpers";
// Utilities
@import "@/node_modules/bootstrap/scss/utilities/api";
@import "custom";
@@ -1,2 +3,4 @@
part of the diff
This part took me a while to understand, so I've created a minimal example.
The format is basically the same the diff -u
unified diff.
For instance:
diff -u <(seq 16) <(seq 16 | grep -Ev '^(2|3|14|15)$')
Here we removed lines 2, 3, 14 and 15. Output:
@@ -1,6 +1,4 @@
1
-2
-3
4
5
6
@@ -11,6 +9,4 @@
11
12
13
-14
-15
16
@@ -1,6 +1,4 @@
means:
-1,6
means that this piece of the first file starts at line 1 and shows a total of 6 lines. Therefore it shows lines 1 to 6.
1
2
3
4
5
6
-
means "old", as we usually invoke it as diff -u old new
.
+1,4
means that this piece of the second file starts at line 1 and shows a total of 4 lines. Therefore it shows lines 1 to 4.
+
means "new".
We only have 4 lines instead of 6 because 2 lines were removed! The new hunk is just:
1
4
5
6
@@ -11,6 +9,4 @@
for the second hunk is analogous:
on the old file, we have 6 lines, starting at line 11 of the old file:
11
12
13
14
15
16
on the new file, we have 4 lines, starting at line 9 of the new file:
11
12
13
16
Note that line 11
is the 9th line of the new file because we have already removed 2 lines on the previous hunk: 2 and 3.
Hunk header
Depending on your git version and configuration, you can also get a code line next to the @@
line, e.g. the func1() {
in:
@@ -4,7 +4,6 @@ func1() {
This can also be obtained with the -p
flag of plain diff
.
Example: old file:
func1() {
1;
2;
3;
4;
5;
6;
7;
8;
9;
}
If we remove line 6
, the diff shows:
@@ -4,7 +4,6 @@ func1() {
3;
4;
5;
- 6;
7;
8;
9;
Note that this is not the correct line for func1
: it skipped lines 1
and 2
.
This awesome feature often tells exactly to which function or class each hunk belongs, which is very useful to interpret the diff.
How the algorithm to choose the header works exactly is discussed at: Where does the excerpt in the git diff hunk header come from?
For single-byte strings (e.g. US-ASCII, ISO 8859 family, etc.) use substr
and for multi-byte strings (e.g. UTF-8, UTF-16, etc.) use mb_substr
:
// singlebyte strings
$result = substr($myStr, 0, 5);
// multibyte strings
$result = mb_substr($myStr, 0, 5);
CSV files could be in any format, depending on what encoding option was specified during the export from Excel: (Save Dialog, Tools Button, Web Options Item, Encoding Tab)
UPDATE: Excel (including Office 2013) doesn't actually respect the web options selected in the "save as..." dialog, so this is a bug of some sort. I just use OpenOffice Calc now to open my XLSX files and export them as CSV files (edit filter settings, choose UTF-8 encoding).
A context manager for python3:
import sys
from io import StringIO
class RedirectedStdout:
def __init__(self):
self._stdout = None
self._string_io = None
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._string_io = StringIO()
return self
def __exit__(self, type, value, traceback):
sys.stdout = self._stdout
def __str__(self):
return self._string_io.getvalue()
use like this:
>>> with RedirectedStdout() as out:
>>> print('asdf')
>>> s = str(out)
>>> print('bsdf')
>>> print(s, out)
'asdf\n' 'asdf\nbsdf\n'
Italian version:
=CONCATENA(
DECIMALE.HEX(CASUALE.TRA(0;4294967295);8);"-";
DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
DECIMALE.HEX(CASUALE.TRA(0;4294967295);8);
DECIMALE.HEX(CASUALE.TRA(0;42949);4))
Here's a good mnemonic. Apply uses Arrays and Always takes one or two Arguments. When you use Call you have to Count the number of arguments.
In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic
about following the C++ standard), you can do:
int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++
If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:
int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!
Or, better yet, use a standard container:
int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>
If you still want a proper array, you can use a constant, not a variable, when creating it:
const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)
Similarly, if you want to get the size from a function in C++11, you can use a constexpr
:
constexpr int n()
{
return 10;
}
double a[n()]; // n() is a compile time constant expression
I assume you want to know the performance difference between the following:
WHERE foo IN ('a', 'b', 'c')
WHERE foo = 'a' OR foo = 'b' OR foo = 'c'
According to the manual for MySQL if the values are constant IN
sorts the list and then uses a binary search. I would imagine that OR
evaluates them one by one in no particular order. So IN
is faster in some circumstances.
The best way to know is to profile both on your database with your specific data to see which is faster.
I tried both on a MySQL with 1000000 rows. When the column is indexed there is no discernable difference in performance - both are nearly instant. When the column is not indexed I got these results:
SELECT COUNT(*) FROM t_inner WHERE val IN (1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000);
1 row fetched in 0.0032 (1.2679 seconds)
SELECT COUNT(*) FROM t_inner WHERE val = 1000 OR val = 2000 OR val = 3000 OR val = 4000 OR val = 5000 OR val = 6000 OR val = 7000 OR val = 8000 OR val = 9000;
1 row fetched in 0.0026 (1.7385 seconds)
So in this case the method using OR is about 30% slower. Adding more terms makes the difference larger. Results may vary on other databases and on other data.
If you are looking for this:
Here is the link:
http://css-tricks.com/overriding-the-default-text-selection-color-with-css/
There are some different way to do that
sass --watch --style=compressed main.scss main.css
or
sass --watch a.scss:a.css --style compressed
or
By Using visual studio code extension live sass compiler
You've got several options:
x
ecute permissions on that directory.x
ecute permissions.
chmod(1)
to change the permissions orsetfacl(1)
command to add an access control list entry for your user account. (This also requires mounting the filesystem with the acl
option; see mount(8)
and fstab(5)
for details on the mount parameter.)It's impossible to suggest the correct approach without knowing more about the problem; why are the directory permissions set the way they are? Why do you need access to that directory?
File file = new File(PropertiesReader.FILE_PATH);
MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
String mimeType = fileTypeMap.getContentType(file);
URLConnection uconnection = file.toURL().openConnection();
mimeType = uconnection.getContentType();
File > Workspace Settings > Build System > Legacy Build System
This worked for me. Xcode 10.0
AS Scott mentioned here http://weblogs.asp.net/scottgu/archive/2010/09/30/asp-net-security-fix-now-on-windows-update.aspx After windows installed security update for .net framework, you will meet this problem. just modify the configuration section in your web.config file and switch to a different cookie name.
Following is a sample of five different ways to summate values. The first is a naive way to perform the summation (and fails). The second attempts to use sprintf()
, but it too fails. The third uses sprintf()
successfully while the final two (4th & 5th) use floor($value + 0.5)
.
use strict;
use warnings;
use POSIX;
my @values = (26.67,62.51,62.51,62.51,68.82,79.39,79.39);
my $total1 = 0.00;
my $total2 = 0;
my $total3 = 0;
my $total4 = 0.00;
my $total5 = 0;
my $value1;
my $value2;
my $value3;
my $value4;
my $value5;
foreach $value1 (@values)
{
$value2 = $value1;
$value3 = $value1;
$value4 = $value1;
$value5 = $value1;
$total1 += $value1;
$total2 += sprintf('%d', $value2 * 100);
$value3 = sprintf('%1.2f', $value3);
$value3 =~ s/\.//;
$total3 += $value3;
$total4 += $value4;
$total5 += floor(($value5 * 100.0) + 0.5);
}
$total1 *= 100;
$total4 = floor(($total4 * 100.0) + 0.5);
print '$total1: '.sprintf('%011d', $total1)."\n";
print '$total2: '.sprintf('%011d', $total2)."\n";
print '$total3: '.sprintf('%011d', $total3)."\n";
print '$total4: '.sprintf('%011d', $total4)."\n";
print '$total5: '.sprintf('%011d', $total5)."\n";
exit(0);
#$total1: 00000044179
#$total2: 00000044179
#$total3: 00000044180
#$total4: 00000044180
#$total5: 00000044180
Note that floor($value + 0.5)
can be replaced with int($value + 0.5)
to remove the dependency on POSIX
.
I believe you should escape the dot. Try:
String filename = "D:/some folder/001.docx";
String extensionRemoved = filename.split("\\.")[0];
Otherwise dot is interpreted as any character in regular expressions.
You're instantiating the Random
object inside your method.
The Random
object is seeded from the system clock, which means that if you call your method several times in quick succession it'll use the same seed each time, which means that it'll generate the same sequence of random numbers, which means that you'll get the same string.
To solve the problem, move your Random
instance outside of the method itself (and while you're at it you could get rid of that crazy sequence of calls to Convert
and Floor
and NextDouble
):
private readonly Random _rng = new Random();
private const string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private string RandomString(int size)
{
char[] buffer = new char[size];
for (int i = 0; i < size; i++)
{
buffer[i] = _chars[_rng.Next(_chars.Length)];
}
return new string(buffer);
}
You want the :checkbox:checked
selector and map
to create an array of the values:
var checkedValues = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked')
, or for a common name $('input[name="Foo"]:checked')
- Update -
If you don't need IE support then you can now make the map()
call more succinct by using an arrow function:
var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();
Since you don't care, I chose the max ID for each number.
select tbl.* from tbl
inner join (
select max(id) as maxID, number from tbl group by number) maxID
on maxID.maxID = tbl.id
Query Explanation
select
tbl.* -- give me all the data from the base table (tbl)
from
tbl
inner join ( -- only return rows in tbl which match this subquery
select
max(id) as maxID -- MAX (ie distinct) ID per GROUP BY below
from
tbl
group by
NUMBER -- how to group rows for the MAX aggregation
) maxID
on maxID.maxID = tbl.id -- join condition ie only return rows in tbl
-- whose ID is also a MAX ID for a given NUMBER
This JavaScript function considers whether to use insert or replace to handle the swap.
(Insert or replace HTML line breaks)
/**
* This function is same as PHP's nl2br() with default parameters.
*
* @param {string} str Input text
* @param {boolean} replaceMode Use replace instead of insert
* @param {boolean} isXhtml Use XHTML
* @return {string} Filtered text
*/
function nl2br (str, replaceMode, isXhtml) {
var breakTag = (isXhtml) ? '<br />' : '<br>';
var replaceStr = (replaceMode) ? '$1'+ breakTag : '$1'+ breakTag +'$2';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, replaceStr);
}
This worked for me.
.alert:not(:first-child){
margin: 30px;
}
I had a momentary 5 minute lapse and I forgot to specify the form in full like this:
myformName.ActiveForm.TopMost = true;
But what I really wanted was THIS!
this.TopMost = true;
You will find complete list of time zone with its GMToffsets
here and you can use "Name of Time Zone" column value to find time zone by ID
e.g
TimeZoneInfo objTimeZoneInfo = TimeZoneInfo.FindTimeZoneById("Dateline Standard Time");
You will get time zone info class that contains dateline standard time time zone which is used for GMT-12:00.
=>
is the separator for associative arrays. In the context of that foreach loop, it assigns the key of the array to $user
and the value to $pass
.
Example:
$user_list = array(
'dave' => 'apassword',
'steve' => 'secr3t'
);
foreach ($user_list as $user => $pass) {
echo "{$user}'s pass is: {$pass}\n";
}
// Prints:
// "dave's pass is: apassword"
// "steve's pass is: secr3t"
Note that this can be used for numerically indexed arrays too.
Example:
$foo = array('car', 'truck', 'van', 'bike', 'rickshaw');
foreach ($foo as $i => $type) {
echo "{$i}: {$type}\n";
}
// prints:
// 0: car
// 1: truck
// 2: van
// 3: bike
// 4: rickshaw
This one is I think more efficient to check prime number :
function prime(num){
if(num == 1) return true;
var t = num / 2;
var k = 2;
while(k <= t) {
if(num % k == 0) {
return false
} else {
k++;
}
}
return true;
}
console.log(prime(37))
I was facing "java.lang.OutOfMemoryError: Java heap space" error while building my project using maven install command.
I was able to get rid of it by changing maven runner settings.
Settings
| Build, Execution, Deployment
| Build Tools
| Maven
| Runner
| VM options
to -Xmx512m
To get this working in Javascript, I had to do the following:
myString.split(/\s+/g)
So you are doing the right thing concerning "-XX:MaxPermSize=512m": it is indeed the correct syntax. You could try to set these options directly to the Catalyna server files so they are used on server start.
Maybe this post will help you!
How to make sure that Tomcat6 reads CATALINA_OPTS on Windows?
For your first question, find the position of some value in a list x using index(), like so:
x.index(value)
For your second question, to check for multiple same values you should split your list into chunks and use the same logic from above. They say divide and conquer. It works. Try this:
value = 1
x = [1,2,3,4,5,6,2,1,4,5,6]
chunk_a = x[:int(len(x)/2)] # get the first half of x
chunk_b = x[int(len(x)/2):] # get the rest half of x
print(chunk_a.index(value))
print(chunk_b.index(value))
Hope that helps!
Here's a very simple way to emulate a do-while loop:
condition = True
while condition:
# loop body here
condition = test_loop_condition()
# end of loop
The key features of a do-while loop are that the loop body always executes at least once, and that the condition is evaluated at the bottom of the loop body. The control structure show here accomplishes both of these with no need for exceptions or break statements. It does introduce one extra Boolean variable.
The answer is "Yes, But..."
But cPython cannot when you are using regular threads for concurrency.
You can either use something like multiprocessing
, celery
or mpi4py
to split the parallel work into another process;
Or you can use something like Jython or IronPython to use an alternative interpreter that doesn't have a GIL.
A softer solution is to use libraries that don't run afoul of the GIL for heavy CPU tasks, for instance numpy
can do the heavy lifting while not retaining the GIL, so other python threads can proceed. You can also use the ctypes
library in this way.
If you are not doing CPU bound work, you can ignore the GIL issue entirely (kind of) since python won't aquire the GIL while it's waiting for IO.
Although the question specifically describes installing 2.6, I would like to add some importants points to the excellent answers above in case someone comes across this. For the record, my case was that I was trying to install 2.7 on an ubuntu 10.04 box.
First, my motivation towards the methods described in all the answers here is that installing Python from deadsnake's ppa's has been a total failure. So building a local Python is the way to go.
Having tried so, I thought relying to the default installation of pip (with sudo apt-get install pip
) would be adequate. This unfortunately is wrong. It turned out that I was getting all shorts of nasty issues and eventually not being able to create a virtualenv.
Therefore, I highly recommend to install pip locally with wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py && python get-pip.py --user
. This related question gave me this hint.
Now if this doesn't work, make sure that libssl-dev
for Ubuntu or openssl-dev
for CentOS is installed. Install them with apt-get
or yum
and then re-build Python (no need to remove anything if already installed, do so on top). get-pip
complains about that, you can check so by running import ssl
on a py shell.
Last, don't forget to declare .local/bin
and local python to path, check with which pip
and which python
.
This should do it:
//Returns the index of the first occurence of char c in char* string. If not found -1 is returned.
int get_index(char* string, char c) {
char *e = strchr(string, c);
if (e == NULL) {
return -1;
}
return (int)(e - string);
}
// In MyClass.h
MyClass<T>& operator+=(const MyClass<T>& classObj);
// In MyClass.cpp
template <class T>
MyClass<T>& MyClass<T>::operator+=(const MyClass<T>& classObj) {
// ...
return *this;
}
This is invalid for templates. The full source code of the operator must be in all translation units that it is used in. This typically means that the code is inline in the header.
Edit: Technically, according to the Standard, it is possible to export templates, however very few compilers support it. In addition, you CAN also do the above if the template is explicitly instantiated in MyClass.cpp for all types that are T- but in reality, that normally defies the point of a template.
More edit: I read through your code, and it needs some work, for example overloading operator[]. In addition, typically, I would make the dimensions part of the template parameters, allowing for the failure of + or += to be caught at compile-time, and allowing the type to be meaningfully stack allocated. Your exception class also needs to derive from std::exception. However, none of those involve compile-time errors, they're just not great code.
In addition to the answer of @Charles-Duffy, you can use winpty directly without installing/downloading anything extra. Just run winpty c:/Python27/python.exe
. The utility winpty.exe can be found at Git\usr\bin. I'm using Git for Windows v2.7.1
The prebuilt binaries from @Charles-Duffy is version 0.1.1(according to the file name), while the included one is 0.2.2
There is also a SURROGATE KEY: it occurs if one non prime attribute depends on another non prime attribute. that time you don't now to choose which key as primary key to split up your table. In that case use a surrogate key instead of a primary key. Usually this key is system defined and always have numeric values and its value often automatically incremented for new rows. Eg : ms acces = auto number & my SQL = identity column & oracle = sequence.
I'm by know means an expert, but I'm incredibly proud of myself for having worked something out about this code. If you do:
div {
display: none;
}
a:hover > div {
display: block;
}
(Note the '>') You can contain the whole thing in an a tag, then, as long as your trigger (which can be in it's own div, or straight up in the a tag, or anything you want) is physically touching the revealed div, you can move your mouse from one to the other.
Maybe this isn't useful for a great deal, but I had to set my revealed div to overflow: auto, so sometimes it had scroll bars, which couldn't be used as soon as you move away from the div.
In fact, after finally working out how to make the revealed div, (although it is now a child of the trigger, not a sibling), sit behind the trigger, in terms of z-index, (with a little help from this page: How to get a parent element to appear above child) you don't even have to roll over the revealed div to scroll it, just stay hovering over the trigger and use your wheel, or whatever.
My revealed div covers most of the page, so this technique makes it a lot more permanent, rather than the screen flashing from one state to another with every move of the mouse. It's really intuitive actually, hence why I'm really quite proud of myself.
The only downside is that you can't put links within the whole thing, but you can use the whole thing as one big link.
If using from .NET 4 this sample can help you:
class Program
{
static void Main(string[] args)
{
Task task1 = Task.Factory.StartNew(() => doStuff());
Task task2 = Task.Factory.StartNew(() => doStuff());
Task task3 = Task.Factory.StartNew(() => doStuff());
Task.WaitAll(task1, task2, task3);
Console.WriteLine("All threads complete");
}
static void doStuff()
{
// Do stuff here
}
}
From: Create multiple threads and wait all of them to complete
You can also use template reference variables
<form (submit)="onSubmit(player.value)">
<input #player placeholder="player name">
</form>
onSubmit(playerName: string) {
console.log(playerName)
}
Something like this should work (can't test it right now - from memory):
UPDATE SHIPMENT
SET
OrgAddress1 = BD.OrgAddress1,
OrgAddress2 = BD.OrgAddress2,
OrgCity = BD.OrgCity,
OrgState = BD.OrgState,
OrgZip = BD.OrgZip,
DestAddress1 = BD.DestAddress1,
DestAddress2 = BD.DestAddress2,
DestCity = BD.DestCity,
DestState = BD.DestState,
DestZip = BD.DestZip
FROM
BookingDetails BD
WHERE
SHIPMENT.MyID2 = @MyID2
AND
BD.MyID = @MyID
Does that help?
You are using Lists, concrete ArrayList. ArrayList also implements Collection interface. Collection interface has sort method which is used to sort the elements present in the specified list of Collection in ascending order. This will be the quickest and possibly the best way for your case.
Sorting a list in ascending order can be performed as default operation on this way:
Collections.sort(list);
Sorting a list in descending order can be performed on this way:
Collections.reverse(list);
According to these facts, your solution has to be written like this:
public class tes
{
public static void main(String args[])
{
List<Integer> lList = new ArrayList<Integer>();
lList.add(4);
lList.add(1);
lList.add(7);
lList.add(2);
lList.add(9);
lList.add(1);
lList.add(5);
Collections.sort(lList);
for(int i=0; i<lList.size();i++ )
{
System.out.println(lList.get(i));
}
}
}
More about Collections you can read here.
As my question was marked as duplicate of this one, I think it's O.K. to post why NOT omitting closing tag ?>
can be for some reasons desired.
<?php ... ?>
) PHP source is valid SGML document, which can be parsed and processed without problems with SGML parser. With additional restrictions it can be valid XML/XHTML as well. Nothing prevents you from writing valid XML/HTML/SGML code. PHP documentation is aware of this. Excerpt:
Note: Also note that if you are embedding PHP within XML or XHTML you will need to use the < ?php ?> tags to remain compliant with standards.
Of course PHP syntax is not strict SGML/XML/HTML and you create a document, which is not SGML/XML/HTML, just like you can turn HTML into XHTML to be XML compliant or not.
At some point you may want to concatenate sources. This will be not as easy as simply doing cat source1.php source2.php
if you have inconsistency introduced by omitting closing ?>
tags.
Without ?>
it's harder to tell if document was left in PHP escape mode or PHP ignore mode (PI tag <?php
may have been opened or not). Life is easier if you consistently leave your documents in PHP ignore mode. It's just like work with well formatted HTML documents compared to documents with unclosed, badly nested tags etc.
It seems that some editors like Dreamweaver may have problems with PI left open [1].
Consider a binary tree whose nodes are drawn in a tree fashion. Now start numbering the nodes from top to bottom and left to right. A complete tree has these properties:
If n has children then all nodes numbered less than n have two children.
If n has one child it must be the left child and all nodes less than n have two children. In addition no node numbered greater than n has children.
If n has no children then no node numbered greater than n has children.
A complete binary tree can be used to represent a heap. It can be easily represented in contiguous memory with no gaps (i.e. all array elements are used save for any space that may exist at the end).
For the position for the context menu, y found the problem that I needed a it to be relative to the DataGridView, and the event I needed to use gives the poistion relative to the cell clicked. I haven't found a better solution so I implemented this function in the commons class, so I call it from wherever I need.
It's quite tested and works well. I Hope you find it useful.
/// <summary>
/// When DataGridView_CellMouseClick ocurs, it gives the position relative to the cell clicked, but for context menus you need the position relative to the DataGridView
/// </summary>
/// <param name="dgv">DataGridView that produces the event</param>
/// <param name="e">Event arguments produced</param>
/// <returns>The Location of the click, relative to the DataGridView</returns>
public static Point PositionRelativeToDataGridViewFromDataGridViewCellMouseEventArgs(DataGridView dgv, DataGridViewCellMouseEventArgs e)
{
int x = e.X;
int y = e.Y;
if (dgv.RowHeadersVisible)
x += dgv.RowHeadersWidth;
if (dgv.ColumnHeadersVisible)
y += dgv.ColumnHeadersHeight;
for (int j = 0; j < e.ColumnIndex; j++)
if (dgv.Columns[j].Visible)
x += dgv.Columns[j].Width;
for (int i = 0; i < e.RowIndex; i++)
if (dgv.Rows[i].Visible)
y += dgv.Rows[i].Height;
return new Point(x, y);
}
In kotlin you can add boolean variable in companion object and check its value from any class you want:
companion object{
var isRuning = false
}
Change it value when service is created and destroyed
override fun onCreate() {
super.onCreate()
isRuning = true
}
override fun onDestroy() {
super.onDestroy()
isRuning = false
}
You're looking for a non-greedy (or lazy) match. To get a non-greedy match in regular expressions you need to use the modifier ?
after the quantifier. For example you can change .*
to .*?
.
By default grep
doesn't support non-greedy modifiers, but you can use grep -P
to use the Perl syntax.
You can simply use __qualname__
which stands for qualified name of a function or class
Example:
>>> class C:
... class D:
... def meth(self):
... pass
...
>>> C.__qualname__
'C'
>>> C.D.__qualname__
'C.D'
>>> C.D.meth.__qualname__
'C.D.meth'
documentation link qualname
The way to fix this issue is not within IIS. I was trying to run my application within IIS Express within Visual Studio. I searched the web and some articles were saying to add an identity tag to the system.web tag. This is not the correct way.
The way I was able to solve this issue was to click on the project file and go to properties. Under managed pipeline, I changed the property value from classic to integrated.
This solved my issue.
Understanding that the Angular documents call checking the $$phase
an anti-pattern, I tried to get $timeout
and _.defer
to work.
The timeout and deferred methods create a flash of unparsed {{myVar}}
content in the dom like a FOUT. For me this was not acceptable. It leaves me without much to be told dogmatically that something is a hack, and not have a suitable alternative.
The only thing that works every time is:
if(scope.$$phase !== '$digest'){ scope.$digest() }
.
I don't understand the danger of this method, or why it's described as a hack by people in the comments and the angular team. The command seems precise and easy to read:
"Do the digest unless one is already happening"
In CoffeeScript it's even prettier:
scope.$digest() unless scope.$$phase is '$digest'
What's the issue with this? Is there an alternative that won't create a FOUT? $safeApply looks fine but uses the $$phase
inspection method, too.
What resolution and density should I set?
How can I indicate that this is large screen device?
What hardware does this tablet support?
What is max heap size?
Which Android version?
Hope that helps - check the spec page for all unanswered questions.
Ok, I deleted my previous answer because finally it was not what willlangford was looking for, but I made my point that maybe we were all misunderstanding the question.
I also thought of the SELECT DISTINCT...
thing at first, but it seemed too weird to me that someone needed to know how many people had a different number of pets than the rest... thats why I thought that maybe the question was not clear enough.
So, now that the real question meaning is clarified, making a subquery for this its quite an overhead, I would preferably use a GROUP BY
clause.
Imagine you have the table customer_pets
like this:
+-----------------------+
| customer | pets |
+------------+----------+
| customer1 | 2 |
| customer2 | 3 |
| customer3 | 2 |
| customer4 | 2 |
| customer5 | 3 |
| customer6 | 4 |
+------------+----------+
then
SELECT count(customer) AS num_customers, pets FROM customer_pets GROUP BY pets
would return:
+----------------------------+
| num_customers | pets |
+-----------------+----------+
| 3 | 2 |
| 2 | 3 |
| 1 | 4 |
+-----------------+----------+
as you need.
I'll explain how works this attribute lower android versions step by step:
1- Import android support library 26.x.x on your project gradle file. If there is no support library on IDE, they will download automatically.
dependencies {
compile 'com.android.support:support-v4:26.1.0'
compile 'com.android.support:appcompat-v7:26.1.0'
compile 'com.android.support:support-v13:26.1.0' }
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
} }
2- Open your layout XML file and refactor like this tag your TextView. This scenario is: when incrased font size on system, fit text to avaliable width, not word wrap.
<android.support.v7.widget.AppCompatTextView
android:id="@+id/textViewAutoSize"
android:layout_width="match_parent"
android:layout_height="25dp"
android:ellipsize="none"
android:text="Auto size text with compatible lower android versions."
android:textSize="12sp"
app:autoSizeMaxTextSize="14sp"
app:autoSizeMinTextSize="4sp"
app:autoSizeStepGranularity="0.5sp"
app:autoSizeTextType="uniform" />
Find() will find the element that matches the predicate that you pass as a parameter, so it is not related to Equals() or the == operator.
var element = myList.Find(e => [some condition on e]);
In this case, I have used a lambda expression as a predicate. You might want to read on this. In the case of Find(), your expression should take an element and return a bool.
In your case, that would be:
var reponse = list.Find(r => r.Statement == "statement1")
And to answer the question in the comments, this is the equivalent in .NET 2.0, before lambda expressions were introduced:
var response = list.Find(delegate (Response r) {
return r.Statement == "statement1";
});
@Mikael Svenson's answer is correct. I just wanted to add a small addition to it:
The Messagebox icon can also be included has an additional property like below:
DialogResult dialogResult = MessageBox.Show("Sure", "Please Confirm Your Action", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
You urls are not in the same repository, so you can't do it with the svn diff
command.
svn: 'http://svn.boost.org/svn/boost/sandbox/boost/extension' isn't in the same repository as 'http://cloudobserver.googlecode.com/svn'
Another way you could do it, is export each repos using svn export
, and then use the diff command to compare the 2 directories you exported.
// Export repositories
svn export http://svn.boost.org/svn/boost/sandbox/boost/extension/ repos1
svn export http://cloudobserver.googlecode.com/svn/branches/v0.4/Boost.Extension.Tutorial/libs/boost/extension/ repos2
// Compare exported directories
diff repos1 repos2 > file.diff
Phoronix did some benchmarks about this, but it is about a snapshot version of Clang/LLVM from a few months back. The results being that things were more-or-less a push; neither GCC nor Clang is definitively better in all cases.
Since you'd use the latest Clang, it's maybe a little less relevant. Then again, GCC 4.6 is slated to have some major optimizations for Core 2 and i7, apparently.
I figure Clang's faster compilation speed will be nicer for original developers, and then when you push the code out into the world, Linux distro/BSD/etc. end-users will use GCC for the faster binaries.
OMG... It's not only a problem of "jQuery Library" and "getElementById".
Sure, jQuery helps us to put cross-browser problems aside, but using the traditional way without libraries can still work well, if you really understand JavaScript ENOUGH!!!
Both @Már Örlygsson and @Darryl Hein gave you good ALTARNATIVES(I'd say, they're just altarnatives, not anwsers), where the former used the traditional way, and the latter jQuery way. But do you really know the answer to your problem? What is wrong with your code?
First, .click
is a jQuery way. If you want to use traditional way, use .onclick instead. Or I recommend you concentrating on learning to use jQuery only, in case of confusing. jQuery is a good tool to use without knowing DOM enough.
The second problem, also the critical one, new function(){}
is a very bad syntax, or say it is a wrong syntax.
No matter whether you want to go with jQuery or without it, you need to clarify it.
There are 3 basic ways declaring function:
function name () {code}
... = function() {code} // known as anonymous function or function literal
... = new Function("code") // Function Object
Note that javascript is case-sensitive, so new function()
is not a standard syntax of javascript. Browsers may misunderstand the meaning.
Thus your code can be modified using the second way as
= function(){alert();}
Or using the third way as
= new Function("alert();");
Elaborating on it, the second way works almost the same as the third way, and the second way is very common, while the third is rare. Both of your best answers use the second way.
However, the third way can do something that the second can't do, because of "runtime" and "compile time". I just hope you know new Function()
can be useful sometimes. One day you meet problems using function(){}
, don't forget new Function()
.
To understand more, you are recommended read << JavaScript: The Definitive Guide, 6th Edition >>, O'Reilly.
In case of gray image, I am using this function and it works fine! however you must take care about the function features ;)
CvMat * src= cvCreateMat(300,300,CV_32FC1);
IplImage *dist= cvCreateImage(cvGetSize(dist),IPL_DEPTH_32F,3);
cvConvertScale(src, dist, 1, 0);
I'm getting the same solution as @camino's comment on https://stackoverflow.com/a/19365454/10593190 and XavierStuvw's reply.
I got it to work (for installing ffmpeg) by simply reinstalling the whole thing from the beginning with all instances of $ ./configure
replaced by $ ./configure --enable-shared
(first make sure to delete all the folders and files including the .so files from the previous attempt).
Apparently this works because https://stackoverflow.com/a/13812368/10593190.
Expanding on @Kiran's answer, which I agree is more succinct and Pythonic, this adds codecs to support the reading and writing of UTF-8:
import codecs
from tempfile import mkstemp
from shutil import move
from os import remove
def replace(source_file_path, pattern, substring):
fh, target_file_path = mkstemp()
with codecs.open(target_file_path, 'w', 'utf-8') as target_file:
with codecs.open(source_file_path, 'r', 'utf-8') as source_file:
for line in source_file:
target_file.write(line.replace(pattern, substring))
remove(source_file_path)
move(target_file_path, source_file_path)
If you want to use this in VBA:
For i = 1 To X
UserForm1.Controls("Label" & i).Caption = MySheet.Cells(i + 1, i).Value
Next
The to_sql method works for me.
However, keep in mind that the it looks like it's going to be deprecated in favor of SQLAlchemy:
FutureWarning: The 'mysql' flavor with DBAPI connection is deprecated and will be removed in future versions. MySQL will be further supported with SQLAlchemy connectables. chunksize=chunksize, dtype=dtype)
Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.
<div class="modal-backdrop"></div>
Made a small demo: http://jsfiddle.net/PfBnq/
the computer in question is a Mac.
A macOS-only solution:
/usr/libexec/java_home -v 1.8+ --exec javac -version
Where 1.8+
is Java 1.8 or higher.
Unfortunately, the java_home
helper does not set the proper return code, so checking for failure requires parsing the output (e.g. 2>&1 |grep -v "Unable"
) which varies based on locale.
Note, Java may also exist in /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin
, but at time of writing this, I'm unaware of a JRE that installs there which contains javac
as well.
Web.xml is called as deployment descriptor file and its is is an XML file that contains information on the configuration of the web application, including the configuration of servlets.
just add below line and access direct xml object
import kotlinx.android.synthetic.main.activity_main.*
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
txt_HelloWorld.text = "abc"
}
replace activity_main according to your XML name
So much for this simple question, but I just wanted to highlight a new feature in Java which will avoid all confusions around indexing in arrays even for beginners. Java-8 has abstracted the task of iterating for you.
int[] array = new int[5];
//If you need just the items
Arrays.stream(array).forEach(item -> { println(item); });
//If you need the index as well
IntStream.range(0, array.length).forEach(index -> { println(array[index]); })
What's the benefit? Well, one thing is the readability like English. Second, you need not worry about the ArrayIndexOutOfBoundsException
Why not look at the code for bisect_left/right and adapt it to suit your purpose.
like this:
def binary_search(a, x, lo=0, hi=None):
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
midval = a[mid]
if midval < x:
lo = mid+1
elif midval > x:
hi = mid
else:
return mid
return -1
Sub SelectAllCellsInSheet(SheetName As String)
lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
Sheets(SheetName).Range("A2", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub
To use with ActiveSheet:
Call SelectAllCellsInSheet(ActiveSheet.Name)
Looks like older answers were fine for older Jackson versions, but since objectMapper
has method setTimeZone(tz)
, setting time zone on a dateFormat is totally ignored.
How to properly setup timeZone to the ObjectMapper in Jackson version 2.11.0:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setTimeZone(TimeZone.getTimeZone("Europe/Warsaw"));
Full example
@Test
void test() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.findAndRegisterModules();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
JavaTimeModule module = new JavaTimeModule();
objectMapper.registerModule(module);
objectMapper.setTimeZone(TimeZone.getTimeZone("Europe/Warsaw"));
ZonedDateTime now = ZonedDateTime.now();
String converted = objectMapper.writeValueAsString(now);
ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
System.out.println("serialized: " + now);
System.out.println("converted: " + converted);
System.out.println("restored: " + restored);
Assertions.assertThat(now).isEqualTo(restored);
}
`
Probaly you can use Iframe
for this. Facebook probably uses this technique. You can read more on this here. Stackoverflow uses similar technique, but with HTML5 local storage, more on this on their blog
I had a similar problem: every time I push a particular button, I create a new Timer.
my_timer = new Timer("MY_TIMER");
my_timer.schedule(new TimerTask() {
...
}
Exiting from that activity I deleted the timer:
if(my_timer!=null){
my_timer.cancel();
my_timer = null;
}
But it was not enough because the cancel()
method only canceled the latest Timer. The older ones were ignored an didn't stop running. The purge()
method was not useful for me.
I solved the problem just checking the Timer
instantiation:
if(my_timer == null){
my_timer = new Timer("MY_TIMER");
my_timer.schedule(new TimerTask() {
...
}
}
Internet Explorer 7 (and earlier) displays the value of the alt attribute as a tooltip, when mousing over the image. This is NOT the correct behavior, according to the HTML specification. The title attribute should be used instead. Source: http://www.w3schools.com/tags/att_img_alt.asp
Necromancing.
Actually, doing this correctly is a little bit trickier.
You first need to check if the primary-key exists for the column you want to set your foreign key to reference to.
In this example, a foreign key on table T_ZO_SYS_Language_Forms is created, referencing dbo.T_SYS_Language_Forms.LANG_UID
-- First, chech if the table exists...
IF 0 < (
SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'T_SYS_Language_Forms'
)
BEGIN
-- Check for NULL values in the primary-key column
IF 0 = (SELECT COUNT(*) FROM T_SYS_Language_Forms WHERE LANG_UID IS NULL)
BEGIN
ALTER TABLE T_SYS_Language_Forms ALTER COLUMN LANG_UID uniqueidentifier NOT NULL
-- No, don't drop, FK references might already exist...
-- Drop PK if exists
-- ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT pk_constraint_name
--DECLARE @pkDropCommand nvarchar(1000)
--SET @pkDropCommand = N'ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT ' + QUOTENAME((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
--WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
--AND TABLE_SCHEMA = 'dbo'
--AND TABLE_NAME = 'T_SYS_Language_Forms'
----AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms'
--))
---- PRINT @pkDropCommand
--EXECUTE(@pkDropCommand)
-- Instead do
-- EXEC sp_rename 'dbo.T_SYS_Language_Forms.PK_T_SYS_Language_Forms1234565', 'PK_T_SYS_Language_Forms';
-- Check if they keys are unique (it is very possible they might not be)
IF 1 >= (SELECT TOP 1 COUNT(*) AS cnt FROM T_SYS_Language_Forms GROUP BY LANG_UID ORDER BY cnt DESC)
BEGIN
-- If no Primary key for this table
IF 0 =
(
SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'T_SYS_Language_Forms'
-- AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms'
)
ALTER TABLE T_SYS_Language_Forms ADD CONSTRAINT PK_T_SYS_Language_Forms PRIMARY KEY CLUSTERED (LANG_UID ASC)
;
-- Adding foreign key
IF 0 = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = 'FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms')
ALTER TABLE T_ZO_SYS_Language_Forms WITH NOCHECK ADD CONSTRAINT FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms FOREIGN KEY(ZOLANG_LANG_UID) REFERENCES T_SYS_Language_Forms(LANG_UID);
END -- End uniqueness check
ELSE
PRINT 'FSCK, this column has duplicate keys, and can thus not be changed to primary key...'
END -- End NULL check
ELSE
PRINT 'FSCK, need to figure out how to update NULL value(s)...'
END
I just installed angular cli and it solved my issue, simply run:
npm install -g @angular/cli
The solution for Windows
is to clone the repository to other folder and then copy and paste to the original location or just copy the .git
invisible folder.
Maybe you can use the script i am using to retrieve a certain cell value from another sheet back to a specific sheet.
Sub reviewRow()
Application.ScreenUpdating = False
Results = MsgBox("Do you want to View selected row?", vbYesNo, "")
If Results = vbYes And Range("C10") > 1 Then
i = Range("C10") //this is where i put the row number that i want to retrieve or review that can be changed as needed
Worksheets("Sheet1").Range("C6") = Worksheets("Sheet2").Range("C" & i) //sheet names can be changed as necessary
End if
Application.ScreenUpdating = True
End Sub
You can make a form using this and personalize it as needed.
This is another option:
export default function Counter() {
}
There seems to be a nasty edge case here: Ajax over congested wifi.
Ajax usually means that the KeepAlive has timed out after say 20 seconds. However, the wifi means that the (ideally fast) ajax connection has to make multiple round trips. Worse, the wifi often loses packets, and there are TCP retransmits. In this case, HTTPS performs really really badly!
Based on http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html
What about:
Create Table New_Users Select * from Old_Users Where 1=2;
and if that doesn't work, just select a row and truncate after creation:
Create table New_Users select * from Old_Users Limit 1;
Truncate Table New_Users;
EDIT:
I noticed your comment below about needing indexes, etc. Try:
show create table old_users;
#copy the output ddl statement into a text editor and change the table name to new_users
#run the new query
insert into new_users(id,name...) select id,name,... form old_users group by id;
That should do it. It appears that you are doing this to get rid of duplicates? In which case you may want to put a unique index on id. if it's a primary key, this should already be in place. You can either:
#make primary key
alter table new_users add primary key (id);
#make unique
create unique index idx_new_users_id_uniq on new_users (id);
barryvdh/laravel-cors works perfectly with Laravel 5.1 with just a few key points in enabling it.
After adding it as a composer dependency, make sure you have published the CORS config file and adjusted the CORS headers as you want them. Here is how mine look in app/config/cors.php
<?php
return [
'supportsCredentials' => true,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['*'],
'allowedMethods' => ['GET', 'POST', 'PUT', 'DELETE'],
'exposedHeaders' => ['DAV', 'content-length', 'Allow'],
'maxAge' => 86400,
'hosts' => [],
];
After this, there is one more step that's not mentioned in the documentation, you have to add the CORS handler 'Barryvdh\Cors\HandleCors'
in the App kernel. I prefer to use it in the global middleware stack. Like this
/**
* The application's global HTTP middleware stack.
*
* @var array
*/
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'Barryvdh\Cors\HandleCors',
];
But its up to you to use it as a route middleware and place on specific routes.
This should make the package work with L5.1