A simple way to do it using python :
Python
import numpy as np
import imageio
image = imageio.imread(r'[image-path]', as_gray=True)
# getting the threshold value
thresholdValue = np.mean(image)
# getting the dimensions of the image
xDim, yDim = image.shape
# turn the image into a black and white image
for i in range(xDim):
for j in range(yDim):
if (image[i][j] > thresholdValue):
image[i][j] = 255
else:
image[i][j] = 0
I found that this publication referenced in an answer to a previous similar question. It is very helpful:
http://cadik.posvete.cz/color_to_gray_evaluation/
It shows 'tons' of different methods to generate grayscale images with different outcomes!
Most solutions for getting the IP address via t-sql fall into these two camps:
Run ipconfig.exe
via xp_cmdshell
and parse the output
Query DMV sys.dm_exec_connections
I'm not a fan of option #1. Enabling xp_cmdshell has security drawbacks, and there's lots of parsing involved anyway. That's cumbersome. Option #2 is elegant. And it's a pure t-sql solution, which I almost always prefer. Here are two sample queries for option #2:
SELECT c.local_net_address
FROM sys.dm_exec_connections AS c
WHERE c.session_id = @@SPID;
SELECT TOP(1) c.local_net_address
FROM sys.dm_exec_connections AS c
WHERE c.local_net_address IS NOT NULL;
Sometimes, neither of the above queries works, though. Query #1 returns NULL if you're connected over Shared Memory (logged in and running SSMS on the SQL host). Query #2 may return nothing if there are no connections using a non-Shared Memory protocol. This scenario is likely when connected to a newly installed SQL instance. The solution? Force a connection over TCP/IP. To do this, create a new connection in SSMS and use the "tcp:" prefix with the server name. Then re-run either query and you'll get the IP address.
Dll v/s Exe
1)DLL file is a dynamic link library which can be used in exe files and
other dll files.
EXE file is a executable file which runs in a separate
process which is managed by OS.
2)DLLs are not directly executable . They are separate files containing functions that can be called by programs and other DLLs to perform computations and functions.
An EXE is a program that can be executed . Ex :Windows program
3)Reusability
DLL: They can be reused for some other application. As long as the coder knows the names and parameters of the functions and procedures in the DLL file .
EXE: Only for specific purpose .
4)A DLL would share the same process and memory space of the calling application while an
EXE creates its separate process and memory space.
5)Uses
DLL: You want many applications to use it but you don't want to give them the source code You can't copy-paste the code for the button in every program, so you decide you want to create a DL-Library (DLL).
EXE: When we work with project templates like Windows Forms Applications, Console Applications, WPF Applications and Windows Services they generate an exe assembly when compiled.
6)Similarities :
Both DLL and EXE are binary files have a complex nested structure defined by the Portable Executable format, and they are not intended to be editable by users.
Create a function to call your API. Within this function we define request callApiRequest = $.get(...
- even though this is a definition of a variable, the request is called immediately, but now we have the request defined as a variable. Before the request is called, we check if our variable is defined typeof(callApiRequest) != 'undefined'
and also if it is pending suggestCategoryRequest.state() == 'pending'
- if both are true, we .abort()
the request which will prevent the success callback from running.
// We need to wrap the call in a function
callApi = function () {
//check if request is defined, and status pending
if (typeof(callApiRequest) != 'undefined'
&& suggestCategoryRequest.state() == 'pending') {
//abort request
callApiRequest.abort()
}
//define and make request
callApiRequest = $.get("https://example.com", function (data) {
data = JSON.parse(data); //optional (for JSON data format)
//success callback
});
}
Your server/API might not support aborting the request (what if API executed some code already?), but the javascript callback will not fire. This is useful, when for example you are providing input suggestions to a user, such as hashtags input.
You can further extend this function by adding definition of error callback - what should happen if request was aborted.
Common use-case for this snippet would be a text input that fires on keypress
event. You can use a timeout, to prevent sending (some of) requests that you will have to cancel .abort()
.
This simple method worked for me perfectly in Windows 7:
private void BringToFront() {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
if(jFrame != null) {
jFrame.toFront();
jFrame.repaint();
}
}
});
}
I used this command and it worked:
python -m pip install --user --upgrade pip
Zakaria, that is a reference to an built-in XML layout document that is part of the Android OS, rather than one of your own XML layouts.
Here is a further list of layouts that you can use:
http://developer.android.com/reference/android/R.layout.html
(Updated link thanks @Estel: https://github.com/android/platform_frameworks_base/tree/master/core/res/res/layout )
You can actually view the code for the layouts.
The ssh2 functions aren't very good. Hard to use and harder yet to install, using them will guarantee that your code has zero portability. My recommendation would be to use phpseclib, a pure PHP SFTP implementation.
I think I get the award for the most bone headed reason to get this error. In the Restore Database dialog, the database dropdown under Source is gray and I thought it was disabled. I skipped down to the database dropdown under Destination thinking it was the source and made a selection. Doing this will cause this error message to be displayed.
Since this hasn't been closed yet, here are a few more options.
$FCEDIT
or $EDITOR
or emacs
(tried in that order).option25
(in this case). The line will be displayed. Hit Tab to start editing at this point.s///
modifier. E.g. !-2:s/--option25/--newoption/
would rerun the second-to-last command, but replace option25. To modify the last ./cmd
command, use the !string
syntax: !./cmd:s/--option25/--newoption/
^--option25^--newoption
I recommend the second option. Ctrl+r is really handy and fast, no mucking about with editors, and you see the results before the command is run (unlike the history expansions).
Looks like you have a bad practice here but not where you think.
Catching an IllegalArgumentException
to rethrow another RuntimeException
with a clearer message might look like a good idea but it is not. Because it means you care about messages in your exceptions.
If you care about messages in your exceptions, then it means that your user is somehow seeing your exceptions. This is bad.
If you want to provide an explicit error message to your user, you should check the validity of the enum value when parsing user input and send the appropriate error message in the response if user input is incorrect.
Something like:
// This code uses pure fantasy, you are warned!
class MyApi
{
// Return the 24-hour from a 12-hour and AM/PM
void getHour24(Request request, Response response)
{
// validate user input
int nTime12 = 1;
try
{
nTime12 = Integer.parseInt(request.getParam("hour12"));
if( nTime12 <= 0 || nTime12 > 12 )
{
throw new NumberFormatException();
}
}
catch( NumberFormatException e )
{
response.setCode(400); // Bad request
response.setContent("time12 must be an integer between 1 and 12");
return;
}
AMPM pm = null;
try
{
pm = AMPM.lookup(request.getParam("pm"));
}
catch( IllegalArgumentException e )
{
response.setCode(400); // Bad request
response.setContent("pm must be one of " + AMPM.values());
return;
}
response.setCode(200);
switch( pm )
{
case AM:
response.setContent(nTime12);
break;
case PM:
response.setContent(nTime12 + 12);
break;
}
return;
}
}
element.querySelector('.addDoor').onEvent('click', function (e) { });
element.querySelector('.addDoor').removeListeners();
HTMLElement.prototype.onEvent = function (eventType, callBack, useCapture) {
this.addEventListener(eventType, callBack, useCapture);
if (!this.myListeners) {
this.myListeners = [];
};
this.myListeners.push({ eType: eventType, callBack: callBack });
return this;
};
HTMLElement.prototype.removeListeners = function () {
if (this.myListeners) {
for (var i = 0; i < this.myListeners.length; i++) {
this.removeEventListener(this.myListeners[i].eType, this.myListeners[i].callBack);
};
delete this.myListeners;
};
};
There are multiple ways:
String.valueOf(number)
(my preference)"" + number
(I don't know how the compiler handles it, perhaps it is as efficient as the above)Integer.toString(number)
validator.resetForm()
method clear error text. But if you want to remove the RED border from fields you have to remove the class has-error
$('#[FORM_ID] .form-group').removeClass('has-error');
It works for me:
<mvc:resources mapping="/static/**" location="/static/"/>
<mvc:default-servlet-handler />
<mvc:annotation-driven />
$('selector').css('cursor', 'pointer'); // 'default' to revert
I know that may be confusing per your original question, but the "finger" cursor is actually called "pointer".
The normal arrow cursor is just "default".
After PHP 5 you can use this: echo date("c");
form ISO 8601 formatted datetime.
Note for comments:
Regarding to this, both of these expressions are valid for timezone, for basic format: ±[hh]:[mm], ±[hh][mm], or ±[hh]
.
But note that, +0X:00 is correct, and +0X00 is incorrect for extended usage. So it's better to use date("c")
. A similar discussion here.
Two comments:
and
and or
for logical operations in Python.Path.GetFileNameWithoutExtension
The Path class is wonderful.
This should solve your problem.
To answer your initial question: yes you can. Only Gecko and WebKit browsers support it currently though.
You just need to add link tags in your head:
<link rel="prefetch" href="pathto/font">
<link rel="prerender" href="pathto/page">
The better approach will be:
cell.userInteractionEnabled = NO;
This approach will not call didSelectRowAtIndexPath:
method.
You can use PendingIntent
to setup launching your start activity in the future and then close your application
Intent mStartActivity = new Intent(context, StartActivity.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
Use the static List list = Arrays.asList(stringArray)
or you could just iterate over the array and add the strings to the list.
None of the other answers were "sticking" for me in RHEL 7, even setting JAVA_HOME
and PATH
directly in /etc/profile
or ~/.bash_profile
would not work. Each time I tried to check if JAVA_HOME
was set, it would come up blank:
$ echo $JAVA_HOME
(<-- no output)
What I had to do was set up a script in /etc/profile.d/jdk_home.sh
:
#!/bin/sh
export JAVA_HOME=/opt/ibm/java-x86_64-60/
export PATH=$JAVA_HOME/bin:$PATH
I initially neglected the first line (the #!/bin/sh
), and it won't work without it.
Now it's working:
$ echo $JAVA_HOME
/opt/ibm/java-x86_64-60/
Simplified example of Nicolai Ehmann's comment and wildloop's answer (works with Spring 4.3.3+), basically you can use required = false
now:
@RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET)
public @ResponseBody TestBean testAjax(@PathVariable(required = false) String type) {
if (type != null) {
// ...
}
return new TestBean();
}
You can use the expandable list view explained in API demos to show groups
To animate the list items motion, you will have to override the getView method and apply translate animation on each list item. The values for animation depend on the position of each list item. This was something which i tried on a simple list view long time back.
A three line solution, but works quite well:
int[] source_array = {0,1,2,3,4,5,6,7,8,9,10,11};
ArrayList<Integer> target_list = new ArrayList<Integer>();
for(int i = 0; i < source_array.length; i++){
target_list.add(random_array[i]);
}
Alternatively, you can create a button on your webpage and in the Page_Load type;
Trace.IsEnabled = True
And in the button click event type;
Response.Write(Trace)
This will bring up all the trace information and you will find your ASP.NET version in the "Response Headers Collection" under "X-ASPNet-Version".
1- Comment out bind 127.0.0.1
2- set requirepass yourpassword
then check if the firewall blocked your port
iptables -L -n
service iptables stop
Following worked for me:
If you get the following error In order to install Windows Azure Active Directory Module for Windows PowerShell, you must have Microsoft Online Services Sign-In Assistant version 7.0 or greater installed on this computer, then install the Microsoft Online Services Sign-In Assistant for IT Professionals BETA: http://www.microsoft.com/en-us/download/details.aspx?id=39267
C:\Windows\System32\WindowsPowerShell\v1.0\Modules\
to the folder
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\
https://stackoverflow.com/a/16018733/5810078.
(But I have actually copied all the possible files from
C:\Windows\System32\WindowsPowerShell\v1.0\
to
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\
(For copying you need to alter the security permissions of that folder))
Internal is the default modifier
ok just to answer the original question:
you can get the padding as a usable integer like this:
var padding = parseInt($("myId").css("padding-top").replace("ems",""));
If you have defined another measurement like px just replace "ems" with "px". parseInt interprets the stringpart as a wrong value so its important to replace it with ... nothing.
for num in range(1,101):
prime = True
for i in range(2,num/2):
if (num%i==0):
prime = False
if prime:
print num
What is the difference between them?
Image: the generic Linux kernel binary image file.
zImage: a compressed version of the Linux kernel image that is self-extracting.
uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.
Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:
Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.
(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)
Which type of kernel image do I have to use?
You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.
ADDENDUM
I know that u-boot needs a kernel in uImage format.
That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.
You shouldn't search through that array, but use database capabilities for this
Suppose you're passing username through GET form:
if (isset($_GET['search'])) {
$search = mysql_real_escape_string($_GET['search']);
$sql = "SELECT * FROM users WHERE username = '$search'";
$res = mysql_query($sql) or trigger_error(mysql_error().$sql);
$row = mysql_fetch_assoc($res);
if ($row){
print_r($row); //do whatever you want with found info
}
}
I have an use case where nothing else helped as the solution from Aubin. I adapted the method and changed it by removing and adding an item to the tables' item list as it works in the end only reliable with this hack, the column visible toggle did the job only the first time.
I reported it also in the Jira task: https://javafx-jira.kenai.com/browse/RT-22463
public <T> void tableItemsRefresh(final ObservableList<T> items) {
if (items == null || items.size() == 0)
return;
int idx = items.size() -1;
final T item = items.get(idx);
items.remove(idx);
new Timer().schedule(new TimerTask() {
@Override
public void run() {
Platform.runLater(new Runnable() {
@Override
public void run() {
items.add(item);
}
});
}
}, 100);
}
There seems no way to have google maps api key free without credit card. To test the functionality of google map you can use it while leaving the api key field "EMPTY". It will show a message saying "For Development Purpose Only". And that way you can test google map functionality without putting billing information for google map api key.
<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap" async defer></script>
echo $STRING | cut -d " " -f $N
There may be many reasons for the above problem.
You need to check this:- Unable to Start Debugging on the Web Server
On a side note:- Go to IIS and check that the App Pool you are using is started.
Try this from your command line:-
cd %windir%\Microsoft.NET\Framework\v4.0.30319
aspnet_regiis.exe -i
Your code can get messy fast when dealing with CSS3 transitions. I would recommend using a plugin such as jQuery Transit that handles the complexity of CSS3 animations/transitions.
Moreover, the plugin uses webkit-transform rather than webkit-transition, which allows for mobile devices to use hardware acceleration in order to give your web apps that native look and feel when the animations occur.
Javascript:
$("#startTransition").on("click", function()
{
if( $(".boxOne").is(":visible"))
{
$(".boxOne").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxOne").hide(); });
$(".boxTwo").css({ x: '100%' });
$(".boxTwo").show().transition({ x: '0%', opacity: 1.0 });
return;
}
$(".boxTwo").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxTwo").hide(); });
$(".boxOne").css({ x: '100%' });
$(".boxOne").show().transition({ x: '0%', opacity: 1.0 });
});
Most of the hard work of getting cross-browser compatibility is done for you as well and it works like a charm on mobile devices.
Not the straight forward way, but probably much faster than a simple Python implementation:
line = subprocess.check_output(['tail', '-1', filename])
I just wanted to hop in here and correct (suggest alternative) to the previous answer....
You can actually use compact in the same way, however a lot neater for example...
return View::make('gameworlds.mygame', compact(array('fixtures', 'teams', 'selections')));
Or if you are using PHP > 5.4
return View::make('gameworlds.mygame', compact(['fixtures', 'teams', 'selections']));
This is far neater, and still allows for readability when reviewing what the application does ;)
I was returning valid JSON, getting a response of 200 in my "complete" callback, and could see it in the chrome network console... BUT I hadn't specified
dataType: "json"
once I did, unlike the "accepted answer", that actually fixed the problem.
TEXT
is used for large pieces of string data. If the length of the field exceeed a certain threshold, the text is stored out of row.
VARCHAR
is always stored in row and has a limit of 8000 characters. If you try to create a VARCHAR(x)
, where x > 8000, you get an error:
Server: Msg 131, Level 15, State 3, Line 1
The size () given to the type ‘varchar’ exceeds the maximum allowed for any data type (8000)
These length limitations do not concern VARCHAR(MAX)
in SQL Server 2005, which may be stored out of row, just like TEXT
.
Note that MAX
is not a kind of constant here, VARCHAR
and VARCHAR(MAX)
are very different types, the latter being very close to TEXT
.
In prior versions of SQL Server you could not access the TEXT
directly, you only could get a TEXTPTR
and use it in READTEXT
and WRITETEXT
functions.
In SQL Server 2005 you can directly access TEXT
columns (though you still need an explicit cast to VARCHAR
to assign a value for them).
TEXT
is good:
VARCHAR
is good:
By selecting here I mean issuing any queries that return the value of the column.
By searching here I mean issuing any queries whose result depends on the value of the TEXT
or VARCHAR
column. This includes using it in any JOIN
or WHERE
condition.
As the TEXT
is stored out of row, the queries not involving the TEXT
column are usually faster.
Some examples of what TEXT
is good for:
Some examples of what VARCHAR
is good for:
As a rule of thumb, if you ever need you text value to exceed 200 characters AND do not use join on this column, use TEXT
.
Otherwise use VARCHAR
.
P.S. The same applies to UNICODE
enabled NTEXT
and NVARCHAR
as well, which you should use for examples above.
P.P.S. The same applies to VARCHAR(MAX)
and NVARCHAR(MAX)
that SQL Server 2005+ uses instead of TEXT
and NTEXT
. You'll need to enable large value types out of row
for them with sp_tableoption
if you want them to be always stored out of row.
As mentioned above and here, TEXT
is going to be deprecated in future releases:
The
text in row
option will be removed in a future version of SQL Server. Avoid using this option in new development work, and plan to modify applications that currently usetext in row
. We recommend that you store large data by using thevarchar(max)
,nvarchar(max)
, orvarbinary(max)
data types. To control in-row and out-of-row behavior of these data types, use thelarge value types out of row
option.
In addition to Settings -> Editor -> Use soft wraps in editor I recommend Use soft wraps in console and Use custom soft wraps indent with a setting of 4 to make the wraps indented to match the line they started on.
I had the same exception when trying to use pdo_sqlite
. The problem was that the automatically created 20-pdo_sqlite.ini
and 20-sqlite3.ini
symlinks (in /etc/php5/mods-enabled
) were broken.
Removeing the broken symlinks and adding them manually with:
sudo ln -s /etc/php5/mods-avaliable/pdo_sqlite.ini /etc/php5/mods-enabled/20-pdo_sqlite.ini
sudo ln -s /etc/php5/mods-avaliable/sqlite3.ini /etc/php5/mods-enabled/20-sqlite3.ini
fixed the problem.
Note: this won't work for older php versions as they did not look for configs in
/etc/php5/mods-enabled
Use: cast(date_parse(inv.date_created,'%Y-%m-%d %h24:%i:%s') as date)
Input: String timestamp
Output: date format 'yyyy-mm-dd'
After so much effort, found that the basic difference is you need to send the JsonObject
instead of JSONObject
as parameter.
Share Any File as below ( Kotlin ) :
first create a folder named xml
in the res
folder and create a new XML Resource File named provider_paths.xml
and put the below code inside it :
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path
name="files"
path="."/>
<external-path
name="external_files"
path="."/>
</paths>
now go to the manifests
folder and open the AndroidManifest.xml
and then put the below code inside the <application>
tag :
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" /> // provider_paths.xml file path in this example
</provider>
now you put the below code in the setOnLongClickListener
:
share_btn.setOnClickListener {
try {
val file = File("pathOfFile")
if(file.exists()) {
val uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file)
val intent = Intent(Intent.ACTION_SEND)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.setType("*/*")
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent)
}
} catch (e: java.lang.Exception) {
e.printStackTrace()
toast("Error")
}
}
If you want to retrieve POST data:
first_name = request.form.get("firstname")
If you want to retrieve GET (query string) data:
first_name = request.args.get("firstname")
Or if you don't care/know whether the value is in the query string or in the post data:
first_name = request.values.get("firstname")
request.values is a CombinedMultiDict that combines Dicts from request.form and request.args.
http://docs.python.org/library/configparser.html
Python's standard library might be helpful in this case.
toBe()
versus toEqual()
: toEqual()
checks equivalence. toBe()
, on the other hand, makes sure that they're the exact same object.
I would say use toBe()
when comparing values, and toEqual()
when comparing objects.
When comparing primitive types, toEqual()
and toBe()
will yield the same result. When comparing objects, toBe()
is a stricter comparison, and if it is not the exact same object in memory this will return false. So unless you want to make sure it's the exact same object in memory, use toEqual()
for comparing objects.
Check this link out for more info : http://evanhahn.com/how-do-i-jasmine/
Now when looking at the difference between toBe()
and toEqual()
when it comes to numbers, there shouldn't be any difference so long as your comparison is correct. 5
will always be equivalent to 5
.
A nice place to play around with this to see different outcomes is here
An easy way to look at toBe()
and toEqual()
is to understand what exactly they do in JavaScript. According to Jasmine API, found here:
toEqual() works for simple literals and variables, and should work for objects
toBe() compares with
===
Essentially what that is saying is toEqual()
and toBe()
are similar Javascripts ===
operator except toBe()
is also checking to make sure it is the exact same object, in that for the example below objectOne === objectTwo //returns false
as well. However, toEqual()
will return true in that situation.
Now, you can at least understand why when given:
var objectOne = {
propertyOne: str,
propertyTwo: num
}
var objectTwo = {
propertyOne: str,
propertyTwo: num
}
expect(objectOne).toBe(objectTwo); //returns false
That is because, as stated in this answer to a different, but similar question, the ===
operator actually means that both operands reference the same object, or in case of value types, have the same value.
eval('(' + jsonObject + ')')
ind_list = [1, 3]
df.ix[ind_list]
should do the trick! When I index with data frames I always use the .ix() method. Its so much easier and more flexible...
UPDATE
This is no longer the accepted method for indexing. The ix
method is deprecated. Use .iloc
for integer based indexing and .loc
for label based indexing.
#include <iostream>
using namespace std ;
typedef int (*Type)[3][3] ;
Type Demo_function( Type ); //prototype
int main (){
cout << "\t\t!!!!!Passing and returning 2D array from function!!!!!\n"
int array[3][3] ;
Type recieve , ptr = &array;
recieve = Demo_function( ptr ) ;
for ( int i = 0 ; i < 3 ; i ++ ){
for ( int j = 0 ; j < 3 ; j ++ ){
cout << (*recieve)[i][j] << " " ;
}
cout << endl ;
}
return 0 ;
}
Type Demo_function( Type array ){/*function definition */
cout << "Enter values : \n" ;
for (int i =0 ; i < 3 ; i ++)
for ( int j = 0 ; j < 3 ; j ++ )
cin >> (*array)[i][j] ;
return array ;
}
This:
doc.LoadXml(HttpContext.Current.Server.MapPath("officeList.xml"));
should be:
doc.Load(HttpContext.Current.Server.MapPath("officeList.xml"));
LoadXml()
is for loading an XML string, not a file name.
Use the not
function instead:
var lastOpenSite = $(this).siblings().not('.closedTab');
hasClass
only tests whether an element has a class, not
will remove elements from the selected set matching the provided selector.
There is no pre-defined class to implement directly from hex code to color name so what you have to do is Try key value pair concept simple, follow this code.
String hexCode = "Any Hex code" //#0000FF
HashMap<String, String> color_namme = new HashMap<String, String>();
color_namme.put("#000000", "Black");
color_namme.put("#000080", "Navy Blue");
color_namme.put("#0000C8", "Dark Blue");
color_namme.put("0000FF", "Blue");
color_namme.put("000741", "Stratos");
color_namme.put("001B1C", "Swamp");
color_namme.put("002387", "Resolution Blue");
color_namme.put("002900", "Deep Fir");
color_namme.put("002E20", "Burnham");
for (Map.Entry<String, String> entry : color_namme.entrySet()) {
String key = (String) entry.getKey();
String thing = (String) entry.getValue();
if (hexCode.equals(key))
Color_namme.setText(thing); //Here i display using textview
}
_x000D_
ALTER USER
Example:
ALTER USER 'username' IDENTIFIED BY 'password';
Because:
SET PASSWORD ... = PASSWORD('auth_string')
syntax is deprecated as of MySQL 5.7.6 and will be removed in a future MySQL release.
SET PASSWORD ... = 'auth_string'
syntax is not deprecated, but ALTER USER
is now the preferred statement for assigning passwords.
You simply select dates that are higher than the current time minus 1 day.
SELECT * FROM news WHERE date >= now() - INTERVAL 1 DAY;
You don't need jquery for this, in plain javascript, the following will work!
var intervalId = window.setInterval(function(){
/// call your function here
}, 5000);
To stop the loop you can use
clearInterval(intervalId)
Make sure you include the = sign in addition to passing the arguments to the function. I.E.
=SUM(A1:A3) //this would give you the sum of cells A1, A2, and A3.
To do it for your whole collection you can also use a loop (based on Niels example):
db.status.find().forEach(function(doc){
doc._id=doc.UserId; db.status_new.insert(doc);
});
db.status_new.renameCollection("status", true);
In this case UserId was the new ID I wanted to use
Using awk.
i starts at 0, i++
will increment the value of i, but return the original value that i held before being incremented.
awk '{print i++ "," $0}' file
You can run something like
git ls-files | xargs wc -l
which will give you the total count ?
Or use this tool ? http://line-count.herokuapp.com/
Files related for deployment (and others temporary items) are created in standalone/tmp/vfs (Virtual File System). You may add a policy at startup for evicting temporary files :
-Djboss.vfs.cache=org.jboss.virtual.plugins.cache.IterableTimedVFSCache
-Djboss.vfs.cache.TimedPolicyCaching.lifetime=1440
Another example. When building a complex map of maps, the computeIfAbsent() method is a replacement for map's get() method. Through chaining of computeIfAbsent() calls together, missing containers are constructed on-the-fly by provided lambda expressions:
// Stores regional movie ratings
Map<String, Map<Integer, Set<String>>> regionalMovieRatings = new TreeMap<>();
// This will throw NullPointerException!
regionalMovieRatings.get("New York").get(5).add("Boyhood");
// This will work
regionalMovieRatings
.computeIfAbsent("New York", region -> new TreeMap<>())
.computeIfAbsent(5, rating -> new TreeSet<>())
.add("Boyhood");
setLoanItem is an instance method, meaning you need an instance of the Media class in order to call it. You're attempting to call it on the Media type itself.
You may want to look into some basic object-oriented tutorials to see how static/instance members work.
You better use disabled for your inputs, in order to prevent auto-completion.
<input type="password" ... disabled />
I had similar experience and it took me time to solve the problem. Though, my own case was ASP.Net MVC Core
and Core
framework. Setting Trusted_Connection=False;
solved my problem.
Inside appsettings.json
file
"ConnectionStrings": {
"DefaultConnection": "Server=servername; Database=databasename; User Id=userid; Password=password; Trusted_Connection=False; MultipleActiveResultSets=true",
},
Using importlib
the only thing you've got to add is
from importlib import import_module
from pathlib import Path
__all__ = [
import_module(f".{f.stem}", __package__)
for f in Path(__file__).parent.glob("*.py")
if "__" not in f.stem
]
del import_module, Path
Here is a function that is part of the helpRFunctions package that will return a list of all of the various data types in your data frame, as well as the specific variable names associated with that type.
install.package('devtools') # Only needed if you dont have this installed.
library(devtools)
install_github('adam-m-mcelhinney/helpRFunctions')
library(helpRFunctions)
my.data <- data.frame(y=rnorm(5),
x1=c(1:5),
x2=c(TRUE, TRUE, FALSE, FALSE, FALSE),
X3=letters[1:5])
t <- list.df.var.types(my.data)
t$factor
t$integer
t$logical
t$numeric
You could then do something like var(my.data[t$numeric])
.
Hope this is helpful!
You can use list comprehension:
res_list = [i[0] for i in rows]
This should make the trick
The error is because of the sql mode which can be strict mode as per latest MYSQL 5.7 documentation.
For more information read this.
Hope it helps.
You're talking about template literals.
They allow for both multiline strings and string interpolation.
Multiline strings:
console.log(`foo_x000D_
bar`);_x000D_
// foo_x000D_
// bar
_x000D_
String interpolation:
var foo = 'bar';_x000D_
console.log(`Let's meet at the ${foo}`);_x000D_
// Let's meet at the bar
_x000D_
This error can be due to many many things.
The key here seems the hint about error reading
. I see you are working on a flash drive or something similar? Try to run the install on a local folder owned by your current user.
You could also try with sudo
, that might solve a permission problem if that's the case.
Another reason why it cannot read could be because it has not downloaded correctly, or saved correctly. A little problem in your network could have caused that, and the cache clean would remove the files and force a refetch but that does not solve your problem. That means it would be more on the save part, maybe it didn't save because of permissions, maybe it didn't not save correctly because it was lacking disk space...
Basically, there are three main characters which should be always escaped in your HTML and XML files, so they don't interact with the rest of the markups, so as you probably expect, two of them gonna be the syntax wrappers, which are <>, they are listed as below:
1) < (<)
2) > (>)
3) & (&)
Also we may use double-quote (") as " and the single quote (') as &apos
Avoid putting dynamic content in <script>
and <style>
.These rules are not for applied for them. For example, if you have to include JSON in a , replace < with \x3c, the U+2028 character with \u2028, and U+2029 with \u2029 after JSON serialisation.)
HTML Escape Characters: Complete List: http://www.theukwebdesigncompany.com/articles/entity-escape-characters.php
So you need to escape <, or & when followed by anything that could begin a character reference. Also The rule on ampersands is the only such rule for quoted attributes, as the matching quotation mark is the only thing that will terminate one. But if you don’t want to terminate the attribute value there, escape the quotation mark.
Changing to UTF-8 means re-saving your file:
Using the character encoding UTF-8 for your page means that you can avoid the need for most escapes and just work with characters. Note, however, that to change the encoding of your document, it is not enough to just change the encoding declaration at the top of the page or on the server. You need to re-save your document in that encoding. For help understanding how to do that with your application read Setting encoding in web authoring applications.Invisible or ambiguous characters:
A particularly useful role for escapes is to represent characters that are invisible or ambiguous in presentation.
One example would be Unicode character U+200F RIGHT-TO-LEFT MARK. This character can be used to clarify directionality in bidirectional text (eg. when using the Arabic or Hebrew scripts). It has no graphic form, however, so it is difficult to see where these characters are in the text, and if they are lost or forgotten they could create unexpected results during later editing. Using ? (or its numeric character reference equivalent ?) instead makes it very easy to spot these characters.
An example of an ambiguous character is U+00A0 NO-BREAK SPACE. This type of space prevents line breaking, but it looks just like any other space when used as a character. Using makes it quite clear where such spaces appear in the text.
I figured it out! The steps make it look like it will take more effort than it actually does.
These instructions are for creating a project from scratch. If you have existing Python scripts that you wish to include in this project, you will obviously need to slightly deviate from these instructions.
If you find that these instructions no longer work or are unclear due to changes in Xcode updates, please let me know. I will make the necessary corrections.
Note that if you open the "Utilities" panel, with the "Show the File inspector" tab active, the file type is automatically set to "Default - Python script". Feel free to look through all the file type options it has, to gain an idea as to what all it is capable of doing. The method above can be applied to any interpreted language. As of right now, I have yet to figure out exactly how to get it to work with Java; then again, I haven't done too much research. Surely there is some documentation floating around on the web about all of this.
If you do not have administrative privileges or are not in the Developer group, you can still use Xcode for Python programming (but you still won't be able to develop in languages that require compiling). Instead of using the play button, in the menu bar, click "Product" ? "Perform Action" ? "Run Without Building" or simply use the keyboard shortcut ^?R.
To change the text encoding, line endings, and/or indentation settings, open the "Utilities" panel and click "Show the File inspector" tab active. There, you will find these settings.
For more information about Xcode's build settings, there is no better source than this. I'd be interested in hearing from somebody who got this to work with unsupported compiled languages. This process should work for any other interpreted language. Just be sure to change Step 5 and Step 16 accordingly.
Why not use a list comprehension?
In Python 2
ran_floats = [random.uniform(low,high) for _ in xrange(size)]
In Python 3, range
works like xrange
(ref)
ran_floats = [random.uniform(low,high) for _ in range(size)]
The input date value format needs the date specified as per http://tools.ietf.org/html/rfc3339#section-5.6 full-date.
So I've ended up doing:
<input type="date" id="last-start-date" value="@string.Format("{0:yyyy-MM-dd}", Model.LastStartDate)" />
I did try doing it "properly" using:
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime LastStartDate
{
get { return lastStartDate; }
set { lastStartDate = value; }
}
with
@Html.TextBoxFor(model => model.LastStartDate,
new { type = "date" })
Unfortunately that always seemed to set the value attribute of the input to a standard date time so I've ended up applying the formatting directly as above.
Edit:
According to Jorn if you use
@Html.EditorFor(model => model.LastStartDate)
instead of TextBoxFor it all works fine.
I think using
select rownum st.Branch
from student st
where st.name like '%ram%'
is a simple way; you should add single quotes in the LIKE statement. If you use row_number()
, you should add over (order by 'sort column' 'asc/desc')
, for instance:
select st.branch, row_number() over (order by 'sort column' 'asc/desc')
from student st
where st.name like '%ram%'
I might misunderstand, but are you trying to delete files newly ignored or do you want to ignore new modifications to these files ? In this case, the thing is working.
If you want to delete ignored files previously commited, then use
git rm –cached `git ls-files -i –exclude-standard`
git commit -m 'clean up'
Use this one:
function onKeyPress(evt){
evt = (evt) ? evt : (window.event) ? event : null;
if (evt)
{
var charCode = (evt.charCode) ? evt.charCode :((evt.keyCode) ? evt.keyCode :((evt.which) ? evt.which : 0));
if (charCode == 13)
alert('User pressed Enter');
}
}
For me everything else was almost ok, but somehow my project settings changed & iisExpress was getting used instead of IISLocal. When I changed & pointed to the virtual directory (in IISLocal), it stared working perfectly again.
You can also add underscore.js to your project and will be able to do it in one line:
_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})
This example (although not pretty one) can provide more insight into locking mechanism. If incrementA is synchronized, and incrementB is not synchronized, then incrementB will be executed ASAP, but if incrementB is also synchronized then it has to 'wait' for incrementA to finish, before incrementB can do its job.
Both methods are called onto single instance - object, in this example it is: job, and 'competing' threads are aThread and main.
Try with 'synchronized' in incrementB and without it and you will see different results.If incrementB is 'synchronized' as well then it has to wait for incrementA() to finish. Run several times each variant.
class LockTest implements Runnable {
int a = 0;
int b = 0;
public synchronized void incrementA() {
for (int i = 0; i < 100; i++) {
this.a++;
System.out.println("Thread: " + Thread.currentThread().getName() + "; a: " + this.a);
}
}
// Try with 'synchronized' and without it and you will see different results
// if incrementB is 'synchronized' as well then it has to wait for incrementA() to finish
// public void incrementB() {
public synchronized void incrementB() {
this.b++;
System.out.println("*************** incrementB ********************");
System.out.println("Thread: " + Thread.currentThread().getName() + "; b: " + this.b);
System.out.println("*************** incrementB ********************");
}
@Override
public void run() {
incrementA();
System.out.println("************ incrementA completed *************");
}
}
class LockTestMain {
public static void main(String[] args) throws InterruptedException {
LockTest job = new LockTest();
Thread aThread = new Thread(job);
aThread.setName("aThread");
aThread.start();
Thread.sleep(1);
System.out.println("*************** 'main' calling metod: incrementB **********************");
job.incrementB();
}
}
Here is some code that will give you the general idea.
You need to create a custom ClientHttpRequestFactory
in order to trust the certificate.
It looks like this:
final ClientHttpRequestFactory clientHttpRequestFactory =
new MyCustomClientHttpRequestFactory(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER, serverInfo);
restTemplate.setRequestFactory(clientHttpRequestFactory);
This is the implementation for MyCustomClientHttpRequestFactory
:
public class MyCustomClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
private final HostnameVerifier hostNameVerifier;
private final ServerInfo serverInfo;
public MyCustomClientHttpRequestFactory (final HostnameVerifier hostNameVerifier,
final ServerInfo serverInfo) {
this.hostNameVerifier = hostNameVerifier;
this.serverInfo = serverInfo;
}
@Override
protected void prepareConnection(final HttpURLConnection connection, final String httpMethod)
throws IOException {
if (connection instanceof HttpsURLConnection) {
((HttpsURLConnection) connection).setHostnameVerifier(hostNameVerifier);
((HttpsURLConnection) connection).setSSLSocketFactory(initSSLContext()
.getSocketFactory());
}
super.prepareConnection(connection, httpMethod);
}
private SSLContext initSSLContext() {
try {
System.setProperty("https.protocols", "TLSv1");
// Set ssl trust manager. Verify against our server thumbprint
final SSLContext ctx = SSLContext.getInstance("TLSv1");
final SslThumbprintVerifier verifier = new SslThumbprintVerifier(serverInfo);
final ThumbprintTrustManager thumbPrintTrustManager =
new ThumbprintTrustManager(null, verifier);
ctx.init(null, new TrustManager[] { thumbPrintTrustManager }, null);
return ctx;
} catch (final Exception ex) {
LOGGER.error(
"An exception was thrown while trying to initialize HTTP security manager.", ex);
return null;
}
}
In this case my serverInfo
object contains the thumbprint of the server.
You need to implement the TrustManager
interface to get
the SslThumbprintVerifier
or any other method you want to verify your certificate (you can also decide to also always return true
).
The value org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
allows all host names.
If you need to verify the host name,
you will need to implement it differently.
I'm not sure about the user and password and how you implemented it.
Often,
you need to add a header to the restTemplate
named Authorization
with a value that looks like this: Base: <encoded user+password>
.
The user+password
must be Base64
encoded.
my use case was slight different. I had to construct a query where more then 20 fields were dynamic. I followed this approach of using format method
query = "insert into {0}({1},{2},{3}) values({4}, {5}, {6})"
query.format('users','name','age','dna','suzan',1010,'nda')
this was comparatively simpler for me instead of using + or other ways
You can also query by following code snippet as backward compatible;
int hasPermission = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_CONTACTS);
if (hasPermission == PackageManager.PERMISSION_GRANTED) {
//Do smthng
}
It is also possible to use http proxy to monitor http requests from emulator. You can pass -http-proxy
flag when starting a new emulator to set proxy (Example burp) to monitor Android traffic. Example usage ./emulator -http-proxy localhost:8080 -avd android2.2
. Note that in my example I'm using Burp, and it is listening port 8080. More info can be found here.
You need to add type assertion .(string)
. It is necessary because the map is of type map[string]interface{}
:
host := arguments["<host>"].(string) + ":" + arguments["<port>"].(string)
Latest version of Docopt returns Opts object that has methods for conversion:
host, err := arguments.String("<host>")
port, err := arguments.String("<port>")
host_port := host + ":" + port
If you want time in 00:00 format: I solved it like that:
select strftime('%H:%M',CAST ((julianday(FinishTime) - julianday(StartTime)) AS REAL),'12:00') from something
I had a more complicated query, and found that I had to use GROUP_CONCAT
in an outer query to get it to work:
SELECT DISTINCT userID
FROM event GROUP BY userID
HAVING count(distinct(cohort))=2);
SELECT GROUP_CONCAT(sub.userID SEPARATOR ', ')
FROM (SELECT DISTINCT userID FROM event
GROUP BY userID HAVING count(distinct(cohort))=2) as sub;
Hope this might help someone.
I used this
:top
cls
type G:\empty.txt
type I:\empty.txt
timeout /T 500
goto top
if you have xcopy
, you can use the /E
param, which will copy directories and subdirectories and the files within them, including maintaining the directory structure for empty directories
xcopy [source] [destination] /E
Maybe you are using:
$(document).ready(function(){
// Your code here
});
Try this instead:
window.onload = function(){ }
I've been working kind of similar to this and I have some code that might help you. The live example is here and below, is the code I'm using for you to have it as reference.
create-page.php
<?php
// Session is started.
session_start();
// Name of the template file.
$template_file = 'couples-template.php';
// Root folder if working in subdirectory. Name is up to you ut must match with server's folder.
$base_path = '/couple/';
// Path to the directory where you store the "couples-template.php" file.
$template_path = '../template/';
// Path to the directory where php will store the auto-generated couple's pages.
$couples_path = '../couples/';
// Posted data.
$data['groom-name'] = str_replace(' ', '', $_POST['groom-name']);
$data['bride-name'] = str_replace(' ', '', $_POST['bride-name']);
// $data['groom-surname'] = $_POST['groom-surname'];
// $data['bride-surname'] = $_POST['bride-surname'];
$data['wedding-date'] = $_POST['wedding-date'];
$data['email'] = $_POST['email'];
$data['code'] = str_replace(array('/', '-', ' '), '', $_POST['wedding-date']).strtoupper(substr($data['groom-name'], 0, 1)).urlencode('&').strtoupper(substr($data['bride-name'], 0, 1));
// Data array (Should match with data above's order).
$placeholders = array('{groom-name}', '{bride-name}', '{wedding-date}', '{email}', '{code}');
// Get the couples-template.php as a string.
$template = file_get_contents($template_path.$template_file);
// Fills the template.
$new_file = str_replace($placeholders, $data, $template);
// Generates couple's URL and makes it frendly and lowercase.
$couples_url = str_replace(' ', '', strtolower($data['groom-name'].'-'.$data['bride-name'].'.php'));
// Save file into couples directory.
$fp = fopen($couples_path.$couples_url, 'w');
fwrite($fp, $new_file);
fclose($fp);
// Set the variables to pass them to success page.
$_SESSION['couples_url'] = $couples_url;
// If working in root directory.
$_SESSION['couples_path'] = str_replace('.', '', $couples_path);
// If working in a sub directory.
//$_SESSION['couples_path'] = substr_replace($base_path, '', -1).str_replace('.', '',$couples_path);
header('Location: success.php');
?>
Hope this file can help and work as reference to start and boost your project.
Use an absolutely positioned pseudo element:
ul:after {
content: '';
width: 0;
height: 100%;
position: absolute;
border: 1px solid black;
top: 0;
left: 100px;
}
I was searching for something similar and came accross something called the Singleton Pattern
.
Reference: Singleton Pattern
I am working on a BulkLoader class to load different types of files and wanted to use the Singleton pattern for it. This way I can load files from my main application class and retrieve the loaded files easily from other classes.
Below is a simple example how you can make a score manager for a game with TypeScript and the Singleton pattern.
class SingletonClass {
private static _instance:SingletonClass = new SingletonClass(); private _score:number = 0; constructor() { if(SingletonClass._instance){ throw new Error("Error: Instantiation failed: Use SingletonDemo.getInstance() instead of new."); } SingletonClass._instance = this; } public static getInstance():SingletonClass { return SingletonClass._instance; } public setScore(value:number):void { this._score = value; } public getScore():number { return this._score; } public addPoints(value:number):void { this._score += value; } public removePoints(value:number):void { this._score -= value; } }
Then anywhere in your other classes you would get access to the Singleton by:
var scoreManager = SingletonClass.getInstance(); scoreManager.setScore(10); scoreManager.addPoints(1); scoreManager.removePoints(2); console.log( scoreManager.getScore() );
I got it working by adding to ~/.profile. Somehow after updating to El Capitan beta, it didnt work even though JAVA_HOME was defined in .bash_profile.
If there are any El Capitan beta users, try adding to .profile
Go into task manager and see if you have any Microsoft Excel Processes running in the background. I closed my excel background processes and my code worked again.
I'm assuming from your question that you don't want directories names, just files.
animals
+-- all.jpg
+-- mammals
¦ +-- cat.jpg
¦ +-- dog.jpg
+-- insects
+-- bee.jpg
Walk
functionCredits go to Justin Maier in this gist
If you want just an array of the files paths use return_object: false
:
const fs = require('fs').promises;
const path = require('path');
async function walk(dir) {
let files = await fs.readdir(dir);
files = await Promise.all(files.map(async file => {
const filePath = path.join(dir, file);
const stats = await fs.stat(filePath);
if (stats.isDirectory()) return walk(filePath);
else if(stats.isFile()) return filePath;
}));
return files.reduce((all, folderContents) => all.concat(folderContents), []);
}
async function main() {
console.log(await walk('animals'))
}
[
"/animals/all.jpg",
"/animals/mammals/cat.jpg",
"/animals/mammals/dog.jpg",
"/animals/insects/bee.jpg"
];
OID's are still in use for Postgres with large objects (though some people would argue large objects are not generally useful anyway). They are also used extensively by system tables. They are used for instance by TOAST which stores larger than 8KB BYTEA's (etc.) off to a separate storage area (transparently) which is used by default by all tables. Their direct use associated with "normal" user tables is basically deprecated.
The oid type is currently implemented as an unsigned four-byte integer. Therefore, it is not large enough to provide database-wide uniqueness in large databases, or even in large individual tables. So, using a user-created table's OID column as a primary key is discouraged. OIDs are best used only for references to system tables.
Apparently the OID sequence "does" wrap if it exceeds 4B 6. So in essence it's a global counter that can wrap. If it does wrap, some slowdown may start occurring when it's used and "searched" for unique values, etc.
See also https://wiki.postgresql.org/wiki/FAQ#What_is_an_OID.3F
For Windows:
Better still (or shorter anyway):
SUM(ccc_news_comments.id = 'approved')
This works since the Boolean type in MySQL is represented as INT
0
and 1
, just like in C. (May not be portable across DB systems though.)
As for COALESCE()
as mentioned in other answers, many language APIs automatically convert NULL
to ''
when fetching the value. For example with PHP's mysqli
interface it would be safe to run your query without COALESCE()
.
If the user or sysadmin did not kill the program the kernel may have. The kernel would only kill a process under exceptional circumstances such as extreme resource starvation (think mem+swap exhaustion).
Solution from: http://forums.devshed.com/c-programming-42/wstring-to-string-444006.html
std::wstring wide( L"Wide" );
std::string str( wide.begin(), wide.end() );
// Will print no problemo!
std::cout << str << std::endl;
Beware that there is no character set conversion going on here at all. What this does is simply to assign each iterated wchar_t
to a char
- a truncating conversion. It uses the std::string c'tor:
template< class InputIt >
basic_string( InputIt first, InputIt last,
const Allocator& alloc = Allocator() );
As stated in comments:
values 0-127 are identical in virtually every encoding, so truncating values that are all less than 127 results in the same text. Put in a chinese character and you'll see the failure.
-
the values 128-255 of windows codepage 1252 (the Windows English default) and the values 128-255 of unicode are mostly the same, so if that's teh codepage you're using most of those characters should be truncated to the correct values. (I totally expected á and õ to work, I know our code at work relies on this for é, which I will soon fix)
And note that code points in the range 0x80 - 0x9F
in Win1252 will not work. This includes €
, œ
, ž
, Ÿ
, ...
The message is clear: you have a repeated column in the mapping. That means you mapped the same database column twice. And indeed, you have:
@Column(nullable=false)
private Long customerId;
and also:
@ManyToOne(optional=false)
@JoinColumn(name="customerId",referencedColumnName="id_customer")
private Customer customer;
(and the same goes for productId
/product
).
You shouldn't reference other entities by their ID, but by a direct reference to the entity. Remove the customerId
field, it's useless. And do the same for productId
. If you want the customer ID of a sale, you just need to do this:
sale.getCustomer().getId()
A few updates for Flask 1.0 and above
the basic approach to hot re-loading is:
$ export FLASK_APP=my_application
$ export FLASK_ENV=development
$ flask run
FLASK_ENV=development
(not FLASK_DEBUG=1
)flask run --debugger
just to make sure it's turned onFLASK_APP
and FLASK_ENV
if you have an .env
file in the project root and have python-dotenv installedYou can also achieve this using the backreference technique
sed -i.bak 's/\(.*\)/prefix\1/' foo.txt
You can also use with awk like this
awk '{print "prefix"$0}' foo.txt > tmp && mv tmp foo.txt
My solition is working
can testing by change where 1=2 to where 1=1
select * from (
select col_x,case when count(1) over (partition by 1) =1 then 1 else HIDE end as HIDE from (
select 'test' col_x,1 as HIDE
where 1=2
union
select 'if no rows write here that you want' as col_x,0 as HIDE
) a
) b where HIDE=1
I think you have to calculate latitudine min and longitude min: Here is an Example with the function to use to center your point:
//Example values of min & max latlng values
var lat_min = 1.3049337;
var lat_max = 1.3053515;
var lng_min = 103.2103116;
var lng_max = 103.8400188;
map.setCenter(new google.maps.LatLng(
((lat_max + lat_min) / 2.0),
((lng_max + lng_min) / 2.0)
));
map.fitBounds(new google.maps.LatLngBounds(
//bottom left
new google.maps.LatLng(lat_min, lng_min),
//top right
new google.maps.LatLng(lat_max, lng_max)
));
you can try the solution, compatible with all browser.
Following is orientationchange
compatibility pic:
therefore, I author a orientaionchange
polyfill, it is a based on @media attribute to fix orientationchange utility library——orientationchange-fix
window.addEventListener('orientationchange', function(){
if(window.neworientation.current === 'portrait|landscape'){
// do something……
} else {
// do something……
}
}, false);
what about creating a stub node (document.createElement('div') - or using your library equivalent), filling it with the xml string (via innerHTML) and calling simple recursive function for the root element/or the stub element in case you don't have a root. The function would call itself for all the child nodes.
You could then syntax-highlight along the way, be certain the markup is well-formed (done automatically by browser when appending via innerHTML) etc. It wouldn't be that much code and probably fast enough.
You can only install a language pack at install time in VS 2017 RC. To install RC with a different language:
You can have multiple instances of VS 2017 side by side so this shouldn't interfere with your other installation.
Disclosure: I work on Visual Studio at Microsoft.
In Visual C++ you can also use this notation inside constructor: this->Classname::Classname(parameters of another constructor). See an example below:
class Vertex
{
private:
int x, y;
public:
Vertex(int xCoo, int yCoo): x(xCoo), y(yCoo) {}
Vertex()
{
this->Vertex::Vertex(-1, -1);
}
};
I don't know whether it works somewhere else, I only tested it in Visual C++ 2003 and 2008. You may also call several constructors this way, I suppose, just like in Java and C#.
P.S.: Frankly, I was surprised that this was not mentioned earlier.
You could include in your data hash a key called: _method with value 'delete'.
For example:
data = { id: 1, _method: 'delete' };
url = '/products'
request = $.post(url, data);
request.done(function(res){
alert('Yupi Yei. Your product has been deleted')
});
This will also apply for
Try this
public static int [] insertArry (int inputArray[], int index, int value){
for(int i=0; i< inputArray.length-1; i++) {
if (i == index){
for (int j = inputArray.length-1; j >= index; j-- ){
inputArray[j]= inputArray[j-1];
}
inputArray[index]=value;
}
}
return inputArray;
}
var str = 'abcdefghijkl';_x000D_
console.log(str.match(/.{1,3}/g));
_x000D_
Note: Use {1,3}
instead of just {3}
to include the remainder for string lengths that aren't a multiple of 3, e.g:
console.log("abcd".match(/.{1,3}/g)); // ["abc", "d"]
_x000D_
A couple more subtleties:
.
won't capture those. Use /[\s\S]{1,3}/
instead. (Thanks @Mike).match()
will return null
when you may be expecting an empty array. Protect against this by appending || []
.So you may end up with:
var str = 'abcdef \t\r\nghijkl';_x000D_
var parts = str.match(/[\s\S]{1,3}/g) || [];_x000D_
console.log(parts);_x000D_
_x000D_
console.log(''.match(/[\s\S]{1,3}/g) || []);
_x000D_
Use a HashSet<T>
. For example:
var items = "A B A D A C".Split(' ');
var unique_items = new HashSet<string>(items);
foreach (string s in unique_items)
Console.WriteLine(s);
prints
A B D C
To anyone reading this in 2017, this is how I've done something similar.
DELETE pets, pets_activities FROM pets inner join pets_activities
on pets_activities.id = pets.id WHERE pets.`order` > :order AND
pets.`pet_id` = :pet_id
Generally, to delete rows from multiple tables, the syntax I follow is given below. The solution is based on an assumption that there is some relation between the two tables.
DELETE table1, table2 FROM table1 inner join table2 on table2.id = table1.id
WHERE [conditions]
If you're using Ubuntu, check out the pkgcreator project: http://code.google.com/p/pkgcreator
Based on Agus's function, but I prefer return just the match values:
var bob = "> bob <";
function matchAll(str, regex) {
var res = [];
var m;
if (regex.global) {
while (m = regex.exec(str)) {
res.push(m[1]);
}
} else {
if (m = regex.exec(str)) {
res.push(m[1]);
}
}
return res;
}
var Amatch = matchAll(bob, /(&.*?;)/g);
console.log(Amatch); // yeilds: [>, <]
First things first :) reading books is an excellent approach to problem solving; it's the difference between band-aid fixes and long-term investments in solving problems. Never miss an opportunity to learn. :D
You might choose to interpret the 1
as a number, but environment variables don't care. They just pass around strings:
The argument envp is an array of character pointers to null-
terminated strings. These strings shall constitute the
environment for the new process image. The envp array is
terminated by a null pointer.
(From environ(3posix)
.)
You access environment variables in python using the os.environ
dictionary-like object:
>>> import os
>>> os.environ["HOME"]
'/home/sarnold'
>>> os.environ["PATH"]
'/home/sarnold/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games'
>>> os.environ["PATH"] = os.environ["PATH"] + ":/silly/"
>>> os.environ["PATH"]
'/home/sarnold/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/silly/'
In the Facebook app control panel make sure you have a forward slash on the end of any specified URL if you are only specifying a folder name
i.e.
Page Tab URL: http://mypagetabserver.com/custom_tab/
Having observed people, who have learned Java first, struggle with the concepts of pointers and memory management in C++, I'd say that learning C first is a good idea, in order to grasp these two concepts, isolated from the complexities of other C++ features.
You can use following commands to run any shell command. I have used them on ubuntu.
import os
os.popen('your command here').read()
Note: This is deprecated since python 2.6. Now you must use subprocess.Popen
. Below is the example
import subprocess
p = subprocess.Popen("Your command", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
print p.split("\n")
A point that people haven't mentioned is that while .NET languages don't really make a proper distinction, the question of whether one should take action when an exception occurs, and whether one will resolve it, are actually distinct questions. There are many cases where one should take action based upon exceptions one has no hope of resolving, and there are some cases where all that is necessary to "resolve" an exception is to unwind the stack to a certain point--no further action required.
Because of the common wisdom that one should only "catch" things one can "handle", a lot of code which should take action when exceptions occur, doesn't. For example, a lot of code will acquire a lock, put the guarded object "temporarily" into a state which violates its invariants, then put it object into a legitimate state, and then release the lock back before anyone else can see the object. If an exception occurs while the object is in a dangerously-invalid state, common practice is to release the lock with the object still in that state. A much better pattern would be to have an exception that occurs while the object is in a "dangerous" condition expressly invalidate the lock so any future attempt to acquire it will immediately fail. Consistent use of such a pattern would greatly improve the safety of so-called "Pokemon" exception handling, which IMHO gets a bad reputation primarily because of code which allows exceptions to percolate up without taking appropriate action first.
In most .NET languages, the only way for code to take action based upon an exception is to catch
it (even though it knows it's not going to resolve the exception), perform the action in question and then re-throw
). Another possible approach if code doesn't care about what exception is thrown is to use an ok
flag with a try/finally
block; set the ok
flag to false
before the block, and to true
before the block exits, and before any return
that's within the block. Then, within finally
, assume that if ok
isn't set, an exception must have occurred. Such an approach is semantically better than a catch
/throw
, but is ugly and is less maintainable than it should be.
I've built a function that deals with plotting FFT of real signals. The extra bonus in my function relative to the previous answers is that you get the actual amplitude of the signal.
Also, because of the assumption of a real signal, the FFT is symmetric, so we can plot only the positive side of the x-axis:
import matplotlib.pyplot as plt
import numpy as np
import warnings
def fftPlot(sig, dt=None, plot=True):
# Here it's assumes analytic signal (real signal...) - so only half of the axis is required
if dt is None:
dt = 1
t = np.arange(0, sig.shape[-1])
xLabel = 'samples'
else:
t = np.arange(0, sig.shape[-1]) * dt
xLabel = 'freq [Hz]'
if sig.shape[0] % 2 != 0:
warnings.warn("signal preferred to be even in size, autoFixing it...")
t = t[0:-1]
sig = sig[0:-1]
sigFFT = np.fft.fft(sig) / t.shape[0] # Divided by size t for coherent magnitude
freq = np.fft.fftfreq(t.shape[0], d=dt)
# Plot analytic signal - right half of frequence axis needed only...
firstNegInd = np.argmax(freq < 0)
freqAxisPos = freq[0:firstNegInd]
sigFFTPos = 2 * sigFFT[0:firstNegInd] # *2 because of magnitude of analytic signal
if plot:
plt.figure()
plt.plot(freqAxisPos, np.abs(sigFFTPos))
plt.xlabel(xLabel)
plt.ylabel('mag')
plt.title('Analytic FFT plot')
plt.show()
return sigFFTPos, freqAxisPos
if __name__ == "__main__":
dt = 1 / 1000
# Build a signal within Nyquist - the result will be the positive FFT with actual magnitude
f0 = 200 # [Hz]
t = np.arange(0, 1 + dt, dt)
sig = 1 * np.sin(2 * np.pi * f0 * t) + \
10 * np.sin(2 * np.pi * f0 / 2 * t) + \
3 * np.sin(2 * np.pi * f0 / 4 * t) +\
7.5 * np.sin(2 * np.pi * f0 / 5 * t)
# Result in frequencies
fftPlot(sig, dt=dt)
# Result in samples (if the frequencies axis is unknown)
fftPlot(sig)
Try this first, you may be passing a Null Model:
@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
<label for="Image">Change picture</label>
}
else
{
<label for="Image">Add picture</label>
}
Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.
<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>
Since the other answers here, even though correct, do not explicitly address your initial doubts, I'll do it.
If you call string.Replace(char oldChar, char newChar)
it will replace the occurrences of a character with another character. It is a one-for-one replacement. Because of this the length of the resulting string will be the same.
What you want is to remove the dashes, which, obviously, is not the same thing as replacing them with another character. You cannot replace it by "no character" because 1 character is always 1 character. That's why you need to use the overload that takes strings: strings can have different lengths. If you replace a string of length 1, with a string of length 0, the effect is that the dashes are gone, replaced by "nothing".
int i=99;//is what row you want to select and focus
listViewRamos.FocusedItem = listViewRamos.Items[0];
listViewRamos.Items[i].Selected = true;
listViewRamos.Select();
listViewRamos.EnsureVisible(i);//This is the trick
To make Omar's (or Mahendra's) solution even more universal, the block of code relative to Firefox should be replaced by the following:
/* Firefox */
display: flex;
justify-content: center;
align-items: center;
The problem with Omar's code, otherwise operative, arises when you want to center the box in the screen or in its immediate ancestor. This centering is done either by setting its position to
position: relative;
or position:static;
(not with position:absolute nor fixed).
And then margin: auto; or margin-right: auto; margin-left: auto;
Under this box center aligning environment, Omar's suggestion does not work. It doesn't work either in Internet Explorer 8 (yet 7.7% market share). So for Internet Explorer 8 (and other browsers), a workaround as seen in other above solutions should be considered.
Using the rowid()
function in data.table
:
> set.seed(100)
> df <- data.frame(cat = c(rep("aaa", 5), rep("bbb", 5), rep("ccc", 5)), val = runif(15))
> df <- df[order(df$cat, df$val), ]
> df$num <- data.table::rowid(df$cat)
> df
cat val num
4 aaa 0.05638315 1
2 aaa 0.25767250 2
1 aaa 0.30776611 3
5 aaa 0.46854928 4
3 aaa 0.55232243 5
10 bbb 0.17026205 1
8 bbb 0.37032054 2
6 bbb 0.48377074 3
9 bbb 0.54655860 4
7 bbb 0.81240262 5
13 ccc 0.28035384 1
14 ccc 0.39848790 2
11 ccc 0.62499648 3
15 ccc 0.76255108 4
12 ccc 0.88216552 5
With React Hook, form is made super easy (React Hook Form: https://github.com/bluebill1049/react-hook-form)
i have reused your html markup.
import React from "react";
import useForm from 'react-hook-form';
function Test() {
const { useForm, register } = useForm();
const contactSubmit = data => {
console.log(data);
};
return (
<form name="contactform" onSubmit={contactSubmit}>
<div className="col-md-6">
<fieldset>
<input name="name" type="text" size="30" placeholder="Name" ref={register} />
<br />
<input name="email" type="text" size="30" placeholder="Email" ref={register} />
<br />
<input name="phone" type="text" size="30" placeholder="Phone" ref={register} />
<br />
<input name="address" type="text" size="30" placeholder="Address" ref={register} />
<br />
</fieldset>
</div>
<div className="col-md-6">
<fieldset>
<textarea name="message" cols="40" rows="20" className="comments" placeholder="Message" ref={register} />
</fieldset>
</div>
<div className="col-md-12">
<fieldset>
<button className="btn btn-lg pro" id="submit" value="Submit">
Send Message
</button>
</fieldset>
</div>
</form>
);
}
In the following post, I documented queries to retrieve TABLE and COLUMN comments from Redshift. https://sqlsylvia.wordpress.com/2017/04/29/redshift-comment-views-documenting-data/
Enjoy!
Table Comments
SELECT n.nspname AS schema_name
, pg_get_userbyid(c.relowner) AS table_owner
, c.relname AS table_name
, CASE WHEN c.relkind = 'v' THEN 'view' ELSE 'table' END
AS table_type
, d.description AS table_description
FROM pg_class As c
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_tablespace t ON t.oid = c.reltablespace
LEFT JOIN pg_description As d
ON (d.objoid = c.oid AND d.objsubid = 0)
WHERE c.relkind IN('r', 'v') AND d.description > ''
ORDER BY n.nspname, c.relname ;
Column Comments
SELECT n.nspname AS schema_name
, pg_get_userbyid(c.relowner) AS table_owner
, c.relname AS table_name
, a.attname AS column_name
, d.description AS column_description
FROM pg_class AS c
INNER JOIN pg_attribute As a ON c.oid = a.attrelid
INNER JOIN pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_tablespace t ON t.oid = c.reltablespace
LEFT JOIN pg_description As d
ON (d.objoid = c.oid AND d.objsubid = a.attnum)
WHERE c.relkind IN('r', 'v')
AND a.attname NOT
IN ('cmax', 'oid', 'cmin', 'deletexid', 'ctid', 'tableoid','xmax', 'xmin', 'insertxid')
ORDER BY n.nspname, c.relname, a.attname;
I personally prefer using the following code if it is for a single link. Otherwise it's probably best if you create a function with similar code.
onclick="this.target='_blank';"
I started using that to bypass the W3C's XHTML strict test.
?? No, Nesting an html button
in an html a
(or vice-versa) is not valid html
setTimeout
is a kind of Thread, it holds a operation for a given time and execute.
setTimeout(function,time_in_mills);
in here the first argument should be a function type; as an example if you want to print your name after 3 seconds, your code should be something like below.
setTimeout(function(){console.log('your name')},3000);
Key point to remember is, what ever you want to do by using the setTimeout
method, do it inside a function. If you want to call some other method by parsing some parameters, your code should look like below:
setTimeout(function(){yourOtherMethod(parameter);},3000);
I've encountered similar problems. The reason is that the path to my eclipse includes Chinese characters. Once those characters are deleted, the problem is solved. Please check if there are characters other than English in your path.
finalName is created as:
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
</build>
One of the solutions is to add own property:
<properties>
<finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
<finalName>${finalName}</finalName>
</build>
And now try:
mvn -DfinalName=build clean package
This answer works in SQL Server 2005, 2008, 2012.
At times the value has MANY single quotes. Rather than add a single quote next to each single quote as described above with 'John''s'
. And there are examples using the REPLACE
function to handle many single quotes in a value.
Try the following. This is an update statement but you can use it in an INSERT
statement as well.
SET QUOTED_IDENTIFIER OFF
DECLARE @s VARCHAR(1000)
SET @s = "SiteId:'1'; Rvc:'6'; Chk:'1832'; TrEmp:'150'; WsId:'81'; TtlDue:'-9.40'; TtlDsc:'0'; TtlSvc:'0'; TtlTax:'-0.88'; TtlPay:'0'; TipAmt:'0.00'; SvcSeq:'09'; ReTx:'N'; TraceId:'160110124347N091832';"
UPDATE TransactionPaymentPrompt
set PromptData = @s
from TransactionPaymentPrompt tpp with (nolock)
where tpp.TransactionID = '106627343'
Hash results varies between 32bit and 64bit platforms
If a calculated hash shall be the same on both platforms consider using
def hash32(value):
return hash(value) & 0xffffffff
For support to all API levels you can use it like this:
ViewPropertyAnimator.animate(view).translationYBy(-yourY).translationXBy(-yourX).setDuration(0);
I would use a mysqli connection to connect to the database. Here is an example:
$connection = new mysqli("127.0.0.1", "username", "password", "database_name", 3306);
The next step is to select the information. In your case I would do:
$query = $connection->query("SELECT `names` FROM `Customers`;");
And finally we make an array from all these names by typing:
$array = Array();
while($result = $query->fetch_assoc()){
$array[] = $result['names'];
}
print_r($array);
So what I've done in this code: I selected all names from the table using a mysql query. Next I use a while loop to check if the $query has a next value. If so the while loop continues and adds that value to the array '$array'. Else the loop stops. And finally I print the array using the 'print_r' method so you can see it all works. I hope this was helpful.
Easy and php's in-built function.
So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]
I've always just selected Export from Eclipse. It builds the war file and includes all necessary files. Providing you created the project as a web project that's all you'll need to do. Eclipse makes it very simple to do.
Instead of use set_userdata you should use set_flashdata.
According to CI user guide:
CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared. These can be very useful, and are typically used for informational or status messages (for example: "record 2 deleted").
http://ellislab.com/codeigniter/user-guide/libraries/sessions.html
Retrieve File name first then in Blade file use anchor(a) tag like below shown. This would works for image view also.
<a href="{{ asset('storage/admission-document-uploads/' . $filename) }}" target="_black"> view Pdf </a>;
For Single valued associations, i.e.-One-to-One and Many-to-One:-
Default Lazy=proxy
Proxy lazy loading:- This implies a proxy object of your associated entity is loaded. This means that only the id connecting the two entities is loaded for the proxy object of associated entity.
Eg: A and B are two entities with Many to one association. ie: There may be multiple A's for every B. Every object of A will contain a reference of B.
`
public class A{
int aid;
//some other A parameters;
B b;
}
public class B{
int bid;
//some other B parameters;
}
`
The relation A will contain columns(aid,bid,...other columns of entity A).
The relation B will contain columns(bid,...other columns of entity B)
Proxy implies when A is fetched, only id is fetched for B and stored into a proxy object of B which contains only id.
Proxy object of B is a an object of a proxy-class which is a subclass of B with only minimal fields.
Since bid is already part of relation A, it is not necessary to fire a query to get bid from the relation B.
Other attributes of entity B are lazily loaded only when a field other than bid is accessed.
For Collections, i.e.-Many-to-Many and One-to-Many:-
Default Lazy=true
Please also note that the fetch strategy(select,join etc) can override lazy.
ie: If lazy='true' and fetch='join', fetching of A will also fetch B or Bs(In case of collections). You can get the reason if you think about it.
Default fetch for single valued association is "join".
Default fetch for collections is "select".
Please verify the last two lines. I have deduced that logically.
I found out that with HostGator you have to set files to CMOD 644 and Folders to 755. Since I did this based on their tech support it works with HostGator
Add -L/opt/lib
to your compiler parameters, this makes the compiler and linker search that path for libcalc.so
in that folder.
I managed to do a portable, non-polling solution with 3 processes by abusing terminal control and sessions.
The trick is:
That way:
Shortcomings:
Running Visual Studio Code as Administrator should do the trick.
If you're on Windows you can:
Make sure you have all other instances of VS Code closed and then try to run as Administrator. The electron framework likes to stall processes when closing them so it's best to check your task manager and kill the remaining processes.
Related Changes in CodebaseIf for some weird reason this is not running your commands as an Administrator you can try the runas
command. Microsoft: runas command
runas /user:Administrator myCommand
runas "/user:First Last" "my command"
Try
sed 'NUMq;d' /etc/*release | awk {'print $1}'
where NUM is line number
ex. sed '1q;d' /etc/*release | awk {'print $1}'
I'm using following markup and had encoutered the same problem:
<ul class="nav">
<li><a href="abc.html">abc</a></li>
<li><a href="def.html">def</a></li>
</ul>
Here I have used the following logic:
$(".nav > li").click(function(e){
if(e.target != this) return; // only continue if the target itself has been clicked
// this section only processes if the .nav > li itself is clicked.
alert("you clicked .nav > li, but not it's children");
});
In terms of the exact question, I can see that working as follows:
$(".example").click(function(e){
if(e.target != this) return; // only continue if the target itself has been clicked
$(".example").fadeOut("fast");
});
or of course the other way around:
$(".example").click(function(e){
if(e.target == this){ // only if the target itself has been clicked
$(".example").fadeOut("fast");
}
});
Hope that helps.
SELECT CAST(CAST(year AS varchar) + '/' + CAST(month AS varchar) + '/' + CAST(day as varchar) AS datetime) AS MyDateTime
FROM table
Try This:
mydict = {'one': 1, 'two': 2, 'three': 3}
mykeys = ['three', 'one','ten']
newList=[mydict[k] for k in mykeys if k in mydict]
print newList
[3, 1]
1. If that class from which you want to call this method, is in the same package, then create an instance of this class and call the method.
2. Use Composition
3. It would be better to have a Generic ArrayList
like ArrayList<Integer>
etc...
eg:
public class Test{
public ArrayList<Integer> myNumbers() {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(11);
numbers.add(3);
return(numbers);
}
}
public class T{
public static void main(String[] args){
Test t = new Test();
ArrayList<Integer> arr = t.myNumbers(); // You can catch the returned integer arraylist into an arraylist.
}
}
You can use the function toprettyxml()
from xml.dom.minidom
in order to do that:
def prettify(elem):
"""Return a pretty-printed XML string for the Element.
"""
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent="\t")
The idea is to print your Element
in a string, parse it using minidom and convert it again in XML using the toprettyxml
function.
Source: http://pymotw.com/2/xml/etree/ElementTree/create.html
a csv-file is just like any other file a stream of characters. the getline reads from the file up to a delimiter however in your case the delimiter for the last item is not ' ' as you assume
getline(file, genero, ' ') ;
it is newline \n
so change that line to
getline(file, genero); // \n is default delimiter
You just need to do:
#!/bin/bash
count=$(cat last_queries.txt | wc -l)
$(perl test.pl test2 $count)
However, if you want to call your Perl command later, and that's why you want to assign it to a variable, then:
#!/bin/bash
count=$(cat last_queries.txt | wc -l)
var="perl test.pl test2 $count" # You need double quotes to get your $count value substituted.
...stuff...
eval $var
As per Bash's help:
~$ help eval
eval: eval [arg ...]
Execute arguments as a shell command.
Combine ARGs into a single string, use the result as input to the shell,
and execute the resulting commands.
Exit Status:
Returns exit status of command or success if command is null.
This works in all chrome, IE, Firefox.
In Database > table > field type .for example set the symbol column TO varchar(2) utf8_bin
php code:
$symbol = '£';
echo mb_convert_encoding($symbol, 'UTF-8', 'HTML-ENTITIES');
or
html_entity_decode($symbol, ENT_NOQUOTES, 'UTF-8');
And also make sure set the HTML OR XML encoding to encoding="UTF-8"
Note: You should make sure that database, document type and php code all have a same encoding
How ever the better solution would be using £
Get the path of running Apache
$ ps -ef | grep apache
apache 12846 14590 0 Oct20 ? 00:00:00 /usr/sbin/apache2
Append -V
argument to the path
$ /usr/sbin/apache2 -V | grep SERVER_CONFIG_FILE
-D SERVER_CONFIG_FILE="/etc/apache2/apache2.conf"
Reference:
http://commanigy.com/blog/2011/6/8/finding-apache-configuration-file-httpd-conf-location
Just setting Skip Install to YES did not work for me. Hopefully this will help somebody.
I went to dependence of my project targets: Coreplot-CocoaTouch. Then went to Coreplot-CocoaTouch Targets. In its Targets opened Build Phases. Then opened Copy Headers. There I had some of headers in Public, some in Private and some in Project. Moved ALL of them to Project.
Of course, in Build Settings of Coreplot-CocoaTouch Targets checked that Skip Install was set to YES in Deployment options.
And this time Archive made an archive that could be signed and .ipa produced.
$('#my_select option:selected').attr('id');
I am beginner to iOS development so I would like to share whole info I got in this section.
First from image assets (images.xcassets) create image set .
According to Documentation here is all sizes need to create background image.
For iPhone 5:
640 x 1136
For iPhone 6:
750 x 1334 (@2x) for portrait
1334 x 750 (@2x) for landscape
For iPhone 6 Plus:
1242 x 2208 (@3x) for portrait
2208 x 1242 (@3x) for landscape
iPhone 4s (@2x)
640 x 960
iPad and iPad mini (@2x)
1536 x 2048 (portrait)
2048 x 1536 (landscape)
iPad 2 and iPad mini (@1x)
768 x 1024 (portrait)
1024 x 768 (landscape)
iPad Pro (@2x)
2048 x 2732 (portrait)
2732 x 2048 (landscape)
call the image background we can call image from image assets by using this method UIImage(named: "background")
here is full code example
override func viewDidLoad() {
super.viewDidLoad()
assignbackground()
// Do any additional setup after loading the view.
}
func assignbackground(){
let background = UIImage(named: "background")
var imageView : UIImageView!
imageView = UIImageView(frame: view.bounds)
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.clipsToBounds = true
imageView.image = background
imageView.center = view.center
view.addSubview(imageView)
self.view.sendSubviewToBack(imageView)
}
Oracle Setup:
CREATE OR REPLACE FUNCTION split_String(
i_str IN VARCHAR2,
i_delim IN VARCHAR2 DEFAULT ','
) RETURN SYS.ODCIVARCHAR2LIST DETERMINISTIC
AS
p_result SYS.ODCIVARCHAR2LIST := SYS.ODCIVARCHAR2LIST();
p_start NUMBER(5) := 1;
p_end NUMBER(5);
c_len CONSTANT NUMBER(5) := LENGTH( i_str );
c_ld CONSTANT NUMBER(5) := LENGTH( i_delim );
BEGIN
IF c_len > 0 THEN
p_end := INSTR( i_str, i_delim, p_start );
WHILE p_end > 0 LOOP
p_result.EXTEND;
p_result( p_result.COUNT ) := SUBSTR( i_str, p_start, p_end - p_start );
p_start := p_end + c_ld;
p_end := INSTR( i_str, i_delim, p_start );
END LOOP;
IF p_start <= c_len + 1 THEN
p_result.EXTEND;
p_result( p_result.COUNT ) := SUBSTR( i_str, p_start, c_len - p_start + 1 );
END IF;
END IF;
RETURN p_result;
END;
/
Query
SELECT ROWNUM AS ID,
COLUMN_VALUE AS Data
FROM TABLE( split_String( 'A,B,C,D' ) );
Output:
ID DATA
-- ----
1 A
2 B
3 C
4 D
It's easier using Array.filter
:
var unique = arr.filter(function(elem, index, self) {
return index === self.indexOf(elem);
})
This is what worked for me. I am not sure why the syntax is different, But it was extremely frustrating trying every combination of activate, inactive, deactivated, disabled, etc. In lower case upper case in quotes out of quotes in brackets out of brackets etc. Well, here's the winning combination for me, for some reason.. different than everyone else?
import tkinter
class App(object):
def __init__(self):
self.tree = None
self._setup_widgets()
def _setup_widgets(self):
butts = tkinter.Button(text = "add line", state="disabled")
butts.grid()
def main():
root = tkinter.Tk()
app = App()
root.mainloop()
if __name__ == "__main__":
main()
I am facing this problem many times from last few days, the answer above works perfectly fine. I was looking for the exact reason for this problem and in my case I found slow internet or no internet on your machine(assuming you are taking project to windows from mac, that may not be required).
I've noticed while doing build it stopped fetching a URL(http://.maven.org/). I don't know why android studio doing these things again, but that seems to be the only problem in my case.
Since None of the above solutions worked for my usecase, here I provide a solution using None
(pun!) which can be adapted to a wide variety of scenarios.
Here is a sample piece of code that produces cluttered ticks on both X
and Y
axes.
# Note the super cluttered ticks on both X and Y axis.
# inputs
x = np.arange(1, 101)
y = x * np.log(x)
fig = plt.figure() # create figure
ax = fig.add_subplot(111)
ax.plot(x, y)
ax.set_xticks(x) # set xtick values
ax.set_yticks(y) # set ytick values
plt.show()
Now, we clean up the clutter with a new plot that shows only a sparse set of values on both x and y axes as ticks.
# inputs
x = np.arange(1, 101)
y = x * np.log(x)
fig = plt.figure() # create figure
ax = fig.add_subplot(111)
ax.plot(x, y)
ax.set_xticks(x)
ax.set_yticks(y)
# which values need to be shown?
# here, we show every third value from `x` and `y`
show_every = 3
sparse_xticks = [None] * x.shape[0]
sparse_xticks[::show_every] = x[::show_every]
sparse_yticks = [None] * y.shape[0]
sparse_yticks[::show_every] = y[::show_every]
ax.set_xticklabels(sparse_xticks, fontsize=6) # set sparse xtick values
ax.set_yticklabels(sparse_yticks, fontsize=6) # set sparse ytick values
plt.show()
Depending on the usecase, one can adapt the above code simply by changing show_every
and using that for sampling tick values for X or Y or both the axes.
If this stepsize based solution doesn't fit, then one can also populate the values of sparse_xticks
or sparse_yticks
at irregular intervals, if that is what is desired.
Try using batch file
php -S localhost:8000
.bat
extension, server.bat
server.bat
file your server is ready on http://localhost:8000
if you got error php not recognize any internal or external command
then goto environment variable and edit path to php.exe
"C:\wamp\bin\php\php5.4.3"
As a quick solution you can copy the JavaFX runtime JAR file and those referenced from Oracle JRE(JDK) or any self-contained application that uses JavaFX(e.g. JavaFX Scene Builder 2.0):
cp <JRE_WITH_JAVAFX_HOME>/lib/ext/jfxrt.jar <JRE_HOME>/lib/ext/
cp <JRE_WITH_JAVAFX_HOME>/lib/javafx.properties <JRE_HOME>/lib/
cp <JRE_WITH_JAVAFX_HOME>/lib/amd64/libprism_* <JRE_HOME>/lib/amd64/
cp <JRE_WITH_JAVAFX_HOME>/lib/amd64/libglass.so <JRE_HOME>/lib/amd64/
cp <JRE_WITH_JAVAFX_HOME>/lib/amd64/libjavafx_* <JRE_HOME>/lib/amd64/
just make sure you have the gtk 2.18 or higher
the Microsoft Mediaplayer can do all, you need. I use the MS Mediaservices of 2003 / 2008 Server to deliver Video as Broadcast and Unicast Stream. This Service could GET the Stream from the cam and Broadcast it. Than you have "only" the Problem to "Display" that Picture in ALL Browers at all OS-Systems
My Tip :check first the OS , than load your plugin . on Windows it is easy -take WMP , on other take MS Silverligt ...
Since rows already exist in the table, the ALTER
statement is trying to insert NULL
into the newly created column for all of the existing rows. You would have to add the column as allowing NULL
, then fill the column with the values you want, and then set it to NOT NULL
afterwards.
You can use three quotes to do it.
You can use single quotes:
def myfunction(para1,para2):
'''
The stuff inside the function
'''
Or double quotes:
def myfunction(para1,para2):
"""
The stuff inside the function
"""
SELECT FIELD FROM TABLE
ORDER BY
isnumeric(FIELD) desc,
CASE ISNUMERIC(test)
WHEN 1 THEN CAST(CAST(test AS MONEY) AS INT)
ELSE NULL
END,
FIELD
As per this link you need to cast to MONEY then INT to avoid ordering '$' as a number.
Easy Workaround (no VBA required)
From here, edit the SQL directly by adding '?' wherever you want a parameter. Works the same way as before except you don't get nagged.
There are a lot of sources for selenium - here is good one for simple use Selenium, and here is a example snippet too Selenium Examples
You can find a lot of good sources to use selenium, it's not too hard to get it set up and start using it.
.wrapper{
float: left;
width: 100%;
text-align: center;
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.button{
display:inline-block;
}
<div class="wrapper">
<button class="button">Button1</button>
<button class="button">Button2</button>
</div>
1) I'd add a /n after init. i.e. write( USB, "init\n", 5);
2) Double check the serial port configuration. Odds are something is incorrect in there. Just because you don't use ^Q/^S or hardware flow control doesn't mean the other side isn't expecting it.
3) Most likely: Add a "usleep(100000); after the write(). The file-descriptor is set not to block or wait, right? How long does it take to get a response back before you can call read? (It has to be received and buffered by the kernel, through system hardware interrupts, before you can read() it.) Have you considered using select() to wait for something to read()? Perhaps with a timeout?
Edited to Add:
Do you need the DTR/RTS lines? Hardware flow control that tells the other side to send the computer data? e.g.
int tmp, serialLines;
cout << "Dropping Reading DTR and RTS\n";
ioctl ( readFd, TIOCMGET, & serialLines );
serialLines &= ~TIOCM_DTR;
serialLines &= ~TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
usleep(100000);
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
sleep (2);
cout << "Setting Reading DTR and RTS\n";
serialLines |= TIOCM_DTR;
serialLines |= TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
Use the NSNumber method intValue
Here is Apple reference documentation
Replace this:
StreamWriter file2 = new StreamWriter("c:/file.txt");
with this:
StreamWriter file2 = new StreamWriter("c:/file.txt", true);
true
indicates that it appends text.
In JavaScript, \w and \d are ASCII, while \s is Unicode. Don't ask me why. JavaScript does support \p with Unicode categories, which you can use to emulate a Unicode-aware \w and \d.
For \d use \p{N} (numbers)
For \w use [\p{L}\p{N}\p{Pc}\p{M}] (letters, numbers, underscores, marks)
Update: Unfortunately, I was wrong about this. JavaScript does does not officially support \p either, though some implementations may still support this. The only Unicode support in JavaScript regexes is matching specific code points with \uFFFF. You can use those in ranges in character classes.
Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.
That option could be useful when copying very large files over a potentially unstable connection.
Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.
gettimeofday() will probably do what you want.
If you're on Intel hardware, here's how to read the CPU real-time instruction counter. It will tell you the number of CPU cycles executed since the processor was booted. This is probably the finest-grained, lowest overhead counter you can get for performance measurement.
Note that this is the number of CPU cycles. On linux you can get the CPU speed from /proc/cpuinfo and divide to get the number of seconds. Converting this to a double is quite handy.
When I run this on my box, I get
11867927879484732 11867927879692217 it took this long to call printf: 207485
Here's the Intel developer's guide that gives tons of detail.
#include <stdio.h>
#include <stdint.h>
inline uint64_t rdtsc() {
uint32_t lo, hi;
__asm__ __volatile__ (
"xorl %%eax, %%eax\n"
"cpuid\n"
"rdtsc\n"
: "=a" (lo), "=d" (hi)
:
: "%ebx", "%ecx");
return (uint64_t)hi << 32 | lo;
}
main()
{
unsigned long long x;
unsigned long long y;
x = rdtsc();
printf("%lld\n",x);
y = rdtsc();
printf("%lld\n",y);
printf("it took this long to call printf: %lld\n",y-x);
}
ES6: In HTML, include the main JavaScript file using attribute type="module"
(browser support):
<script type="module" src="script.js"></script>
And in the script.js
file, include another file like this:
import { hello } from './module.js';
...
// alert(hello());
Inside the included file (module.js
), you must export the function/class that you will import:
export function hello() {
return "Hello World";
}
A working example is here. More information is here.
Another Hamming weight algorithm if you're on a BMI2 capable CPU
the_weight=__tzcnt_u64(~_pext_u64(data[i],data[i]));
Have fun!
In Eclipse, go to Window → Preferences → General → Network Connections. In the Active Provider combo box, choose "Manual". In the proxy entries table, for each entry click "Edit..." and supply your proxy host, port, username and password details.
Here is a simple example of adding an image to a JFrame
:
frame.add(new JLabel(new ImageIcon("Path/To/Your/Image.png")));
If your input file is in.txt, you can use freopen to set stdin file as in.txt
freopen("in.txt","r",stdin);
if you want to do the same with your output:
freopen("out.txt","w",stdout);
this will work for std::cin (if using c++), printf, etc...
This will also help you in debugging your code in clion, vscode
Use Callback. It worked for me!
export function addProduct(props, callback) {
return dispatch =>
axios.post(`${ROOT_URL}/cart`, props, config)
.then(response => {
dispatch({ type: types.AUTH_USER });
localStorage.setItem('token', response.data.token);
callback();
});
}
In component, you just have to add the callback
this.props.addProduct(props, () => this.props.history.push('/cart'))
Try this
Sub Txt2Col()
Dim rng As Range
Set rng = [C7]
Set rng = Range(rng, Cells(Rows.Count, rng.Column).End(xlUp))
rng.TextToColumns Destination:=rng, DataType:=xlDelimited, ' rest of your settings
Update: button click event to act on another sheet
Private Sub CommandButton1_Click()
Dim rng As Range
Dim sh As Worksheet
Set sh = Worksheets("Sheet2")
With sh
Set rng = .[C7]
Set rng = .Range(rng, .Cells(.Rows.Count, rng.Column).End(xlUp))
rng.TextToColumns Destination:=rng, DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, _
Semicolon:=False, _
Comma:=True,
Space:=False,
Other:=False, _
FieldInfo:=Array(Array(1, xlGeneralFormat), Array(2, xlGeneralFormat), Array(3, xlGeneralFormat)), _
TrailingMinusNumbers:=True
End With
End Sub
Note the .
's (eg .Range
) they refer to the With
statement object
You could use Reachability
by ? (available here).
#import "Reachability.h"
- (BOOL)networkConnection {
return [[Reachability reachabilityWithHostName:@"www.google.com"] currentReachabilityStatus];
}
if ([self networkConnection] == NotReachable) { /* No Network */ } else { /* Network */ } //Use ReachableViaWiFi / ReachableViaWWAN to get the type of connection.
with this command:
for f in `find .`; do echo `file -i "$f"`; done
you can list all files in a directory and subdirectories and the corresponding encoding.
David's answer is correct, but if it's still a little abstract, here are two examples:
You might want to zero all freed pointers to catch memory problems earlier. C-style you'd do:
void freeAndZero(void** ptr)
{
free(*ptr);
*ptr = 0;
}
void* ptr = malloc(...);
...
freeAndZero(&ptr);
In C++ to do the same, you might do:
template<class T> void freeAndZero(T* &ptr)
{
delete ptr;
ptr = 0;
}
int* ptr = new int;
...
freeAndZero(ptr);
When dealing with linked-lists - often simply represented as pointers to a next node:
struct Node
{
value_t value;
Node* next;
};
In this case, when you insert to the empty list you necessarily must change the incoming pointer because the result is not the NULL
pointer anymore. This is a case where you modify an external pointer from a function, so it would have a reference to pointer in its signature:
void insert(Node* &list)
{
...
if(!list) list = new Node(...);
...
}
There's an example in this question.
I can usually resolve this problem when a computer is under my control, but it's more of a nuisance when working with a grid. When a grid is not homogenous, not all libraries may be installed, and my experience has often been that a package wasn't installed because a dependency wasn't installed. To address this, I check the following:
.libPaths()
is a good check.ldd
results for R, to be sure about shared librariesHaving encountered this quite a bit, some of these steps become fairly routine. Although #7 might seem like a good starting point, these are listed in approximate order of the frequency that I use them.
Try this:
while read line
do
echo -e |wc -m
done <abc.txt