I had a problem with a CSV that contains fields with a quote character in them, so using the TextFieldParser, I came up with the following:
private static string[] parseCSVLine(string csvLine)
{
using (TextFieldParser TFP = new TextFieldParser(new MemoryStream(Encoding.UTF8.GetBytes(csvLine))))
{
TFP.HasFieldsEnclosedInQuotes = true;
TFP.SetDelimiters(",");
try
{
return TFP.ReadFields();
}
catch (MalformedLineException)
{
StringBuilder m_sbLine = new StringBuilder();
for (int i = 0; i < TFP.ErrorLine.Length; i++)
{
if (i > 0 && TFP.ErrorLine[i]== '"' &&(TFP.ErrorLine[i + 1] != ',' && TFP.ErrorLine[i - 1] != ','))
m_sbLine.Append("\"\"");
else
m_sbLine.Append(TFP.ErrorLine[i]);
}
return parseCSVLine(m_sbLine.ToString());
}
}
}
A StreamReader is still used to read the CSV line by line, as follows:
using(StreamReader SR = new StreamReader(FileName))
{
while (SR.Peek() >-1)
myStringArray = parseCSVLine(SR.ReadLine());
}
var valKeyDown;
var valKeyUp;
function integerOnly(e) {
e = e || window.event;
var code = e.which || e.keyCode;
if (!e.ctrlKey) {
var arrIntCodes1 = new Array(96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 8, 9, 116); // 96 TO 105 - 0 TO 9 (Numpad)
if (!e.shiftKey) { //48 to 57 - 0 to 9
arrIntCodes1.push(48); //These keys will be allowed only if shift key is NOT pressed
arrIntCodes1.push(49); //Because, with shift key (48 to 57) events will print chars like @,#,$,%,^, etc.
arrIntCodes1.push(50);
arrIntCodes1.push(51);
arrIntCodes1.push(52);
arrIntCodes1.push(53);
arrIntCodes1.push(54);
arrIntCodes1.push(55);
arrIntCodes1.push(56);
arrIntCodes1.push(57);
}
var arrIntCodes2 = new Array(35, 36, 37, 38, 39, 40, 46);
if ($.inArray(e.keyCode, arrIntCodes2) != -1) {
arrIntCodes1.push(e.keyCode);
}
if ($.inArray(code, arrIntCodes1) == -1) {
return false;
}
}
return true;
}
$('.integerOnly').keydown(function (event) {
valKeyDown = this.value;
return integerOnly(event);
});
$('.integerOnly').keyup(function (event) { //This is to protect if user copy-pastes some character value ,..
valKeyUp = this.value; //In that case, pasted text is replaced with old value,
if (!new RegExp('^[0-9]*$').test(valKeyUp)) { //which is stored in 'valKeyDown' at keydown event.
$(this).val(valKeyDown); //It is not possible to check this inside 'integerOnly' function as,
} //one cannot get the text printed by keydown event
}); //(that's why, this is checked on keyup)
$('.integerOnly').bind('input propertychange', function(e) { //if user copy-pastes some character value using mouse
valKeyUp = this.value;
if (!new RegExp('^[0-9]*$').test(valKeyUp)) {
$(this).val(valKeyDown);
}
});
For example, To store data in the session, you will typically use the put
method or the session
helper:
// Via a request instance...
$request->session()->put('key', 'value');
or
// Via the global helper...
session(['key' => 'value']);
for retrieving an item from the session, you can use get
:
$value = $request->session()->get('key', 'default value');
or global session
helper :
$value = session('key', 'default value');
To determine if an item is present in the session, you may use the has
method:
if ($request->session()->has('users')) {
//
}
Run the following Command: npm install --save-dev @angular/cli@latest
After running the above command the console might popup the below message
The Angular CLI configuration format has been changed, and your existing configuration can be updated automatically by running the following command: ng update @angular/cli
CREATE PROCEDURE UpdateTables
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @RowCount1 INTEGER
DECLARE @RowCount2 INTEGER
DECLARE @RowCount3 INTEGER
DECLARE @RowCount4 INTEGER
UPDATE Table1 Set Column = 0 WHERE Column IS NULL
SELECT @RowCount1 = @@ROWCOUNT
UPDATE Table2 Set Column = 0 WHERE Column IS NULL
SELECT @RowCount2 = @@ROWCOUNT
UPDATE Table3 Set Column = 0 WHERE Column IS NULL
SELECT @RowCount3 = @@ROWCOUNT
UPDATE Table4 Set Column = 0 WHERE Column IS NULL
SELECT @RowCount4 = @@ROWCOUNT
SELECT @RowCount1 AS Table1, @RowCount2 AS Table2, @RowCount3 AS Table3, @RowCount4 AS Table4
END
If none of this did not help, then try to swap ^ in "^version" to ~ "~version".
I know this is not the case but if you need to keep the original freq column, you can use another tidyverse
approach together with rep
:
library(purrr)
df <- data.frame(var1 = c('a', 'b', 'c'), var2 = c('d', 'e', 'f'), freq = 1:3)
df %>%
map_df(., rep, .$freq)
#> # A tibble: 6 x 3
#> var1 var2 freq
#> <fct> <fct> <int>
#> 1 a d 1
#> 2 b e 2
#> 3 b e 2
#> 4 c f 3
#> 5 c f 3
#> 6 c f 3
Created on 2019-12-21 by the reprex package (v0.3.0)
null is unknown in sql so we cant expect two unknowns to be same.
However you can get that behavior by setting ANSI_NULLS to Off(its On by Default) You will be able to use = operator for nulls
SET ANSI_NULLS off
if null=null
print 1
else
print 2
set ansi_nulls on
if null=null
print 1
else
print 2
simply add the following attribute
// for disabled i.e. cannot highlight value or change
disabled="disabled"
// for readonly i.e. can highlight value but not change
readonly="readonly"
jQuery to make the change to the element (substitute disabled
for readonly
in the following for setting readonly
attribute).
$('#fieldName').attr("disabled","disabled")
or
$('#fieldName').attr("disabled", true)
NOTE: As of jQuery 1.6, it is recommended to use .prop()
instead of .attr()
. The above code will work exactly the same except substitute .attr()
for .prop()
.
"Sleep" state connections are most often created by code that maintains persistent connections to the database.
This could include either connection pools created by application frameworks, or client-side database administration tools.
As mentioned above in the comments, there is really no reason to worry about these connections... unless of course you have no idea where the connection is coming from.
(CAVEAT: If you had a long list of these kinds of connections, there might be a danger of running out of simultaneous connections.)
Neither. You should use bcrypt
. The hashes you mention are all optimized to be quick and easy on hardware, and so cracking them share the same qualities. If you have no other choice, at least be sure to use a long salt and re-hash multiple times.
PHP 5.5 offers new functions for password hashing. This is the recommend approach for password storage in modern web applications.
// Creating a hash
$hash = password_hash($password, PASSWORD_DEFAULT, ['cost' => 12]);
// If you omit the ['cost' => 12] part, it will default to 10
// Verifying the password against the stored hash
if (password_verify($password, $hash)) {
// Success! Log the user in here.
}
If you're using an older version of PHP you really should upgrade, but until you do you can use password_compat to expose this API.
Also, please let password_hash()
generate the salt for you. It uses a CSPRNG.
NUL
characters.(Proof of Concept for both caveats here.)
You might be tempted to resolve the first caveat by pre-hashing your passwords before running them through bcrypt, but doing so can cause your application to run headfirst into the second.
Instead of writing your own scheme, use an existing library written and/or evaluated by security experts.
Zend\Crypt
(part of Zend Framework) offers BcryptSha
PasswordLock
is similar to BcryptSha
but it also encrypts the bcrypt hashes with an authenticated encryption library.TL;DR - Use bcrypt.
My solution is:
import threading, time
def a():
t = threading.currentThread()
while getattr(t, "do_run", True):
print('Do something')
time.sleep(1)
def getThreadByName(name):
threads = threading.enumerate() #Threads list
for thread in threads:
if thread.name == name:
return thread
threading.Thread(target=a, name='228').start() #Init thread
t = getThreadByName('228') #Get thread by name
time.sleep(5)
t.do_run = False #Signal to stop thread
t.join()
this solution it gonna be ok on Redhat 8.0
sudo yum install libxml2-devel
If you have yum you could do:
yum remove nodesource-release* nodejs
yum clean all
And after that check if its deleted:
rpm -qa 'node|npm'
Just to add to answers by Mr. Dimitrov and Jason, if you are using a specific profile and you have put your region setting there,then for all the requests you need to add
"--profile" option.
For example:
Lets say you have AWS Playground profile, and the ~/.aws/config has [profile playground] which further has something like,
[profile playground]
region=us-east-1
then, use something like below
aws ecs list-container-instances --cluster default --profile playground
the source to the ssl version of this is here: http://atmospherian.wordpress.com/downloads/
java.util.UUID.randomUUID();
Looking at your own answer @Bog, I think you want;
$plugin_dir_path = dirname(__FILE__);
I'm using this tutorial and it works nicely for my application.
In my activity I put this code:
GPSTracker tracker = new GPSTracker(this);
if (!tracker.canGetLocation()) {
tracker.showSettingsAlert();
} else {
latitude = tracker.getLatitude();
longitude = tracker.getLongitude();
}
also check if your emulator runs with Google API
print_r($this->session->userdata);
or
print_r($this->session->all_userdata());
There is actually quite a difference, a solutions architect looks a a requirement holistically, say for example the requirement is to reduce the number of staff in a call center taking Pizza orders, a solutions architect looks at all of the component pieces that will have to come together to satisfy this, things like what voice recognition software to use, what hardware is required, what OS would be best suited to host it, integration of the IVR software with the provisioning system etc.
An application archirect in this scenario on the other hand deals with the specifics of how the software will interact, what language is best suited, how to best use any existing api's, creating an api if none exists etc.
Both have their place, both tasks must be done in order to staisfy the requirement and in large orgs you will have dedicated people doing it, in smaller dev shops often times a developer will have to pick up all of the architectural tasks as part of the overall development, because there is no-one else, imo its overly cynical to say that its just a marketing term, it is a real role (even if it's the dev picking it up ad-hoc) and particulary valuable at project kick-off.
if you use to generate the id = GenerationType.AUTO
strategy in your entity.
Replaces user.setId (1)
by user.setId (null)
, and the problem is solved.
This resolved the issue on Windows 10 after the last update
go Control Panel ->> Programs ->> Programs and Features ->> Turn Windows features on or off ->> Internet Information Services
But based on previous response it doesn't work unless checking all these options as on pic below
You can also try the find
command. If you only want files in the current directory:
find . -d 1 -prune -ls
Run a command on each of them?
find . -d 1 -prune -exec echo {} \;
Count lines, but only in files?
find . -d 1 -prune -type f -exec wc -l {} \;
if you just want to check if one or the other element are present you can use this custom helper
Handlebars.registerHelper('if_or', function(elem1, elem2, options) {
if (Handlebars.Utils.isEmpty(elem1) && Handlebars.Utils.isEmpty(elem2)) {
return options.inverse(this);
} else {
return options.fn(this);
}
});
like this
{{#if_or elem1 elem2}}
{{elem1}} or {{elem2}} are present
{{else}}
not present
{{/if_or}}
if you also need to be able to have an "or" to compare function return values I would rather add another property that returns the desired result.
The templates should be logicless after all!
I was stuck in same problem for many hours. I tried everything found on internet.
At last, I figured out a surprising solution : I had missed \SQLEXPRESS
part of the Server name: MY-COMPUTER-NAME\SQLEXPRESS
I hope this helps someone who is stuck in similar kind of problem.
Here is the answer in Razor syntax
<table border="1" cellpadding="5">
<thead>
<tr>
@foreach (System.Data.DataColumn col in Model.Columns)
{
<th>@col.Caption</th>
}
</tr>
</thead>
<tbody>
@foreach(System.Data.DataRow row in Model.Rows)
{
<tr>
@foreach (var cell in row.ItemArray)
{
<td>@cell.ToString()</td>
}
</tr>
}
</tbody>
</table>
you will get the time without specifying the date format. convert the string to date using Date
object
var myDate = new Date('Mon 03-Jul-2017, 06:00 PM');
working solution:
var myDate= new Date('Mon 03-Jul-2017, 06:00 PM');_x000D_
console.log(moment(myDate).format('HH:mm')); // 24 hour format _x000D_
console.log(moment(myDate).format('hh:mm'));_x000D_
console.log(moment(myDate).format('hh:mm A'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
Using CROSS APPLY
:
SELECT ID, Col1, Col2, Col3, MinValue
FROM YourTable
CROSS APPLY (SELECT MIN(d) AS MinValue FROM (VALUES (Col1), (Col2), (Col3)) AS a(d)) A
You need a development provisioning profile on your build machine. Apps can run on the simulator without a profile, but they are required to run on an actual device.
If you open the project in Xcode, it may automatically set up provisioning for you. Otherwise you will have to create go to the iOS Dev Center and create a profile.
A simple way to used copy module to transfer the file from one server to another
Here is playbook
---
- hosts: machine1 {from here file will be transferred to another remote machine}
tasks:
- name: transfer data from machine1 to machine2
copy:
src=/path/of/machine1
dest=/path/of/machine2
delegate_to: machine2 {file/data receiver machine}
I prepared a piece of code to show you how to use the task for some of these scenarios.
// method to run tasks in a parallel
public async Task RunMultipleTaskParallel(Task[] tasks) {
await Task.WhenAll(tasks);
}
// methode to run task one by one
public async Task RunMultipleTaskOneByOne(Task[] tasks)
{
for (int i = 0; i < tasks.Length - 1; i++)
await tasks[i];
}
// method to run i task in parallel
public async Task RunMultipleTaskParallel(Task[] tasks, int i)
{
var countTask = tasks.Length;
var remainTasks = 0;
do
{
int toTake = (countTask < i) ? countTask : i;
var limitedTasks = tasks.Skip(remainTasks)
.Take(toTake);
remainTasks += toTake;
await RunMultipleTaskParallel(limitedTasks.ToArray());
} while (remainTasks < countTask);
}
Using a terminal command i.e. "clear", in a script called from cron (no terminal) will trigger this error message. In your particular script, the smbmount command expects a terminal in which case the work-arounds above are appropriate.
You shouldn't be using the BinaryFormatter
for this - that's for serializing .Net types to a binary file so they can be read back again as .Net types.
If it's stored in the database, hopefully, as a varbinary
- then all you need to do is get the byte array from that (that will depend on your data access technology - EF and Linq to Sql, for example, will create a mapping that makes it trivial to get a byte array) and then write it to the file as you do in your last line of code.
With any luck - I'm hoping that fileContent
here is the byte array? In which case you can just do
System.IO.File.WriteAllBytes("hello.pdf", fileContent);
When deciding to use Array or ArrayList, your first instinct really shouldn't be worrying about performance, though they do perform differently. You first concern should be whether or not you know the size of the Array before hand. If you don't, naturally you would go with an array list, just for functionality.
I'm not sure how to do it in one command but you could do something like:
git reset --hard
git pull
or even
git stash
git pull
For NetBeans to be able to interact with tomcat, it needs the user as setup in netbeans to be properly configured in the tomcat-users.xml
file. NetBeans can do so automatically.
That is, within the tomcat-users.xml
, which you can find in ${CATALINA_HOME}/conf
, or ${CATALINA_BASE}/conf
,
script-manager
roleExample, change
<user password="tomcat" roles="manager,admin" username="tomcat"/>
To
<user password="tomcat" roles="manager-script,manager,admin" username="tomcat"/>
manager-script
role is declaredAdd
<role rolename="manager-script"/>
Actually the netbeans online-help incorrectly states:
Username - Specifies the user name that the IDE uses to log into the server's manager application. The user must be associated with the manager role. The first time the IDE started the Tomcat Web Server, such as through the Start/Stop menu action or by executing a web component from the IDE, the IDE adds an admin user with a randomly-generated password to the
tomcat-base-path/conf/tomcat-users.xml
file. (Right-click the Tomcat Web server instance node in the Services window and select Properties. In the Properties dialog box, the Base Directory property points to thebase-dir
directory.) The admin user entry in thetomcat-users.xml
file looks similar to the following:<user username="idea" password="woiehh" roles="manager"/>
The role should be manager-script
, and not manager
.
For a more complete tomcat-users.xml
file:
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<role rolename="manager-gui"/>
<user password="tomcat" roles="manager-script" username="tomcat"/>
<user password="pass" roles="manager-gui" username="me"/>
</tomcat-users>
There is another nice posting on why am I getting the deployment error?
Another solution cold be:
$value = $arr[count($arr) - 1];
The above will count the amount of array values, substract 1 and then return the value.
Note: This can only be used if your array keys are numeric.
In fact there are several things you need to check. 1. check your nginx's running status
ps -ef|grep nginx
ps aux|grep nginx|grep -v grep
Here we need to check who is running nginx. please remember the user and group
check folder's access status
ls -alt
compare with the folder's status with nginx's
(1) if folder's access status is not right
sudo chmod 755 /your_folder_path
(2) if folder's user and group are not the same with nginx's running's
sudo chown your_user_name:your_group_name /your_folder_path
and change nginx's running username and group
nginx -h
to find where is nginx configuration file
sudo vi /your_nginx_configuration_file
//in the file change its user and group
user your_user_name your_group_name;
//restart your nginx
sudo nginx -s reload
Because nginx default running's user is nobody and group is nobody. if we haven't notice this user and group, 403 will be introduced.
Try it, it will work for any number of substrings
<?php
$string = 'bcadef abcdef';
$substr = 'a';
$attachment = '+++';
//$position = strpos($string, 'a');
$newstring = str_replace($substr, $substr.$attachment, $string);
// bca+++def a+++bcdef
?>
import cv2 as cv
im_color = cv.imread("lena.png", cv.IMREAD_COLOR)
im_gray = cv.cvtColor(im_color, cv.COLOR_BGR2GRAY)
At this point you have a color and a gray image. We are dealing with 8-bit
, uint8
images here. That means the images can have pixel values in the range of [0, 255]
and the values have to be integers.
Let's do a binary thresholding operation. It creates a black and white masked image. The black regions have value 0
and the white regions 255
_, mask = cv.threshold(im_gray, thresh=180, maxval=255, type=cv.THRESH_BINARY)
im_thresh_gray = cv.bitwise_and(im_gray, mask)
The mask can be seen below on the left. The image on it's right is the result of applying bitwise_and
operation between the gray image and the mask. What happened is, the spatial locations where the mask had a pixel value zero (black), became pixel value zero in the result image. The locations where the mask had pixel value 255 (white), the resulting image retained it's original gray value.
To apply this mask to our original color image, we need to convert the mask into a 3 channel image as the original color image is a 3 channel image.
mask3 = cv.cvtColor(mask, cv.COLOR_GRAY2BGR) # 3 channel mask
Then, we can apply this 3 channel mask to our color image using the same bitwise_and
function.
im_thresh_color = cv.bitwise_and(im_color, mask3)
mask3
from the code is the image below on the left, and im_thresh_color
is on its right.
You can plot the results and see for yourself.
cv.imshow("original image", im_color)
cv.imshow("binary mask", mask)
cv.imshow("3 channel mask", mask3)
cv.imshow("im_thresh_gray", im_thresh_gray)
cv.imshow("im_thresh_color", im_thresh_color)
cv.waitKey(0)
The original image is lenacolor.png
that I found here.
If you use jQuery built-in after()
with empty value it will create a dynamic object that will match your :after
CSS selector.
$('.active').after().click(function () {
alert('clickable!');
});
See the jQuery documentation.
You can use sed
for this. For example:
$ sed -n '/Feb 23 13:55/,/Feb 23 14:00/p' /var/log/mail.log
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: connect from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: lost connection after CONNECT from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: disconnect from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie pop3d: Connection, ip=[::ffff:127.0.0.1]
...
The -n
switch tells sed to not output each line of the file it reads (default behaviour).
The last p
after the regular expressions tells it to print lines that match the preceding expression.
The expression '/pattern1/,/pattern2/'
will print everything that is between first pattern and second pattern. In this case it will print every line it finds between the string Feb 23 13:55
and the string Feb 23 14:00
.
com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(data);
if("OK".equals(jsonObject.getString("status"))){
String formatted_address;
JSONArray results = jsonObject.getJSONArray("results");
if(results != null && results.size() > 0){
com.alibaba.fastjson.JSONObject object = results.getJSONObject(0);
String addressComponents = object.getString("address_components");
formatted_address = object.getString("formatted_address");
Log.e("amaya","formatted_address="+formatted_address+"--url="+url);
if(findCity){
boolean finded = false;
JSONArray ac = JSONArray.parseArray(addressComponents);
if(ac != null && ac.size() > 0){
for(int i=0;i<ac.size();i++){
com.alibaba.fastjson.JSONObject jo = ac.getJSONObject(i);
JSONArray types = jo.getJSONArray("types");
if(types != null && types.size() > 0){
for(int j=0;j<ac.size();j++){
String string = types.getString(i);
if("administrative_area_level_1".equals(string)){
finded = true;
break;
}
}
}
if(finded) break;
}
}
Log.e("amaya","city="+formatted_address);
}else{
Log.e("amaya","poiName="+hotspotPoi.getPoi_name()+"--"+hotspotPoi);
}
if(hotspotPoi != null) hotspotPoi.setPoi_name(formatted_address);
EventBus.getDefault().post(new AmayaEvent.GeoEvent(hotspotPoi));
}
}
this is a method to parse google feedback data.
I wanted a more compact output than the great answers above using lapply
, so here's an alternative wrapped as a small function.
# Example data
df <-
data.frame(
w = seq.int(10),
x = LETTERS[seq.int(10)],
y = factor(letters[seq.int(10)]),
z = seq(
as.POSIXct('2020-01-01'),
as.POSIXct('2020-10-01'),
length.out = 10
)
)
# Function returning compact column classes
col_classes <- function(df) {
t(as.data.frame(lapply(df, function(x) paste(class(x), collapse = ','))))
}
# Return example data's column classes
col_classes(df)
[,1]
w "integer"
x "character"
y "factor"
z "POSIXct,POSIXt"
I've found that in 17.09 there is a simplest way to do it within docker container:
$ cat /proc/self/cgroup | head -n 1 | cut -d '/' -f3
4de1c09d3f1979147cd5672571b69abec03d606afcc7bdc54ddb2b69dec3861c
Or like it has already been told, a shorter version with
$ cat /etc/hostname
4de1c09d3f19
Or simply:
$ hostname
4de1c09d3f19
Here is an article with full details on how to do this.
Private Sub btnScale_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnScale.Click
' Get the scale factor.
Dim scale_factor As Single = Single.Parse(txtScale.Text)
' Get the source bitmap.
Dim bm_source As New Bitmap(picSource.Image)
' Make a bitmap for the result.
Dim bm_dest As New Bitmap( _
CInt(bm_source.Width * scale_factor), _
CInt(bm_source.Height * scale_factor))
' Make a Graphics object for the result Bitmap.
Dim gr_dest As Graphics = Graphics.FromImage(bm_dest)
' Copy the source image into the destination bitmap.
gr_dest.DrawImage(bm_source, 0, 0, _
bm_dest.Width + 1, _
bm_dest.Height + 1)
' Display the result.
picDest.Image = bm_dest
End Sub
[Edit]
One more on the similar lines.
You can extend the accepted answer with a default value to avoid exceptions:
public static T ParseEnum<T>(string value, T defaultValue) where T : struct
{
try
{
T enumValue;
if (!Enum.TryParse(value, true, out enumValue))
{
return defaultValue;
}
return enumValue;
}
catch (Exception)
{
return defaultValue;
}
}
Then you call it like:
StatusEnum MyStatus = EnumUtil.ParseEnum("Active", StatusEnum.None);
If the default value is not an enum the Enum.TryParse would fail and throw an exception which is catched.
After years of using this function in our code on many places maybe it's good to add the information that this operation costs performance!
This data not found causes because of some datatype we are using .
like select empid into v_test
above empid and v_test has to be number type , then only the data will be stored .
So keep track of the data type , when getting this error , may be this will help
Just in case someone from Blogger arrives, I had this problem when using Beautify
extension in VSCode. Don´t use it, don´t beautify
it.
You need to make the changes in the binding configuration (in the app.config file) on the SERVER and the CLIENT, or it will not take effect.
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding maxReceivedMessageSize="2147483647 " max...=... />
</basicHttpBinding>
</bindings>
</system.serviceModel>
What is JavaScript garbage collection?
check this
What's important for a web programmer to understand about JavaScript garbage collection, in order to write better code?
In Javascript you don't care about memory allocation and deallocation. The whole problem is demanded to the Javascript interpreter. Leaks are still possible in Javascript, but they are bugs of the interpreter. If you are interested in this topic you could read more in www.memorymanagement.org
I had the same problem, but I didnt find export command in line 70 in gradle file for the latest version 2.13, but I understand a silly mistake there, that is following,
If you don't find line 70 with export command in gradle file in your gradle folder/bin/ , then check your ~/.bashrc, if you find export JAVA_HOME==/usr/lib/jvm/java-7-openjdk-amd64/bin/java
, then remove /bin/java
from this line, like JAVA_HOME==/usr/lib/jvm/java-7-openjdk-amd64
, and it in path>>> instead of this export PATH=$PATH:$HOME/bin:JAVA_HOME/
, it will be export PATH=$PATH:$HOME/bin:JAVA_HOME/bin/java
. Then run source ~/.bashrc
.
The reason is, if you check your gradle file, you will find in line 70 (if there's no export command) or in line 75,
JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
That means
/bin/java
is already there, so it needs to be substracted fromJAVA_HOME
path.
That happened in my case.
I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.
I have to assume you are using windows because you have mentioned notepad++.
Use notepad++. Right click on the file and choose "edit with notepad++"
Use notepad Change the filename extension to .txt and double click the file.
Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"
If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.
std::vector
uses the heap. Geez, what a waste that would be just for the sake of a const
sanity-check. The point of std::vector
is dynamic growth at run-time, not any old syntax checking that should be done at compile-time. If you're not going to grow then create a class to wrap a normal array.
#include <stdio.h>
template <class Type, size_t MaxLength>
class ConstFixedSizeArrayFiller {
private:
size_t length;
public:
ConstFixedSizeArrayFiller() : length(0) {
}
virtual ~ConstFixedSizeArrayFiller() {
}
virtual void Fill(Type *array) = 0;
protected:
void add_element(Type *array, const Type & element)
{
if(length >= MaxLength) {
// todo: throw more appropriate out-of-bounds exception
throw 0;
}
array[length] = element;
length++;
}
};
template <class Type, size_t Length>
class ConstFixedSizeArray {
private:
Type array[Length];
public:
explicit ConstFixedSizeArray(
ConstFixedSizeArrayFiller<Type, Length> & filler
) {
filler.Fill(array);
}
const Type *Array() const {
return array;
}
size_t ArrayLength() const {
return Length;
}
};
class a {
private:
class b_filler : public ConstFixedSizeArrayFiller<int, 2> {
public:
virtual ~b_filler() {
}
virtual void Fill(int *array) {
add_element(array, 87);
add_element(array, 96);
}
};
const ConstFixedSizeArray<int, 2> b;
public:
a(void) : b(b_filler()) {
}
void print_items() {
size_t i;
for(i = 0; i < b.ArrayLength(); i++)
{
printf("%d\n", b.Array()[i]);
}
}
};
int main()
{
a x;
x.print_items();
return 0;
}
ConstFixedSizeArrayFiller
and ConstFixedSizeArray
are reusable.
The first allows run-time bounds checking while initializing the array (same as a vector might), which can later become const
after this initialization.
The second allows the array to be allocated inside another object, which could be on the heap or simply the stack if that's where the object is. There's no waste of time allocating from the heap. It also performs compile-time const checking on the array.
b_filler
is a tiny private class to provide the initialization values. The size of the array is checked at compile-time with the template arguments, so there's no chance of going out of bounds.
I'm sure there are more exotic ways to modify this. This is an initial stab. I think you can pretty much make up for any of the compiler's shortcoming with classes.
I remember someday that I spent a lot of time trying to center a div, using margin: 0 auto
.
I had display: inline-block
on it, when I removed it, the div centered correctly.
As Ross pointed out, it doesn't work on inline elements.
The string you give split
is the string form of a regular expression, so:
private void getId(String pdfName){
String[]tokens = pdfName.split("[\\-.]");
}
That means to split on any character in the []
(we have to escape -
with a backslash because it's special inside []
; and of course we have to escape the backslash because this is a string). (Conversely, .
is normally special but isn't special inside []
.)
Try
sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)
Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
SELECT last_value, increment_by from "other_schema".id_seq;
for adding a seq to a column where the schema is not public try this.
nextval('"other_schema".id_seq'::regclass)
A better and more organized way of overriding Devise controllers and views using namespaces:
Create the following folders:
app/controllers/my_devise
app/views/my_devise
Put all controllers that you want to override into app/controllers/my_devise and add MyDevise
namespace to controller class names. Registrations
example:
# app/controllers/my_devise/registrations_controller.rb
class MyDevise::RegistrationsController < Devise::RegistrationsController
...
def create
# add custom create logic here
end
...
end
Change your routes accordingly:
devise_for :users,
:controllers => {
:registrations => 'my_devise/registrations',
# ...
}
Copy all required views into app/views/my_devise
from Devise gem folder or use rails generate devise:views
, delete the views you are not overriding and rename devise
folder to my_devise
.
This way you will have everything neatly organized in two folders.
If you'd like to use printf()
, you might want to also:
#include <stdio.h>
Try this :
import urllib, urllib2, json
url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
request = urllib2.Request(url)
request.add_header('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
request.add_header('Content-Type','application/json')
response = urllib2.urlopen(request)
json_object = json.load(response)
#print json_object['results']
if json_object['team'] == []:
print 'No Data!'
else:
for rows in json_object['team']:
print 'Team ID:' + rows['team_id']
print 'Team Name:' + rows['team_name']
print 'Team URL:' + rows['team_icon_url']
I was having issues where the animation was always starting from the top of the page after a page refresh in the other examples.
I fixed this by not animating the css directly but rather calling window.scrollTo();
on each step:
$({myScrollTop:window.pageYOffset}).animate({myScrollTop:300}, {
duration: 600,
easing: 'swing',
step: function(val) {
window.scrollTo(0, val);
}
});
This also gets around the html
vs body
issue as it's using cross-browser JavaScript.
Have a look at http://james.padolsey.com/javascript/fun-with-jquerys-animate/ for more information on what you can do with jQuery's animate function.
So the package will be downloaded in a temp folder C:\Users\U122337.BOSTONADVISORS\AppData\Local\Temp\Rtmp404t8Y\downloaded_packages from where it will be installed into your library folder, e.g. C:\R\library\zoo
What you have to do once install command is done: Open Packages menu -> Load package...
You will see your package on the list. You can automate this: How to load packages in R automatically?
The simple example of using a property in an interface:
using System;
interface IName
{
string Name { get; set; }
}
class Employee : IName
{
public string Name { get; set; }
}
class Company : IName
{
private string _company { get; set; }
public string Name
{
get
{
return _company;
}
set
{
_company = value;
}
}
}
class Client
{
static void Main(string[] args)
{
IName e = new Employee();
e.Name = "Tim Bridges";
IName c = new Company();
c.Name = "Inforsoft";
Console.WriteLine("{0} from {1}.", e.Name, c.Name);
Console.ReadKey();
}
}
/*output:
Tim Bridges from Inforsoft.
*/
Try:
msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
The +
operator is overridden in python to concatenate strings.
A previous poster said..
If you have PHP installed as a command line tool… your shebang (#!) line needs to look like this:
#!/usr/bin/php
While this could be true… just because you can type in php
does NOT necessarily mean that's where php is going to be... /usr/bin/php
is A common location… but as with any shebang… it needs to be tailored to YOUR env
.
a quick way to find out WHERE YOUR particular executable is located on your $PATH
, try..
?which -a php
ENTER, which for me looks like..
php is /usr/local/php5/bin/php
php is /usr/bin/php
php is /usr/local/bin/php
php is /Library/WebServer/CGI-Executables/php
The first one is the default i'd get if I just typed in php at a command prompt… but I can use any of them in a shebang, or directly… You can also combine the executable name with env
, as is often seen, but I don't really know much about / trust that. XOXO.
Also think about using
$(document).ready(function() {});
Don't know why no one here came up with this yet (kinda sad). When do you execute your code??? Right at the start? Then you might want to use upper mentioned ready() function so your code is being executed after the whole page (with all it's dom elements) has been loaded and not before! Of course this is useless if you run some code that adds dom elements after page load! Then you simply want to wait for those functions and execute your code afterwards...
A lone print
will output a newline.
print
In 3.x print
is a function, therefore:
print()
If you want to DUMP your inserts into an .sql file:
cd
to the location which you want to .sql
file to be locatedpg_dump --column-inserts --data-only --table=<table> <database> > my_dump.sql
Note the > my_dump.sql
command. This will put everything into a sql file named my_dump
(I just got this working, with my main issue being that I don't have a real internet hostname, so answering this question in case it helps someone)
You need to specify a hostname with HELO. Even so, you should get an error, so Postfix is probably not running.
Also, the => is not a command. The '.' on a single line without any text around it is what tells Postfix that the entry is complete. Here are the entries I used:
telnet localhost 25
(says connected)
EHLO howdy.com
(returns a bunch of 250 codes)
MAIL FROM: [email protected]
RCPT TO: (use a real email address you want to send to)
DATA (type whatever you want on muliple lines)
. (this on a single line tells Postfix that the DATA is complete)
You should get a response like:
250 2.0.0 Ok: queued as 6E414C4643A
The email will probably end up in a junk folder. If it is not showing up, then you probably need to setup the 'Postfix on hosts without a real Internet hostname'. Here is the breakdown on how I completed that step on my Ubuntu box:
sudo vim /etc/postfix/main.cf
smtp_generic_maps = hash:/etc/postfix/generic (add this line somewhere)
(edit or create the file 'generic' if it doesn't exist)
sudo vim /etc/postfix/generic
(add these lines, I don't think it matters what names you use, at least to test)
[email protected] [email protected]
[email protected] [email protected]
@localdomain.local [email protected]
then run:
postmap /etc/postfix/generic (this needs to be run whenever you change the
generic file)
Happy Trails
Frames have been deprecated because they caused trouble for url navigation and hyperlinking, because the url would just take to you the index page (with the frameset) and there was no way to specify what was in each of the frame windows. Today, webpages are often generated by server-side technologies such as PHP, ASP.NET, Ruby etc. So instead of using frames, pages can simply be generated by merging a template with content like this:
Template File
<html>
<head>
<title>{insert script variable for title}</title>
</head>
<body>
<div class="menu">
{menu items inserted here by server-side scripting}
</div>
<div class="main-content">
{main content inserted here by server-side scripting}
</div>
</body>
</html>
If you don't have full support for a server-side scripting language, you could also use server-side includes (SSI). This will allow you to do the same thing--i.e. generate a single web page from multiple source documents.
But if you really just want to have a section of your webpage be a separate "window" into which you can load other webpages that are not necessarily located on your own server, you will have to use an iframe.
You could emulate your example like this:
Frames Example
<html>
<head>
<title>Frames Test</title>
<style>
.menu {
float:left;
width:20%;
height:80%;
}
.mainContent {
float:left;
width:75%;
height:80%;
}
</style>
</head>
<body>
<iframe class="menu" src="menu.html"></iframe>
<iframe class="mainContent" src="events.html"></iframe>
</body>
</html>
There are probably better ways to achieve the layout. I've used the CSS float attribute, but you could use tables or other methods as well.
Check the node version using node -v
.
Check the npm version using npm -v
. If these commands gave you version number you are good to go with NodeJs
development
Time to test node
Create a Directory using mkdir NodeJs
. Inside the NodeJs
folder create a file using touch index.js
. Open your index.js
either using vi
or in your favourite text editor. Type in console.log('Welcome to NodesJs.')
and save it. Navigate back to your saved file and type node index.js
. If you see Welcome to NodesJs.
you did a nice job and you are up with NodeJs.
NSArray *array = [mutableArray copy];
Copy
makes immutable copies. This is quite useful because Apple can make various optimizations. For example sending copy
to a immutable array only retains the object and returns self
.
If you don't use garbage collection or ARC remember that -copy
retains the object.
I am using a .Net Core 2.1 Web Application and could not get a single answer here to work. I either got a blank parameter (if the method was called at all) or a 500 server error. I started playing with every possible combination of answers and finally got a working result.
In my case the solution was as follows:
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: mycontrolleraction,
data: JSON.stringify(things)
});
[HttpPost]
public IActionResult NewBranch([FromBody]IEnumerable<Thing> things)
{
return Ok();
}
Naming the content
data: { content: nodes }, // Server error 500
Not having the contentType = Server error 500
dataType
is not needed, despite what some answers say, as that is used for the response decoding (so not relevant to the request examples here).List<Thing>
also works in the controller methodInstead use window.open()
:
The syntax is:
window.open(strUrl, strWindowName[, strWindowFeatures]);
Your code should have:
window.open('Prosjektplan.pdf');
Your code should be:
<p class="downloadBoks"
onclick="window.open('Prosjektplan.pdf')">Prosjektbeskrivelse</p>
There is a ToObject method now.
var obj = jsonObject["date_joined"];
var result = obj.ToObject<DateTime>();
It also works with any complex type, and obey to JsonPropertyAttribute rules
var result = obj.ToObject<MyClass>();
public class MyClass
{
[JsonProperty("date_field")]
public DateTime MyDate {get;set;}
}
(And if you have no admin access to the server)
ALTER ROLE <your_login_role> SET search_path TO a,b,c;
Two important things to know about:
a, b, c
matters, as it is also the order in which the schemas will be looked up for tables. So if you have the same table name in more than one schema among the defaults, there will be no ambiguity, the server will always use the table from the first schema you specified for your search_path
.using jquery $.each
you can access all data and also set in table like this
<table style="width: 100%">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Category</th>
<th>Color</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
$.each(data, function (index, item) {
var eachrow = "<tr>"
+ "<td>" + item[1] + "</td>"
+ "<td>" + item[2] + "</td>"
+ "<td>" + item[3] + "</td>"
+ "<td>" + item[4] + "</td>"
+ "</tr>";
$('#tbody').append(eachrow);
});
if($("#id").length) /*exists*/
if(!$("#id").length) /*doesn't exist*/
In my case both 2015 express web and 2015 Community had memory leaks (up to 1.5 GB) froze and crashed every 5 minutes. But only in projects with Node js. what solved this issue for me was disabling the intellisense: tools--> options--> text editor-->Node.js--> intellisense-->intellisense level=No intellisense.
And somehow intellisense still works))
The value
attribute on submit
-type <input>
elements controls the text displayed.
<input type="submit" class="like" value="Like" />
Yeah, by using $(this)
, you enabled jQuery functionality for the object. By just using this
, it only has generic Javascript functionality.
The answer from @laughing_man is quite accurate. But still, I wanted to give a recommendation which I learned from Kafka expert Stephane Maarek.
Kafka isn’t meant to handle large messages.
Your API should use cloud storage (Ex AWS S3), and just push to Kafka or any message broker a reference of S3. You must find somewhere to persist your data, maybe it’s a network drive, maybe it’s whatever, but it shouldn't be message broker.
Now, if you don’t want to go with the above solution
The message max size is 1MB (the setting in your brokers is called message.max.bytes
) Apache Kafka. If you really needed it badly, you could increase that size and make sure to increase the network buffers for your producers and consumers.
And if you really care about splitting your message, make sure each message split has the exact same key so that it gets pushed to the same partition, and your message content should report a “part id” so that your consumer can fully reconstruct the message.
You can also explore compression, if your message is text-based (gzip, snappy, lz4 compression) which may reduce the data size, but not magically.
Again, you have to use an external system to store that data and just push an external reference to Kafka. That is a very common architecture and one you should go with and widely accepted.
Keep that in mind Kafka works best only if the messages are huge in amount but not in size.
Source: https://www.quora.com/How-do-I-send-Large-messages-80-MB-in-Kafka
you can also go for this.... this will only show the HTML section once javascript has loaded.
<!-- Adds the hidden style and removes it when javascript has loaded -->
<style type="text/css">
.hideAll {
visibility:hidden;
}
</style>
<script type="text/javascript">
$(window).load(function () {
$("#tabs").removeClass("hideAll");
});
</script>
<div id="tabs" class="hideAll">
##Content##
</div>
If you want to exclude numbers that are contained within words, such as bar1 or aa1bb, then add word boundaries \b to any of the regex based answers. For example:
Pattern p = Pattern.compile("\\b-?\\d+\\b");
Matcher m = p.matcher("9There 9are more9 th9an -2 and less than 12 numbers here9");
while (m.find()) {
System.out.println(m.group());
}
displays:
2
12
There are two options:
Go into the hub, and create the repository first, and mark it as private. Then when you push to that repo, it will be private. This is the most common approach.
log into your docker hub account, and go to your global settings. There is a setting that allows you to set what your default visability is for the repositories that you push. By default it is set to public, but if you change it to private, all of your repositories that you push will be marked as private by default. It is important to note that you will need to have enough private repos available on your account, or else the repo will be locked until you upgrade your plan.
Generic command would be
find /path/to/files -name '<search>*' -exec bash -c 'mv $0 ${0/<search>/<replace>}' {} \;
where <search>
and <replace>
should be replaced with your source and target respectively.
As a more specific example tailored to your problem (should be run from the same folder where your files are), the above command would look like:
find . -name 'gfh*' -exec bash -c 'mv $0 ${0/gfh/jkl}' {} \;
For a "dry run" add echo
before mv
, so that you'd see what commands are generated:
find . -name 'gfh*' -exec bash -c 'echo mv $0 ${0/gfh/jkl}' {} \;
Also, you can utilize crash dumps to debug your software. The customer sends it to you and then you can use it to identify the exact version of your source - and Visual Studio will even pull the right set of debugging symbols (and source if you're set up correctly) using the crash dump. See Microsoft's documentation on Symbol Stores.
If you use it on normal html tags, it means that you can programatically manipulate them in event handlers etc, eg change the href or class of an anchor tag on page load... only do that if you have to, because vanilla html tags go faster.
As far as user controls and server controls, no, they just wont work without them, without having delved into the innards of the aspx preprocessor, couldn't say exactly why, but would take a guess that for probably good reasons, they just wrote the parser that way, looking for things explicitly marked as "do something".
If @JonSkeet is around anywhere, he will probably be able to provide a much better answer.
//gradle.properties
systemProp.http.proxyHost=www.somehost.org
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=userid
systemProp.http.proxyPassword=password
systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost
You can use upstream headers (named starting with $http_) and additional custom headers. For example:
add_header X-Upstream-01 $http_x_upstream_01;
add_header X-Hdr-01 txt01;
next, go to console and make request with user's header:
curl -H "X-Upstream-01: HEADER1" -I http://localhost:11443/
the response contains X-Hdr-01, seted by server and X-Upstream-01, seted by client:
HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Mon, 30 Nov 2015 23:54:30 GMT
Content-Type: text/html;charset=UTF-8
Connection: keep-alive
X-Hdr-01: txt01
X-Upstream-01: HEADER1
# create uniform spiral grid
numOfPoints = varargin[0]
vxyz = zeros((numOfPoints,3),dtype=float)
sq0 = 0.00033333333**2
sq2 = 0.9999998**2
sumsq = 2*sq0 + sq2
vxyz[numOfPoints -1] = array([(sqrt(sq0/sumsq)),
(sqrt(sq0/sumsq)),
(-sqrt(sq2/sumsq))])
vxyz[0] = -vxyz[numOfPoints -1]
phi2 = sqrt(5)*0.5 + 2.5
rootCnt = sqrt(numOfPoints)
prevLongitude = 0
for index in arange(1, (numOfPoints -1), 1, dtype=float):
zInc = (2*index)/(numOfPoints) -1
radius = sqrt(1-zInc**2)
longitude = phi2/(rootCnt*radius)
longitude = longitude + prevLongitude
while (longitude > 2*pi):
longitude = longitude - 2*pi
prevLongitude = longitude
if (longitude > pi):
longitude = longitude - 2*pi
latitude = arccos(zInc) - pi/2
vxyz[index] = array([ (cos(latitude) * cos(longitude)) ,
(cos(latitude) * sin(longitude)),
sin(latitude)])
See ?merge
:
the name "row.names" or the number 0 specifies the row names.
Example:
R> de <- merge(d, e, by=0, all=TRUE) # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0 # replace NA values
R> de
Row.names a b c d e f g h i j k l m n o p q r s
1 1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2 2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 0 0 0 0 0 0 0 0 0
3 3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 21 22 23 24 25 26 27 28 29
t
1 20
2 0
3 30
Since git 1.8 you can do
git submodule update --remote --merge
This will update the submodule to the latest remote commit. You will then need to commit the change so the gitlink in the parent repository is updated
git commit
And then push the changes as without this, the SHA-1 identity the pointing to the submodule won't be updated and so the change won't be visible to anyone else.
Start from version 2012-03-20 (3.7.11), sqlite support the following INSERT syntax:
INSERT INTO 'tablename' ('column1', 'column2') VALUES
('data1', 'data2'),
('data3', 'data4'),
('data5', 'data6'),
('data7', 'data8');
Read documentation: http://www.sqlite.org/lang_insert.html
PS: Please +1 to Brian Campbell's reply/answer. not mine! He presented the solution first.
Without using any external dependency or library:
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
$response is an object. Properties can be accessed as usual, e.g. $response->...
where $data is the array contaning your data:
$data = array(
'userID' => 'a7664093-502e-4d2b-bf30-25a2b26d6021',
'itemKind' => 0,
'value' => 1,
'description' => 'Boa saudaÁ„o.',
'itemID' => '03e76d0a-8bab-11e0-8250-000c29b481aa'
);
Warning: this won't work if the allow_url_fopen setting is set to Off in the php.ini.
If you're developing for WordPress, consider using the provided APIs: https://developer.wordpress.org/plugins/http-api/
Please check both OracleServiceXE
and OracleXETNSListener
having the status started when you navigate through start->run->services.msc
.
For my case only OracleXETNSListener
was started but OracleServiceXE
was not started, when I started by right clicking -> start
and checked the connection its working for me
The first version:
function[0] = 42; // version 1
may or may not insert the value 42 into the map. If the key 0
exists, then it will assign 42 to that key, overwriting whatever value that key had. Otherwise it inserts the key/value pair.
The insert functions:
function.insert(std::map<int, int>::value_type(0, 42)); // version 2
function.insert(std::pair<int, int>(0, 42)); // version 3
function.insert(std::make_pair(0, 42)); // version 4
on the other hand, don't do anything if the key 0
already exists in the map. If the key doesn't exist, it inserts the key/value pair.
The three insert functions are almost identical. std::map<int, int>::value_type
is the typedef
for std::pair<const int, int>
, and std::make_pair()
obviously produces a std::pair<>
via template deduction magic. The end result, however, should be the same for versions 2, 3, and 4.
Which one would I use? I personally prefer version 1; it's concise and "natural". Of course, if its overwriting behavior is not desired, then I would prefer version 4, since it requires less typing than versions 2 and 3. I don't know if there is a single de facto way of inserting key/value pairs into a std::map
.
Another way to insert values into a map via one of its constructors:
std::map<int, int> quadratic_func;
quadratic_func[0] = 0;
quadratic_func[1] = 1;
quadratic_func[2] = 4;
quadratic_func[3] = 9;
std::map<int, int> my_func(quadratic_func.begin(), quadratic_func.end());
Generally you can achieve the same effect by using normal blocking IO and multiplexing several IO operations using select(2)
, poll(2)
or some other system calls available on your system.
See The C10K problem for the comparison of approaches to scalable IO multiplexing.
try this:
@media (hover:<s>on-demand</s>) {
button:hover {
background-color: #color-when-NOT-touch-device;
}
}
UPDATE: unfortunately W3C has removed this property from the specs (https://github.com/w3c/csswg-drafts/commit/2078b46218f7462735bb0b5107c9a3e84fb4c4b1).
Add_ supplier is name of the form
private void add_supplier_Load(object sender, EventArgs e)
{
add_supplier childform = new add_supplier();
childform.MdiParent = this;
childform.Show();
}
Let's make things simple, you don't need to read the document about a "custom tag" (as a 16 years web developer, I have enough this kind of tags, such as in struts, webwork, jsp, rails and now it's vuejs)
just press F12, and you will see the source code like:
<div>
<a href="#/topologies" class="luelue">page1</a>
<a href="#/" aria-current="page" class="router-link-exact-active router-link-active">page2</a>
<a href="#/databases" class="">page3</a>
</div>
so just add styles for the .router-link-active
or router-link-exact-active
if you want more details, check the router-link
api:
I found a nice solution in pure Markdown with a little CSS 3 hack :-)
![image alt >](/image-right.jpg)
![image alt <](/image-left.jpg)
![image alt ><](/center-image.jpg)
Follow the CSS 3 code float image on the left or right, when the image alt
ends with <
or >
.
img[alt$=">"] {
float: right;
}
img[alt$="<"] {
float: left;
}
img[alt$="><"] {
display: block;
max-width: 100%;
height: auto;
margin: auto;
float: none!important;
}
ASP.NET Web API 2 really simplified it. For example, the following code:
public HttpResponseMessage GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
var message = string.Format("Product with id = {0} not found", id);
HttpError err = new HttpError(message);
return Request.CreateResponse(HttpStatusCode.NotFound, err);
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, item);
}
}
returns the following content to the browser when the item is not found:
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
Date: Thu, 09 Aug 2012 23:27:18 GMT
Content-Length: 51
{
"Message": "Product with id = 12 not found"
}
Suggestion: Don't throw HTTP Error 500 unless there is a catastrophic error (for example, WCF Fault Exception). Pick an appropriate HTTP status code that represents the state of your data. (See the apigee link below.)
Links:
I have not tried this, so I am not guarantueeing anything, however
foreach Bar f in filterBars
{
search(f)
}
Foo search(Bar b)
{
fooSelect = (from f in fooBunch
where !(from b in f.BarList select b.BarId).Contains(b.ID)
select f).ToList();
return fooSelect;
}
You should't write data-toggle="modal" in the element which triggered the modal (like a button), and you manually can show the modal with:
$('#myModal').modal('show');
and hide with:
$('#myModal').modal('hide');
I still think the best/safe way to test these two conditions is to cast the value to a string:
var EmpName = $("div#esd-names div#name").attr('class');
// Undefined check
if (Object.prototype.toString.call(EmpName) === '[object Undefined]'){
// Do something with your code
}
// Nullcheck
if (Object.prototype.toString.call(EmpName) === '[object Null]'){
// Do something with your code
}
You can scale the image with pygame.transform.scale
:
import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))
You can then get the bounding rectangle of picture
with
rect = picture.get_rect()
and move the picture with
rect = rect.move((x, y))
screen.blit(picture, rect)
where screen
was set with something like
screen = pygame.display.set_mode((1600, 900))
To allow your widgets to adjust to various screen sizes, you could make the display resizable:
import os
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
pygame.event.pump()
event = pygame.event.wait()
if event.type == QUIT:
pygame.display.quit()
elif event.type == VIDEORESIZE:
screen = pygame.display.set_mode(
event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
pygame.display.flip()
They don't convert directly, but it allows for interoperability between .NET and J2EE.
Have you tried this?
$(document).ajaxError(function(){ alert('error'); }
That should handle all AjaxErrors. I´ve found it here. There you find also a possibility to write these errors to your firebug console.
Which SDKs? If you mean the SDK for Cocoa development, you can check in /Developer/SDKs/
to see which ones you have installed.
If you're looking for the Java SDK version, then open up /Applications/Utilities/Java Preferences
. The versions of Java that you have installed are listed there.
On Mac OS X 10.6, though, the only Java version is 1.6.
There is a fresh answer to that question now. SWIG, as of version 3.0 seems to provide javascript interface generators for Node.js, Webkit and v8.
I've been using SWIG extensively for Java and Python for a while, and once you understand how SWIG works, there is almost no effort(compared to ffi or the equivalent in the target language) needed for interfacing C++ code to the languages that SWIG supports.
As a small example, say you have a library with the header myclass.h:
#include<iostream>
class MyClass {
int myNumber;
public:
MyClass(int number): myNumber(number){}
void sayHello() {
std::cout << "Hello, my number is:"
<< myNumber <<std::endl;
}
};
In order to use this class in node, you simply write the following SWIG interface file (mylib.i):
%module "mylib"
%{
#include "myclass.h"
%}
%include "myclass.h"
Create the binding file binding.gyp:
{
"targets": [
{
"target_name": "mylib",
"sources": [ "mylib_wrap.cxx" ]
}
]
}
Run the following commands:
swig -c++ -javascript -node mylib.i
node-gyp build
Now, running node from the same folder, you can do:
> var mylib = require("./build/Release/mylib")
> var c = new mylib.MyClass(5)
> c.sayHello()
Hello, my number is:5
Even though we needed to write 2 interface files for such a small example, note how we didn't have to mention the MyClass
constructor nor the sayHello
method anywhere, SWIG discovers these things, and automatically generates natural interfaces.
That exception means that you are trying to unpack a tuple, but the tuple has too many values with respect to the number of target variables. For example: this work, and prints 1, then 2, then 3
def returnATupleWithThreeValues():
return (1,2,3)
a,b,c = returnATupleWithThreeValues()
print a
print b
print c
But this raises your error
def returnATupleWithThreeValues():
return (1,2,3)
a,b = returnATupleWithThreeValues()
print a
print b
raises
Traceback (most recent call last):
File "c.py", line 3, in ?
a,b = returnATupleWithThreeValues()
ValueError: too many values to unpack
Now, the reason why this happens in your case, I don't know, but maybe this answer will point you in the right direction.
var a = "13:15"_x000D_
var b = toDate(a, "h:m")_x000D_
//alert(b);_x000D_
document.write(b);_x000D_
_x000D_
function toDate(dStr, format) {_x000D_
var now = new Date();_x000D_
if (format == "h:m") {_x000D_
now.setHours(dStr.substr(0, dStr.indexOf(":")));_x000D_
now.setMinutes(dStr.substr(dStr.indexOf(":") + 1));_x000D_
now.setSeconds(0);_x000D_
return now;_x000D_
} else_x000D_
return "Invalid Format";_x000D_
}
_x000D_
I believe on OS X when you use -i an extension for the backup files is required. Try:
sed -i .bak 's/hello/gbye/g' *
Using GNU sed
the extension is optional.
I found the InvokeRequired
not reliable, so I simply use
if (!this.IsHandleCreated)
{
this.CreateHandle();
}
I might be picking up the wrong things from so many comments, but if you are using Maven, then are you doing the usual command prompt build and clean?
Go to cmd, navigate to your workspace (usually c:/workspace). Then run "mvn clean install -DskipTests"
After that run "mvn eclipse:eclipse eclipse:clean" (don't need to worry about piping).
Also, do you have any module dependencies in your projects?
If so, try removing the dependencies clicking apply, then readding the dependencies. As this can set eclipse right when it get's confused with buildpath sometimes.
Hope this helps!
To list the Docker images
$ docker images
If your application wants to run in with port 80, and you can expose a different port to bind locally, say 8080:
$ docker run -d --restart=always -p 8080:80 image_name:version
Try this if you are on ubuntu:
sudo apt-get update
sudo apt-get install build-essential libpq-dev libssl-dev openssl libffi-dev zlib1g-dev
sudo apt-get install python3-pip python3.7-dev
sudo apt-get install python3.7
In case you don't have the repository and so it fires a not-found package you first have to install this:
sudo apt-get install -y software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
more info here: http://devopspy.com/python/install-python-3-6-ubuntu-lts/
i believe all the major opensource JS engines (JavaScriptCore, SpiderMonkey, V8, and KJS) provide embedding APIs. The only one I am actually directly familiar with is JavaScriptCore (which is name of the JS engine the SquirrelFish lives in) which provides a pure C API. If memory serves (it's been a while since i used .NET) .NET has fairly good support for linking in C API's.
I'm honestly not sure what the API's for the other engines are like, but I do know that they all provide them.
That said, depending on your purposes JScript.NET may be best, as all of these other engines will require you to include them with your app, as JSC is the only one that actually ships with an OS, but that OS is MacOS :D
I have also faced this problem. Finally I got a solution. Use this bellow code. Hope: problem will be solve.
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
I already said that I was new to exec()
function. After doing some more digging, I came upon 2>&1
which needs to be added at the end of command in exec()
.
Thanks @mattosmat
for pointing it out in the comments too. I did not try this at once because you said it is a Linux command, I am on Windows.
So, what I have discovered, the command is actually executing in the back-end. That is why I could not see it actually running, which I was expecting to happen.
For all of you, who had similar problem, my advise is to use that command. It will point out all the errors and also tell you info/details about execution.
exec('some_command 2>&1', $output);
print_r($output); // to see the response to your command
Thanks for all the help guys, I appreciate it ;)
It sounds like your m2eclipse install is using the embedded Maven, which has its own repository (located under user home) and settings.
If you open up the Maven preferences (Window->Preferences->Maven->Installations, you can add your Maven installation by selecting Add... then browsing to the M2_HOME directory.
(source: sonatype.com)
For more details see the m2eclipse book
The first time I came up against this, I came up with an onclick()/JavaScript hack when choices are not prev/next that I still like for its simplicity. It goes like this:
@model myApp.Models.myModel
<script type="text/javascript">
function doOperation(op) {
document.getElementById("OperationId").innerText = op;
// you could also use Ajax to reference the element.
}
</script>
<form>
<input type="text" id = "TextFieldId" name="TextField" value="" />
<input type="hidden" id="OperationId" name="Operation" value="" />
<input type="submit" name="write" value="Write" onclick='doOperation("Write")'/>
<input type="submit" name="read" value="Read" onclick='doOperation("Read")'/>
</form>
When either submit button is clicked, it stores the desired operation in a hidden field (which is a string field included in the model the form is associated with) and submits the form to the Controller, which does all the deciding. In the Controller, you simply write:
// Do operation according to which submit button was clicked
// based on the contents of the hidden Operation field.
if (myModel.Operation == "Read")
{
// Do read logic
}
else if (myModel.Operation == "Write")
{
// Do write logic
}
else
{
// Do error logic
}
You can also tighten this up slightly using numeric operation codes to avoid the string parsing, but unless you play with enumerations, the code is less readable, modifiable, and self-documenting and the parsing is trivial, anyway.
I prefer to use getters rather than constants. Those getters might return constant values, e.g. public int getMaxConnections() {return 10;}
, but anything that needs the constant will go through a getter.
One benefit is that if your program outgrows the constant--you find that it needs to be configurable--you can just change how the getter returns the constant.
The other benefit is that in order to modify the constant you don't have to recompile everything that uses it. When you reference a static final field, the value of that constant is compiled into any bytecode that references it.
I've always found it easier to invert the test against the list in situations like this. For instance...
SELECT
field0, field1, field2
FROM
my_table
WHERE
',' + @mysearchlist + ',' LIKE '%,' + CAST(field3 AS VARCHAR) + ',%'
This means that there is no complicated mish-mash required for the values that you are looking for.
As an example, if our list was ('1,2,3')
, then we add a comma to the start and end of our list like so: ',' + @mysearchlist + ','
.
We also do the same for the field value we're looking for and add wildcards: '%,' + CAST(field3 AS VARCHAR) + ',%'
(notice the %
and the ,
characters).
Finally we test the two using the LIKE
operator: ',' + @mysearchlist + ',' LIKE '%,' + CAST(field3 AS VARCHAR) + ',%'
.
I hope this helps somebody else. I was suffering with this while working on a project a few years ago and then a job in a newer project started failing a few days ago. I found this post and was trying to recollect what I had modified in my project and then I remembered that I had changed my maven pom and removed the entry for maven-jar-plugin. When you build a jar whose purpose is to be executable, you need to include this so that certain entries get written into the manifest. I opened the old project, copied that entry (with some modifications for project name) and it worked.
You are looking for System.Reflection.Assembly.GetExecutingAssembly()
string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string xmlFileName = Path.Combine(assemblyFolder,"AggregatorItems.xml");
Note:
The .Location
property returns the location of the currently running DLL file.
Under some conditions the DLL is shadow copied before execution, and the .Location
property will return the path of the copy. If you want the path of the original DLL, use the Assembly.GetExecutingAssembly().CodeBase
property instead.
.CodeBase
contains a prefix (file:\
), which you may need to remove.
If you want your scripts to load after page has been rendered, you can use:
function getScript(a, b) {
var c = document.createElement("script");
c.src = a;
var d = document.getElementsByTagName("head")[0],
done = false;
c.onload = c.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
b();
c.onload = c.onreadystatechange = null;
d.removeChild(c)
}
};
d.appendChild(c)
}
//call the function
getScript("http://www.google-analytics.com/ga.js", function() {
// do stuff after the script has loaded
});
To locate jars that match a given string:
find . -name \*.jar -exec grep -l YOUR_CLASSNAME {} \;
I met this in kubernetes/minikube + nodejs + mongoose environment. The problem was that DNS service was up with a kind of latency. Checking DNS is ready solved my problem.
const dns = require('dns');_x000D_
_x000D_
var dnsTimer = setInterval(() => {_x000D_
dns.lookup('mongo-0.mongo', (err, address, family) => {_x000D_
if (err) {_x000D_
console.log('DNS LOOKUP ERR', err.code ? err.code : err);_x000D_
} else {_x000D_
console.log('DNS LOOKUP: %j family: IPv%s', address, family);_x000D_
clearTimeout(dnsTimer);_x000D_
mongoose.connect(mongoURL, db_options);_x000D_
}_x000D_
});_x000D_
}, 3000);_x000D_
_x000D_
_x000D_
var db = mongoose.connection;_x000D_
var db_options = {_x000D_
autoReconnect:true,_x000D_
_x000D_
poolSize: 20,_x000D_
socketTimeoutMS: 480000,_x000D_
keepAlive: 300000,_x000D_
_x000D_
keepAliveInitialDelay : 300000,_x000D_
connectTimeoutMS: 30000,_x000D_
reconnectTries: Number.MAX_VALUE,_x000D_
reconnectInterval: 1000,_x000D_
useNewUrlParser: true_x000D_
};
_x000D_
(the numbers in db_options are arbitrary found on stackoverflow and similar like sites)
Have you tried JQuery? Vanilla javascript can be tough. Try using this:
$('.container-element').add('<div>Insert Div Content</div>');
.container-element
is a JQuery selector that marks the element with the class "container-element" (presumably the parent element in which you want to insert your divs). Then the add()
function inserts HTML into the container-element.
In addition to @CB Bailey's answer:
I tried to remove multiple folders (in subfolders) named et-cache
(caching folder from Wordpress divi theme) from the index and from being tracked.
I added
et-cache/
to the .gitignore
file. But
git rm -r --cached et-cache
resulted in an error:
fatal: pathspec 'et-cache' did not match any files
So the solution was to use powershell:
Get-ChildItem et-cache -Recurse |% {git rm -r --cached $_.FullName}
This searches for all subfolders named et-cache. Each of the folders path (fullname) is then used to remove it from tracking in git.
Maybe you should try
^[#;].*$
^
matches the beggining, $
the end.
If you look at the down arrow in environment tab. The attached file can appear multiple times. You may need to highlight and run detach(filename)
several times until all cases are gone then attach(newfilename)
should have no output message.
I came across this and it went away when I switched from https to http. The SSL certs we use in dev aren't verified by a 3rd party. They're just locally generated dev certs.
The same calls work just fine in Chrome Canary and Firefox. These browsers don't appear to be as strict about the SSL cert as Chrome is. The calls would fail in Chrome with the "CAUTION: Provisional headers..." message.
I think/hope that when we use a legit SSL cert in stage and prod, we won't see this behavior in Chrome anymore.
volatile:
volatile
is a keyword. volatile
forces all threads to get latest value of the variable from main memory instead of cache. No locking is required to access volatile variables. All threads can access volatile variable value at same time.
Using volatile
variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable.
This means that changes to a volatile
variable are always visible to other threads. What's more, it also means that when a thread reads a volatile
variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.
When to use: One thread modifies the data and other threads have to read latest value of data. Other threads will take some action but they won't update data.
AtomicXXX:
AtomicXXX
classes support lock-free thread-safe programming on single variables. These AtomicXXX
classes (like AtomicInteger
) resolves memory inconsistency errors / side effects of modification of volatile variables, which have been accessed in multiple threads.
When to use: Multiple threads can read and modify data.
synchronized:
synchronized
is keyword used to guard a method or code block. By making method as synchronized has two effects:
First, it is not possible for two invocations of synchronized
methods on the same object to interleave. When one thread is executing a synchronized
method for an object, all other threads that invoke synchronized
methods for the same object block (suspend execution) until the first thread is done with the object.
Second, when a synchronized
method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized
method for the same object. This guarantees that changes to the state of the object are visible to all threads.
When to use: Multiple threads can read and modify data. Your business logic not only update the data but also executes atomic operations
AtomicXXX
is equivalent of volatile + synchronized
even though the implementation is different. AmtomicXXX
extends volatile
variables + compareAndSet
methods but does not use synchronization.
Related SE questions:
Difference between volatile and synchronized in Java
Volatile boolean vs AtomicBoolean
Good articles to read: ( Above content is taken from these documentation pages)
https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html
https://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html
Simple Steps:
-Open Eclipse.
If you parse the JSON with eval
, you're allowing the string being parsed to contain absolutely anything, so instead of just being a set of data, you could find yourself executing function calls, or whatever.
Also, JSON's parse
accepts an aditional parameter, reviver, that lets you specify how to deal with certain values, such as datetimes (more info and example in the inline documentation here)
Construct some data
df <- data.frame( name=c("John", "Adam"), date=c(3, 5) )
Extract exact matches:
subset(df, date==3)
name date
1 John 3
Extract matches in range:
subset(df, date>4 & date<6)
name date
2 Adam 5
The following syntax produces identical results:
df[df$date>4 & df$date<6, ]
name date
2 Adam 5
You'd be much better off using the same array with both lists, and creating angular filters to achieve your goal.
http://docs.angularjs.org/guide/dev_guide.templates.filters.creating_filters
Rough, untested code follows:
appModule.filter('checked', function() {
return function(input, checked) {
if(!input)return input;
var output = []
for (i in input){
var item = input[i];
if(item.checked == checked)output.push(item);
}
return output
}
});
and the view (i added an "uncheck" button too)
<div id="AddItem">
<h3>Add Item</h3>
<input value="1" type="number" placeholder="1" ng-model="itemAmount">
<input value="" type="text" placeholder="Name of Item" ng-model="itemName">
<br/>
<button ng-click="addItem()">Add to list</button>
</div>
<!-- begin: LIST OF CHECKED ITEMS -->
<div id="CheckedList">
<h3>Checked Items: {{getTotalCheckedItems()}}</h3>
<h4>Checked:</h4>
<table>
<tr ng-repeat="item in items | checked:true" class="item-checked">
<td><b>amount:</b> {{item.amount}} -</td>
<td><b>name:</b> {{item.name}} -</td>
<td>
<i>this item is checked!</i>
<button ng-click="item.checked = false">uncheck item</button>
</td>
</tr>
</table>
</div>
<!-- end: LIST OF CHECKED ITEMS -->
<!-- begin: LIST OF UNCHECKED ITEMS -->
<div id="UncheckedList">
<h3>Unchecked Items: {{getTotalItems()}}</h3>
<h4>Unchecked:</h4>
<table>
<tr ng-repeat="item in items | checked:false" class="item-unchecked">
<td><b>amount:</b> {{item.amount}} -</td>
<td><b>name:</b> {{item.name}} -</td>
<td>
<button ng-click="item.checked = true">check item</button>
</td>
</tr>
</table>
</div>
<!-- end: LIST OF ITEMS -->
Then you dont need the toggle methods etc in your controller
Off the top of my head, Set is used to assign COM objects to variables. By doing a Set I suspect that under the hood it's doing an AddRef() call on the object to manage it's lifetime.
I had a similar error using spring/jhipster
RESTful service (via Postman
)
The endpoint was something like:
@RequestMapping(value = "/index-entries/{id}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<IndexEntry> getIndexEntry(@PathVariable Long id) {
I was attempting to call the restful
endpoint via Postman
with header Accept: text/plain
but I needed to use Accept: application/json
This code worked for me
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<UserDetail>()
.HasRequired(d => d.User)
.WithOptional(u => u.UserDetail)
.WillCascadeOnDelete(true);
}
The migration code was:
public override void Up()
{
AddForeignKey("UserDetail", "UserId", "User", "UserId", cascadeDelete: true);
}
And it worked fine. When I first used
modelBuilder.Entity<User>()
.HasOptional(a => a.UserDetail)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
The migration code was:
AddForeignKey("User", "UserDetail_UserId", "UserDetail", "UserId", cascadeDelete: true);
but it does not match any of the two overloads available (in EntityFramework 6)
When using the $array.Add()
-method, you're trying to add the element into the existing array. An array is a collection of fixed size, so you will receive an error because it can't be extended.
$array += $element
creates a new array with the same elements as old one + the new item, and this new larger array replaces the old one in the $array
-variable
You can use the += operator to add an element to an array. When you use it, Windows PowerShell actually creates a new array with the values of the original array and the added value. For example, to add an element with a value of 200 to the array in the $a variable, type:
$a += 200
Source: about_Arrays
+=
is an expensive operation, so when you need to add many items you should try to add them in as few operations as possible, ex:
$arr = 1..3 #Array
$arr += (4..5) #Combine with another array in a single write-operation
$arr.Count
5
If that's not possible, consider using a more efficient collection like List
or ArrayList
(see the other answer).
We have to make sure the type= file with name attribute should be same as the parameter name passed in
upload.single('attr')
var multer = require('multer');
var upload = multer({ dest: 'upload/'});
var fs = require('fs');
/** Permissible loading a single file,
the value of the attribute "name" in the form of "recfile". **/
var type = upload.single('recfile');
app.post('/upload', type, function (req,res) {
/** When using the "single"
data come in "req.file" regardless of the attribute "name". **/
var tmp_path = req.file.path;
/** The original name of the uploaded file
stored in the variable "originalname". **/
var target_path = 'uploads/' + req.file.originalname;
/** A better way to copy the uploaded file. **/
var src = fs.createReadStream(tmp_path);
var dest = fs.createWriteStream(target_path);
src.pipe(dest);
src.on('end', function() { res.render('complete'); });
src.on('error', function(err) { res.render('error'); });
});
You could have is_hammer
in terms of row["Open"]
etc. as follows
def is_hammer(rOpen,rLow,rClose,rHigh):
return lower_wick_at_least_twice_real_body(rOpen,rLow,rClose) \
and closed_in_top_half_of_range(rHigh,rLow,rClose)
Then you can use map:
df["isHammer"] = map(is_hammer, df["Open"], df["Low"], df["Close"], df["High"])
You can use NOW()
:
INSERT INTO servers (server_name, online_status, exchange, disk_space, network_shares, c_time)
VALUES('m1', 'ONLINE', 'exchange', 'disk_space', 'network_shares', NOW())
In the fileName
you must put the relative path to the file (without /asset
)
for example:
player.setDataSource(
getAssets().openFd(**"media/video.mp4"**).getFileDescriptor()
);
The java.sql.Timestamp class has no format. Its toString method generates a String with a format.
Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.
First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.
Instant instant = mySqlDate.toInstant() ;
Lose the fraction of a second you don't want.
instant = instant.truncatedTo( ChronoUnit.Seconds );
Assign the time zone to adjust from UTC used by Instant.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );
Generate a String close to your desired output. Replace its T
in the middle with a SPACE.
DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );
If you have a list view you can do this:
Define a select list:
@{
var Acciones = new SelectList(new[]
{
new SelectListItem { Text = "Modificar", Value =
Url.Action("Edit", "Countries")},
new SelectListItem { Text = "Detallar", Value =
Url.Action("Details", "Countries") },
new SelectListItem { Text = "Eliminar", Value =
Url.Action("Delete", "Countries") },
}, "Value", "Text");
}
Use the defined SelectList, creating a diferent id for each record (remember that id of each element must be unique in a view), and finally call a javascript function for onchange event (include parameters in example url and record key):
@Html.DropDownList("ddAcciones", Acciones, "Acciones", new { id =
item.CountryID, @onchange = "RealizarAccion(this.value ,id)" })
onchange function can be something as:
@section Scripts {
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript">
function RealizarAccion(accion, country)
{
var url = accion + '/' + country;
if (url != null && url != '') {
window.location.href = url ;
}
}
</script>
@Scripts.Render("~/bundles/jqueryval")
}
Just need to add version of which you want
upgrade or downgrade
npm install -g npm@version
Example if you want to downgrade from npm 5.6.0 to 4.6.1 then,
npm install -g [email protected]
It is tested on linux
Python 3
from urllib.error import HTTPError
Python 2
from urllib2 import HTTPError
Just catch HTTPError
, handle it, and if it's not Error 404, simply use raise
to re-raise the exception.
See the Python tutorial.
e.g. complete example for Pyhton 2
import urllib2
from urllib2 import HTTPError
try:
urllib2.urlopen("some url")
except HTTPError as err:
if err.code == 404:
<whatever>
else:
raise
Had the same problem, but I could not be certain that the data was sorted or not. I could not use a 3rd party library so this is just vanilla Js; Input data can be taken from @Stephen's example;
var arr = [_x000D_
{'id':1 ,'parentid' : 0},_x000D_
{'id':4 ,'parentid' : 2},_x000D_
{'id':3 ,'parentid' : 1},_x000D_
{'id':5 ,'parentid' : 0},_x000D_
{'id':6 ,'parentid' : 0},_x000D_
{'id':2 ,'parentid' : 1},_x000D_
{'id':7 ,'parentid' : 4},_x000D_
{'id':8 ,'parentid' : 1}_x000D_
];_x000D_
function unflatten(arr) {_x000D_
var tree = [],_x000D_
mappedArr = {},_x000D_
arrElem,_x000D_
mappedElem;_x000D_
_x000D_
// First map the nodes of the array to an object -> create a hash table._x000D_
for(var i = 0, len = arr.length; i < len; i++) {_x000D_
arrElem = arr[i];_x000D_
mappedArr[arrElem.id] = arrElem;_x000D_
mappedArr[arrElem.id]['children'] = [];_x000D_
}_x000D_
_x000D_
_x000D_
for (var id in mappedArr) {_x000D_
if (mappedArr.hasOwnProperty(id)) {_x000D_
mappedElem = mappedArr[id];_x000D_
// If the element is not at the root level, add it to its parent array of children._x000D_
if (mappedElem.parentid) {_x000D_
mappedArr[mappedElem['parentid']]['children'].push(mappedElem);_x000D_
}_x000D_
// If the element is at the root level, add it to first level elements array._x000D_
else {_x000D_
tree.push(mappedElem);_x000D_
}_x000D_
}_x000D_
}_x000D_
return tree;_x000D_
}_x000D_
_x000D_
var tree = unflatten(arr);_x000D_
document.body.innerHTML = "<pre>" + (JSON.stringify(tree, null, " "))
_x000D_
JS Fiddle
This solved my problem completely:
.gm-style-iw {
overflow: visible !important;
height: auto !important;
width: auto !important;
}
If you are trying something similar like source <( curl -sS $url )
and getting the (23) Failed writing body
error, it is because sourcing a process substitution doesn't work in bash 3.2
(the default for macOS).
Instead, you can use this workaround.
source /dev/stdin <<<"$( curl -sS $url )"
For me, running the ad-hoc network on Windows 8.1, it was two things:
Any IP will allow you to connect, but if you want internet access the static IP should match the subnet from the shared internet connection.
I'm not sure why I couldn't get a longer password to work, but it's worth a try. Maybe a more knowledgeable person could fill us in.
The simplest way is to create a VBA macro that wraps that function, like so:
Function UserNameWindows() As String
UserName = Environ("USERNAME")
End Function
Then call it from the cell:
=UserNameWindows()
See this article for more details, and other ways.
Your data may not be what you expect -- it seems you're expecting, but not getting, floats.
A simple solution to figuring out where this occurs would be to add a try/except to the for-loop:
for i in range(0,N):
w=f[i].split()
l1=w[1:8]
l2=w[8:15]
try:
list1=[float(x) for x in l1]
list2=[float(x) for x in l2]
except ValueError, e:
# report the error in some way that is helpful -- maybe print out i
result=stats.ttest_ind(list1,list2)
print result[1]
Although similar in general cases ("run and get results for many tasks"), each function has some specific functionality for other cases:
asyncio.gather()
Returns a Future instance, allowing high level grouping of tasks:
import asyncio
from pprint import pprint
import random
async def coro(tag):
print(">", tag)
await asyncio.sleep(random.uniform(1, 3))
print("<", tag)
return tag
loop = asyncio.get_event_loop()
group1 = asyncio.gather(*[coro("group 1.{}".format(i)) for i in range(1, 6)])
group2 = asyncio.gather(*[coro("group 2.{}".format(i)) for i in range(1, 4)])
group3 = asyncio.gather(*[coro("group 3.{}".format(i)) for i in range(1, 10)])
all_groups = asyncio.gather(group1, group2, group3)
results = loop.run_until_complete(all_groups)
loop.close()
pprint(results)
All tasks in a group can be cancelled by calling group2.cancel()
or even all_groups.cancel()
. See also .gather(..., return_exceptions=True)
,
asyncio.wait()
Supports waiting to be stopped after the first task is done, or after a specified timeout, allowing lower level precision of operations:
import asyncio
import random
async def coro(tag):
print(">", tag)
await asyncio.sleep(random.uniform(0.5, 5))
print("<", tag)
return tag
loop = asyncio.get_event_loop()
tasks = [coro(i) for i in range(1, 11)]
print("Get first result:")
finished, unfinished = loop.run_until_complete(
asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED))
for task in finished:
print(task.result())
print("unfinished:", len(unfinished))
print("Get more results in 2 seconds:")
finished2, unfinished2 = loop.run_until_complete(
asyncio.wait(unfinished, timeout=2))
for task in finished2:
print(task.result())
print("unfinished2:", len(unfinished2))
print("Get all other results:")
finished3, unfinished3 = loop.run_until_complete(asyncio.wait(unfinished2))
for task in finished3:
print(task.result())
loop.close()
This problem may occur because your MySQL server is not installed and running. To do that start command prompt as admin and enter command:
"C:\Program Files (x86)\MySQL\MySQL Server 5.1\bin\mysqld" --install
If you get "service successfully installed" message then you need to start the MySQL service. To do that: go to Services window (Task Manager -> Services -> Open Services) Search for MySQL and Start it from the top navigation bar. Then if try to open mysql.exe it will work.
right click -> build path -> remove from build path and then again add it -> Right click on the folder named 'Test' > Build Path > Use as Source Folder.
I cannot believe Oracle's documentation is SO LAME! In some documents it is misleading people to point to the JDK by specifying the path to the JDK root, e.g. on a Mac:
/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/
Reviewing /Applications/SQLDeveloper.app/Contents/MacOS/sqldeveloper.sh revealed the method they use to set up the path:
TMP_PATH=
/usr/libexec/java_home -F -v 9if [ -z "$TMP_PATH" ] ; then TMP_PATH=
/usr/libexec/java_home -F -v 1.8if [ -z "$TMP_PATH" ] ; then osascript -e 'tell app "System Events" to display dialog "SQL Developer requires a minimum of Java 8. \nJava 8 can be downloaded from:\n http://www.oracle.com/technetwork/java/javase/downloads/"' exit 1 fi fi
Executing this manually from Terminal:
/usr/libexec/java_home -F -v 1.8
Lists the path as:
/Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home
And this is what you need to specify as the value for
SetJavaHome /Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home
Thank you Oracle for wasting half a day on your "product" that does NOT even support your latest Java version, also released by you.
Here is easy one: Simple directive
On keydown event it checks the length of a key is one and key is not a number to preventDefault()
and it won't renders that char.
import {Directive, ElementRef, HostListener} from '@angular/core';
@Directive({
selector: '[numbersOnly]'
})
export class NumbersOnlyDirective {
@HostListener('keydown', ['$event'])
keyDownEvent(event: KeyboardEvent) {
if (event.key.length === 1 && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
}
}
HTML:
<input type="text" [(ngModel)]="numModel" numbersOnly />
Limitations: It will allow pasting using a mouse that way will accept other char. To avoid that you can pass the model as input to the directive and ngOnChage
to that model change value to only numbers:
Like below:
EDIT: Added Code to detect change in Model and update the input's value
import {Directive, ElementRef, HostListener, Input, OnChanges} from '@angular/core';
@Directive({
selector: '[numbersOnly]'
})
export class NumbersOnlyDirective implements OnChanges {
@Input() numbersOnly: any;
constructor(private el: ElementRef) {}
@HostListener('keydown', ['$event'])
keyDownEvent(event: KeyboardEvent) {
// Add other conditions if need to allow ctr+c || ctr+v
if (event.key.length === 1 && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
}
ngOnChanges(changes) {
if (changes.numbersOnly) {
this.el.nativeElement.value = this.el.nativeElement.value.replace(/[^0-9]/g, '');
}
}
}
HTML:
<input type="text" [(ngModel)]="numModel" [numbersOnly]="numModel" />
An empty tree is height-balanced. A non-empty binary tree T is balanced if:
1) Left subtree of T is balanced
2) Right subtree of T is balanced
3) The difference between heights of left subtree and right subtree is not more than 1.
/* program to check if a tree is height-balanced or not */
#include<stdio.h>
#include<stdlib.h>
#define bool int
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* The function returns true if root is balanced else false
The second parameter is to store the height of tree.
Initially, we need to pass a pointer to a location with value
as 0. We can also write a wrapper over this function */
bool isBalanced(struct node *root, int* height)
{
/* lh --> Height of left subtree
rh --> Height of right subtree */
int lh = 0, rh = 0;
/* l will be true if left subtree is balanced
and r will be true if right subtree is balanced */
int l = 0, r = 0;
if(root == NULL)
{
*height = 0;
return 1;
}
/* Get the heights of left and right subtrees in lh and rh
And store the returned values in l and r */
l = isBalanced(root->left, &lh);
r = isBalanced(root->right,&rh);
/* Height of current node is max of heights of left and
right subtrees plus 1*/
*height = (lh > rh? lh: rh) + 1;
/* If difference between heights of left and right
subtrees is more than 2 then this node is not balanced
so return 0 */
if((lh - rh >= 2) || (rh - lh >= 2))
return 0;
/* If this node is balanced and left and right subtrees
are balanced then return true */
else return l&&r;
}
/* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
int main()
{
int height = 0;
/* Constructed binary tree is
1
/ \
2 3
/ \ /
4 5 6
/
7
*/
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->left->left->left = newNode(7);
if(isBalanced(root, &height))
printf("Tree is balanced");
else
printf("Tree is not balanced");
getchar();
return 0;
}
Time Complexity: O(n)
Although there are a lot of good tips here I'd like to answer the question you asked:
So in other words can they work hand in hand just like Apache/Perl or Apache/PHP etc..
YES, you can run Node.js on Apache along side Perl and PHP IF you run it as a CGI module. As of yet, I am unable to find a mod-node for Apache but check out: CGI-Node for Apache here http://www.cgi-node.org/ .
The interesting part about cgi-node is that it uses JavaScript exactly like you would use PHP to generate dynamic content, service up static pages, access SQL database etc. You can even share core JavaScript libraries between the server and the client/browser.
I think the shift to a single language between client and server is happening and JavaScript seems to be a good candidate.
A quick example from cgi-node.org site:
<? include('myJavaScriptFile.js'); ?>
<html>
<body>
<? var helloWorld = 'Hello World!'; ?>
<b><?= helloWorld ?><br/>
<? for( var index = 0; index < 10; index++) write(index + ' '); ?>
</body>
</html>
This outputs:
Hello World!
0 1 2 3 4 5 6 7 8 9
You also have full access to the HTTP request. That includes forms, uploaded files, headers etc.
I am currently running Node.js through the cgi-node module on Godaddy.
CGI-Node.org site has all the documentation to get started.
I know I'm raving about this but it is finally a relief to use something other than PHP. Also, to be able to code JavaScript on both client and server.
Hope this helps.
If you are using ContentProvider then you can use:
Cursor cursor = getContentResolver().query(CONTENT_URI, new String[] {"count(*)"},
uname=" + loginname + " and pwd=" + loginpass, null, null);
cursor.moveToFirst();
int count = cursor.getInt(0);
Swift 5
This handy extension handles few more cases than previous answers. These cases are VC(view controller) is the root VC of app window, VC is added as child to parent VC. It tries to return true only if the viewcontroller is modally presented.
extension UIViewController {
/**
returns true only if the viewcontroller is presented.
*/
var isModal: Bool {
if let index = navigationController?.viewControllers.firstIndex(of: self), index > 0 {
return false
} else if presentingViewController != nil {
if let parent = parent, !(parent is UINavigationController || parent is UITabBarController) {
return false
}
return true
} else if let navController = navigationController, navController.presentingViewController?.presentedViewController == navController {
return true
} else if tabBarController?.presentingViewController is UITabBarController {
return true
}
return false
}
}
Thanks to Jonauz's answer. Again there is space for more optimizations. Please discuss about case that need to be handled in comment section.
This code retrieves first 100 rows from table in SQLSERVER 2012 and saves a picture per row as a file on local disk
public void SavePicture()
{
SqlConnection con = new SqlConnection("Data Source=localhost;Integrated security=true;database=databasename");
SqlDataAdapter da = new SqlDataAdapter("select top 100 [Name] ,[Picture] From tablename", con);
SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
DataSet ds = new DataSet("tablename");
byte[] MyData = new byte[0];
da.Fill(ds, "tablename");
DataTable table = ds.Tables["tablename"];
for (int i = 0; i < table.Rows.Count;i++ )
{
DataRow myRow;
myRow = ds.Tables["tablename"].Rows[i];
MyData = (byte[])myRow["Picture"];
int ArraySize = new int();
ArraySize = MyData.GetUpperBound(0);
FileStream fs = new FileStream(@"C:\NewFolder\" + myRow["Name"].ToString() + ".jpg", FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(MyData, 0, ArraySize);
fs.Close();
}
}
please note: Directory with NewFolder name should exist in C:\
If you are only interested in the direct parent, and not other ancestors, you can just use parent()
, and give it the selector, as in target.parent('div#hello')
.
Example: http://jsfiddle.net/6BX9n/
function fun(evt) {
var target = $(evt.target);
if (target.parent('div#hello').length) {
alert('Your clicked element is having div#hello as parent');
}
}
Or if you want to check to see if there are any ancestors that match, then use .parents()
.
Example: http://jsfiddle.net/6BX9n/1/
function fun(evt) {
var target = $(evt.target);
if (target.parents('div#hello').length) {
alert('Your clicked element is having div#hello as parent');
}
}
You're near :)
First, the batch (%%variable) and Windows CMD (%variable) uses different variable naming. Second, i dont figure out how do you use zip from CMD. This is from Linux users i think. Use built-in zip manipulation is not like easy on Win, and even harder with batch scripting.
But you're lucky anyway. I got (extracted to target folder) zip.exe and cygwin1.dll from the cygwin package (3mb filesize both together) and start play with it right now.
Of course, i use CMD for better/faster testing instead batch. Only remember modify the %varname to %%varname before blame me :P
for /d %d in (*) do zip -r %d %d
Explanation:
for /d ...
that matches any folder inside. Only folder ignoring files. (use for /f to filesmatch)
for /d %d in ...
the %d tells cmd wich name do you wanna assign to your variable. I put d to match widh d (directory meaning).
for /d %d in (*) ...
Very important. That suposses that I CD
to desired folder, or run from. (*)
this will mean all on THIS dir, because we use /d
the files are not processed so no need to set a pattern, even if you can get only some folders if you need. You can use absolute paths. Not sure about issues with relatives from batch.
for /d %d in (*) do zip -r ...
Do ZIP is obvious. (exec zip itself and see the help display to use your custom rules). r- is for recursive, so anyting will be added.
for /d %d in (*) do zip -r %d %d
The first %d is the zip name. You can try with myzip.zip, but if will fail because if you have 2 or more folders the second cannot gave the name of the first and will not try to overwrite without more params. So, we pass %d to both, wich is the current for iteration folder name zipped into a file with the folder name. Is not neccesary to append ".zip" to name.
Is pretty short than i expected when start to play with.
A JUnit4 test with Autowired and bean mocking (Mockito):
// JUnit starts spring context
@RunWith(SpringRunner.class)
// spring load context configuration from AppConfig class
@ContextConfiguration(classes = AppConfig.class)
// overriding some properties with test values if you need
@TestPropertySource(properties = {
"spring.someConfigValue=your-test-value",
})
public class PersonServiceTest {
@MockBean
private PersonRepository repository;
@Autowired
private PersonService personService; // uses PersonRepository
@Test
public void testSomething() {
// using Mockito
when(repository.findByName(any())).thenReturn(Collection.emptyList());
Person person = new Person();
person.setName(null);
// when
boolean found = personService.checkSomething(person);
// then
assertTrue(found, "Something is wrong");
}
}
If you can't find the build path error, sometimes menu Project ? Clean... works like a charm.
Well, if you have Visual Studio (I know it's in 2005, not sure about earlier versions though), you can add the remote machine to your "Server Explorer" tag. At that point, you'll have access to the SERVICES that are running, or can be ran, from that machine (as well as event logs, and queues, and a couple other interesting things).
I know this is an old post and I do favor extension methods, but here's a simple class I use from time to time to handle dictionaries when I need default values.
I wish this were just part of the base Dictionary class.
public class DictionaryWithDefault<TKey, TValue> : Dictionary<TKey, TValue>
{
TValue _default;
public TValue DefaultValue {
get { return _default; }
set { _default = value; }
}
public DictionaryWithDefault() : base() { }
public DictionaryWithDefault(TValue defaultValue) : base() {
_default = defaultValue;
}
public new TValue this[TKey key]
{
get {
TValue t;
return base.TryGetValue(key, out t) ? t : _default;
}
set { base[key] = value; }
}
}
Beware, however. By subclassing and using new
(since override
is not available on the native Dictionary
type), if a DictionaryWithDefault
object is upcast to a plain Dictionary
, calling the indexer will use the base Dictionary
implementation (throwing an exception if missing) rather than the subclass's implementation.
If you're trying to do stuff with the Java default system keystore (cacerts
), then the default password is changeit
.
You can list keys without needing the password (even if it prompts you) so don't take that as an indication that it is blank.
(Incidentally who in the history of Java ever has changed the default keystore password? They should have left it blank.)
=>Easy way to install Python any version on Ubuntu 18.04 or Ubuntu 20.04 follow these steps:-
Step 1: Update Local Repositories:-
sudo apt update
Step 2: Install Supporting Software:-
sudo apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev wget
Step3: Create directory on your home directory To download the newest release of Python Source Code, navigate to the /python-source-files directory and use the wget command:-
mkdir python-source-files
Step 4: Download the Latest Version of Python Source Code:-
wget https://www.python.org/ftp/python/3.7.5/Python-3.7.5.tgz
"you can change python version by just modifies this:-"3.7.5" with the version you want example:-"3.5.2"
Step 5: Extract Compressed Files:-
tar –xf Python-3.7.5.tgz
or
tar xvzf Python-3.7.5.tgz
Step 6: Test System and Optimize Python:-
cd python-3.7.5
or your version of python.
Step 7: Now configure(Using the ––optimization option speeds code execution by 10-20%.):-
./configure ––enable–optimizations
OR you can also do this also if you facing ssl error:-
./configure --with-openssl
Step 8: Install a Second Instance of Python:-
sudo make altinstall
"It is recommended that you use the altinstall method. Your Ubuntu system may have software packages dependent on Python 2.x.
OR
If you want to Overwrite Default Python Installation/version:-
sudo make install"
Step 9:Now check Python Version:-
python3 ––version
Step 10: To install pip for python3 just go with this command:-
sudo apt-get install python3-pip
tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.
If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.
Notice: Trying to get property of non-object in C:\wamp\www\phone\pages\init.php on line 22
@22 is
<?php echo $sidemenu->mname."<br />";?>
$sidemenu
is not an object, and you are trying to access one of its properties.
That is the reason for your error.
The following cites the C11 standard (final draft).
6.3.1.2: When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.
bool
(mapped by stdbool.h
to the internal name _Bool
for C) itself is an unsigned integer type:
... The type _Bool and the unsigned integer types that correspond to the standard signed integer types are the standard unsigned integer types.
According to 6.2.5p2:
An object declared as type _Bool is large enough to store the values 0 and 1.
AFAIK these definitions are semantically identical to C++ - with the minor difference of the built-in(!) names. bool
for C++ and _Bool
for C.
Note that C does not use the term rvalues as C++ does. However, in C pointers are scalars, so assigning a pointer to a _Bool
behaves as in C++.
I was running a job which ran a shell script in Jenkins on a Windows machine. The job was failing due to the error given below. I was able to fix the error thanks to clues in Andrejz's answer.
Error :
Started by user james
Running as SYSTEM
Building in workspace C:\Users\jamespc\.jenkins\workspace\myfolder\my-job
[my-job] $ sh -xe C:\Users\jamespc\AppData\Local\Temp\jenkins933823447809390219.sh
The system cannot find the file specified
FATAL: command execution failed
java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.base/java.lang.ProcessImpl.create(Native Method)
at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:478)
at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:154)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
Caused: java.io.IOException: Cannot run program "sh" (in directory "C:\Users\jamespc\.jenkins\workspace\myfolder\my-job"): CreateProcess error=2, The system cannot find the file specified
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
at hudson.Proc$LocalProc.<init>(Proc.java:250)
at hudson.Proc$LocalProc.<init>(Proc.java:219)
at hudson.Launcher$LocalLauncher.launch(Launcher.java:937)
at hudson.Launcher$ProcStarter.start(Launcher.java:455)
at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:109)
at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:66)
at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:741)
at hudson.model.Build$BuildExecution.build(Build.java:206)
at hudson.model.Build$BuildExecution.doRun(Build.java:163)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:504)
at hudson.model.Run.execute(Run.java:1853)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:427)
Build step 'Execute shell' marked build as failure
Finished: FAILURE
Solution :
1 - Install Cygwin and note the directory where it gets installed.
It was C:\cygwin64 in my case. The sh.exe which is needed to run shell scripts is in the "bin" sub-directory, i.e. C:\cygwin64\bin.
2 - Tell Jenkins where sh.exe is located.
Jenkins web console > Manage Jenkins > Configure System > Under shell, set the "Shell executable" = C:\cygwin64\bin\sh.exe > Click apply & also click save.
That's all I did to make my job pass. I was running Jenkins from a war file and I did not need to restart it to make this work.
If you don't pass the correct web URL and don't have a browser, ActivityNotFoundException occurs, so check those requirements or handle the exception explicitly. That can resolve your problem.
public static void openWebPage(Context context, String url) {
try {
if (!URLUtil.isValidUrl(url)) {
Toast.makeText(context, " This is not a valid link", Toast.LENGTH_LONG).show();
} else {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
context.startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(context, " You don't have any browser to open web page", Toast.LENGTH_LONG).show();
}
}
It's very easy. Try the below code
$(document).ready(function(){
var hashValue = location.hash.replace(/^#/, '');
//do something with the value here
});
Set a value to 'name' property in initial state.
this.state={ name:''};
_x000D_
For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin
to the PATH
. Use whatever directory you have this installed in.
Then you can run from any directory in command line:
httpd -k restart
The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?
$(document).ready(function() {
var CookieSet = $.cookie('cookietitle', 'yourvalue');
if (CookieSet == null) {
// Do Nothing
}
if (jQuery.cookie('cookietitle')) {
// Reactions
}
});
It feels pretty hacky, but I managed to get the correct look by adding an extra column and row beyond what is needed. Then I filled the extra column with a Space in each row defining a height and filled the extra row with a Space in each col defining a width. For extra flexibility, I imagine these Space sizes could be set in code to provide something similar to weights. I tried to add a screenshot, but I do not have the reputation necessary.
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnCount="9"
android:orientation="horizontal"
android:rowCount="8" >
<Button
android:layout_columnSpan="2"
android:layout_gravity="fill"
android:layout_rowSpan="2"
android:text="1" />
<Button
android:layout_columnSpan="2"
android:layout_gravity="fill_horizontal"
android:text="2" />
<Button
android:layout_gravity="fill_vertical"
android:layout_rowSpan="4"
android:text="3" />
<Button
android:layout_columnSpan="3"
android:layout_gravity="fill"
android:layout_rowSpan="2"
android:text="4" />
<Button
android:layout_columnSpan="3"
android:layout_gravity="fill_horizontal"
android:text="5" />
<Button
android:layout_columnSpan="2"
android:layout_gravity="fill_horizontal"
android:text="6" />
<Space
android:layout_width="36dp"
android:layout_column="0"
android:layout_row="7" />
<Space
android:layout_width="36dp"
android:layout_column="1"
android:layout_row="7" />
<Space
android:layout_width="36dp"
android:layout_column="2"
android:layout_row="7" />
<Space
android:layout_width="36dp"
android:layout_column="3"
android:layout_row="7" />
<Space
android:layout_width="36dp"
android:layout_column="4"
android:layout_row="7" />
<Space
android:layout_width="36dp"
android:layout_column="5"
android:layout_row="7" />
<Space
android:layout_width="36dp"
android:layout_column="6"
android:layout_row="7" />
<Space
android:layout_width="36dp"
android:layout_column="7"
android:layout_row="7" />
<Space
android:layout_height="36dp"
android:layout_column="8"
android:layout_row="0" />
<Space
android:layout_height="36dp"
android:layout_column="8"
android:layout_row="1" />
<Space
android:layout_height="36dp"
android:layout_column="8"
android:layout_row="2" />
<Space
android:layout_height="36dp"
android:layout_column="8"
android:layout_row="3" />
<Space
android:layout_height="36dp"
android:layout_column="8"
android:layout_row="4" />
<Space
android:layout_height="36dp"
android:layout_column="8"
android:layout_row="5" />
<Space
android:layout_height="36dp"
android:layout_column="8"
android:layout_row="6" />
</GridLayout>
When i reach this post it really help me to understand patterns with example so i have make below table to clearly see the Design patterns & their example in Android Framework
I hope you will find it helpful.
Some useful links for reference:
To print out an SQL query in Doctrine, use:
$query->getResult()->getSql();
You can achieve this with: EventTarget.dispatchEvent(event)
and by passing in a new KeyboardEvent as the event.
For example: element.dispatchEvent(new KeyboardEvent('keypress', {'key': 'a'}))
Working example:
// get the element in question_x000D_
const input = document.getElementsByTagName("input")[0];_x000D_
_x000D_
// focus on the input element_x000D_
input.focus();_x000D_
_x000D_
// add event listeners to the input element_x000D_
input.addEventListener('keypress', (event) => {_x000D_
console.log("You have pressed key: ", event.key);_x000D_
});_x000D_
_x000D_
input.addEventListener('keydown', (event) => {_x000D_
console.log(`key: ${event.key} has been pressed down`);_x000D_
});_x000D_
_x000D_
input.addEventListener('keyup', (event) => {_x000D_
console.log(`key: ${event.key} has been released`);_x000D_
});_x000D_
_x000D_
// dispatch keyboard events_x000D_
input.dispatchEvent(new KeyboardEvent('keypress', {'key':'h'}));_x000D_
input.dispatchEvent(new KeyboardEvent('keydown', {'key':'e'}));_x000D_
input.dispatchEvent(new KeyboardEvent('keyup', {'key':'y'}));
_x000D_
<input type="text" placeholder="foo" />
_x000D_
using from ListSelectionModel
:
ListSelectionModel cellSelectionModel = table.getSelectionModel();
cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
String selectedData = null;
int[] selectedRow = table.getSelectedRows();
int[] selectedColumns = table.getSelectedColumns();
for (int i = 0; i < selectedRow.length; i++) {
for (int j = 0; j < selectedColumns.length; j++) {
selectedData = (String) table.getValueAt(selectedRow[i], selectedColumns[j]);
}
}
System.out.println("Selected: " + selectedData);
}
});
Here's an extension method which does not suffer from integer overflow (like some of the above answers do). It also caches some powers of 10 for efficiency.
static double[] pow10 = { 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10 };
public static double Truncate(this double x, int precision)
{
if (precision < 0)
throw new ArgumentException();
if (precision == 0)
return Math.Truncate(x);
double m = precision >= pow10.Length ? Math.Pow(10, precision) : pow10[precision];
return Math.Truncate(x * m) / m;
}
Use google guava libs to handle is-null-check (deamon's update)
Drawable drawable = Optional.of(Common.getDrawableFromUrl(this, product.getMapPath())).or(getRandomDrawable());
TL;DR: use px
.
First, it's extremely important to know that per spec, the CSS px
unit does not equal one physical display pixel. This has always been true – even in the 1996 CSS 1 spec.
CSS defines the reference pixel, which measures the size of a pixel on a 96 dpi display. On a display that has a dpi substantially different than 96dpi (like Retina displays), the user agent rescales the px
unit so that its size matches that of a reference pixel. In other words, this rescaling is exactly why 1 CSS pixel equals 2 physical Retina display pixels.
That said, up until 2010 (and the mobile zoom situation notwithstanding), the px
almost always did equal one physical pixel, because all widely available displays were around 96dpi.
Sizes specified in em
s are relative to the parent element. This leads to the em
's "compounding problem" where nested elements get progressively larger or smaller. For example:
body { font-size:20px; }
div { font-size:0.5em; }
Gives us:
<body> - 20px
<div> - 10px
<div> - 5px
<div> - 2.5px
<div> - 1.25px
The CSS3 rem
, which is always relative only to the root html
element, is now supported on 96% of all browsers in use.
I think everyone agrees that it's good to design your pages to be accommodating to everyone, and to make consideration for the visually impaired. One such consideration (but not the only one!) is allowing users to make the text of your site bigger, so that it's easier to read.
In the beginning, the only way to provide users a way to scale text size was by using relative size units (such as em
s). This is because the browser's font size menu simply changed the root font size. Thus, if you specified font sizes in px
, they wouldn't scale when changing the browser's font size option.
Modern browsers (and even the not-so-modern IE7) all changed the default scaling method to simply zooming in on everything, including images and box sizes. Essentially, they make the reference pixel larger or smaller.
Yes, someone could still change their browser default stylesheet to tweak the default font size (the equivalent of the old-style font size option), but that's a very esoteric way of going about it and I'd wager nobody1 does it. (In Chrome, it's buried under the advanced settings, Web content, Font Sizes. In IE9, it's even more hidden. You have to press Alt, and go to View, Text Size.) It's much easier to just select the Zoom option in the browser's main menu (or use Ctrl++/-/mouse wheel).
1 - within statistical error, naturally
If we assume most users scale pages using the zoom option, I find relative units mostly irrelevant. It's much easier to develop your page when everything is specified in the same unit (images are all dealt with in pixels), and you don't have to worry about compounding. ("I was told there would be no math" – there's dealing with having to calculate what 1.5em actually works out to.)
One other potential problem of using only relative units for font sizes is that user-resized fonts may break assumptions your layout makes. For example, this might lead to text getting clipped or running too long. If you use absolute units, you don't have to worry about unexpected font sizes from breaking your layout.
So my answer is use pixel units. I use px
for everything. Of course, your situation may vary, and if you must support IE6 (may the gods of the RFCs have mercy on you), you'll have to use em
s anyway.
update the server arguments from -Dhttps.protocols=SSLv3 to -Dhttps.protocols=TLSv1,SSLv3
To get the last record details, use the code below:
Model::where('field', 'value')->get()->last()
Since this topic never received a verified solution, I can offer a simple solution to the two issues I see you asked solutions for.
The string class offers a replace method for the string object you want to update:
Example:
$myString = $myString.replace(".","")
The system.int32 class (or simply [int] in powershell) has a method available called "TryParse" which will not only pass back a boolean indicating whether the string is an integer, but will also return the value of the integer into an existing variable by reference if it returns true.
Example:
[string]$convertedInt = "1500"
[int]$returnedInt = 0
[bool]$result = [int]::TryParse($convertedInt, [ref]$returnedInt)
I hope this addresses the issue you initially brought up in your question.
From http://www.sqlite.org/cvstrac/wiki?p=UnsupportedSql
To create a new database, just do sqlite_open(). To drop a database, delete the file.