Assuming there are a few ignore directories, why not use "git status node/logs/" which will tell you what files are to be added? In the directory I have a text file that is not part of status output, e.g.:
On branch master
Your branch is up-to-date with 'origin/master'.
Untracked files:
(use "git add ..." to include in what will be committed)
node/logs/.gitignore
.gitignore is:
*
!.gitignore
Please write following code in menu.xml file:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:my_menu_tutorial_app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.mymenus.menu_app.MainActivity">
<item android:id="@+id/item_one"
android:icon="@drawable/menu_icon"
android:orderInCategory="l01"
android:title="Item One"
my_menu_tutorial_app:showAsAction="always">
<!--sub-menu-->
<menu>
<item android:id="@+id/sub_one"
android:title="Sub-menu item one" />
<item android:id="@+id/sub_two"
android:title="Sub-menu item two" />
</menu>
Also write this java code in activity class file:
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
Toast.makeText(this, "Menus item selected: " +
item.getTitle(), Toast.LENGTH_SHORT).show();
switch (item.getItemId())
{
case R.id.sub_one:
isItemOneSelected = true;
supportInvalidateOptionsMenu();
return true;
case MENU_ITEM + 1:
isRemoveItem = true;
supportInvalidateOptionsMenu();
return true;
default:
return false;
}
}
This is the easiest way to display menus in action bar.
Like what Amber says in her answer: create a function. In fact when you don't have to make classes if you have something like:
class Person(object):
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
def compute(self, other):
""" Example of bad class design, don't care about the result """
return self.arg1 + self.arg2 % other
Here you just have a function encapsulate in a class. This just make the code less readable and less efficient. In fact the function compute
can be written just like this:
def compute(arg1, arg2, other):
return arg1 + arg2 % other
You should use classes only if you have more than 1 function to it and if keep a internal state (with attributes) has sense. Otherwise, if you want to regroup functions, just create a module in a new .py
file.
You might look this video (Youtube, about 30min), which explains my point. Jack Diederich shows why classes are evil in that case and why it's such a bad design, especially in things like API.
It's quite a long video but it's a must see.
Try jcabi-http
, which is a fluent Java HTTP client, for example:
String html = new JdkRequest("https://www.google.com")
.header(HttpHeaders.ACCEPT, MediaType.TEXT_HTML)
.fetch()
.as(HttpResponse.class)
.assertStatus(HttpURLConnection.HTTP_OK)
.body();
Check also this blog post: http://www.yegor256.com/2014/04/11/jcabi-http-intro.html
as explained in above answers Also, to return only one field from the entire array you can use projection
into find. and use $
db.getCollection("sizer").find(
{ awards: { $elemMatch: { award: "National Medal", year: 1975 } } },
{ "awards.$": 1, name: 1 }
);
will be reutrn
{
_id: 1,
name: {
first: 'John',
last: 'Backus'
},
awards: [
{
award: 'National Medal',
year: 1975,
by: 'NSF'
}
]
}
I use the following code that works very reliably.
The JSON data is passed in the parameter $request, and the specific request type passed in the variable $searchType.
The code includes a trap to detect and report an unsuccessful or invalid call which will then return false.
If the call is sucessful then json_decode ($result->getBody(), $return=true) returns an array of the results.
public function callAPI($request, $searchType) {
$guzzleClient = new GuzzleHttp\Client(["base_uri" => "https://example.com"]);
try {
$result = $guzzleClient->post( $searchType, ["json" => $request]);
} catch (Exception $e) {
$error = $e->getMessage();
$error .= '<pre>'.print_r($request, $return=true).'</pre>';
$error .= 'No returnable data';
Event::logError(__LINE__, __FILE__, $error);
return false;
}
return json_decode($result->getBody(), $return=true);
}
Recursively calling the deepFlatten
function so we can spread the inner array without using any external helper method is the way to go.
const innerArr = ['a', 'b'];
const multiDimArr = [[1, 2], 3, 4, [5, 6, innerArr], 9];
const deepFlatten = (arr) => {
const flatList = [];
arr.forEach(item => {
Array.isArray(item)
? flatList.push(...deepFlatten(item)) // recursive call
: flatList.push(item)
});
return flatList;
}
I'm using Windows 7 with VS 2013 (Update 3) and Intel Parallel Studio XE Composer Edition for Fortran Windows (Update 5). Out of the box I had the same issue.
Once I fixed the missing rc.exe problem I had another issue. The linker was missing kernel32.lib.
I corrected both issues by updating the Intel Composer Options (TOOLS->Options...->Intel Composer XE->Visual Fortran->Compilers).
For the Win32 tab I added:
Executables: C:\Program Files (x86)\Windows Kits\8.0\bin\x86; (just before $(PATH))
Libraries: C:\Program Files (x86)\Windows Kits\8.0\Lib\win8\um\x86; (at the end)
For the x64 tab I added:
Executables: C:\Program Files (x86)\Windows Kits\8.0\bin\x64; (just before $(PATH))
Libraries: C:\Program Files (x86)\Windows Kits\8.0\Lib\win8\um\x64; (at the end)
Update...
I was also missing some SDK header files (winver.h and winapifamily.h). I added the following to the same TOOLS->Options... area.
For both the win32 and x64 tabs
Includes: C:\Program Files (x86)\Windows Kits\8.0\Include\um;C:\Program Files (x86)\Windows Kits\8.0\Include\shared;
Try following int git bash
1.git add -u :/
2.git commit -m "your commit message"
git push -u origin master
Note:if you have not initialized your repo.
First of all
git init
and follow above mentioned steps in order. This worked for me
if you return var-binary data from DB to display PDF on popup or browser means follow this code:-
View page:
@using (Html.BeginForm("DisplayPDF", "Scan", FormMethod.Post))
{
<a href="javascript:;" onclick="document.forms[0].submit();">View PDF</a>
}
Scan controller:
public ActionResult DisplayPDF()
{
byte[] byteArray = GetPdfFromDB(4);
MemoryStream pdfStream = new MemoryStream();
pdfStream.Write(byteArray, 0, byteArray.Length);
pdfStream.Position = 0;
return new FileStreamResult(pdfStream, "application/pdf");
}
private byte[] GetPdfFromDB(int id)
{
#region
byte[] bytes = { };
string constr = System.Configuration.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Scan_Pdf_File FROM PWF_InvoiceMain WHERE InvoiceID=@Id and Enabled = 1";
cmd.Parameters.AddWithValue("@Id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows == true)
{
sdr.Read();
bytes = (byte[])sdr["Scan_Pdf_File"];
}
}
con.Close();
}
}
return bytes;
#endregion
}
How about
[@"7" intValue];
Additionally if you want an NSNumber
you could do
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter numberFromString:@"7"];
colrm x
For example, if you need the first 100 characters:
cat file |colrm 101
It's been around for years and is in most linux's and bsd's (freebsd for sure), usually by default. I can't remember ever having to type apt-get install colrm
.
You have to use execute immediate (dynamic sql).
DECLARE
v_owner varchar2(40);
v_table_name varchar2(40);
cursor get_tables is
select distinct table_name,user
from user_tables
where lower(user) = 'schema_name';
begin
open get_tables;
loop
fetch get_tables into v_table_name,v_owner;
EXIT WHEN get_tables%NOTFOUND;
execute immediate 'INSERT INTO STATS_TABLE(TABLE_NAME,SCHEMA_NAME,RECORD_COUNT,CREATED)
SELECT ''' || v_table_name || ''' , ''' || v_owner ||''',COUNT(*),TO_DATE(SYSDATE,''DD-MON-YY'') FROM ' || v_table_name;
end loop;
CLOSE get_tables;
END;
say sum lines
~$ perl6 -e '.say for 0..1000000' > test.in
~$ perl6 -e 'say sum lines' < test.in
500000500000
The most common way of doing this is to include the binary as base-64 in an element. However, this is a workaround, and adds a bit of volume to the file.
For example, this is the bytes 00 to 09 (note we needed 16 bytes to encode 10 bytes worth of data):
<xml><image>AAECAwQFBgcICQ==</image></xml>
how you do this encoding varies per architecture. For example, with .NET you might use Convert.ToBase64String
, or XmlWriter.WriteBase64
.
I had the same problem thanks to french specials characters. Here is my class in case anybody needs it. It has to be saved here : /application/core/MY_Input.php
(also this extension will report witch character is not allowed in the future)
class MY_Input extends CI_Input {
function __construct()
{
parent::__construct();
}
/**
* Clean Keys
*
* This is a helper function. To prevent malicious users
* from trying to exploit keys we make sure that keys are
* only named with alpha-numeric text and a few other items.
*
* @access private
* @param string
* @return string
*/
function _clean_input_keys($str)
{
if ( ! preg_match("/^[a-z0-9:_\/-àâçéèêëîôùû]+$/i", $str))
{
exit('Disallowed Key Characters : '.$str);
}
// Clean UTF-8 if supported
if (UTF8_ENABLED === TRUE)
{
$str = $this->uni->clean_string($str);
}
return $str;
}
}
Read The Friendly Manual about core classes extension : http://ellislab.com/codeigniter/user-guide/general/core_classes.html
It appears to me that you have two issues here. One is that JFrame does not have a close
method, which has been addressed in the other answers.
The other is that you're having trouble referencing your JFrame. Within actionPerformed
, super
refers to ActionListener. To refer to the JFrame instance there, use MyExtendedJFrame.super
instead (you should also be able to use MyExtendedJFrame.this
, as I see no reason why you'd want to override the behaviour of dispose
or setVisible
).
Here's an alternative method using the inbuilt properties of the anchor HTML element:
var a = document.createElement('a'),_x000D_
_x000D_
getHrefWithUpdatedQueryString = function(param, value) {_x000D_
return updatedQueryString(window.location.href, param, value);_x000D_
},_x000D_
_x000D_
updatedQueryString = function(url, param, value) {_x000D_
/*_x000D_
A function which modifies the query string _x000D_
by setting one parameter to a single value._x000D_
_x000D_
Any other instances of parameter will be removed/replaced._x000D_
*/_x000D_
var fragment = encodeURIComponent(param) + _x000D_
'=' + encodeURIComponent(value);_x000D_
_x000D_
a.href = url;_x000D_
_x000D_
if (a.search.length === 0) {_x000D_
a.search = '?' + fragment;_x000D_
} else {_x000D_
var didReplace = false,_x000D_
// Remove leading '?'_x000D_
parts = a.search.substring(1)_x000D_
// Break into pieces_x000D_
.split('&'),_x000D_
_x000D_
reassemble = [],_x000D_
len = parts.length;_x000D_
_x000D_
for (var i = 0; i < len; i++) {_x000D_
_x000D_
var pieces = parts[i].split('=');_x000D_
if (pieces[0] === param) {_x000D_
if (!didReplace) {_x000D_
reassemble.push('&' + fragment);_x000D_
didReplace = true;_x000D_
}_x000D_
} else {_x000D_
reassemble.push(parts[i]);_x000D_
}_x000D_
}_x000D_
_x000D_
if (!didReplace) {_x000D_
reassemble.push('&' + fragment);_x000D_
}_x000D_
_x000D_
a.search = reassemble.join('&');_x000D_
}_x000D_
_x000D_
return a.href;_x000D_
};
_x000D_
This commit, which is part of version 1.1.5 and above, exposes the $promise
object of $resource
. Versions of ngResource including this commit allow resolving resources like this:
$routeProvider
resolve: {
data: function(Resource) {
return Resource.get().$promise;
}
}
controller
app.controller('ResourceCtrl', ['$scope', 'data', function($scope, data) {
$scope.data = data;
}]);
Your kth FFT result's frequency is 2*pi*k/N.
I had the problem with a ASP.NET project in VS 2019.
Another symptom was, that some references (System.Web.Http) were marked as faulty in the project references list (Solution Explorer)
My solution:
The cause:
Looking at the difference in the csproj file I could see the reason for the trouble. Someone managed to reference a DLL in the Windows Program file folder!
<Reference Include="System.Web.Http">
<HintPath>..\..\..\..\..\..\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Packages\Microsoft.AspNet.WebApi.Core.4.0.30506.0\lib\net40\System.Web.Http.dll</HintPath>
</Reference>
<Reference Include="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Packages\Microsoft.AspNet.Mvc.4.0.30506.0\lib\net40\System.Web.Mvc.dll</HintPath>
</Reference>
Composer is avialble and install the packages in the global path but they are not available in the shell, Mac in my case. I managed to fix this by adding the global bin to the path at my bash file.
Steps:
First, check what is your home directory by typing in the shell:
cd ~
pwd
this will tell you the home path
The next step is to verify that composer set the global directory there:
ls -al .composer
If you got list of files that's mean composer set up the directory, if not - look above or in the documentation.
The next step is to edit the bash profile. Mine is ~/.bash_profile but other can ~/.zshrc. If you don't have any one like this try to see how to set up aliases and place the the code in aliases file:
PATH="YOUR_HOME_PATH/.composer/vendor/bin:${PATH}"
export PATH
That's it! just reload the file with
source PATH_TO_FILE
And you good to go!
In order to add an EventListener to an element in angular 2+, we can use the method listen of the Renderer2 service (Renderer is deprecated, so use Renderer2):
listen(target: 'window'|'document'|'body'|any, eventName: string, callback: (event: any) => boolean | void): () => void
Example:
export class ListenDemo implements AfterViewInit {
@ViewChild('testElement')
private testElement: ElementRef;
globalInstance: any;
constructor(private renderer: Renderer2) {
}
ngAfterViewInit() {
this.globalInstance = this.renderer.listen(this.testElement.nativeElement, 'click', () => {
this.renderer.setStyle(this.testElement.nativeElement, 'color', 'green');
});
}
}
Note:
When you use this method to add an event listener to an element in the dom, you should remove this event listener when the component is destroyed
You can do that this way:
ngOnDestroy() {
this.globalInstance();
}
The way of use of ElementRef
in this method should not expose your angular application to a security risk. for more on this referrer to ElementRef security risk angular 2
Found out what was wrong. I never installed the setuptools for python, so it was missing some vital files, like the egg ones.
If you find yourself having my issue above, download this file and then in powershell or command prompt, navigate to ez_setup’s directory and execute the command and this will run the file for you:
$ [sudo] python ez_setup.py
If you still need to install pip at this point, run:
$ [sudo] easy_install pip
easy_install was part of the setuptools, and therefore wouldn't work for installing pip.
Then, pip will successfully install django with the command:
$ [sudo] pip install django
Hope I saved someone the headache I gave myself!
~Zorpix
Invalidate Caches and Restart did not work for me. I also updated all my Android Studio files with no success.
The solution I found was importing the android folder by clicking "Import project (Eclipse ADT, Gradle, etc.)" rather than clicking "Open an existing Android Studio Project" or dragging the folder onto the app icon.
Apparently the problem is caused because a module in the project has an *.iml file that does not contain external.system.id="GRADLE".
When you import the project (as opposed to opening it), the iml files are completely re-written, thus removing the error.
I found the info here: https://issuetracker.google.com/issues/37008041
You can use style display:none with tr to hide and it will work with all browsers.
Add | select FullName
to the end of your line above. If you need to actually do something with that afterwards, you might have to pipe it into a foreach loop, like so:
get-childitem "C:\windows\System32" -recurse | where {$_.extension -eq ".txt"} | % {
Write-Host $_.FullName
}
I would just query for the for
attribute instead of repetitively recursing the DOM tree.
$("input:checkbox").on("change", function() {
$("label[for='"+this.id+"']").text("TESTTTT");
});
Error Message: Gradle sync failed: Minimum supported Gradle version is 4.9. Current version is 4.1-milestone-1. If using the gradle wrapper, try editing the distributionUrl in SampleProj/app/gradle/wrapper/gradle-wrapper.properties to gradle-4.9-all.zip
I am using Android studio IDE version 3.2 beta 2.
Solution: When we open gradle-wrapper.properties file in IDE it shows correct distributionUrl. but originally it has not been updated. So change the distributionUrl property manually.
Example : open a gradle-wrapper.properties file in notepad or any other editor. /Project/app/gradle/wrapper/gradle-wrapper.properties and change distributionUrl property to like this
distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-all.zip
In C and C++ memory requirements of some variable :
signed char: -2^07 to +2^07-1
short: -2^15 to +2^15-1
int: -2^15 to +2^15-1
long: -2^31 to +2^31-1
long long: -2^63 to +2^63-1
signed char: -2^07 to +2^07-1
short: -2^15 to +2^15-1
int: -2^31 to +2^31-1
long: -2^31 to +2^31-1
long long: -2^63 to +2^63-1
depends on compiler and architecture of hardware
The international standard for the C language requires only that the size of short variables should be less than or equal to the size of type int, which in turn should be less than or equal to the size of type long.
For 32 bit Notepad++ only
Plugins -> Plugin Manager -> Show Plugin Manager -> Available tab -> TextFX Characters -> Install.
It was removed from the default installation as it caused issues with certain configurations, and there's no maintainer.
I can stop at the first requirement "A daemon which cannot be stopped ..."
Not possible my friend; however, you can achieve the same with a much better tool, a kernel module.
http://www.infoq.com/articles/inotify-linux-file-system-event-monitoring
All daemons can be stopped. Some are more easily stopped than others. Even a daemon pair with the partner in hold down, respawning the partner if lost, can be stopped. You just have to work a little harder at it.
Your object can also implement the Parcelable interface. Then you can use the Bundle.putParcelable()
method and pass your object between activities within intent.
The Photostream application uses this approach and may be used as a reference.
Add an identity column (PeopleID) and then use a correlated subquery to return the first value for each value.
SELECT *
FROM People p
WHERE PeopleID = (
SELECT MIN(PeopleID)
FROM People
WHERE IDNo = p.IDNo
)
I am working behind a proxy and just installed SASS by downloading directly from http://rubygems.org.
I then ran sudo gem install [path/to/downloaded/gem/file]
. I cannot say this will work for all gems, but it may help some people.
The sp_xml_preparedocument
stored procedure will parse the XML and the OPENXML
rowset provider will show you a relational view of the XML data.
For details and more examples check the OPENXML documentation.
As for your question,
DECLARE @XML XML
SET @XML = '<rows><row>
<IdInvernadero>8</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>8</IdCaracteristica1>
<IdCaracteristica2>8</IdCaracteristica2>
<Cantidad>25</Cantidad>
<Folio>4568457</Folio>
</row>
<row>
<IdInvernadero>3</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>1</IdCaracteristica1>
<IdCaracteristica2>2</IdCaracteristica2>
<Cantidad>72</Cantidad>
<Folio>4568457</Folio>
</row></rows>'
DECLARE @handle INT
DECLARE @PrepareXmlStatus INT
EXEC @PrepareXmlStatus= sp_xml_preparedocument @handle OUTPUT, @XML
SELECT *
FROM OPENXML(@handle, '/rows/row', 2)
WITH (
IdInvernadero INT,
IdProducto INT,
IdCaracteristica1 INT,
IdCaracteristica2 INT,
Cantidad INT,
Folio INT
)
EXEC sp_xml_removedocument @handle
The disabled option approach seems to look the best and be the best supported. I've also included an example of using the optgroup.
optgroup (this way kinda sucks):
<select>_x000D_
<optgroup>_x000D_
<option>First</option>_x000D_
</optgroup>_x000D_
<optgroup label="_________">_x000D_
<option>Second</option>_x000D_
<option>Third</option>_x000D_
</optgroup>_x000D_
</select>
_x000D_
disabled option (a bit better):
<select>_x000D_
<option>First</option>_x000D_
<option disabled>_________</option>_x000D_
<option>Second</option>_x000D_
<option>Third</option>_x000D_
</select>
_x000D_
And if you want to be really fancy, use the horizontal unicode box drawing character.
(BEST OPTION!)
<select>_x000D_
<option>First</option>_x000D_
<option disabled>----------</option>_x000D_
<option>Second</option>_x000D_
<option>Third</option>_x000D_
</select>
_x000D_
import json
myDict = {'dict': [{'a': 'none', 'b': 'none', 'c': 'none'}]}
test = json.dumps(myDict)
print(test)
{"dict": [{"a": "none", "b": "none", "c": "none"}]}
myDict['dict'].append(({'a': 'aaaa', 'b': 'aaaa', 'c': 'aaaa'}))
test = json.dumps(myDict)
print(test)
{"dict": [{"a": "none", "b": "none", "c": "none"}, {"a": "aaaa", "b": "aaaa", "c": "aaaa"}]}
I recommend you to checkout @angular-material-components/datetime-picker. This is a DatetimePicker like @angular/material Datepicker by adding support for choosing time.
CSS Cursor:Pointer;
is a great solution. FastClick https://github.com/ftlabs/fastclick is another solution which doesn't require you to change css if you didn't want Cursor:Pointer;
on an element for some reason. I use fastclick now anyway to eliminate the 300ms delay on iOS devices.
ProcessStartInfo pStartInfo = new ProcessStartInfo();
pStartInfo.FileName = "CMD";
pStartInfo.Arguments = @"/C mysql --user=root --password=sa casemanager && \. " + Environment.CurrentDirectory + @"\MySQL\CaseManager.sql"
pStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(pStartInfo);
The &&
is the way to tell the command shell that there is another command to execute.
That should be possible using Socket.IO-client: https://github.com/LearnBoost/socket.io-client
You could try:
agg <- aggregate(list(x$val1, x$val2, x$val3, x$val4), by = list(x$id1, x$id2), mean)
The minimum ranges you can rely on are:
short int
and int
: -32,767 to 32,767unsigned short int
and unsigned int
: 0 to 65,535long int
: -2,147,483,647 to 2,147,483,647unsigned long int
: 0 to 4,294,967,295This means that no, long int
cannot be relied upon to store any 10 digit number. However, a larger type long long int
was introduced to C in C99 and C++ in C++11 (this type is also often supported as an extension by compilers built for older standards that did not include it). The minimum range for this type, if your compiler supports it, is:
long long int
: -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807unsigned long long int
: 0 to 18,446,744,073,709,551,615So that type will be big enough (again, if you have it available).
A note for those who believe I've made a mistake with these lower bounds - I haven't. The C requirements for the ranges are written to allow for ones' complement or sign-magnitude integer representations, where the lowest representable value and the highest representable value differ only in sign. It is also allowed to have a two's complement representation where the value with sign bit 1 and all value bits 0 is a trap representation rather than a legal value. In other words, int
is not required to be able to represent the value -32,768.
If you want to use pip
to install required package and import it after installation, you can use this code:
def install_and_import(package):
import importlib
try:
importlib.import_module(package)
except ImportError:
import pip
pip.main(['install', package])
finally:
globals()[package] = importlib.import_module(package)
install_and_import('transliterate')
If you installed a package as a user you can encounter the problem that you cannot just import the package. See How to refresh sys.path? for additional information.
Google Reflection if you want to discover interfaces as well.
Spring ClassPathScanningCandidateComponentProvider
is not discovering interfaces.
Isn't encoding taking the text TO base64 and decoding taking base64 BACK to text? You seem be mixing them up here. When I decode using this online decoder I get:
BASE64: blahblah
UTF8: nVnV
not the other way around. I can't reproduce it completely in PS though. See sample below:
PS > [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("blahblah"))
nV?nV?
PS > [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("nVnV"))
blZuVg==
EDIT I believe you're using the wrong encoder for your text. The encoded base64 string is encoded from UTF8(or ASCII) string.
PS > [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
blahblah
PS > [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
????
PS > [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
blahblah
Many people will suggest you use MERGE
, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:
http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/
Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;
A lot of folks will suggest this way:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
UPDATE ...
END
ELSE
BEGIN
INSERT ...
END
COMMIT TRANSACTION;
But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)
Others will suggest this way:
BEGIN TRY
INSERT ...
END TRY
BEGIN CATCH
IF ERROR_NUMBER() = 2627
UPDATE ...
END CATCH
However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:
Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE
is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.
ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet. See the reference for ModelChoiceField.
So, provide a QuerySet to the field's queryset
attribute. Depends on how your form is built. If you build an explicit form, you'll have fields named directly.
form.rate.queryset = Rate.objects.filter(company_id=the_company.id)
If you take the default ModelForm object, form.fields["rate"].queryset = ...
This is done explicitly in the view. No hacking around.
Nothing here that is not covered. But would like to add my 2 cents. At times, I run a build and it changes lot of files and then I want to work on something, so this command really helps me a lot.
git update-index --assume-unchanged `git status | grep modified | sed 's|modified:||g'| xargs`
Hope someone else find it useful as well.
Well I guess you can use checked="false". That is the html way to leave a checkbox unchecked. You can refer to http://www.w3schools.com/jsref/dom_obj_checkbox.asp.
I will recommend to use an alternative method using seaborn
which more powerful tool for data plotting. You can use seaborn scatterplot
and define colum 3 as hue
and size
.
Working code:
import pandas as pd
import seaborn as sns
import numpy as np
#creating sample data
sample_data={'col_name_1':np.random.rand(20),
'col_name_2': np.random.rand(20),'col_name_3': np.arange(20)*100}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df, hue="col_name_3",size="col_name_3")
The following solution bypasses the automatic exponentional formatting for very big and very small numbers. This is outis's solution with a bugfix: It was not working for very small negative numbers.
function numberToString(num)_x000D_
{_x000D_
let numStr = String(num);_x000D_
_x000D_
if (Math.abs(num) < 1.0)_x000D_
{_x000D_
let e = parseInt(num.toString().split('e-')[1]);_x000D_
if (e)_x000D_
{_x000D_
let negative = num < 0;_x000D_
if (negative) num *= -1_x000D_
num *= Math.pow(10, e - 1);_x000D_
numStr = '0.' + (new Array(e)).join('0') + num.toString().substring(2);_x000D_
if (negative) numStr = "-" + numStr;_x000D_
}_x000D_
}_x000D_
else_x000D_
{_x000D_
let e = parseInt(num.toString().split('+')[1]);_x000D_
if (e > 20)_x000D_
{_x000D_
e -= 20;_x000D_
num /= Math.pow(10, e);_x000D_
numStr = num.toString() + (new Array(e + 1)).join('0');_x000D_
}_x000D_
}_x000D_
_x000D_
return numStr;_x000D_
}_x000D_
_x000D_
// testing ..._x000D_
console.log(numberToString(+0.0000000000000000001));_x000D_
console.log(numberToString(-0.0000000000000000001));_x000D_
console.log(numberToString(+314564649798762418795));_x000D_
console.log(numberToString(-314564649798762418795));
_x000D_
Everyone else has answered the PUT vs PATCH. I was just going to answer what part of the title of the original question asks: "... in REST API real life scenarios". In the real world, this happened to me with internet application that had a RESTful server and a relational database with a Customer table that was "wide" (about 40 columns). I mistakenly used PUT but had assumed it was like a SQL Update command and had not filled out all the columns. Problems: 1) Some columns were optional (so blank was valid answer), 2) many columns rarely changed, 3) some columns the user was not allowed to change such as time stamp of Last Purchase Date, 4) one column was a free-form text "Comments" column that users diligently filled with half-page customer services comments like spouses name to ask about OR usual order, 5) I was working on an internet app at time and there was worry about packet size.
The disadvantage of PUT is that it forces you to send a large packet of info (all columns including the entire Comments column, even though only a few things changed) AND multi-user issue of 2+ users editing the same customer simultaneously (so last one to press Update wins). The disadvantage of PATCH is that you have to keep track on the view/screen side of what changed and have some intelligence to send only the parts that changed. Patch's multi-user issue is limited to editing the same column(s) of same customer.
You can also do something like:
SELECT COUNT(DISTINCT id + name + address) FROM mytable
+new
is equivalent to +alloc/-init
in Apple's NSObject
implementation. It is highly unlikely that this will ever change, but depending on your paranoia level, Apple's documentation for +new
appears to allow for a change of implementation (and breaking the equivalency) in the future. For this reason, because "explicit is better than implicit" and for historical continuity, the Objective-C community generally avoids +new
. You can, however, usually spot the recent Java comers to Objective-C by their dogged use of +new
.
Use the backslash \
or choose a different delimiter, ie m#.\d#
instead of /.\d/
"In Perl, you can change the / regular expression delimiter to almost any other special character if you preceed it with the letter m (for match);"
You are dividing integers then converting to float. Divide by floats instead.
As a bonus, use the awesome string formatting methods described here: http://docs.python.org/library/string.html#format-specification-mini-language
To specify a percent conversion and precision.
>>> float(1) / float(3)
[Out] 0.33333333333333331
>>> 1.0/3.0
[Out] 0.33333333333333331
>>> '{0:.0%}'.format(1.0/3.0) # use string formatting to specify precision
[Out] '33%'
>>> '{percent:.2%}'.format(percent=1.0/3.0)
[Out] '33.33%'
A great gem!
You can use the parseInt() function to convert the string to a number, e.g:
parseInt($('#elem').css('top'));
Update: (as suggested by Ben): You should give the radix too:
parseInt($('#elem').css('top'), 10);
Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).
The latest dwr (http://directwebremoting.org/dwr/index.html) has ajax file uploads, complete with examples and nice stuff for users (like progress indicators and such).
It looks pretty nifty and dwr is fairly easy to use in general so this will be pretty good as well.
I got the same issue, and it was happening because of different feature module included this component by mistake. When removed it from the other feature, it worked!
Dashboard -> [your app] -> [View Details] -> Settings -> Basic
You could use sed:
ls * | sed -e 'p;s@_.*_@_@g' | xargs -n2 mv
result:
prefix_567.png prefix_efg.png
*to do a dry-run first, replace mv
at the end with echo
Explanation:
You can do (pre-Java 8):
List<Enum> enumValues = Arrays.asList(Enum.values());
or
List<Enum> enumValues = new ArrayList<Enum>(EnumSet.allOf(Enum.class));
Using Java 8 features, you can map each constant to its name:
List<String> enumNames = Stream.of(Enum.values())
.map(Enum::name)
.collect(Collectors.toList());
I wouldn't reference the parent directly in the child objects. In my opinion the childs shouldn't know anything about the parents. This will limits the flexibility!
I would solve this with events/handlers.
public class Meter
{
private int _powerRating = 0;
private Production _production;
public Meter()
{
_production = new Production();
_production.OnRequestPowerRating += new Func<int>(delegate { return _powerRating; });
_production.DoSomething();
}
}
public class Production
{
protected int RequestPowerRating()
{
if (OnRequestPowerRating == null)
throw new Exception("OnRequestPowerRating handler is not assigned");
return OnRequestPowerRating();
}
public void DoSomething()
{
int powerRating = RequestPowerRating();
Debug.WriteLine("The parents powerrating is :" + powerRating);
}
public Func<int> OnRequestPowerRating;
}
In this case I solved it with the Func<> generic, but can be done with 'normal' functions. This why the child(Production) is totally independent from it's parent(Meter).
But! If there are too many events/handlers or you just want to pass a parent object, i would solve it with an interface:
public interface IMeter
{
int PowerRating { get; }
}
public class Meter : IMeter
{
private int _powerRating = 0;
private Production _production;
public Meter()
{
_production = new Production(this);
_production.DoSomething();
}
public int PowerRating { get { return _powerRating; } }
}
public class Production
{
private IMeter _meter;
public Production(IMeter meter)
{
_meter = meter;
}
public void DoSomething()
{
Debug.WriteLine("The parents powerrating is :" + _meter.PowerRating);
}
}
This looks pretty much the same as the solution mentions, but the interface could be defined in another assembly and can be implemented by more than 1 class.
Regards, Jeroen van Langen.
Note that the search query is now case sensitive.
When using
SELECT * FROM table WHERE `first_name` LIKE '%$search_term%'
It will match both "Larry" and "larry". With this concat_ws, it will suddenly become case sensitive!
This can be fixed by using the following query:
SELECT * FROM table WHERE UPPER(CONCAT_WS(' ', `first_name`, `last_name`) LIKE UPPER('%$search_term%')
Edit: Note that this only works on non-binary elements. See also mynameispaulie's answer.
Arulx Z's answer was exactly what I was looking for.
I'm writing an app with Navigation Drawer with recyclerview and webviews, for keeping the web browsing inside the app regardless of hyperlinks clicked (thus not launching the external web browser). For that it will suffice to put the following 2 lines of code:
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.setWebViewClient(new WebViewClient());?
exactly under your WebView statement.
Here's a example of my implemented WebView code:
public class WebView1 extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView wv = (WebView) findViewById(R.id.wv1); //webview statement
wv.setWebViewClient(new WebViewClient()); //the lines of code added
wv.setWebChromeClient(new WebChromeClient()); //same as above
wv.loadUrl("http://www.google.com");
}}
this way, every link clicked in the website will load inside your WebView. (Using Android Studio 1.2.2 with all SDK's updated)
You can request a path in this format:
/package/path/to/the/resource.ext
Even the bytes for creating the classes in memory are found this way:
my.Class -> /my/Class.class
and getResource
will give you a URL which can be used to retrieve an InputStream
.
But... I'd recommend using directly getClass().getResourceAsStream(...)
with the same argument, because it returns directly the InputStream and don't have to worry about creating a (probably complex) URL object that has to know how to create the InputStream.
In short: try using getResourceAsStream
and some constructor of ImageIcon
that uses an InputStream
as an argument.
Classloaders
Be careful if your app has many classloaders. If you have a simple standalone application (no servers or complex things) you shouldn't worry. I don't think it's the case provided ImageIcon
was capable of finding it.
Edit: classpath
getResource
is—as mattb says—for loading resources from the classpath (from your .jar or classpath directory). If you are bundling an app it's nice to have altogether, so you could include the icon file inside the jar of your app and obtain it this way.
You can also do:
NSString * query = @"SELECT * FROM foo "
@"WHERE "
@"bar = 42 "
@"AND baz = datetime() "
@"ORDER BY fizbit ASC";
As soon as the page loads, the init
function is fired and the page is redirected:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script>
function init()
{
window.location.href = "www.wherever.com";
}
</script>
</head>
<body onload="init()">
</body>
</html>
nil is an empty value bound/corresponding with an object (the id type in Objective-C). nil got no reference/address, just an empty value.
NSString *str = nil;
So nil should be used, if we are dealing with an object.
if(str==nil)
NSLog("str is empty");
Now NULL is used for non-object pointer (like a C pointer) in Objective-C. Like nil , NULL got no value nor address.
char *myChar = NULL;
struct MyStruct *dStruct = NULL;
So if there is a situation, when I need to check my struct (structure type variable) is empty or not then, I will use:
if (dStruct == NULL)
NSLog("The struct is empty");
Let’s have another example, the
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
Of key-value observing, the context should be a C pointer or an object reference. Here for the context we can not use nil; we have to use NULL.
Finally the NSNull class defines a singleton object used to represent null values in collection objects(NSArray, NSDictionary). The [NSNull null] will returns the singleton instance of NSNull. Basically [NSNull null] is a proper object.
There is no way to insert a nil object into a collection type object. Let's have an example:
NSMutableArray *check = [[NSMutableArray alloc] init];
[check addObject:[NSNull null]];
[check addObject:nil];
On the second line, we will not get any error, because it is perfectly fair to insert a NSNull object into a collection type object. On the third line, we will get "object cannot be nil" error. Because nil is not an object.
You can use Electron, it allows hybrid browserjs and nodejs.
Before, I tried to use canvas2d in nodejs, but finally I gave up. It's not supported by nodejs default, and too hard to install it (many many ... dependeces). Until I use Electron, I can easily use all my previous browserjs code, even WebGL, and pass the result value(eg. result base64 image data) to nodejs code.
The easiest way that I have found is to set the activity's theme in the AndroidManifest to android:theme="@android:style/Theme.Holo.Dialog"
.
Then in the activity's onCreate method, call getWindow().setBackgroundDrawable(new ColorDrawable(0));
.
Here is a very nice and compact way to do this, you can also change this function as your case needs:
result: 03.11.2017
//get date now function
getNowDate() {
//return string
var returnDate = "";
//get datetime now
var today = new Date();
//split
var dd = today.getDate();
var mm = today.getMonth() + 1; //because January is 0!
var yyyy = today.getFullYear();
//Interpolation date
if (dd < 10) {
returnDate += `0${dd}.`;
} else {
returnDate += `${dd}.`;
}
if (mm < 10) {
returnDate += `0${mm}.`;
} else {
returnDate += `${mm}.`;
}
returnDate += yyyy;
return returnDate;
}
For Windows, try:
NBTSTAT -A 10.100.3.104
or
ping -a 10.100.3.104
For Linux, try:
nmblookup -A 10.100.3.104
They are almost same.
try this
<iframe name="myIframe" id="myIframe" width="400px" height="400px" runat="server"></iframe>
Expose this iframe in the master page's codebehind:
public HtmlControl iframe
{
get
{
return this.myIframe;
}
}
Add the MasterType directive for the content page to strongly typed Master Page.
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits=_Default" Title="Untitled Page" %>
<%@ MasterType VirtualPath="~/MasterPage.master" %>
In code behind
protected void Page_Load(object sender, EventArgs e)
{
this.Master.iframe.Attributes.Add("src", "some.aspx");
}
For API 21 (5.0) and later you can use the CameraManager API's
try {
String desiredCameraId = null;
for(String cameraId : mCameraIDsList) {
CameraCharacteristics chars = mCameraManager.getCameraCharacteristics(cameraId);
List<CameraCharacteristics.Key<?>> keys = chars.getKeys();
try {
if(CameraCharacteristics.LENS_FACING_FRONT == chars.get(CameraCharacteristics.LENS_FACING)) {
// This is the one we want.
desiredCameraId = cameraId;
break;
}
} catch(IllegalArgumentException e) {
// This key not implemented, which is a bit of a pain. Either guess - assume the first one
// is rear, second one is front, or give up.
}
}
}
You forgot the HTTP part:
window.location.href = "http://example.com/Registration/Success/";
I found a slight alteration on what @jota3 suggested worked perfectly for me.
var intersections = array1.filter(e => array2.indexOf(e) !== -1);
Hope this helps!
I figured out that I was not generating Credentials for the right app type.
If you're using Postman to test Google oAuth 2 APIs, select
Credentials -> Add credentials -> OAuth2.0 client ID -> Web Application.
Seems like you have your path right. But what is your working directory? on command prompt run:
javac -version
this should show your java version. if it doesnt, you have not set java in path correctly.
navigate to C:
cd \
Then:
javac -sourcepath users\AccName\Desktop -d users\AccName\Desktop first.java
-sourcepath is the complete path to your .java file, -d is the path/directory you want your .class files to be, then finally the file you want compiled (first.java).
No magic involved, just subtract from the offset top of the element
$('html, body').animate({scrollTop: $('#contact').offset().top -100 }, 'slow');
var root = document.createElement("div");
root.innerHTML = "My name is <b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";
var texts = [].map.call( root.querySelectorAll("b"), function(v){
return v.textContent || v.innerText || "";
});
//["Bob", "20", "programming"]
Incase Anyone wants to implement something like this in Main class instead of Adapter class, you can use:
public void removeAt(int position) {
peopleListUser.remove(position);
friendsListRecycler.getAdapter().notifyItemRemoved(position);
friendsListRecycler.getAdapter().notifyItemRangeChanged(position, peopleListUser.size());
}
where friendsListRecycler is the Adapter name
A quick string "GOTCHA" with JSON Unmarshall which will add wrapping quotes to strings.
(example: the string value of {"first_name":" I have whitespace "}
will convert to "\" I have whitespace \""
)
Before you can trim anything, you'll need to remove the extra quotes first:
// ScrubString is a string that might contain whitespace that needs scrubbing.
type ScrubString string
// UnmarshalJSON scrubs out whitespace from a valid json string, if any.
func (s *ScrubString) UnmarshalJSON(data []byte) error {
ns := string(data)
// Make sure we don't have a blank string of "\"\"".
if len(ns) > 2 && ns[0] != '"' && ns[len(ns)] != '"' {
*s = ""
return nil
}
// Remove the added wrapping quotes.
ns, err := strconv.Unquote(ns)
if err != nil {
return err
}
// We can now trim the whitespace.
*s = ScrubString(strings.TrimSpace(ns))
return nil
}
With boundary conditions like empty sentence and very long first word. Also, it uses no language specific string api/library.
function solution(message, k) {_x000D_
if(!message){_x000D_
return ""; //when message is empty_x000D_
}_x000D_
const messageWords = message.split(" ");_x000D_
let result = messageWords[0];_x000D_
if(result.length>k){_x000D_
return ""; //when length of first word itself is greater that k_x000D_
}_x000D_
for(let i = 1; i<messageWords.length; i++){_x000D_
let next = result + " " + messageWords[i];_x000D_
_x000D_
if(next.length<=k){_x000D_
result = next;_x000D_
}else{_x000D_
break;_x000D_
}_x000D_
}_x000D_
return result;_x000D_
}_x000D_
_x000D_
console.log(solution("this is a long string i cant display", 10));
_x000D_
with open(destPath+'\\'+csvXML, 'a+') as csvFile:
writer = csv.writer(csvFile, delimiter=';', lineterminator='\r')
writer.writerows(xmlList)
The "lineterminator='\r'" permit to pass to next row, without empty row between two.
i know its a little late but i think all these answers do have some problems while i did it like below and that works perfect.
create a activity life cycle callback like this:
class ActivityLifeCycle implements ActivityLifecycleCallbacks{
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
}
Activity lastActivity;
@Override
public void onActivityResumed(Activity activity) {
//if (null == lastActivity || (activity != null && activity == lastActivity)) //use this condition instead if you want to be informed also when app has been killed or started for the first time
if (activity != null && activity == lastActivity)
{
Toast.makeText(MyApp.this, "NOW!", Toast.LENGTH_LONG).show();
}
lastActivity = activity;
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}
and just register it on your application class like below:
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifeCycle());
}
pgcrypto
ExtensionAs of Postgres 9.4, the pgcrypto
module includes the gen_random_uuid()
function. This function generates one of the random-number based Version 4 type of UUID.
Get contrib modules, if not already available.
sudo apt-get install postgresql-contrib-9.4
Use pgcrypto
module.
CREATE EXTENSION "pgcrypto";
The gen_random_uuid()
function should now available;
Example usage.
INSERT INTO items VALUES( gen_random_uuid(), 54.321, 31, 'desc 1', 31.94 ) ;
Quote from Postgres doc on uuid-ossp
module.
Note: If you only need randomly-generated (version 4) UUIDs, consider using the gen_random_uuid() function from the pgcrypto module instead.
There don't seem to be a variable which holds exactly what you want.
However, quoting the docs:
Also available,
inventory_dir
is the pathname of the directory holding Ansible’s inventory host file,inventory_file
is the pathname and the filename pointing to the Ansible’s inventory host file.playbook_dir contains the playbook base directory.
And finally,
role_path
will return the current role’s pathname (since 1.8). This will only work inside a role.
Dependent on your setup, those or the $ pwd
-based solution might be enough.
I found a way to do this (without decorators) for my specific use case.
The important part that checks for static members is IObjectClass
and using cls: IObjectClass<T>
in the createObject
method:
//------------------------
// Library
//------------------------
interface IObject {
id: number;
}
interface IObjectClass<T> {
new(): T;
table_name: string;
}
function createObject<T extends IObject>(cls: IObjectClass<T>, data:Partial<T>):T {
let obj:T = (<any>Object).assign({},
data,
{
id: 1,
table_name: cls.table_name,
}
)
return obj;
}
//------------------------
// Implementation
//------------------------
export class User implements IObject {
static table_name: string = 'user';
id: number;
name: string;
}
//------------------------
// Application
//------------------------
let user = createObject(User, {name: 'Jimmy'});
console.log(user.name);
Also you can try opensource WebRTC Media Server Kurento
Which can play RTSP video stream and send it to WebRTC or transcode to RTMP or saving on server.
We are useing it on Production for the following cases:
- WebRTC to Webrtc (many to many) - WebRTC to RTMP - RTSP to WebRTC
You use the Headers
property with a string index:
request.Headers["X-My-Custom-Header"] = "the-value";
According to MSDN, this has been available since:
https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers(v=vs.110).aspx
for future developers, i recommend, delete the index in INDEX TAB using compass... this NOT DELETE ANY document in your collection Manage Indexes
For your interest, to do the same with double
double doubleVal = 1.745;
double doubleVal2 = 0.745;
doubleVal = Math.round(doubleVal * 100 + 0.005) / 100.0;
doubleVal2 = Math.round(doubleVal2 * 100 + 0.005) / 100.0;
System.out.println("bdTest: " + doubleVal); //1.75
System.out.println("bdTest1: " + doubleVal2);//0.75
or just
double doubleVal = 1.745;
double doubleVal2 = 0.745;
System.out.printf("bdTest: %.2f%n", doubleVal);
System.out.printf("bdTest1: %.2f%n", doubleVal2);
both print
bdTest: 1.75
bdTest1: 0.75
I prefer to keep code as simple as possible. ;)
As @mshutov notes, you need to add a little more to ensure that a half value always rounds up. This is because numbers like 265.335
are a little less than they appear.
Moving the file to the main/resources directory worked.
My case was rather embarrassing: I added a typescript binding for a JS library without adding the library itself.
So if you do:
npm install --save @types/lucene
Don't forget to do:
npm install --save lucene
Kinda obvious, but I just totally forgot and that cost me quite some time.
Eventually a native :terminal
command was added to vim in 2017.
Here is an excerpt from the :terminal readme:
This feature is for running a terminal emulator in a Vim window. A job can be started connected to the terminal emulator. For example, to run a shell:
:term bash
Or to run build command:
:term make myprogram
The job runs asynchronously from Vim, the window will be updated to show output from the job, also while editing in another window.
The file you give is a shell script, not an awk program. So, try sh my.awk
.
If you want to use awk -f my.awk life.csv > life_out.cs
, then remove awk -F , '
and the last line from the file and add FS=","
in BEGIN
.
as @MikeM pointed out.
select exists(select 1 from contact where id=12)
with index on contact, it can usually reduce time cost to 1 ms.
CREATE INDEX index_contact on contact(id);
You could try this:
if(typeof(results) == "undefined") {
return 0;
} else {
return results[1] || 0;
}
Everything in one line:
get-aduser -filter * -Properties memberof | select name, @{ l="GroupMembership"; e={$_.memberof -join ";" } } | export-csv membership.csv
This expands on Paul's answer. In Pandas, indexing a DataFrame returns a reference to the initial DataFrame. Thus, changing the subset will change the initial DataFrame. Thus, you'd want to use the copy if you want to make sure the initial DataFrame shouldn't change. Consider the following code:
df = DataFrame({'x': [1,2]})
df_sub = df[0:1]
df_sub.x = -1
print(df)
You'll get:
x
0 -1
1 2
In contrast, the following leaves df unchanged:
df_sub_copy = df[0:1].copy()
df_sub_copy.x = -1
You didn't publish your code, and I suspect you do something wrong. it is possible to change the size by assigning width and height attributes using numbers:
canvasNode.width = 200; // in pixels
canvasNode.height = 100; // in pixels
At least it works for me. Make sure you don't assign strings (e.g., "2cm", "3in", or "2.5px"), and don't mess with styles.
Actually this is a publicly available knowledge — you can read all about it in the HTML canvas spec — it is very small and unusually informative. This is the whole DOM interface:
interface HTMLCanvasElement : HTMLElement {
attribute unsigned long width;
attribute unsigned long height;
DOMString toDataURL();
DOMString toDataURL(in DOMString type, [Variadic] in any args);
DOMObject getContext(in DOMString contextId);
};
As you can see it defines 2 attributes width
and height
, and both of them are unsigned long
.
jQuery: Use this as a starting point - as inspiration. I solved it like this: (this is not a perfect solution, it just aborts the last instance and is WIP code)
var singleAjax = function singleAjax_constructor(url, params) {
// remember last jQuery's get request
if (this.lastInstance) {
this.lastInstance.abort(); // triggers .always() and .fail()
this.lastInstance = false;
}
// how to use Deferred : http://api.jquery.com/category/deferred-object/
var $def = new $.Deferred();
// pass the deferrer's request handlers into the get response handlers
this.lastInstance = $.get(url, params)
.fail($def.reject) // triggers .always() and .fail()
.success($def.resolve); // triggers .always() and .done()
// return the deferrer's "control object", the promise object
return $def.promise();
}
// initiate first call
singleAjax('/ajax.php', {a: 1, b: 2})
.always(function(a,b,c) {console && console.log(a,b,c);});
// second call kills first one
singleAjax('/ajax.php', {a: 1, b: 2})
.always(function(a,b,c) {console && console.log(a,b,c);});
// here you might use .always() .fail() .success() etc.
T(N) = T(N/2) + 1
T(N) = T(N/2) + 1 = (T(N/4) + 1)+ 1
...
T(N) = T(N/N) + (1 + 1 + 1 +... + 1) = 1 + logN (base 2 log) = 1 + logN
So the time complexity of binary search is O(logN)
{=FIND("cell I want to search","list of words I want to search for")}
{=SUM(FIND($A$1:$A$100&"|";A3))}
this ensures spreadsheet will compare strings like "cellvlaue|" againts "pattern1|", "pattern2|" etc. which sorts out conflicts like pattern1="newly added", pattern2="added" (sum of all cells matching "added" would be too high, including the target values for cells matching "newly added", which would be a logical error)es6 - Symbol.iterator and generator functions:
let fibonacci = {
*[Symbol.iterator]() {
let pre = 0, cur = 1
for (;;) {
[ pre, cur ] = [ cur, pre + cur ]
yield cur
}
}
}
for (let n of fibonacci) {
if (n > 1000)
break
console.log(n)
}
Encapsulation: Wrapping code and data together into a single unit. Class
is an example of encapsulation, because it wraps the method and property.
Abstraction: Hiding internal details and showing functionality only. Abstraction focus on what the object does instead of how it does. It provides generalized view of classes.
int number = 5;
string aStringNumber = number.ToString();
Here, ToString() is abstraction. And how this mechanism number
variable converted to string and initialize into aStringNumber
is encapsulation.
Let us take a real world example of calculator. Encapsulation is the internal circuits, battery, etc., that combine to make it a calculator. Abstraction is the different buttons like on-off, clear and other buttons provided to operate it.
In WPF there is a control named Popup.
Popup myPopup = new Popup();
//(...)
myPopup.IsOpen = true;
Have you considered using Fetch Injection? I rolled an open source library called fetch-inject to handle cases like these. Here's what your loader might look like using the lib:
fetcInject([
'js/jquery-1.6.2.min.js',
'js/marquee.js',
'css/marquee.css',
'css/custom-theme/jquery-ui-1.8.16.custom.css',
'css/main.css'
]).then(() => {
'js/jquery-ui-1.8.16.custom.min.js',
'js/farinspace/jquery.imgpreload.min.js'
})
For backwards compatibility leverage feature detection and fall-back to XHR Injection or Script DOM Elements, or simply inline the tags into the page using document.write
.
private bool CheckAll()
{
if ( ....)
{
return true;
}
return false;
}
When the if-condition is false the method doesn't know what value should be returned (you probably get an error like "not all paths return a value").
As CQQL pointed out if you mean to return true when your if-condition is true you could have simply written:
private bool CheckAll()
{
return (your_condition);
}
If you have side effects, and you want to handle them before you return, the first (long) version would be required.
You can use Carbon library.
Example: Next week friday
Carbon::parse("friday next week");
Line magics are prefixed with the % character and work much like OS command-line calls: they get as an argument the rest of the line, where arguments are passed without parentheses or quotes. Cell magics are prefixed with a double %%, and they are functions that get as an argument not only the rest of the line, but also the lines below it in a separate argument.
What causes runtime error 380? Attempting to set a property of an object or control to a value that is not allowed. Look through the code that runs when your search form loads (Form_Load etc.) for any code that sets a property to something that depends on runtime values.
My other advice is to add some error handling and some logging to track down the exact line that is causing the error.
Erl
to report line numbers and find the exact line - MZTools can automatically put in line numbers for you. _
On Error Goto Handler
<routine contents>
Handler:
Err.Raise Err.Number, "(function_name)->" & Err.source, Err.Description
Returns true if comes 'y', '1', 'true', 'on'or whatever you add in similar way
boolean getValue(String value) {
return ("Y".equals(value.toUpperCase())
|| "1".equals(value.toUpperCase())
|| "TRUE".equals(value.toUpperCase())
|| "ON".equals(value.toUpperCase())
);
}
I also experienced this cmderror. After trying all the answers on here, I couldn't still figure out the problem, here is what I did:
The much more simple and logical is to do this:
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
return [[UIView alloc] initWithFrame:CGRectZero];
}
In most cases you don't want to see only the last table view cell separator. And this approach removes only the last table view cell separator, and you don't need to think about Auto Layout issues (i.e. rotating device) or hardcode values to set up separator insets.
An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.
There are different types of joins available in SQL:
INNER JOIN: returns rows when there is a match in both tables.
LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table.
RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table.
FULL JOIN: It combines the results of both left and right outer joins.
The joined table will contain all records from both the tables and fill in NULLs for missing matches on either side.
SELF JOIN: is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement.
CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more joined tables.
WE can take each first four joins in Details :
We have two tables with the following values.
TableA
id firstName lastName
.......................................
1 arun prasanth
2 ann antony
3 sruthy abc
6 new abc
TableB
id2 age Place
................
1 24 kerala
2 24 usa
3 25 ekm
5 24 chennai
....................................................................
INNER JOIN
Note :it gives the intersection of the two tables, i.e. rows they have common in TableA and TableB
Syntax
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
INNER JOIN TableB
ON TableA.id = TableB.id2;
Result Will Be
firstName lastName age Place
..............................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
LEFT JOIN
Note : will give all selected rows in TableA, plus any common selected rows in TableB.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
LEFT JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
LEFT JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
new abc NULL NULL
RIGHT JOIN
Note : will give all selected rows in TableB, plus any common selected rows in TableA.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
RIGHT JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
RIGHT JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
NULL NULL 24 chennai
FULL JOIN
Note :It will return all selected values from both tables.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
FULL JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
FULL JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
new abc NULL NULL
NULL NULL 24 chennai
Interesting Fact
For INNER joins the order doesn't matter
For (LEFT, RIGHT or FULL) OUTER joins,the order matter
Better to go check this Link it will give you interesting details about join order
This solution works in Windows 7 using Workbench. You will need Administrator privileges to do this. It creates a junction (like a shortcut) to wherever you really want to store your data
Open Workbench and select INSTANCE - Startup / Shutdown Stop the server
Install Junction Master from https://bitsum.com/junctionmaster.php
Navigate to C:\ProgramData\MySQL\MySQL Server 5.6
Right click on Data and select "MOVE and then LINK folder to ..." Accept the warning Point destination to "Your new data directory here without the quotes" Click MOVE AND LINK
Now go to "Your new data directory here without the quotes"
Right click on Data Go to the security tab Click Edit Click Add Type NETWORK SERVICE then Check Names Click OK Click the Allow Full Control checkbox and then OK
Go back to Workbench and Start the server
This method worked for me using MySQL Workbench 6.2 on Windows 7 Enterprise.
Whitespace includes space, tabs and CRLF. So an elegant and one-liner string function we can use is translate.
' hello apple'.translate(None, ' \n\t\r')
OR if you want to be thorough
import string
' hello apple'.translate(None, string.whitespace)
If anyone still wants to use jms1.1 then add the public jboss repository and maven will find it...
project->dependencies:
<dependencies>
<dependency>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
<version>1.1</version>
</dependency>
project->repositories:
<repositories>
<repository>
<id>repository.jboss.org-public</id>
<name>JBoss.org Maven repository</name>
<url>https://repository.jboss.org/nexus/content/groups/public</url>
</repository>
It works -
F:\mvn-repo-stuff>mvn verify
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building mvn-repo-stuff 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
Downloading: http://repo1.maven.org/maven2/javax/jms/jms/1.1/jms-1.1.pom
Downloaded: http://repo1.maven.org/maven2/javax/jms/jms/1.1/jms-1.1.pom (677 B at 0.8 KB/sec)
[WARNING] The artifact xml-apis:xml-apis:jar:2.0.2 has been relocated to xml-apis:xml-apis:jar:1.0.b2
Downloading: http://repo1.maven.org/maven2/javax/jms/jms/1.1/jms-1.1.jar
Downloading: https://repository.jboss.org/nexus/content/groups/public/javax/jms/jms/1.1/jms-1.1.jar
Downloaded: https://repository.jboss.org/nexus/content/groups/public/javax/jms/jms/1.1/jms-1.1.jar (26 KB at 8.5 KB/sec)
So I struggled with this and thought I was going mad, the thing is bootstrap datepicker was being implemented not jQuery so teh options were different;
$('.dateInput').datepicker({ format: 'dd/mm/yyyy'})
The following POSIX program will print the names of the files in the current directory:
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main (void)
{
DIR *dp;
struct dirent *ep;
dp = opendir ("./");
if (dp != NULL)
{
while (ep = readdir (dp))
puts (ep->d_name);
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
return 0;
}
Credit: http://www.gnu.org/software/libtool/manual/libc/Simple-Directory-Lister.html
Tested in Ubuntu 16.04.
I found that pathlib module also supports this.
from pathlib import Path
>>> Path.home()
WindowsPath('C:/Users/XXX')
Bear in mind that I speak ASFAC++B. :) I've put the most important differentiating factor first.
Garbage Collection
Garbage Collection (GC) is the single most important factor in differentiating between these languages.
While C and C++ can be used with GC, it is a bolted-on afterthought and cannot be made to work as well (the best known is here) - it has to be "conservative" which means that it cannot collect all unused memory.
C# is designed from the ground up to work on a GC platform, with standard libraries also designed that way. It makes an absolutely fundamental difference to developer productivity that has to be experienced to be believed.
There is a belief widespread among C/C++ users that GC equates with "bad performance". But this is out-of-date folklore (even the Boehm collector on C/C++ performs much better than most people expect it to). The typical fear is of "long pauses" where the program stops so the GC can do some work. But in reality these long pauses happen with non-GC programs, because they run on top of a virtual memory system, which occasionally interrupts to move data between physical memory and disk.
There is also widespread belief that GC can be replaced with shared_ptr, but it can't; the irony is that in a multi-threaded program, shared_ptr
is slower than a GC-based system.
There are environments that are so frugal that GC isn't practical - but these are increasingly rare. Cell phones typically have GC. The CLR's GC that C# typically runs on appears to be state-of-the-art.
Since adopting C# about 18 months ago I've gone through several phases of pure performance tuning with a profiler, and the GC is so efficient that it is practically invisible during the operation of the program.
GC is not a panacea, it doesn't solve all programming problems, it only really cleans up memory allocation, if you're allocating very large memory blocks then you will still need to take some care, and it is still possible to have what amounts to a memory leak in a sufficiently complex program - and yet, the effect of GC on productivity makes it a pretty close approximation to a panacea!
Undefined Behaviour
C++ is founded on the notion of undefined behaviour. That is, the language specification defines the outcome of certain narrowly defined usages of language features, and describes all other usages as causing undefined behaviour, meaning in principle that the operation could have any outcome at all (in practice this means hard-to-diagnose bugs involving apparently non-deterministic corruption of data).
Almost everything about C++ touches on undefined behaviour. Even very nice forthcoming features like lambda expressions can easily be used as convenient way to corrupt the stack (capture a local by reference, allow the lambda instance to outlive the local).
C# is founded on the principle that all possible operations should have defined behaviour. The worst that can happen is an exception is thrown. This completely changes the experience of software construction.
(There's unsafe mode, which has pointers and therefore undefined behaviour, but that is strongly discouraged for general use - think of it as analogous to embedded assembly language.)
Complexity
In terms of complexity, C++ has to be singled out, especially if we consider the very-soon-to-be standardized new version. C++ does absolutely everything it can to make itself effective, short of assuming GC, and as a result it has an awesome learning curve. The language designers excuse much of this by saying "Those features are only for library authors, not ordinary users" - but to be truly effective in any language, you need to build your code as reusable libraries. So you can't escape.
On the positive side, C++ is so complex, it's like a playground for nerds! I can assure you that you would have a lot of fun learning how it all fits together. But I can't seriously recommend it as a basis for productive new work (oh, the wasted years...) on mainstream platforms.
C keeps the language simple (simple in the sense of "the compiler is easy to write"), but this makes the coding techniques more arcane.
Note that not all new language features equate with added complexity. Some language features are described as "syntactic sugar", because they are shorthand that the compiler expands for you. This is a good way to think of a great deal of the enhancements to C# over recent years. The language standard even specifies some features by giving the translation to longhand, e.g. using
statement expands into try
/finally
.
At one point, it was possible to think of C++ templates in the same way. But they've since become so powerful that they are now form the basis of a whole separate dimension of the language, with its own enthusiastic user communities and idioms.
Libraries
The strangest thing about C and C++ is that they don't have a standard interchangeable form of pre-compiled library. Integrating someone else's code into your project is always a little fiddly, with obscure decisions to be made about how you'll be linking to it.
Also, the standard library is extremely basic - C++ has a complete set of data structures and a way of representing strings (std::string
), but that's still minimal. Is there a standard way of finding a list of files in a directory? Amazingly, no! Is there standard library support for parsing or generating XML? No. What about accessing databases? Be serious! Writing a web site back-end? Are you crazy? etc.
So you have to go hunting further afield. For XML, try Xerces. But does it use std::string
to represent strings? Of course not!
And do all these third-party libraries have their own bizarre customs for naming classes and functions? You betcha!
The situation in C# couldn't be more different; the fundamentals were in place from the start, so everything inter-operates beautifully (and because the fundamentals are supplied by the CLR, there is cross-language support).
It's not all perfect; generics should have been in place from the start but wasn't, which does leave a visible scar on some older libraries; but it is usually trivial to fix this externally. Also a number of popular libraries are ported from Java, which isn't as good a fit as it first appears.
Closures (Anonymous Methods with Local Variable Capture)
Java and C are practically the last remaining mainstream languages to lack closures, and libraries can be designed and used much more neatly with them than without (this is one reason why ported Java libraries sometimes seem clunky to a C# user).
The amusing thing about C++ is that its standard library was designed as if closures were available in the language (container types, <algorithm>
, <functional>
). Then ten years went by, and now they're finally being added! They will have a huge impact (although, as noted above, they leak underfined behaviour).
C# and JavaScript are the most widely used languages in which closures are "idiomatically established". (The major difference between those languages being that C# is statically typed while JavaScript is dynamically typed).
Platform Support
I've put this last only because it doesn't appear to differentiate these languages as much as you might think. All these languages can run on multiple OSes and machine architectures. C is the most widely-supported, then C++, and finally C# (although C# can be used on most major platforms thanks to an open source implementation called Mono).
My experience of porting C++ programs between Windows and various Unix flavours was unpleasant. I've never tried porting anything very complex in C# to Mono, so I can't comment on that.
If you are having issues when using "type": "module"
in package.json
(described in https://github.com/TypeStrong/ts-node/issues/1007) use the following config:
{
"watch": ["src"],
"ext": "ts,json",
"ignore": ["src/**/*.spec.ts"],
"exec": "node --loader ts-node/esm --experimental-specifier-resolution ./src/index.ts"
}
or in the command line
nodemon --watch "src/**" --ext "ts,json" --ignore "src/**/*.spec.ts" --exec "node --loader ts-node/esm --experimental-specifier-resolution src/index.ts"
It works fine with the object literal notation:
var map = { key : { "aaa", "rrr" },
key2: { "bbb", "ppp" } // trailing comma leads to syntax error in IE!
}
Btw, the common way to instantiate arrays
var array = [];
// directly with values:
var array = [ "val1", "val2", 3 /*numbers may be unquoted*/, 5, "val5" ];
and objects
var object = {};
Also you can do either:
obj.property // this is prefered but you can also do
obj["property"] // this is the way to go when you have the keyname stored in a var
var key = "property";
obj[key] // is the same like obj.property
Simply install a higher version of Node. As till Node v10 es6 is not supported. You need to disable a few flags or use
class HashMap:
def __init__(self):
self.size = 64
self.map = [None] * self.size
def _get_hash(self, key):
hash = 0
for char in str(key):
hash += ord(char)
return hash % self.size
def add(self, key, value):
key_hash = self._get_hash(key)
key_value = [key, value]
if self.map[key_hash] is None:
self.map[key_hash] = list([key_value])
return True
else:
for pair in self.map[key_hash]:
if pair[0] == key:
pair[1] = value
return True
else:
self.map[key_hash].append(list([key_value]))
return True
def get(self, key):
key_hash = self._get_hash(key)
if self.map[key_hash] is not None:
for pair in self.map[key_hash]:
if pair[0] == key:
return pair[1]
return None
def delete(self, key):
key_hash = self._get_hash(key)
if self.map[key_hash] is None :
return False
for i in range(0, len(self.map[key_hash])):
if self.map[key_hash][i][0] == key:
self.map[key_hash].pop(i)
return True
def print(self):
print('---Phonebook---')
for item in self.map:
if item is not None:
print(str(item))
h = HashMap()
var string = 123 (is string),
parseInt(parameter is string);
var string = '123';
var int= parseInt(string );
console.log(int); //Output will be 123.
I thought perf stat
is what you need.
It shows a specific usage of a process when you specify a --cpu=list
option. Here is an example of monitoring cpu usage of building a project using perf stat --cpu=0-7 --no-aggr -- make all -j
command. The output is:
CPU0 119254.719293 task-clock (msec) # 1.000 CPUs utilized (100.00%)
CPU1 119254.724776 task-clock (msec) # 1.000 CPUs utilized (100.00%)
CPU2 119254.724179 task-clock (msec) # 1.000 CPUs utilized (100.00%)
CPU3 119254.720833 task-clock (msec) # 1.000 CPUs utilized (100.00%)
CPU4 119254.714109 task-clock (msec) # 1.000 CPUs utilized (100.00%)
CPU5 119254.727721 task-clock (msec) # 1.000 CPUs utilized (100.00%)
CPU6 119254.723447 task-clock (msec) # 1.000 CPUs utilized (100.00%)
CPU7 119254.722418 task-clock (msec) # 1.000 CPUs utilized (100.00%)
CPU0 8,108 context-switches # 0.068 K/sec (100.00%)
CPU1 26,494 context-switches (100.00%)
CPU2 10,193 context-switches (100.00%)
CPU3 12,298 context-switches (100.00%)
CPU4 16,179 context-switches (100.00%)
CPU5 57,389 context-switches (100.00%)
CPU6 8,485 context-switches (100.00%)
CPU7 10,845 context-switches (100.00%)
CPU0 167 cpu-migrations # 0.001 K/sec (100.00%)
CPU1 80 cpu-migrations (100.00%)
CPU2 165 cpu-migrations (100.00%)
CPU3 139 cpu-migrations (100.00%)
CPU4 136 cpu-migrations (100.00%)
CPU5 175 cpu-migrations (100.00%)
CPU6 256 cpu-migrations (100.00%)
CPU7 195 cpu-migrations (100.00%)
The left column is the specific CPU index and the right most column is the usage of the CPU. If you don't specify the --no-aggr
option, the result will aggregated together. The --pid=pid
option will help if you want to monitor a running process.
Try -a --per-core
or -a perf-socket
too, which will present more classified information.
More about usage of perf stat
can be seen in this tutorial: perf cpu statistic, also perf help stat
will help on the meaning of the options.
I use this guard gem to auto-run my test. It execute test after create or update operations on test file.
https://github.com/guard/guard-test
or usually you can run using following command
rspec spec/controllers/groups_controller_spec.rb
By default Ansible will attempt to run on all hosts in parallel. See these Ansible docs for details. You can also use the serial
parameter to limit the number of parallel hosts you want to be processed at any given time, so if you want to have a playbook run on just one host at a time you can specify serial:1
, etc.
Ansible is designed so that each task will be run on all hosts before continuing on to the next task. So if you have 3 tasks it will ensure task 1 runs on all your hosts first, then task 2 is run, then task 3 is run. See this section of the Ansible docs for more details on this.
Seba Illingworth's code, In case you need time in your file name (it gives 2014-02-21_1035)
echo off
cls
echo -- BACKUP DATABASE --
set /p DATABASENAME=Enter database name:
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
:: filename format Name-Date (eg MyDatabase-2009.5.19.bak)
set DATESTAMP=%mydate%_%mytime%
set BACKUPFILENAME=%CD%\%DATABASENAME%-%DATESTAMP%.bak
set SERVERNAME=.
echo.
sqlcmd -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = N'%BACKUPFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%DATABASENAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
pause
The CBO builds a decision tree, estimating the costs of each possible execution path available per query. The costs are set by the CPU_cost or I/O_cost parameter set on the instance. And the CBO estimates the costs, as best it can with the existing statistics of the tables and indexes that the query will use. You should not tune your query based on cost alone. Cost allows you to understand WHY the optimizer is doing what it does. Without cost you could figure out why the optimizer chose the plan it did. Lower cost does not mean a faster query. There are cases where this is true and there will be cases where this is wrong. Cost is based on your table stats and if they are wrong the cost is going to be wrong.
When tuning your query, you should take a look at the cardinality and the number of rows of each step. Do they make sense? Is the cardinality the optimizer is assuming correct? Is the rows being return reasonable. If the information present is wrong then its very likely the optimizer doesn't have the proper information it needs to make the right decision. This could be due to stale or missing statistics on the table and index as well as cpu-stats. Its best to have stats updated when tuning a query to get the most out of the optimizer. Knowing your schema is also of great help when tuning. Knowing when the optimizer chose a really bad decision and pointing it in the correct path with a small hint can save a load of time.
If you want to use the font to draw with graphics2d or similar, this works:
InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream("roboto-bold.ttf")
Font font = Font.createFont(Font.TRUETYPE_FONT, stream).deriveFont(48f)
$url = 'http://legis.senado.leg.br/dadosabertos/materia/tramitando';
$xml = file_get_contents("xml->{$url}");
$xml = simplexml_load_file($url);
How about:
DELETE guide_category
WHERE id_guide_category IN (
SELECT id_guide_category
FROM guide_category AS gc
LEFT JOIN guide AS g
ON g.id_guide = gc.id_guide
WHERE g.title IS NULL
)
I'm pretty sure you can do explicit casting here.
foo f = (foo)value;
So long as you say the enum inherits(?) from int, which you have.
enum foo : int
EDIT Yes it turns out that by default, an enums underlying type is int. You can however use any integral type except char.
You can also cast from a value that's not in the enum, producing an invalid enum. I suspect this works by just changing the type of the reference and not actually changing the value in memory.
enum (C# Reference)
Enumeration Types (C# Programming Guide)
In order to have a popop with Chrome 14+, you need to do the following :
jQuery(window).bind('beforeunload', function(){
return 'my text';
});
The user will be asked if he want to stay or leave.
var otherInput = $(this).closest('.row').find('.inputQty');
That goes up to a row level, then back down to .inputQty
.
If you are working with devtools
try to save the files with:
devtools::use_data(x, internal = TRUE)
Then, delete all files saved previously.
From doc:
internal If FALSE, saves each object in individual .rda files in the data directory. These are available whenever the package is loaded. If TRUE, stores all objects in a single R/sysdata.rda file. These objects are only available within the package.
You should let the user do that if they want (and you can't stop them anyway).
Your problem is that you need to know that they have and then assume that they mean OK, not cancel. Replace confirm(x)
with myConfirm(x)
:
function myConfirm(message) {
var start = Number(new Date());
var result = confirm(message);
var end = Number(new Date());
return (end<(start+10)||result==true);
}
The MSDN Documentation states that there is no guarantee of any order on the return values. You have to use the Sort() method.
function isPrevDate() {
alert("startDate is " + Startdate);
if(Startdate.length != 0 && Startdate !='') {
var start_date = Startdate.split('-');
alert("Input date: "+ start_date);
start_date=start_date[1]+"/"+start_date[2]+"/"+start_date[0];
alert("start date arrray format " + start_date);
var a = new Date(start_date);
//alert("The date is a" +a);
var today = new Date();
var day = today.getDate();
var mon = today.getMonth()+1;
var year = today.getFullYear();
today = (mon+"/"+day+"/"+year);
//alert(today);
var today = new Date(today);
alert("Today: "+today.getTime());
alert("a : "+a.getTime());
if(today.getTime() > a.getTime() )
{
alert("Please select Start date in range");
return false;
} else {
return true;
}
}
}
I have found this useful more than once when the DataGrid is bound to a table.
DataTable dt = (DataTable)dgvData.DataSource;
DataRow row = dt.NewRow();
foreach (var something in something)
{
row["ColumnName"] = something ;
}
dt.Rows.Add(row);
dgvData.DataSource = dt;
Still another solution:
timezone('utc', now())
+1 way, that works in ksh, dash, etc: use printf to insert TAB:
grep "$(printf 'BEGIN\tEND')" testfile.txt
Use either auto-fill
or auto-fit
as the first argument of the repeat()
notation.
<auto-repeat>
variant of the repeat()
notation:
repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
auto-fill
When
auto-fill
is given as the repetition number, if the grid container has a definite size or max size in the relevant axis, then the number of repetitions is the largest possible positive integer that does not cause the grid to overflow its grid container.
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fill, 186px);
}
.grid>* {
background-color: green;
height: 200px;
}
_x000D_
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
_x000D_
The grid will repeat as many tracks as possible without overflowing its container.
In this case, given the example above (see image), only 5 tracks can fit the grid-container without overflowing. There are only 4 items in our grid, so a fifth one is created as an empty track within the remaining space.
The rest of the remaining space, track #6, ends the explicit grid. This means there was not enough space to place another track.
auto-fit
The
auto-fit
keyword behaves the same asauto-fill
, except that after grid item placement any empty repeated tracks are collapsed.
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fit, 186px);
}
.grid>* {
background-color: green;
height: 200px;
}
_x000D_
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
_x000D_
The grid will still repeat as many tracks as possible without overflowing its container, but the empty tracks will be collapsed to 0
.
A collapsed track is treated as having a fixed track sizing function of 0px
.
Unlike the auto-fill
image example, the empty fifth track is collapsed, ending the explicit grid right after the 4th item.
auto-fill
vs auto-fit
The difference between the two is noticeable when the minmax()
function is used.
Use minmax(186px, 1fr)
to range the items from 186px
to a fraction of the leftover space in the grid container.
When using auto-fill
, the items will grow once there is no space to place empty tracks.
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));
}
.grid>* {
background-color: green;
height: 200px;
}
_x000D_
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
_x000D_
When using auto-fit
, the items will grow to fill the remaining space because all the empty tracks will be collapsed to 0px
.
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fit, minmax(186px, 1fr));
}
.grid>* {
background-color: green;
height: 200px;
}
_x000D_
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
_x000D_
Playground:
Inspecting auto-fill tracks
Inspecting auto-fit tracks
Surprised no one posted this solution
.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>
</title>
</head>
<body>
<script>
var list = [100,33,45,54,9,12,80,100];
var newObj = {};
var newArr = [];
for(var i=0; i<list.length; i++){
newObj[list[i]] = i;
}
for(var j in newObj){
newArr.push(j);
}
console.log(newArr);
</script>
</body>
</html>
In this case that you know that you have all items in the first place on array you can parse the string to JArray and then parse the first item using JObject.Parse
var jsonArrayString = @"
[
{
""country"": ""India"",
""city"": ""Mall Road, Gurgaon"",
},
{
""country"": ""India"",
""city"": ""Mall Road, Kanpur"",
}
]";
JArray jsonArray = JArray.Parse(jsonArrayString);
dynamic data = JObject.Parse(jsonArray[0].ToString());
For some time now, you can also only rely on the data.table
package and its IDate
class plus associated functions. (Check ?as.IDate()
). So, no need to additionally install lubridate
.
require(data.table)
some_date <- c("01/02/1979", "03/04/1980")
month(as.IDate(some_date, '%d/%m/%Y')) # all data.table functions
To start your node in PST time zone , use following command in ubuntu.
TZ=\"/usr/share/zoneinfo/GMT+0\" && export TZ && npm start &
Then You can refer Date Library to get the custom calculation date and time functions in node.
To use it client side refer this link, download index.js and assertHelper.js and include that in your HTML.
<script src="assertHelper.js"></script>
<script type="text/javascript" src="index.js"></script>
$( document ).ready(function() {
DateLibrary.getDayOfWeek(new Date("2015-06-15"),{operationType:"Day_of_Week"}); // Output : Monday
}
You can use different functions as given in examples to get custom dates.
If first day of week is Sunday, what day will be on 15th June 2015.
DateLibrary.getDayOfWeek(new Date("2015-06-15"),
{operationType:"Day_Number_of_Week",
startDayOfWeek:"Sunday"}) // Output : 1
If first day of week is Tuesday, what week number in year will be follow in 15th June 2015 as one of the date.
DateLibrary.getWeekNumber(new Date("2015-06-15"),
{operationType:"Week_of_Year",
startDayOfWeek:"Tuesday"}) // Output : 24
Refer other functions to fulfill your custom date requirements.
After each case statement require break or goto statement even if it is a default case.
AFAIK, the browser (at least Firefox) requests every resource as soon as it parses it. If it encounters an img tag it will request that image as soon as the img tag has been parsed. And that can be even before it has received the totality of the HTML document... that is it could still be downloading the HTML document when that happens.
For Firefox, there are browser queues that apply, depending on how they are set in about:config. For example it will not attempt to download more then 8 files at once from the same server... the additional requests will be queued. I think there are per-domain limits, per proxy limits, and other stuff, which are documented on the Mozilla website and can be set in about:config. I read somewhere that IE has no such limits.
The jQuery ready event is fired as soon as the main HTML document has been downloaded and it's DOM parsed. Then the load event is fired once all linked resources (CSS, images, etc.) have been downloaded and parsed as well. It is made clear in the jQuery documentation.
If you want to control the order in which all that is loaded, I believe the most reliable way to do it is through JavaScript.
You can do this with a custom action. You can add a refrence to your custom action under <InstallExecuteSequence>
:
<InstallExecuteSequence>
...
<Custom Action="FileCleaner" After='InstallFinalize'>
Installed AND NOT UPGRADINGPRODUCTCODE</Custom>
Then you will also have to define your Action under <Product>
:
<Product>
...
<CustomAction Id='FileCleaner' BinaryKey='FileCleanerEXE'
ExeCommand='' Return='asyncNoWait' />
Where FileCleanerEXE is a binary (in my case a little c++ program that does the custom action) which is also defined under <Product>
:
<Product>
...
<Binary Id="FileCleanerEXE" SourceFile="path\to\fileCleaner.exe" />
The real trick to this is the Installed AND NOT UPGRADINGPRODUCTCODE
condition on the Custom Action, with out that your action will get run on every upgrade (since an upgrade is really an uninstall then reinstall). Which if you are deleting files is probably not want you want during upgrading.
On a side note: I recommend going through the trouble of using something like C++ program to do the action, instead of a batch script because of the power and control it provides -- and you can prevent the "cmd prompt" window from flashing while your installer runs.
You need to use the -F
option:
-F/--form <name=content> Specify HTTP multipart POST data (H)
Try this:
curl \
-F "userid=1" \
-F "filecomment=This is an image file" \
-F "image=@/home/user1/Desktop/test.jpg" \
localhost/uploader.php
If you are using a version of jQuery that is less than version 1.8 you can use the $('.class').size() which takes zero parameters. See documentation for more information on .size() method.
However if you are using (or plan to upgrade) to 1.8 or greater you can use $('.class').length property. See documentation for more information on .length property.
You should look at the members of the thrown exception, particularly .Message
and .InnerException
.
I would also see whether or not the documentation for InvokeMethod tells you whether it throws some more specialized Exception class than Exception - such as the Win32Exception suggested by @Preet. Catching and just looking at the Exception base class may not be particularly useful.
I don't see this answer already posted, so I'll throw this one into the mix too. This is similar to Jeff's answer with the half-width Hangul space.
var a = 1;_x000D_
var a = 2;_x000D_
var ? = 3;_x000D_
if(a == 1 && a == 2 && ? == 3) {_x000D_
console.log("Why hello there!")_x000D_
}
_x000D_
You might notice a slight discrepancy with the second one, but the first and third are identical to the naked eye. All 3 are distinct characters:
a
- Latin lower case A
a
- Full Width Latin lower case A
?
- Cyrillic lower case A
The generic term for this is "homoglyphs": different unicode characters that look the same. Typically hard to get three that are utterly indistinguishable, but in some cases you can get lucky. A, ?, ?, and ? would work better (Latin-A, Greek Alpha, Cyrillic-A, and Cherokee-A respectively; unfortunately the Greek and Cherokee lower-case letters are too different from the Latin a
: a
,?
, and so doesn't help with the above snippet).
There's an entire class of Homoglyph Attacks out there, most commonly in fake domain names (eg. wikipedi?.org
(Cyrillic) vs wikipedia.org
(Latin)), but it can show up in code as well; typically referred to as being underhanded (as mentioned in a comment, [underhanded] questions are now off-topic on PPCG, but used to be a type of challenge where these sorts of things would show up). I used this website to find the homoglyphs used for this answer.
Actually there are 3 places where gradle.properties
can be placed:
GRADLE_USER_HOME
environment variable, which if not set defaults to USER_HOME/.gradlemyProject2
in your case)myProject
)Gradle looks for gradle.properties
in all these places while giving precedence to properties definition based on the order above. So for example, for a property defined in gradle user home directory (#1) and the sub-project (#2) its value will be taken from gradle user home directory (#1).
You can find more details about it in gradle documentation here.
You can use inline assembly for the function call. (in this code I assume the arguments are characters).
void format_string(char *fmt, ...);
void debug_print(int dbg_level, int numOfArgs, char *fmt, ...)
{
va_list argumentsToPass;
va_start(argumentsToPass, fmt);
char *list = new char[numOfArgs];
for(int n = 0; n < numOfArgs; n++)
list[n] = va_arg(argumentsToPass, char);
va_end(argumentsToPass);
for(int n = numOfArgs - 1; n >= 0; n--)
{
char next;
next = list[n];
__asm push next;
}
__asm push fmt;
__asm call format_string;
fprintf(stdout, fmt);
}
For any PWA application using angular you can put the code to check if browser is supported or not in body section of index.html -
<body>
<div id="browser"></div>
<script>
var operabrowser = true;
operabrowser = (navigator.userAgent.indexOf('Opera Mini') > -1);
if (operabrowser) {
txt = "<p>Browser not supported use different browser...</p>";
document.getElementById("browser").innerHTML = txt;
}
</script>
</body>
For Angular 2+ to get the offset of the current element (this.el.nativeElement is equvalent of $(this) in jquery):
export class MyComponent implements OnInit {
constructor(private el: ElementRef) {}
ngOnInit() {
//This is the important line you can use in your function in the code
//--------------------------------------------------------------------------
let offset = this.el.nativeElement.getBoundingClientRect().top;
//--------------------------------------------------------------------------
console.log(offset);
}
}
You will then be able to push it to the remote repository, for example if that is your way of keeping a copy (backup) and making sure nothing gets lost.
You can fetch the remote branch to have a local copy and examine the differences between (i) what the remote had (with the old branch name) and (ii) what you have (with the new branch name), and decide what to do. Since you weren't aware of the remote's differences in the first place (hence the problem), simply merging or forcing changes somewhere is far too brutal.
Look at the differences, pick which branch you want to work on, cherry pick changes you want from the other branch, or revert changes you don't want on the branch you've got etc.
Then you should be in a position to decide whether you want to force your clean version onto the remote, or add new changes, or whatever.
The iframe element.
<iframe src="name.html"></iframe>
But content that you way to have appear on multiple pages is better handled using templates.
Well, if you use cout you can just write the integer directly to it, as in
std::cout << text << i;
The C++ way of converting all kinds of objects to strings is through string streams. If you don't have one handy, just create one.
#include <sstream>
std::ostringstream oss;
oss << text << i;
std::cout << oss.str();
Alternatively, you can just convert the integer and append it to the string.
oss << i;
text += oss.str();
Finally, the Boost libraries provide boost::lexical_cast
, which wraps around the stringstream conversion with a syntax like the built-in type casts.
#include <boost/lexical_cast.hpp>
text += boost::lexical_cast<std::string>(i);
This also works the other way around, i.e. to parse strings.
Well, this question is asked many times before, and the short typical answer is: It cannot be done by pure CSS. It's in the name: Cascading Style Sheets only supports styling in cascading direction, not up.
But in most circumstances where this effect is wished, like in the given example, there still is the possibility to use these cascading characteristics to reach the desired effect. Consider this pseudo markup:
<parent>
<sibling></sibling>
<child></child>
</parent>
The trick is to give the sibling the same size and position as the parent and to style the sibling instead of the parent. This will look like the parent is styled!
Now, how to style the sibling?
When the child is hovered, the parent is too, but the sibling is not. The same goes for the sibling. This concludes in three possible CSS selector paths for styling the sibling:
parent sibling { }
parent sibling:hover { }
parent:hover sibling { }
These different paths allow for some nice possibilities. For instance, unleashing this trick on the example in the question results in this fiddle:
div {position: relative}
div:hover {background: salmon}
div p:hover {background: white}
div p {padding-bottom: 26px}
div button {position: absolute; bottom: 0}
Obviously, in most cases this trick depends on the use of absolute positioning to give the sibling the same size as the parent, ánd still let the child appear within the parent.
Sometimes it is necessary to use a more qualified selector path in order to select a specific element, as shown in this fiddle which implements the trick multiple times in a tree menu. Quite nice really.
To make more than one element fade in/out sequentially such as 5 elements fade each 4s,
1- make unique animation for each element with animation-duration
equal to [ 4s (duration for each element) * 5 (number of elements) ] = 20s
animation-name: anim1 , anim2, anim3 ...
animation-duration : 20s, 20s, 20s ...
2- get animation keyframe for each element.
100% (keyframes percentage) / 5 (elements) = 20% (frame for each element)
3- define starting and ending point for each animation:
each animation has 20% frame length and @keyframes percentage always starts from 0%, so first animation will start from 0% and end in his frame(20%), and each next animation will starts from previous animation ending point and end when it reach his frame (+20% ),
@keyframes animation1 { 0% {}, 20% {}}
@keyframes animation2 { 20% {}, 40% {}}
@keyframes animation3 { 40% {}, 60% {}}
and so on
now we need to make each animation fade in from 0 to 1 opacity and fade out from 1 to 0,
so we will add another 2 points (steps) for each animation after starting and before ending point to handle the full opacity(1)
http://codepen.io/El-Oz/pen/WwPPZQ
.slide1 {
animation: fadeInOut1 24s ease reverse forwards infinite
}
.slide2 {
animation: fadeInOut2 24s ease reverse forwards infinite
}
.slide3 {
animation: fadeInOut3 24s ease reverse forwards infinite
}
.slide4 {
animation: fadeInOut4 24s ease reverse forwards infinite
}
.slide5 {
animation: fadeInOut5 24s ease reverse forwards infinite
}
.slide6 {
animation: fadeInOut6 24s ease reverse forwards infinite
}
@keyframes fadeInOut1 {
0% { opacity: 0 }
1% { opacity: 1 }
14% {opacity: 1 }
16% { opacity: 0 }
}
@keyframes fadeInOut2 {
0% { opacity: 0 }
14% {opacity: 0 }
16% { opacity: 1 }
30% { opacity: 1 }
33% { opacity: 0 }
}
@keyframes fadeInOut3 {
0% { opacity: 0 }
30% {opacity: 0 }
33% {opacity: 1 }
46% { opacity: 1 }
48% { opacity: 0 }
}
@keyframes fadeInOut4 {
0% { opacity: 0 }
46% { opacity: 0 }
48% { opacity: 1 }
64% { opacity: 1 }
65% { opacity: 0 }
}
@keyframes fadeInOut5 {
0% { opacity: 0 }
64% { opacity: 0 }
66% { opacity: 1 }
80% { opacity: 1 }
83% { opacity: 0 }
}
@keyframes fadeInOut6 {
80% { opacity: 0 }
83% { opacity: 1 }
99% { opacity: 1 }
100% { opacity: 0 }
}
{
InputStream is = HTTPClient.get(url);
InputStreamReader reader = new InputStreamReader(is);
JSONTokener tokenizer = new JSONTokener(reader);
JSONObject jsonObject = new JSONObject(tokenizer);
}
try this:
select convert (date ,getdate())
or
select CAST (getdate() as DATE)
or
select convert(varchar(10), getdate(),121)
I think you can find it usefull
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-two-datasources
It shows how to define multiple datasources & assign one of them as primary.
Here is a rather full example, also contains distributes transactions - if you need it.
What you need is to create 2 configuration classes, separate the model/repository packages etc to make the config easy.
Also, in above example, it creates the data sources manually. You can avoid this using the method on spring doc, with @ConfigurationProperties annotation. Here is an example of this:
http://xantorohara.blogspot.com.tr/2013/11/spring-boot-jdbc-with-multiple.html
Hope these helps.
I had the same problem and found out that you have to escape spaces in the extra:
adb shell am broadcast -a com.whereismywifeserver.intent.TEST --es sms_body "test\ from\ adb"
So instead of "test from adb" it should be "test\ from\ adb"
Here are two ways:
In HTML:
<div class="ics">⛱</div>
This will result into ⛱
In Css:
.ics::before {content: "\9969;"}
with HTML code <div class="ics"></div>
This also results in ⛱
osx could be using launchctl to launch mysql. Try this:
sudo launchctl unload -w /Library/LaunchDaemons/com.mysql.mysqld.plist
try the following extension
extension UIView {
func addTapGesture(action : @escaping ()->Void ){
let tap = MyTapGestureRecognizer(target: self , action: #selector(self.handleTap(_:)))
tap.action = action
tap.numberOfTapsRequired = 1
self.addGestureRecognizer(tap)
self.isUserInteractionEnabled = true
}
@objc func handleTap(_ sender: MyTapGestureRecognizer) {
sender.action!()
}
}
class MyTapGestureRecognizer: UITapGestureRecognizer {
var action : (()->Void)? = nil
}
and then use it :
submitBtn.addTapGesture {
//your code
}
you can even use it for cell
cell.addTapGesture {
//your code
}
Often there are questions about the java settings in vsCode
. This is a big question and can involve advanced user knowledge to accmplish. But there is simple way to get the existing java settings from vsCode
and copy these setting for use on another PC. This post is using recent versions of vsCode and JDK in mid-December 2020.
There are several screen shots (below) that accompany this post which should provide enough information for the visual learners.
First things first, open vsCode
and either open an existing java folder-file or create a new java file in vsCode
. Then look at the lower right corner of vsCode
(on the blue command bar). The vsCode
should be displaying an icon showing the version of the Java Standard Edition
( Java SE ) being used. The version being on this PC today is JavaSE-15. (link 1)
Click on that icon (JAVASE-15
) which then opens a new window named "java.configuration.runtimes
". There should be two tabs below this name: User
and Workspace
. Below these tabs is a link named, "Edit in settings.json
". Click on that link. (link 2)
Two json
files should then open: Default settings
and settings.json
. This post only focuses on the "settings.json
" file. The settings.json
file shows various settings used for coding different programming languages (Python, R, and java). Near the bottom of the settings.json
file shows the settings this User uses in vsCode
for programming java.
These java settings are the settings that can be "backed up" - meaning these settings get copied and pasted to another PC for creating a java programming environment similar to the java programming environment on this PC. (link 3)
^((http(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.(jpg|png|gif))
See ?merge
:
the name "row.names" or the number 0 specifies the row names.
Example:
R> de <- merge(d, e, by=0, all=TRUE) # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0 # replace NA values
R> de
Row.names a b c d e f g h i j k l m n o p q r s
1 1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2 2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 0 0 0 0 0 0 0 0 0
3 3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 21 22 23 24 25 26 27 28 29
t
1 20
2 0
3 30
Use extend to add a list comprehension to the end.
l.extend([x for i in range(100)])
See the Python docs for more information.
Since version 3.0 of Jquery you might get an error
TypeError: url.indexOf is not a function
Which can be easily fix by doing
$('#iframe').on('load', function() {
alert('frame has (re)loaded ');
});
The best option: os.system('pause')
<-- this will actually display a message saying 'press any key to continue' whereas adding just raw_input('')
will print no message, just the cursor will be available.
not related to answer:
os.system("some cmd command")
is a really great command as the command can execute any batch file/cmd commands.
Update: this literally answers the question asked, but I think KurzedMetal's answer is really what you want.
Assuming that:
master
master
in origin
.... you could do:
# Do a pull as usual, but don't commit the result:
git pull --no-commit
# Overwrite config/config.php with the version that was there before the merge
# and also stage that version:
git checkout HEAD config/config.php
# Create the commit:
git commit -F .git/MERGE_MSG
You could create an alias for that if you need to do it frequently. Note that if you have uncommitted changes to config/config.php
, this would throw them away.
Check the eclipse.ini
file and make sure there is no -vm
option there that is pointing to a non existing java install now. You can delete the option to let Eclipse figure out what java install to use or change it so it's pointing to the new install.
So far this has been the most helpful source of information regarding this I could find. Apparently the numbers do NOT reperesent load average in %: http://forum.xda-developers.com/showthread.php?t=1495763
I know this question is ancient and has an accepted answer, but I found a better solution to the problem. I am posting it here so I don't create a duplicate question, and the solution is still available to others.
Switch the order of the elements. Use the :before
pseudo-element for the content that should be underneath, and adjust margins to compensate. The margin cleanup can be messy, but the desired z-index
will be preserved.
I've tested this with IE8 and FF3.6 successfully.
You could use the function that changes the text of span1 to change the text of the others.
As a work around, if you really want it to have a change
event, then don't asign text to span 1. Instead asign an input variable in jQuery, write a change event to it, and whever ur changing the text of span1 .. instead change the value of your input variable, thus firing change event, like so:
var spanChange = $("<input />");
function someFuncToCalculateAndSetTextForSpan1() {
// do work
spanChange.val($newText).change();
};
$(function() {
spanChange.change(function(e) {
var $val = $(this).val(),
$newVal = some*calc-$val;
$("#span1").text($val);
$("#spanWhatever").text($newVal);
});
});
Though I really feel this "work-around", while useful in some aspects of creating a simple change event, is very overextended, and you'd best be making the changes to other spans at the same time you change span1.
Just look at this solution, make sure you've turned access on to less secure apps on your google account :javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25
In Python2, print
was a keyword which introduced a statement:
print "Hi"
In Python3, print
is a function which may be invoked:
print ("Hi")
In both versions, %
is an operator which requires a string on the left-hand side and a value or a tuple of values or a mapping object (like dict
) on the right-hand side.
So, your line ought to look like this:
print("a=%d,b=%d" % (f(x,n),g(x,n)))
Also, the recommendation for Python3 and newer is to use {}
-style formatting instead of %
-style formatting:
print('a={:d}, b={:d}'.format(f(x,n),g(x,n)))
Python 3.6 introduces yet another string-formatting paradigm: f-strings.
print(f'a={f(x,n):d}, b={g(x,n):d}')
$matches = array();
preg_match('/id=([0-9]+)\?/', $url, $matches);
This is safe for if the format changes. slandau's answer won't work if you ever have any other numbers in the URL.
IE 7 and previous versions sent the full path of the uploaded file to the server related to the input type="file"
field. Firefox and other modern browsers consider this to be a security flaw and do not. However, this appears to be have been fixed in IE 8.
Perhaps you should instead evaluate why you need the full path to the file as it was located on the client's system. I think it is really superfluous information that should never be posted at all. All you should be concerned with the is the file name so that you can save the file without making changes to the name.
Remove the library from your Podfile
Run pod install
on the terminal
You can't select a sheet in a non-active workbook.
You must first activate the workbook, then you can select the sheet.
workbooks("A").activate
workbooks("A").worksheets("B").select
When you use Activate it automatically activates the workbook.
Note you can select >1 sheet in a workbook:
activeworkbook.sheets(array("sheet1","sheet3")).select
but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.
I know this question is old. But anyone looking to do it today here you go.
div.floatablediv{_x000D_
-webkit-column-break-inside: avoid;_x000D_
-moz-column-break-inside: avoid;_x000D_
column-break-inside: avoid;_x000D_
}_x000D_
div.floatcontainer{_x000D_
-webkit-column-count: 2;_x000D_
-webkit-column-gap: 1px;_x000D_
-webkit-column-fill: auto;_x000D_
-moz-column-count: 2;_x000D_
-moz-column-gap: 1px;_x000D_
-moz-column-fill: auto;_x000D_
column-count: 2;_x000D_
column-gap: 1px;_x000D_
column-fill: auto;_x000D_
}
_x000D_
<div style="background-color: #ccc; width: 100px;" class="floatcontainer">_x000D_
<div style="height: 50px; width: 50px; background-color: #ff0000;" class="floatablediv">_x000D_
</div>_x000D_
<div style="height: 70px; width: 50px; background-color: #00ff00;" class="floatablediv"> _x000D_
</div>_x000D_
<div style="height: 30px; width: 50px; background-color: #0000ff;" class="floatablediv"> _x000D_
</div>_x000D_
<div style="height: 40px; width: 50px; background-color: #ffff00;" class="floatablediv"> _x000D_
</div>_x000D_
<div style="clear:both;"></div>_x000D_
</div>
_x000D_
For your first method change ws.Range("A")
to ws.Range("A:A")
which will search the entirety of column a, like so:
Sub Find_Bingo()
Dim wb As Workbook
Dim ws As Worksheet
Dim FoundCell As Range
Set wb = ActiveWorkbook
Set ws = ActiveSheet
Const WHAT_TO_FIND As String = "Bingo"
Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
If Not FoundCell Is Nothing Then
MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
Else
MsgBox (WHAT_TO_FIND & " not found")
End If
End Sub
For your second method, you are using Bingo
as a variable instead of a string literal. This is a good example of why I add Option Explicit
to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.
Additionally, when you are using With...End With
you need a period .
before you reference Cells
, so Cells
should be .Cells
. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)
Change Bingo
to "Bingo"
and change Cells
to .Cells
With Sheet1
Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
End With
If Not FoundCell Is Nothing Then
MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
MsgBox ("Bingo not found")
End If
In my
With Sheet1
.....
End With
The Sheet1
refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1
. I can refer to that in code either with the code name of Sheet1
or I can refer to it with the index of Sheets("Sheet1")
. The advantage to using a codename is that it does not change if you change the name of the worksheet.
Continuing this example, let's say I renamed Sheet1
to Data
. Using Sheet1
would continue to work, as the code name doesn't change, but now using Sheets("Sheet1")
would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data")
.
In the VB Editor you would see something like this:
Notice how, even though I changed the name to Data
, there is still a Sheet1
to the left. That is what I mean by codename.
The Data
worksheet can be referenced in two ways:
Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name
Both should return Data
More discussion on worksheet code names can be found here.
I don't know of any built-in way to do this. However, it would seem easy enough to do, since the only delimiters you have to worry about are the newline character and the equals sign.
It would be very easy to write a routine that will return a NameValueCollection, or an IDictionary given the contents of the file.
input()
by default takes the input in form of strings.
if (0<= vote <=24):
vote takes a string input (suppose 4
,5
,etc) and becomes uncomparable.
The correct way is: vote = int(input("Enter your message")
will convert the input to integer (4
to 4 or 5
to 5 depending on the input)
There are two ways:
Just use tomcat manager console for console deployment or simply copy and paste your application in webapp folder of your server's tomcat_home directory.
Note: Make sure if your war file size is more than 52 MB (the default configuration value), you need to make two little changes in web.xml file of Manager application of your webapp folder(Manager application is provided by Apache tomcat by default upon installing the server).
Go to the web.xml of the manager application (for instance it could be under /tomcat7/webapps/manager/WEB-INF/web.xml.
Increase the max-file-size and max-request-size values in web.xml file:
<multipart-config>
<!– 50MB max –>
<max-file-size>52428800</max-file-size>
<max-request-size>52428800</max-request-size>
<file-size-threshold>0</file-size-threshold>
</multipart-config>
Increase the size by putting the values for <max-file-size>
and <max-request-size>
according to your requirement.