_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d16501 | val | Instead of your (POST) route returning custom_input = "false" and then trying to redirect back in JavaScript, you should redirect in the (POST) route controller (not in blade/js) with what you already have:
redirect()->back()->withErrors(['error', 'has-error']) | unknown | |
d16502 | val | thanks for answering.
I have only done few modifications on the example code provided with the library, both HTML and JS.
HTML
<script type="text/javascript" src="oNet.js"></script>
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', oNet.init);
</script>
<div>
Markers:
<select id="nummarkers">
<option value="6" selected="selected">6</option>
</select>
</div>
<strong>Tralicci Bari</strong>
<div id="markerlist">
</div>
</div>
<div id="map-container">
<div id="map"></div>
</div>
JS
function $(element) {
return document.getElementById(element);
}
var oNet = {};
oNet.tralicci = null;
oNet.map = null;
oNet.markerClusterer = null;
oNet.markers = [];
oNet.infoWindow = null;
oNet.init = function() {
var latlng = new google.maps.LatLng(41, 16.38);
var options = {
'zoom': 6,
'center': latlng,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
oNet.map = new google.maps.Map($('map'), options);
oNet.tralicci = data.tralicci;
var numMarkers = document.getElementById('nummarkers');
google.maps.event.addDomListener(numMarkers, 'change', oNet.change);
oNet.infoWindow = new google.maps.InfoWindow();
oNet.showMarkers();
};
Please note that what here appears as "oNet" is "speedTest" in the distributed example code, and "tralicci" is equivalent to "stations".
Data_BA.json
var data = {
"tralicci":
[
{"trl_id": "BA_01", "trl_nome": "1o traliccio", "longitude": 16.58, "latitude": 41.09,
"title": "Traliccio n. 1\nPotenza 15 KW\nAltezza 37.5 m\nClienti connessi: 40",
"stato": "on", "altezza": 375}
,
{"trl_id": "BA_02", "trl_nome": "2o traliccio", "longitude": 16.578, "latitude": 41.112,
"title": "Traliccio n. 2\nPotenza 18 KW\nAltezza 42.5 m\nClienti connessi: 42",
"stato": "on", "altezza": 350}
,
{"trl_id": "BA_03", "trl_nome": "3o traliccio", "longitude": 16.544, "latitude": 41.09,
"title": "Traliccio n. 3\nPotenza 12 KW\nAltezza 22 m\nClienti connessi: 34",
"stato": "off", "altezza": 474}
,
{"trl_id": "BA_04", "trl_nome": "4o traliccio", "longitude": 16.556, "latitude": 41.08,
"title": "Traliccio n. 4\nPotenza 16 KW\nAltezza 35 m\nClienti connessi: 47",
"stato": "on", "altezza": 375}
,
{"trl_id": "BA_05", "trl_nome": "5o traliccio", "longitude": 16.580, "latitude": 41.085,
"title": "Traliccio n. 5\nPotenza 20 KW\nAltezza 39 m\nClienti connessi: 42",
"stato": "on", "altezza": 375}
,
{"trl_id": "BA_06", "trl_nome": "6o traliccio", "longitude": 16.790, "latitude": 41.12,
"title": "Traliccio n. 6\nPotenza 15 KW\nAltezza 32 m\nClienti connessi: 54",
"stato": "on-off", "altezza": 333}
I've done very little, as you can see. I use my own image as station image, different from the distributed m2.png. | unknown | |
d16503 | val | This warning is caused by JetBrains PhpStorm/WebStorm inspections.
A conventional way that is properly handled by TypeScript is to underscore unused parameters. Unfortunately, this convention isn't supported by JetBrains IDEs.
It's possible to suppress inspections in-place in some cases by triggering suggestion list with Alt+Enter/⌥+Enter and choosing Suppress for statement (this never worked for me for IDE inspections).
It's possible to suppress inspections in inspections results.
This results in adding a comment above the method and affects all unused parameters in this method signature:
// noinspection JSUnusedLocalSymbols
tellThemToDoSomething(_command: string) {}
This can be added to live templates, etc. | unknown | |
d16504 | val | it's available only on .net framework 4.0 & 4.5 | unknown | |
d16505 | val | You can use the > which is a parent > child selector ..
look at Child Selector (“parent > child”)
you could use it something like this
$('#navigation>ul>li>a') | unknown | |
d16506 | val | You cannot map to the destination ReturnedObject type since it doesn't exist when you are mapping the MyResponse1. What you are doing in your edit is exactly that, you are mapping explicitly to a known type.
The only way to automate the mapping would be to declare what object MyResponse2 can expect. Perhaps transforming MyResponse2 to a generics type would be a possible way to do it:
public class MyResponse2<T>
{
public bool IsSuccessful {get;set;}
public string Message {get;set;}
public T ReturnedObject {get;set;}
}
Then you could generalize the mapping process like so:
private static void CreateMapFromUser1To<T>() where T: class {
Mapper.CreateMap<MyResponse1, MyResponse2<T>>()
.ForMember(destination => destination.ReturnedObject, opt => opt.Ignore()) // ignore the object
.AfterMap((source, destination) => destination.ReturnedObject = Mapper.Map(source.ReturnedObject, source.ReturnedObject.GetType(), typeof(T)) as T);
}
You won't be able to map from an object to.. basically nothing so you need a destiantion type. But frankly you may have a bad design in your app and i'd recommend stepping back a taking a good look at the conversions you want to achieve | unknown | |
d16507 | val | The problem here is the photon logic about local player and master client. The rules about who can send are bound up in this.
In the end I found it much easier to go below the higher level 'helper' components (PhotonView etc) and send everything with the lowever level RaiseEvent() / OnEvent() mechanism.
See answer to previous question. | unknown | |
d16508 | val | Try to do this instead:
File file = null;
try
{
file = new File(fileName);
Scanner inputFile = new Scanner(file);
}
catch(IOException ioe) // should actually catch FileNotFoundException instead
{
System.out.println("File " + fileName + " not found.");
System.exit(0);
}
A: As I tried to explain in the comments, you're reading the file in the wrong order. You say your file looks like this:
Chris P. Cream 5 Scott Free 9 Lou Tenant 3 Trish Fish 12 Ella Mentry 4 Holly Day 3 Robyn DeCradle 12 Annette Funicello 4 Elmo 7 Grover 3 Big Bird 9 Bert 7 Ernie 3
You're just calling inputFile.nextInt(), which attempts to read an int, but "Chris P. Cream" is not an int, which is why you're getting that input mismatch exception. So first you need to read the name, then you can read that number.
Now, since it isn't clear how your text file is delimited (it's all on one line), this presents a problem because the names can be one, two, or even three words, and are followed by a number. You can still do this, but you'll need a regular expression that tells it to read up to that number.
while (inputFile.hasNext() && counter < numFans.length)
{
names[counter] = inputFile.findInLine("[^\\d]*").trim();
numFans[counter] = inputFile.nextInt();
System.out.println(names[counter] + ": " + numFans[counter]);
counter++;
}
However, if your file is actually formatted like this (separate lines):
Chris P. Cream
5
Scott Free
9
Lou Tenant
3
Trish Fish
12
Ella Mentry
4
Holly Day
3
Robyn DeCradle
12
Annette Funicello
4
Elmo
7
Grover
3
Big Bird
9
Bert
7
Ernie
3
Then you're in luck, because you can do this instead (doesn't require a regular expression):
while (inputFile.hasNext() && counter < numFans.length)
{
names[counter] = inputFile.nextLine();
numFans[counter] = inputFile.nextInt();
if (inputFile.hasNext())
inputFile.nextLine(); // nextInt() will read a number, but not the newline after it
System.out.println(names[counter] + ": " + numFans[counter]);
counter++;
}
What did Ernie say when Bert asked if he wanted icecream?
Sure Bert. | unknown | |
d16509 | val | If I'm understanding you right, to start, we can get a count by day:
SELECT COUNT(*) AS cnt, `date`
FROM `table`
GROUP BY `date`
That will give you the count of records for each day.
Then we can wrap that in another query:
SELECT dailycount.daycnt AS `type`, COUNT(*) AS cnt
FROM (
SELECT COUNT(*) AS daycnt, `date`
FROM `table`
GROUP BY `date`
) dailycount
WHERE `date` BETWEEN start_date AND end_date
GROUP BY daycnt
This will give you something like this:
type cnt
1 23
2 69
3 3
where type would be your singles, doubles, etc.
A: Without knowing the structure, here's the best SQL I could come out with:
SELECT COUNT(DISTINCT field) FROM table GROUP BY field
That will count the number of field appearances for each value. | unknown | |
d16510 | val | To get the difference between each hour, use a self-join that relates times that are an hour apart.
SELECT a.datetime, b.energy - a.energy AS energy
FROM tableA AS a
JOIN TableA AS b ON a.datetime = DATE_SUB(b.datetime, INTERVAL 1 HOUR)
WHERE MINUTE(a.datetime) = 0
DEMO
A: EXAMPLE WITH MISSING DATA
+--------------------+----------------+
| datetime | energy |
+--------------------+----------------+
| 2010-06-15 10:00:00| 1|
| 2010-06-15 10:45:00| 7|
| 2010-06-15 11:00:00| 9|
| 2010-06-15 11:15:00| 12|
| 2010-06-15 11:30:00| 15|
| 2010-06-15 11:45:00| 28|
| 2010-06-15 12:15:00| 75|
| 2010-06-15 12:30:00| 88|
| 2010-06-15 12:45:00| 102|
| 2010-06-15 13:00:00| 150|
| 2010-06-15 13:15:00| 189|
| 2010-06-15 13:30:00| 200|
| 2010-06-15 13:45:00| 205|
| 2010-06-15 14:00:00| 209|
| 2010-06-15 14:15:00| 400|
| 2010-06-15 14:30:00| 450|
| 2010-06-15 14:45:00| 480|
| 2010-06-15 15:00:00| 500|
+--------------------+----------------+
In this example some samples are missing.
Expected result:
+--------------+----------------+
| datetime | energy |
+--------------+----------------+
| 2010-06-15 10| 8| 11:00 to 10:00
| 2010-06-15 11| 17| 11:45 to 11:00
| 2010-06-15 12| 150| 13:00 to 12:15
| 2010-06-15 13| 69| 13:00 to 14:00
| 2010-06-15 14| 291| 14:00 to 15:00
+--------------+----------------+
I always want to group by a complete hour:
From 10:00 to 11:00 included
From 11:00 to 12:00 included
From 12:00 to 13:00 included
ecc....
immagine | unknown | |
d16511 | val | It's not necessary to use such a precise target selector since there's only one table element (as the other answerer also pointed out). But you don't need to leave rvest behind:
library(rvest)
URL <- "http://caipiao.163.com/award/cqssc/20160513.html"
pg <- read_html(URL)
tab <- html_table(pg, fill=TRUE)[[1]]
str(tab)
## 'data.frame': 40 obs. of 39 variables:
## $ 期号 : int 1 2 3 4 5 6 7 8 9 10 ...
## $ 开奖号码: chr "9 8 4 4 6" "1 8 3 1 6" "2 9 3 5 6" "1 4 5 8 0" ...
## ....
(SO is interpreting some of the unicode glyphs as spam so I had to remove the other columns).
The second column gets compressed via post-page-load javascript actions, so you'll need to clean that up a bit if that's the one you're going for.
A: I would use the function readHTMLTable from package XML to get the whole table, as in your website there is only one <table> element:
install.packages("XML)
library(XML)
url <- "http://caipiao.163.com/award/cqssc/20160513.html"
lotteryResults <- as.data.frame(readHTMLTable(url))
Then you can just do some cleansing procedures, subsetting and using rbind to get a data.frame with 2 columns and 120 observations. | unknown | |
d16512 | val | Below style of initialization is only introduced in C++ 11.
vector <int> num = {2,3,4};
This is not available in initial C++ version. That is what your gcc compiler is complaining. You need to tell the compiler to use C++11 version. Use below command.
g++ -std=c++11 myProgram.cpp | unknown | |
d16513 | val | If you are trying to access multi select element using id the you don't need to set id like Privilege[], you can set any unique identity like privilege-selector but if you are giving name for any multi select element then name must be like Privilege[]
Here is the html :
<form id="form" method="post">
<select id="privilege-selector" multiple>
<option value="yahoo">yahoo</option>
<option value="chrome">chrome</option>
<option value="mozilla">mozilla</option>
</select>
<input type="button" id="Save" Value="SEND"/>
</form>
Please check this below ajax request to post selected data to the server
$("#Save").on("click",function(){
var selection = [];
$.each($("#privilege-selector option:selected"),function(index,element){
selection.push($(element).val());
})
$.ajax({
url : "test5.php",
type : "POST",
data : {Privilege:selection},
success : function(_response){
var res = JSON.parse(_response);
if(res.code == "1"){
console.log(res.data);
} else {
alert(res.message);
}
}
})
});
and here is your server file that will handle the incoming request data
$serverResponse = [];
if(isset($_POST['Privilege']) && !empty($_POST['Privilege'])){
$formattedData = [];
foreach($_POST['Privilege'] as $key => $value){
$formattedData[] = array(
"id" => $key+1,
"name" => $value
);
}
$serverResponse = ["code"=>"1","message"=>"formatted data","data"=>$formattedData];
} else {
$serverResponse = ["code"=>"0","message"=>"Please select at least on value"];
}
echo json_encode($serverResponse); | unknown | |
d16514 | val | firebase-queue lets you use Realtime Database to submit jobs to a backend server you control. Clients write into the database, and that data is received by firebase-queue, where you can do whatever you want with it.
If you have interest in running backend code that reacts to changes in your Firebase project, you are much better off looking into Cloud Functions for Firebase, because you won't have to manage a backend server at all. You just write and deploy code to it. | unknown | |
d16515 | val | Adding as_supervised=True to tfds.load() will solve the problem. Another question is why this problem occurs in the first place, probably a bug in TF. | unknown | |
d16516 | val | Unit testing ensures the code works per requirements. Get the requirements and write tests to check that the code works and show that the code throws appropriate errors. You can use RobotFramework or another test automation SW to automate the tests. Some questions you might ask yourself are listed below:
ssh = paramiko.SSHClient()
*
*Does paramiko.SSHClient exist?
*is it working?
*what if it fails?
*do you get an error or does the SW hang?
ssh.load_system_host_keys()
*
*Can you load the system keys?
*How can you verify this?
ssh.connect(hostname='1.2.3.4', username='ubuntu')
*
*How can you prove the connection exists?
*What happens if you try to connect to another host?
*Do you get an error message?
*Can you logon with username 'ubuntu'?
*What if you try another username?
*Does the connection fail?
*Do you get a generic error so you don't give crackers clues about your security?
Proof of unit testing is usually a screen capture, log entry, or some documentation showing you got the result you expected when you ran the test. Hope this helps.
A: you can use unit test module like below
import unittest
import paramiko
class SimpleWidgetTestCase(unittest.TestCase): #This class inherits unittest.TestCase
#setup will run first
def setUp(self):
self.ssh = paramiko.SSHClient()
self.ssh.load_system_host_keys()
self.ssh.connect(hostname='1.2.3.4', username='ubuntu')
#Your test cases goes here with 'test' prefix
def test_split(self):
#your code here
pass
#this will run after the test cases
def tearDown(self):
#your code to clean or close the connection
pass
if __name__ == '__main__':
unittest.main()
detailed information about how to use unittest can be found here https://docs.python.org/2/library/unittest.html
one suggestion: robotframework is better option to design test cases in comparison to unit test, so until unless its not compulsory , you can invest your time in Robotframework | unknown | |
d16517 | val | You could nest your animations like this
$('#Div1').slideDown('fast', function(){
$('#Div2').slideUp('fast');
});
And do them sequentially...
You could also do something like this:
var animations = 0;
checkAnimation(1);
$('#Div1').slideDown('fast', function(){
checkAnimation(-1);
});
checkAnimation(count){
animations += count;
if(count == 0)
//animations complete
}
else {
//still animating
}
}
Hope this helps.
A: You might be able to make use of .queue to get the functionality you are after. If the length of the queue was 0 you would know that all animations on the object are finished.
Documentation | unknown | |
d16518 | val | DLL load fail error is because either you have not installed Microsoft Visual C++ Redistributable for Visual Studio 2015, 2017 and 2019 or your CPU does not support AVX2 instructions
There is a workaround either you have to compile Tensorflow from source or use google colaboratory to work. Follow the instructions mentioned here to build Tensorflow from source. | unknown | |
d16519 | val | Yes, JavaScript code loaded by .load continues running even if the elements it was loaded with are removed from the DOM. Removing a script tag has no effect whatsoever on the code that the script loaded.
Here's a live example doing the same thing with html (load ends up calling html under the covers):
var content = [
// foo
"This loads a script saying 'foo' once a second " +
"for 100 seconds." +
"<script>" +
"var fooCounter = 0;\n" +
"var fooTimer = setInterval(function() {\n" +
" $('<p>Foo</p>').appendTo(document.body);\n" +
" if (++fooCounter >= 100) {\n" +
" clearInterval(fooTimer);\n" +
" }\n" +
"}, 1000);\n" +
"</scr" + "ipt>",
// bar
"This loads a script saying 'bar' once a second " +
"for 100 seconds." +
"<script>" +
"var barCounter = 0;\n" +
"var barTimer = setInterval(function() {\n" +
" $('<p>Bar</p>').appendTo(document.body);\n" +
" if (++barCounter >= 100) {\n" +
" clearInterval(barTimer);\n" +
" }\n" +
"}, 1000);\n" +
"</scr" + "ipt>"
];
$(".load").on("click", function() {
$("#target").html(content[this.getAttribute("data-index")]);
});
<p>Click 'Load Foo', which loads content in to a target div, then once you see its script running, click 'Load Bar', which replaces the content in that div with new content. Note that now both scripts are running.</p>
<input type="button" data-index="0" class="load" value="Load Foo">
<input type="button" data-index="1" class="load" value="Load Bar">
<div id="target"></div>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> | unknown | |
d16520 | val | Transport transport = mailSession.getTransport("smtps");// change smtp to smtps
and disable your PC antivirus and firewall then try
and turn on 'Access for less secure apps'
https://www.google.com/settings/security/lesssecureapps
then will able to send mail successfully. | unknown | |
d16521 | val | I sent a POST request with: URL= outlook.office.com/api/v2.0/me/MailFolders/root/childfolders content inside: { "DisplayName": "ExampleName" } The folder was created successfully, and reachable via API's. However it is not visible in the Outlook WebUI nor in the Outlook application. Is this by design? –
The end-point for the root folder is incorrect, there is no need to use the “root” keyword. And this end-point give the error when I try to create a folder.
Here is an sample to create a folder under the root folder for your reference:
POST: https://outlook.office.com/api/v2.0/me/MailFolders
Header:
authorization: bearer {token}
content-type: application/json
BODY:
{"DisplayName":"FolderName"}
And we will the 201 status code and response like figure below: | unknown | |
d16522 | val | Your query is expecting two values. But your code below is assigning only one value.
for (int i = 0; i < array_jsn.length(); i++) {
String id = array_jsn.getJSONObject(i).getString("link_video");
PstmtdeleteforLinkVideos.setInt(1,Integer.parseInt(id));
PstmtdeleteforLinkVideos.setInt(2,Integer.parseInt(id));
PstmtdeleteforLinkVideos.addBatch();
}
you have to set parameter index 2 also.
Then it will work. | unknown | |
d16523 | val | If you're not using an ORM in PHP you should not use the SQLAlchemy ORM or SQL-Expression language either but use raw SQL commands. If you're using APC you should make sure that Python has write privileges to the folder your application is in, or that the .py files are precompiled.
Also if you're using the smarty cache consider enabling the Mako cache as well for fairness sake.
However there is a catch: the Python MySQL adapter is incredible bad. For the database connections you will probably notice either slow performance (if SQLAlchemy performs the unicode decoding for itself) or it leaks memory (if the MySQL adapter does that).
Both issues you don't have with PHP because there is no unicode support. So for total fairness you would have to disable unicode in the database connection (which however is an incredible bad idea).
So: there doesn't seem to be a fair way to compare PHP and Pylons :)
A: *
*your PHP version is out of date, PHP has been in the 5.2.x area for awhile and while there are not massive improvements, there are enough changes that I would say to test anything older is an unfair comparison.
*PHP 5.3 is on the verge of becomming final and you should include that in your benchmarks as there are massive improvements to PHP 5.x as well as being the last version of 5.x, if you really want to split hairs PHP 6 is also in alpha/beta and that's a heavy overhaul also.
*Comparing totally different languages can be interesting but don't forget you are comparing apples to oranges, and the biggest bottleneck in any 2/3/N-Tier app is waiting on I/O. So the biggest factor is your database speed, comparing PHP vs Python VS ASP.Net purely on speed is pointless as all 3 of them will execute in less than 1 second but yet you can easily wait 2-3 seconds on your database query, depending on your hardware and what you are doing.
*If you are worried what is faster, you're taking the absolute wrong approach to choosing a platform. There are more important issues, such as (not in order):
a. How easily can I find skilled devs in that platform
b. How much do those skilled devs cost
c. How much ROI does the language offer
d. How feature rich is the language | unknown | |
d16524 | val | Peripheral is advertising. That means it periodically sends an avertisement (ADV_IND) packet on some advertisement channel. In response to this packet, a central may either (Core_v4.2, 6.B.4.4.2.3):
*
*do nothing,
*send a scan request (SCAN_REQ) packet (Figure 4.3), peripheral should respond with a scan response (SCAN_RSP),
*send a connection request (CONN_REQ) packet (Figure 4.5).
Here, you have two centrals trying to reach the same peripheral at the same time. One is doing active scanning (#2 above), the other is initiating (#3 above). Unfortunately, both must send their packet at the exact same time, receiver gets jammed, and both scan request and connection request packets get lost.
There is no acknowledgement for connection requests. Initiator must to assume the advertiser received and accepted the connection request, create the connection speculatively, and possibly time out afterwards. That's why the fast termination feature pointed by bare_metal exists. In case the peripheral does not take the connection request, central should not wait forever.
LE Connection Complete event in your dumps just tell a Connection Request packet got sent, it does not tell it actually got received, processed or accepted by target.
A: on the confusion of connection created vs connection established please see the vol 6, Part B,section 4.5 from low energy specification (core 4.2). so it seems in the second instance the remote device didn't send any
data channel packet after CONNECT_REQ PDU. and in the second case if a disconnect is tried on a link which is not established , the controller will complain about invalid handle ( as there is no valid connection exist). To debug further you could enable Timing in hcidump which will confirm the failed to establish event is received by the host after Supervision Timeout.
"The Link Layer enters the Connection State when an initiator sends a
CONNECT_REQ PDU to an advertiser or an advertiser receives a
CONNECT_REQ PDU from an initiator.
After entering the Connection State, the connection is considered to be
created. The connection is not considered to be established at this point. A connection is only considered to be established once a data channel packet
has been received from the peer device. The only difference between A connection that is created and a connection that is established is the Link Layer connection supervision timeout value that is used"
"If the Link Layer connection supervision timer reaches 6 * connInterval before the connection is established (see Section 4.5), the connection shall be considered lost. This enables fast termination of connections that fail to establish" | unknown | |
d16525 | val | $("img2").title = "®" should work, if not use
$("img2").title ='\u00AE'.
The html entities are not translated for pure text.
A: There are a wealth of answers at http://paulschreiber.com/blog/2008/09/20/javascript-how-to-unescape-html-entities/
But basic gist of it is your setting the text of the node not the html, so there are no html entities.
You can however set the innerHTML of a hidden object and read the text value of that. Or assuming your source encoding allows it just enter the reg symbol directly. | unknown | |
d16526 | val | If you just want to put out the lines that match your pattern in a file, have you tried the following:
grep -E "^Pass: [0-9]+" zoix.progress-N0 | unknown | |
d16527 | val | Just change your route to:
from("file:resource/inbox").marshal(xmlJsonFormat).to("file:resource/outbox");
Then copy SimpleFile.xml into resource/inbox, run the application and you will get JSON in resource/outbox | unknown | |
d16528 | val | The documentation mentions mapstructure tags in its Unmarshaling section, but not in its WriteConfig section.
It looks like WriteConfig will go through one of the default encoders :
*
*location where such encoders are declared:
https://github.com/spf13/viper/blob/b89e554a96abde447ad13a26dcc59fd00375e555/viper.go#L341
*code for the yaml codec (it just calls the default yaml Marshal/Unmarshal functions):
https://github.com/spf13/viper/blob/b89e554a96abde447ad13a26dcc59fd00375e555/internal/encoding/yaml/codec.go
If you know you will read/write from yaml files only, the simplest way is to set yaml tags on your struct (following the documentation of the gopkg.in/yaml.v2 package) :
type config {
Contexts map[string]Context `yaml:"contexts"`
CurrentContext string `yaml:"current-context"`
Tokens []Token `yaml:"tokens"`
}
type Context struct {
Endpoint string `yaml:"endpoint,omitempty"`
Token string `yaml:"token,omitempty"`
Platform string `yaml:"platform"`
Components []string `yaml:"components,omitempty"`
Channel string `yaml:"channel,omitempty"`
Version string `yaml:"version,omitempty"`
EnforcedProvider string `yaml:"enforced-provider,omitempty"`
} | unknown | |
d16529 | val | In PowerBI, one dataset represents a single source of data and has to be in a format:
There are literally hundreds of different data sources you can use
with Power BI. But regardless of where you get your data from, that
data has to be in a format the Power BI service can use to create
reports and dashboards.
Reference: dataset concept and data source for Power BI.
For your issue you can route two devices events to two Power BI dataset.(two outputs in ASA job).
The query looks like this:
SELECT
*
INOT
powerbi
FROM
iothubevents
WHERE
deviceId = 'Raspberry Pi Web'
SELECT
*
INOT
powerbidevice2
FROM
iothubevents
WHERE
deviceId = 'Raspberry Pi Web Client'
See these snapshots:
In stream analytics job:
In Power BI: | unknown | |
d16530 | val | Try this: first install the Search Fields plugin. (You need this because the native EE "search:field_name" parameter only works on custom fields, not entry titles.)
Then use this revised code:
<?php
// Grab the categories selected from the $_POST
// join them with an ampersand - we are searching for AND matches
$cats = array();
foreach($_POST['cat'] as $cat)
{
// check we are working with a number
if(is_numeric($cat))
{
$cats[] = $cat;
}
}
$cats = implode('&', $cats);
if(!empty($_POST['keywords']))
{
$keywords = trim($_POST['keywords']);
}
?>
<?php if($keywords) : ?>
{exp:search_fields search:title="<?php echo($keywords);?>" channel="property" parse="inward"}
<?php endif; ?>
{exp:channel:entries channel="property" <?php if($keywords) : ?>entry_id="{search_results}"<?php endif; ?> category="<?php echo($cats);?>" orderby="date" sort="asc"}
{!-- do stuff --}
{/exp:channel:entries}
<?php if($keywords) : ?>
{/exp:search_fields}
<?php endif; ?> | unknown | |
d16531 | val | Answer to my self:
looking at main.css I found something like:
.listRowTemplate_template.selected {
background-color: rgb(56, 0, 217);
}
Which is the color I want to change ;)
A: Which would have been my answer, shall i vote you up? ;-)
It is easy to forget that when in Dashcode it is "just" JavaScript, CSS and HTML and so many problems will often succumb to those type of solutions such as you have done. | unknown | |
d16532 | val | // Pitch rotation (via mouse).
CameraDirection = Vector3.Transform(CameraDirection,
Matrix.CreateFromAxisAngle(Vector3.Cross(CameraUp, CameraDirection),
(MathHelper.PiOver4 / 100) *
(Mouse.GetState().Y - prevMouseState.Y)
));
CameraUp = Vector3.Transform(CameraUp,
Matrix.CreateFromAxisAngle(Vector3.Cross(CameraUp, CameraDirection),
(MathHelper.PiOver4 / 100) *
(Mouse.GetState().Y - prevMouseState.Y)
));
Whenever you use CreateFromAxisAngle, the first param (the axis) needs to be a unit length vector. If it isn't a unit length vector, it will result in a distorted (skewed) Matrix and one that is over (or under) rotated.
Whenever you cross two vectors the result in rarely a unit length vector. To make a result of a cross unit length. try this:
Vector3.Transform(CameraDirection, Matrix.CreateFromAxisAngle(Vector3.Normalize(Vector3.Cross(CameraUp, CameraDirection)), ...
by adding the 'Normalize', it makes the result of the cross a unit length vector. Don't forget to do the same to the yaw line as well. | unknown | |
d16533 | val | Just use Symbol:
julia> @enum MyEnum A=1 B=2 C=3
julia> Symbol(A)
:A
julia> x = A
A::MyEnum = 1
julia> Symbol(x)
:A
as it is defined as follows:
Base.Symbol(x::Enum) = namemap(typeof(x))[Integer(x)]::Symbol
in particular you have an un-exported:
julia> Base.Enums.namemap(typeof(x))
Dict{Int32,Symbol} with 3 entries:
2 => :B
3 => :C
1 => :A | unknown | |
d16534 | val | Nope, it is not necessary when variables are passed by reference, which is the case here. So it's Visual Studio who is wrong here.
However, you are using obsoleted techniques here, and can get rid of these false positive warnings and reduce the amount of code at once:
$stmt = $conn->prepare("SELECT * FROM `users` WHERE user = ? ");
$stmt->bind_param("s", $filtered_form['user']);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
if ($row and password_verify($filtered_form['pass'], $row['pass']) {
$_SESSION['user'] = $row;
header("Location:index.php");
exit;
} else {
return "Incorrect password";
}
as you can see, get_result() gives you a much better result (pun not intended) than store_result(), letting you to store the user information in a single variable, so it won't litter the $_SESSION array.
And num_rows() proves to be completely useless (as it always happens).
An important note: you should never ever store passwords in plain text. Alwas shore a hashed password instead. | unknown | |
d16535 | val | Search algorithms in general have a performance of O(n) on a not presorted list. If there is no information given about the Excel file you are searching in, there is no algorithm with a better worst-case performance than O(n).
So, that means, iterating over each line until the derised line(s) is found is necessary, no matter what. If you want to improve performance, you can try to use parallelization, for instance MapReduce: https://en.wikipedia.org/wiki/MapReduce | unknown | |
d16536 | val | GLEW must do some tricks in order to deal with the context dependent function pointers on some plattforms. One of these plattforms is Windows. A foolproof way to make things working is to
*
*Test if there's actually a OpenGL context bound
*call glewInit()
everytime a function in the DLL is called that uses extended OpenGL functionality. I.e.
… some_DLL_exported_function(…)
{
if( NULL == wglGetCurrentContext() ||
GLEW_OK == glewInit() ) {
return …;
}
} | unknown | |
d16537 | val | Another approach, breaking the problem down into tiny pieces:
const inPairs = (xs) =>
[...xs].reduce((a, x, i) => i == 0 ? a : [...a, xs[i - 1] + x], [])
const pairFreq = str => str // "this is a good thing"
.split (/\s+/) //=> ["this","is","a","good","thing"]
.filter (s => s.length > 1) //=> ["this","is","good","thing"]
.flatMap (inPairs) //=> ["th","hi","is","is","go","oo","od","th","hi","in","ng"]
.reduce ( (a, s) => ({...a, [s]: (a[s] || 0) + 1}), {})
//=> {"th":2,"hi":2,"is":2,"go":1,"oo":1,"od":1,"in":1,"ng":1}
console .log (
pairFreq('this is a good thing')
)
Obviously you could inline inPairs if you chose. I like this style of transformation, simply stringing together steps that move me toward my end goal.
A: You need to make use of string[i+1] to get the next letter in the pair.
And to avoid accessing outside the array when you use string[i+1], the limit of the loop should be string.length-1.
var string = "this is a good thing";
var histogram = {};
for (var i = 0, len = string.length - 1; i < len; i++) {
if ((string[i] !== " ") && (string[i + 1] !== " ")) {
let pair = string.substr(i, 2);
histogram[pair] = (histogram[pair] || 0) + 1;
}
};
console.log(histogram); | unknown | |
d16538 | val | Here is the code:
StringBuilder sb = new StringBuilder();
Random r = new Random();
for (int i = 0; i < r.Next(100); i++) sb.Append((char)r.Next(65, 255));
string s = sb.ToString();
Make sure you store the string or you won't be able to decrypt
A: If you want some random value for your encryption (for example a salt value, to make the usage of rainbow tables impossible), i always use Guids. They are unique and "random".
Be sure to keep your salt, because you will need it later, for example, if you want to proof wether a password is correct:
PASSWORD + SALT --encryption--> Hash
If you forget the salt, you will not be able to build the same Hash again.
If you want to encrypt passwords, you algorithm is not very useful. I would take the following code-snippet from SO: sha-256 hash in C#
Just be sure, that you pass password + hash to the method, to get your encrypted value with some random "touch". | unknown | |
d16539 | val | You are forgetting the "minibatch dimension", each "1D" sample has indeed two dimensions: the number of channels (7 in your example) and length (10 in your case). However, pytorch expects as input not a single sample, but rather a minibatch of B samples stacked together along the "minibatch dimension".
So a "1D" CNN in pytorch expects a 3D tensor as input: BxCxT. If you only have one signal, you can add a singleton dimension:
out = model(torch.tensor(X)[None, ...]) | unknown | |
d16540 | val | Did you get answer for this ?
This worked before okay, but now the android-chrome comes on top of the page and does not push it up anymore.
I'm using webview, maybe they have some option for it?
Quick fix is to add padding at the bottom of the screen, maybe 200 - 300px | unknown | |
d16541 | val | Mocked something quickly, possibly this is what you are looking for http://jsfiddle.net/kasperoo/eHLBu/1/
<div class="container">
<ul id="insurances">
<li><p><a href="conditions-form.html"><img src="img/estate-insurance.png">Ubezpieczenia nieruchomości</a></p></li>
<li><p><a href="conditions-form.html"><img src="img/estate-insurance.png">Ubezpieczenia nieruchomości</a></p></li>
<li><p><a href="conditions-form.html"><img src="img/estate-insurance.png">Ubezpieczenia nieruchomości</a></p></li>
</ul>
.container {
position: relative;
}
#insurances {
list-style-type: none;
width: auto;
}
#insurances li p {
margin: 0;
width: 200px;
margin: 0 auto;
}
#insurances li:nth-child(even) {
background: green;
}
#insurances li:nth-child(odd) {
background: grey;
} | unknown | |
d16542 | val | Either you can use frameworks like bootstrap and include the images inside grid view. or you can manually to adjust the width of image
@media screen and (min-width: 400px) {
img{
//adjust the width - eg 40%
}
}
@media screen and (min-width: 800px) {
img{
//adjust the width - eg 80%
}
}
A: You need to use media query when the paragraph moves down on next line make an css media query breakpoint at that point and add width of image as 100%. | unknown | |
d16543 | val | Is there a way to upload the symbols manually (e.g. via CLI like we can with the nugets)?
The answer is yes.
You could use the push both primary and symbol packages at the same time using the below command. Both .nupkg and .snupkg files need to be present in the current folder:
nuget push MyPackage.nupkg -source
And publish to a different symbol repository, or to push a legacy symbol package that doesn't follow the naming convention, use the -Source option:
nuget push MyPackage.symbols.nupkg -source https://nuget.smbsrc.net/
Please refere the document for some more details:
Publishing a symbol package
Publishing a legacy symbol package
Anywhere a documentation how the URL of the file share would look like
on an on premise server?
You could check the document Index Sources & Publish Symbols task: | unknown | |
d16544 | val | It is because you are trying to run the Javascript before the dom-ready event.
Try executing your javascript after this event is completed like below
const { app, BrowserWindow } = require('electron');
let win;
function createWindow() {
win = new BrowserWindow({ width: 1000, height: 600 })
win.openDevTools();
// First URL
win.loadURL('https://www.google.com')
// Once dom-ready
win.webContents.once('dom-ready', () => {
// THIS WORKS!!!
win.webContents.executeJavaScript(`
console.log("This loads no problem!");
`)
// Second URL
win.loadURL('https://github.com/electron/electron');
// Once did-navigate seems to function fine
win.webContents.once('did-navigate', () => {
// THIS WORKS!!! So did-navigate is working!
console.log("Main view logs this no problem....");
win.webContents.once('dom-ready', () => {
// NOT WORKING!!! Why?
win.webContents.executeJavaScript(`
console.log("I canot see this nor the affects of the code below...");
const form = document.querySelectorAll('input.js-site-search-form')[0];
const input = form.querySelectorAll('input.header-search-input')[0]
input.value = 'docs';
form.submit();
`)
})
});
})
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
}); | unknown | |
d16545 | val | var filteredGarages = garages.filter(garage =>
garage.Sections.filter(section =>
section.Cars.filter(car => car.Model.indexOf("Bmw")>=0)
.length > 0)
.length > 0) | unknown | |
d16546 | val | you need to start the connection:
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(@"%@",webData);
[theConnection start];
}
else
{
} | unknown | |
d16547 | val | This isn't really a job for formsets. You want a single form with a dynamic set of fields; each field's name is the customer UID and its value is accept or reject. To do that, you can create the fields programmatically when instantiating the form:
class ReviewPaymentMethodForm(forms.Form):
def __init__(self, *args, **kwargs):
accounts = kwargs.pop('accounts')
super(ReviewPaymentMethodForm, self).__init__(*args, **kwargs)
for account in accounts:
self.fields[str(account.id)] = forms.ChoiceField(
label=account.user.username,
choices=DECISION_CHOICES,
widget=forms.RadioSelect(renderer=HorizontalRadioRenderer),
initial='2', # 1 => Approve, 2 => Reject
)
And the view becomes:
def review_payment_methods(request, template):
new_accounts = Account.objects.filter(method_approved=False)
if request.method == "POST":
payment_method_form = ReviewPaymentMethodForm(request.POST, accounts=new_accounts)
if payment_method_form.is_valid():
for acc_id, value in payment_method_form.cleaned_data.items():
approved = (value == '1')
Account.objects.filter(pk=acc_id).update(method_approved=approved)
return HttpResponseRedirect('/admin/')
else:
form = ReviewPaymentMethodForm(accounts=new_accounts)
return render(request, template, {'form': form}) | unknown | |
d16548 | val | Try this you need to use leading
*
*A widget to display before the title.
SAMPLE CODE
AppBar(
title: new Text("Your Title"),
leading: new IconButton(
icon: new Icon(Icons.arrow_back,size: 50.0,),
onPressed: () => {
// Perform Your action here
},
),
);
OUTPUT
A: You can use Transform.scale widget and wrap IconButton with it. This widget has scale property which you can set based on your need. Working sample code below:
appBar: AppBar(
leading: Transform.scale(
scale: 2,
child: IconButton(
icon: Icon(Icons.arrow_back, color: Colors.black),
onPressed: () {}
)
),
centerTitle: false,
backgroundColor: Colors.white,
title: Text(
'test',
style: TextStyle(color: Colors.black87,
),
// elevation: 1.0,
)),
Hope this answers your question. | unknown | |
d16549 | val | There's nothing like that in the current version of C#. The dynamic stuff in C# 4.0 will make this easier.
In the meantime, why not just make Name (and other values) simple properties? While you're at it, you'll find the generic Dictionary<K,V> easier to work with than HashTable.
A: You can't do this with C#, at least not in the current version. What you'd need is the equivalent of method_missing in ruby.
If this was C# 4.0 you could do something similar to this with anonymous types and the dynamic keyword, however you'd need to know the keys up front.
A: Apparently you can do that in .NET 4.0 by implementing the IDynamicMetaObjectProvider interface... doesn't seem trivial though !
A: Depending on how you are rendering the HTML there might be a few ways to solve your problem.
The code above is as noted not possible at current in c#.
First of all I assume there's a reason why you don't use ADO objects, that usually solve the rendering problems you mention (together with GridView or similar).
If you want to generate a class with "dynamic" properties you can create a propertybag
it will not make the above code possible though but will work with a rendering engine based on TypeDescriptor using custom descriptors.
A: Take a look at ExpandoObject in c# 4. | unknown | |
d16550 | val | This cmd should do:
:%s/\\foo{\zs[^}]\+\ze}/\=substitute(submatch(0), '$', len(submatch(0))%2?' ':'','g')/
A: :%s/\\\w\+{\([^}]\{2}\)*[^}]\zs\ze}/ /g
Explanation:
Find pairs of characters (\([^}]\{2}\)*) followed by another character ([^}]) in between a macro \\\w\+{...}. Then do a substitution adding an additional space.
Glory of details:
*
*\\\w\+{...} find macros of the pattern \foo{...}
*Look for character that does not match an ending curly brace, [^}]
*Look for pairs of non-}'s, \([^}]\{2}\)*
*Find an odd length string by finding pairs and then finding one more, \([^}]\{2}\)*[^}]
*Use \zs and \ze to set where the start and end of the match
*Use a space in the replacement portion of the substitution to add additional space and thereby making the string even in length
Fore more help see:
:h :s
:h :range
:h /\[]
:h /\(
:h /\zs
:h /\w
:h /star
:h /\+
A: This should work
:%s/\v[(\{(\w{2})*) ]@<!}/ }/g
break down:
%s " run substitute on every line
\v " very magic mode
[(\{(\w{2})*) ] " matches every `{` followed by an equal number of word
characters and space, since you don't want to add a space again everytime
you run it.
@<!} " negative lookahead, matches all } not following the pattern before
Update
To solve the precise problem as you can read in the comments, the following command helps.
g/^\\foo/s/\v(\{([^}]{2})*)@<!}/ }/g
Changes:
g/^\\foo/... " only run it on lines starting with \foo
[^}] " it does now match all characters between { and } not only word
characters.
Pitfalls: won't work correct with multiple braces on the line ( \foo{"hello{}"} and \foo{string} {here it would also match} f.e. will fail). if one of these is a problem. just tell me | unknown | |
d16551 | val | TestCafe Roles reload a page and apply previously stored cookies and local storage values or perform the initialization steps if there are no stored values. They do not store or change window properties. However, scripts from your page can produce different results due to different local storage values. I think you can create an issue in the TestCafe repository and provide a sample page that can be used to reproduce this behavior.
You can add t.wait or a ClientFunction that returns a Promise to the end of a Role initialization function to postpone creating local storage snapshots. | unknown | |
d16552 | val | Try:
$('#selector img').each(function(i) {
var self = $(this);
var src = self.attr('src');
if (src.match(/img.youtube.com/)) {
self.attr('src', src.replace("/default.jpg","/hqdefault.jpg"));
self.addClass('video');
}
});
A: You can add a condition before replacing and add video class.
$('#selector img').attr('src',function(i,e){
if($(this).attr('src').search('img.youtube.com') > 0){
$(this).addClass('video');
}
return $(this).attr('src').replace("default.jpg","hqdefault.jpg");
}); | unknown | |
d16553 | val | Read somewhere else removing the extensions fixes it for minikube
https://github.com/microsoft/mindaro/issues/111 | unknown | |
d16554 | val | We use Apache Wicket. We have been using it for 9 years or so and have built large scale enterprise applications for financial institutions. It works well with many technologies and it also has a unit testing framework which we use quite a bit. I highly recommend it. Here's a link. http://wicket.apache.org/
I've never used JSF so I can't vouch for it, but a lot of people use it and it is a Java standard. Either one of these technologies are built for solving the problem that you need to solve in an efficient way.
Now, if you want to do everything yourself and you don't want any frameworks in the way you could write a Java Servlet and output the HTML yourself. Here's a tutorial. There are many on the web. http://www.tutorialspoint.com/servlets/servlets-first-example
I recommend using a framework. Hopefully my answer will help you make an educated decision for your needs. | unknown | |
d16555 | val | Use the arrange function in plyr. It allows you to individually pick which variables should be in ascending and descending order:
arrange(ToothGrowth, len, dose)
arrange(ToothGrowth, desc(len), dose)
arrange(ToothGrowth, len, desc(dose))
arrange(ToothGrowth, desc(len), desc(dose))
It also has an elegant implementation:
arrange <- function (df, ...) {
ord <- eval(substitute(order(...)), df, parent.frame())
unrowname(df[ord, ])
}
And desc is just an ordinary function:
desc <- function (x) -xtfrm(x)
Reading the help for xtfrm is highly recommended if you're writing this sort of function.
A: There are a few problems there. sort.data.frame needs to have the same arguments as the generic, so at a minimum it needs to be
sort.data.frame(x, decreasing = FALSE, ...) {
....
}
To have dispatch work, the first argument needs to be the object dispatched on. So I would start with:
sort.data.frame(x, decreasing = FALSE, formula = ~ ., ...) {
....
}
where x is your dat, formula is your form, and we provide a default for formula to include everything. (I haven't studied your code in detail to see exactly what form represents.)
Of course, you don't need to specify decreasing in the call, so:
sort(ToothGrowth, formula = ~ len + dose)
would be how to call the function using the above specifications.
Otherwise, if you don't want sort.data.frame to be an S3 generic, call it something else and then you are free to have whatever arguments you want.
A: I agree with @Gavin that x must come first. I'd put the decreasing parameter after the formula though - since it probably isn't used that much, and hardly ever as a positional argument.
The formula argument would be used much more and therefore should be the second argument. I also strongly agree with @Gavin that it should be called formula, and not form.
sort.data.frame(x, formula = ~ ., decreasing = FALSE, ...) {
...
}
You might want to extend the decreasing argument to allow a logical vector where each TRUE/FALSE value corresponds to one column in the formula:
d <- data.frame(A=1:10, B=10:1)
sort(d, ~ A+B, decreasing=c(A=TRUE, B=FALSE)) # sort by decreasing A, increasing B | unknown | |
d16556 | val | The reason you are seeing this behavior is that the reset button does not have type="button" or type="reset" attribute and therefore it behaves as a submit button by default. So the ng-click that sets the form to pristine actually set $submitted to false correctly, but immediately afterwards, the form is submitted again.
app.js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function() {
this.data = {
name: ''
};
this.reset = function(form) {
this.data.name = '';
form.$setPristine();
};
});
HTML Page:
<html ng-app="plunker">
<head>
<title>form.$submitted</title>
<script src="http://code.angularjs.org/1.3.2/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="MainCtrl as ctrl">
<form name="form" novalidate>
<input name="name" ng-model="ctrl.data.name" placeholder="Name" required />
<input type="submit" />
<button type="button" class="button" ng-click="ctrl.reset(form)">Reset</button>
</form>
<pre>
Pristine: {{form.$pristine}}
Submitted: {{form.$submitted}}
</pre>
</div>
http://plnkr.co/edit/kRxEVu?p=preview
Hope this is the one that you have wanted
Source: https://github.com/angular/angular.js/issues/10006#issuecomment-62640975
A: You can reset the form after submit by adding $setUntouched() & $setPristine() to the form name after submitting the form OR on success of your Ajax request. Eg:-
<form name="userDetailsForm"
ng-submit="addUserDetails(userDetailsForm.$valid)"
novalidate>
<div class="field name-field">
<input class="input" type="text" name="name" ng-model="form.data.name" required placeholder="First Name + Last Name" />
<div ng-if="userDetailsForm.$submitted || userDetailsForm.name.$touched" ng-messages="signupForm.name.$error">
<div ng-message="required">You did not enter your name</div>
</div>
</div>
<input type="submit" value="Add Details" class="btn btn-default" />
</form>
$scope.addUserDetails = function(valid) {
if(!valid) return;
//Your Ajax Request
$scope.userDetailsForm.$setUntouched();
$scope.userDetailsForm.$setPristine();
}; | unknown | |
d16557 | val | 0.7.4 is not valid JSON.
This is valid JSON {"data": "0.7.4"}
Learn more about JSON here json.org
JSON to Object:
$json = '{"data": "0.7.4"}';
$obj = json_decode($json);
var_dump($obj);
JSON to Array:
$json = '{"data": "0.7.4"}';
$array = json_decode($json, true);
var_dump($array);
A: Two things:
*
*Don't check if the result is empty(), check if the result is NULL. json_decode returns NULL if the input could not be decoded.
*The input string 0.7.4 is invalid JSON. Period. It worked at one point in PHP, but it was a mistake that it worked at all. You should not depend on this behavior as it is incorrect.
The modified version of your code should probably look like:
$value = "0.7.4";
if( !empty($value) )
{
$jsonValue = json_decode($value);
if ( $jsonValue !== NULL ) {
// Pick a value to return
$value = $jsonValue->something;
} else {
// Do nothing, leave $value as is
}
}
var_dump($value);
A: As stated, 0.7.4 is not valid JSON (according to the JSON spec), but PHP's json_decode can decode scalar values, too.
PHP implements a superset of JSON as specified in the original » RFC 4627 - it will also encode and decode scalar types and NULL. RFC 4627 only supports these values when they are nested inside an array or an object.
From: http://php.net/json_decode
If you had $value ='"0.7.4"'; (7 characters), then json_decode() would decode this to the string 0.7.4. But since your value is 0.7.4 (5 characters, since it's missing the double quotes), it can't be decoded.
Your example at https://3v4l.org/gX4vM is failing to decode $value and just printing out its original value (see: https://3v4l.org/e3um2).
EDIT: For some weird reason, the example at http://ideone.com/2uuoHw is decoding 0.7.4 as the float 0.7. That shouldn't happen. You should only get 0.7 if you stated with $value = "0.7": (see: https://3v4l.org/H2W5M). | unknown | |
d16558 | val | A public key certificate (PKC) will have the same key pair (public key) as the issuer only if the certificate is a self signed one. It's always possible for a CA to issue a certificate for another key-pair, in which case the new certificate will have the public key of the new key-pair and will be signed by the CA's private key. The subject of this new certificate can in turn be made a CA (through BasicConstraint extension and KeyUsage extension) in which case the new key-pair can be used to issue yet other certificates, thus creating a certificate path or chain. Please see the following code snippet.
public static X509Certificate getCertificte(X500Name subject,
PublicKey subjectPublicKey,
boolean isSubjectCA,
X509Certificate caCertificate,
PrivateKey caPrivateKey,
String signingAlgorithm,
Date validFrom,
Date validTill) throws CertificateEncodingException {
BigInteger sn = new BigInteger(64, random);
X500Name issuerName = new X500Name(caCertificate.getSubjectDN().getName());
SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded());
X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuerName,
sn,
validFrom,
validTill,
subject,
subjectPublicKeyInfo);
JcaX509ExtensionUtils extensionUtil;
try {
extensionUtil = new JcaX509ExtensionUtils();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("No provider found for SHA1 message-digest");
}
// Add extensions
try {
AuthorityKeyIdentifier authorityKeyIdentifier = extensionUtil.createAuthorityKeyIdentifier(caCertificate);
certBuilder.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier);
SubjectKeyIdentifier subjectKeyIdentifier = extensionUtil.createSubjectKeyIdentifier(subjectPublicKey);
certBuilder.addExtension(Extension.subjectKeyIdentifier, false, subjectKeyIdentifier);
BasicConstraints basicConstraints = new BasicConstraints(isSubjectCA);
certBuilder.addExtension(Extension.basicConstraints, true, basicConstraints);
} catch (CertIOException e) {
throw new RuntimeException("Could not add one or more extension(s)");
}
ContentSigner contentSigner;
try {
contentSigner = new JcaContentSignerBuilder(signingAlgorithm).build(caPrivateKey);
} catch (OperatorCreationException e) {
throw new RuntimeException("Could not generate certificate signer", e);
}
try {
return new JcaX509CertificateConverter().getCertificate(certBuilder.build(contentSigner));
} catch (CertificateException e) {
throw new RuntimeException("could not generate certificate", e);
}
}
Please note the arguments:
subjectPublicKey: public key corresponding to the new key-pair for which a new certificate will be issued.
caCertificate: CA certificate which corresponds to the key-pair of the current CA.
caPrivateKey: private key of the CA (private key corresponding to the caCertificate above). This will be used to sign the new certificate.
isSubjectCA: a boolean indicating whether the new certificate holder (subject) will be acting as a CA.
I have omitted keyUsage extensions for brevity, which should be used to indicate what all purposes the public key corresponding to the new cert should be used. | unknown | |
d16559 | val | Your git-bash installation is out of date.
Execute git --version to confirm this. Are you using something from before 2.x?
Please install the latest version of git-bash, which is 2.24.0 as of 2019-11-13.
See the Release Notes for git for more information about performance improvements over time. | unknown | |
d16560 | val | For what concerns the reading in, you can use textscan:
filename = '*** Full path to your text file ***';
fid = fopen(filename, 'r');
if fid == -1, error('Cannot open file! Check filename or location.'); end
readdata = cell2mat(textscan(fid,'%f%f%f%f%f%f'));
fclose(fid);
This code will save the data in a matrix with 6 columns, if the file does not contain data other than the numbers. The format %f can be changed according to your needs (see https://de.mathworks.com/help/matlab/ref/textscan.html).
About the meaning of the data: when I click on the link I don't see any data so please be more specific on that. Besides that, why would you use data of which you don't know the meaning? | unknown | |
d16561 | val | Implement and OnCompletionListener. Here is an example of my code. It should work the same as a RAW file video.
final VideoView vs = (VideoView) findViewById(R.id.imlsplash);
// Set video link (mp4 format )
Uri video = Uri.parse("android.resource://"+getPackageName() +"/" +R.raw.iphonesplashfinal);
vs.setVideoURI(video);
vs.requestFocus();
vs.start();
vs.setOnCompletionListener(new OnCompletionListener(){
@Override
public void onCompletion(MediaPlayer mp) {
startActivity(new Intent(CurrentActivity.this, NextActivity.class));
CurrentActivity.this.finish();
}
});
}
you may have to replace the videoView with whatever you are using.
If you are using a URL change URI to URL and add URL in place of "android.resource://"+getPackageName() +"/" +R.raw.iphonesplashfinal | unknown | |
d16562 | val | Knockout's click binding (and event binding, which click is a subset of) pass the current data as the first argument and the event as the second argument to any handlers.
So, arg would be equal to your viewModel in your case.
A: The parameter arg will reference the parent and as you can see in your example the actual viewmodel is the parent. Putting an argument there is mainly used when you have nested controllers and want to reference the parent dynamically as stated in the second example here, http://knockoutjs.com/documentation/click-binding.html
<ul data-bind="foreach: places">
<li>
<span data-bind="text: $data"></span>
<button data-bind="click: $parent.removePlace">Remove</button>
</li>
</ul>
<script type="text/javascript">
function MyViewModel() {
var self = this;
self.places = ko.observableArray(['London', 'Paris', 'Tokyo']);
// The current item will be passed as the first parameter, so we know which place to remove
self.removePlace = function(place) {
self.places.remove(place)
}
}
ko.applyBindings(new MyViewModel());
</script>
I would also recommend you not to use self as a parameter name in javascript, instead go for that
var that = this; | unknown | |
d16563 | val | Try moving the origin setting to viewWillAppear.
override func viewWillAppear() {
super.viewWillAppear()
VC4.frame.origin = CGstart
}
A: This solved the issue.
override func viewDidLoad() {
super.viewDidLoad()
self.view.layoutIfNeeded()
VC4.frame.origin = CGstart
}
no need for viewDidAppear or layoutSubviews. | unknown | |
d16564 | val | You can use the concept of interceptor of $httpProvider i guess
$httpProvider.interceptors
A: JQuery reference must be added before the angular js reference. If we add reference in this order, then document ready events fired of loaded htmls will be fired. Issue solved now. | unknown | |
d16565 | val | First, you should present the navigation controller, not its root view controller. Then when you want to populate the root view controller with some data, you need to reference it as the navigation controller's root view controller:
UINavigationcontroller *questionnaireNavController = [self.storyboard instantiateViewControllerWithIdentifier:@"QuestionnaireNavigationController"];
[questionnaireNavController setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
QuestionnaireViewController *qvc = (QuestionnaireViewController *)[questionnaireNavController topViewController];
[qvc setQuestionsAndAnswers:_questionsAndAnswers];
[self presentViewController:questionnaireNavController animated:NO completion:nil];
Second, in prepareForSegue:sender: you don't need to reference a navigation controller at all:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
AnswersViewController *answersVC = segue.destinationViewController;
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
NSArray *answers = [[_questionsAndAnswers objectAtIndex:indexPath.row] objectForKey:@"answers"];
[answersVC setAnswers:answers];
}
A: You are not getting the navigationController properly. Instead of segue.destinationViewController, use self.navigationController
By calling segue.destinationViewController, you are getting a pointer to the VC you are segueing to (AnswersViewController) which doesn't understand the message viewControllers because it is not a UINavigationController.
Also the AnswersViewController is objectAtIndex:1 I believe, check this though. | unknown | |
d16566 | val | The CanDeactivate guard has access to the instance of the active component, so you can implement a hasChanges() that check if there have been changes and conditionally ask for the user confirmation before leave.
In the following example the CanDeactivateComponent implements the methods hasChanges() that returns a boolean value indicating if the components has detected any changes.
The implementation of CanDeactivate guard is similar to the CanActivate guard implelementaion (you can create a function, or a class that implements the CanDeactivate interface):
import { CanDeactivate } from '@angular/router';
import { CanDeactivateComponent } from './app/can-deactivate';
export class ConfirmDeactivateGuard implements CanDeactivate<CanDeactivateComponent>
{
canDeactivate(target: CanDeactivateComponent)
{
if(target.hasChanges()){
return window.confirm('Do you really want to cancel?');
}
return true;
}
}
Even though, this is a very trivial implementation, CanDeactivate uses a generic, so you need to specify what component type you want to deactivate.
In the Angular router of the component:
{
path: '',
component: SomeComponent,
canDeactivate: [ConfirmDeactivateGuard]
}
Last, like all other services on Angular, this guard needs to be registered accordingly:
@NgModule({
...
providers: [
...
ConfirmDeactivateGuard
]
})
export class AppModule {}
You can have multiple guards protecting a single route, which helps you implementing sophisticated use cases, where a chain of different checks is needed. | unknown | |
d16567 | val | yes sure this is possible.
Let me give you some background over this. If you are building SPA with multiple pages, you would like to use a client-side routing in otder to display differen page based on the browser url. As I know defacto solution for routing in react is react-router but there are many other to chose from. See this link. Unfortunately, I won't be able to completely explain how to use react-router solution, but here is a brief example.
Inside your main component (like App.jsx) add routing:
// 1. do proper imports
import { BrowserRouter } from "react-router-dom";
// 2. wrap your application inside of BrowserRouter component
class App extends React.Component {
// your code
render() {
return (
<BrowserRouter>
{/* your app code */}
{/* Add routing */}
<Route path="/" exact component={Dashboard} />
<Route path="/questions/id/:id" component={Question} />
{/* your app code */}
<BrowserRouter>
)
}
}
You should see now that when your browser url matches /questions/id/:id component Question should be mounted to the page. Inside this component, you can fetch id that was passed in. It will be inside this.props.match.param.id property
class Question extends React.Component {
// your code
render() {
const id = this.props.match.param.id;
return (
<div>
Page with { id } was opened
<div>
)
}
}
Sure you would like to familiarise yourself with react-router docs.
A: ReactJs don't include a router. But the most popular package to do this is React-router.
The official documentation references other good packages | unknown | |
d16568 | val | Gradle and maven have different conflict resolution strategies when there's more than one version of an artifact in the dependency graph
*
*Maven has a "nearest definition wins" strategy where the version which is defined in a transitive pom which is "nearest" to your project wins. In my opinion this is a stupid strategy. You can force a version by explicitly stating the required version in your project's pom.xml since that is "nearest"
*Gradle by default will pick the highest version number. The resolution strategy is fully configurable in Gradle (eg you can force a specific version)
For maven, type
mvn dependency:tree
For gradle type
gradle dependencies
If you compare the results you should see the difference | unknown | |
d16569 | val | React batches state updates for performance reasons.
In your case the state you are setting to updatedFammily, you can use a locally scoped object to get the intermediate results
let res = {}
...
.then(keyUid => {
let updatedFamily = {...family, [keyUid]: [firstHousehold, lastHousehold, householdDropdown]};
res.updatedFamily = updatedFamily;
this.props.firebase.db.ref('organization/' + currentOrganization + '/members/' + keyUid ).set(
{
first: firstHousehold,
last: lastHousehold,
phone: phone,
email: email,
address: address,
address2: address2,
city: city,
zip: zip,
headOfHousehold: headOfHousehold,
}, (error) => {
if(error){
console.log(error);
}
else{
this.setState({ family: updatedFamily }, () => console.log(1));
}
})
})
.then(() => {
console.log(2);
Object.keys(res.updatedFamily).forEach(key => {
this.props.firebase.db.ref('organization/' + currentOrganization + '/members/' +
key ).update({
family: 'howdly'
})
});
})
You can also use async await to get around this but that would require changing bit more,
Hope it helps | unknown | |
d16570 | val | It turns out that unix has a nice little command called
echo
so what I can do is use this command to edit that file.
ShellCommand(
name = "append config instruction"
command=['echo','I am adding this configuration cause it was missing','>','~/user-config.jam']
)
This command will add that line in the configuration file.
if you want to make it look like
"I am adding this configuration cause it was missing" I meant to add "" then
echo "\"xyz\"" > text.txt | unknown | |
d16571 | val | You can use .str.extract, convert each row of results to a list, and then use .str.join (and of course concatenate a + at the beginning):
df['Contact phone number'] = '+' + df['Contact phone number'].dropna().astype(str).str.extract(r'(\d)(\d{3})(\d{3})(\d{3})').apply(list, axis=1).str.join('-')
Output:
>>> df
Company phone number Contact phone number num_specimen_seen
falcon +1-541-296-2271 +1-511-296-227 10
dog +1-542-296-2271 NaN 2
cat +1-543-296-2271 +1-531-296-227 3
A: You can use
df['Contact phone number'] = df['Contact phone number'].str.replace(r'^(\d)(\d{3})(\d{3})(\d+)$', r'+1-\1-\2-\3-\4', regex=True)
Details:
*
*^ - a start of string
*(\d) - Group 1 (\1): a digit
*(\d{3}) - Group 2 (\2): three digits
*(\d{3}) - Group 3 (\3): three digits
*(\d+) - Group 4 (\4): any one or more digits (use \d{4} if you need to match exactly four next digits)
*$ - end of string.
Output:
>>> df['Contact phone number']
falcon +1-1-511-296-2271
dog None
cat +1-1-531-296-2271
See the regex demo. | unknown | |
d16572 | val | ProcessBuilder.start method returns an instance of Process class. YOu can use waitFor method to wait until created process stops:
...
Process process = processBuilderObject.start();
process.waitFor();
}
processBuilderObject.wait() is a invocation of Object's wait method. It is used for concurrency and doesn't relate to processes at all. | unknown | |
d16573 | val | I gave the idea in a comment. Here it is in code :
function findMostReaptedWord(str){
var counts = {}, mr, mc;
str.match(/\w+/g).forEach(function(w){ counts[w]=(counts[w]||0)+1 });
for (var w in counts) {
if (!(counts[w]<mc)) {
mc = counts[w];
mr = w;
}
}
return mr;
}
A few details :
*
*I use str.match(/\w+/g) for a better decomposition in words. Yours would take anything not a space as a word or part of a word.
*counts is a map giving the number of occurrences of each words (i.e. counts["do"] is 2)
*using a map avoids doing two levels of loop, which is very slow
A: Here is my approach
*
*First, separate the words from the string using Regular Expression.
*Declare an object as a Map which will help you to find the occurrences of each word. (You can use Map Data Structure!)
*Find the most repeated word from that object.
let str = 'How do you do?';
console.log(findMostRepeatedWord(str)); // Result: "do"
function findMostRepeatedWord(str) {
let words = str.match(/\w+/g);
console.log(words); // [ 'How', 'do', 'you', 'do' ]
let occurances = {};
for (let word of words) {
if (occurances[word]) {
occurances[word]++;
} else {
occurances[word] = 1;
}
}
console.log(occurances); // { How: 1, do: 2, you: 1 }
let max = 0;
let mostRepeatedWord = '';
for (let word of words) {
if (occurances[word] > max) {
max = occurances[word];
mostRepeatedWord = word;
}
}
return mostRepeatedWord;
}
A: Here I give you an approach,
*
*Sort the words first. That way "how do you do" becomes "do do how you".
*Iterate the string to count the words that repeat, keep the maximum number of times repeating word in memory while iterating.
-
Mebin
A: This function may help you
function maxWord (str)
{
var max = 0;
var maxword = '';
var words = str.split(' ');
for(i=0;i<words.length;i++)
{
var count = 0;
var word = '';
for(j=0;j<words.length;j++)
{
if(j !== i && words[i] === words[j])
{
count++;
word = words[i];
}
}
if(count>maxword)
{
max = count;
maxword = word;
}
}
return maxword;
}
maxWord('how do you do'); // returns do | unknown | |
d16574 | val | setColumnLayout needs to be done in conjunction with getColumnLayout. Not sure where SelectedColumnSettings is coming from. Also getColumnSettings is a property of a table and I do see it being called that way:
var columnSettings=getColumnSettings(SelectedColumnSettings);
A: Use Set Column
var columnSettings = [
{title:"id", field:"id", visible:false},
{title:"Company", field:"Company Name", sorter:"string"},
{title:"Name", field:"Name", sorter:"string"},
{title:"Word Count Rate", field:"Word Count Rate", sorter:"number", align:"center"},
{title:"Hourly Rate", field:"Hourly Rate", sorter:"number", align:"center"},
{title:"Resourced", field:"Resourced", sorter:"number", align:"center"},
{title:"Language Source", field:"Language Source", sorter:"string"},
{title:"Profile Picture", field:"Profile Picture", align:"center"},
{title:"Completed Projects", field:"Completed Projects", sorter:"number", align:"center"}];
// var columnSettings=getColumnSettings("Contacts");
table.setColumn(columnSettings); | unknown | |
d16575 | val | var float first_close = 0.
if barstate.isfirst
first_close := supertrend
A: You will have to save the close price whenever the direction changes into a variable and then you can plot that variable. Example below
//@version=5
indicator("Supertrend", overlay=true, timeframe="", timeframe_gaps=true)
atrPeriod = input(10, "ATR Length")
factor = input.float(3.0, "Factor", step = 0.01)
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
bodyMiddle = plot((open + close) / 2, display=display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = color.red, style=plot.style_linebr)
fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)
var firstbarsclose=close
if direction<0 and direction[1]>0
firstbarsclose:=close
if direction>0 and direction[1]<0
firstbarsclose:=close
plot(firstbarsclose,style=plot.style_stepline) | unknown | |
d16576 | val | I've seen this problem pop up before. Are you including bootstrap.js and bootstrap-modal.js? If so, remove the include for bootstrap-modal.js. See if that helps :) | unknown | |
d16577 | val | Such heavy duty should probably not be part of a django view. You might want to look into django celery for asynchronous task management.
However you can do something like that just fine by polling your server. The easy setup, use short polling (basically a javascript loop that triggers an ajax request to the server every i seconds, retrieving a status response* which you can use to show your user anything).
*You'll have to setup an url and function that calculates the status somehow or if you're using celery you can use it's asynchronous result | unknown | |
d16578 | val | Using Pandas (as you suggested), you can do an outer-join style merge of the two tables, keyed on the document ID. This will give you a dataframe where each row contains all of the information you need.
import pandas as pd
df1 = pd.DataFrame([[1, 1, "Desc 1"], [2, 2, "Desc 1"], [3, 3, "Desc 3"]],
columns=["Doc Number", "Tax Amount 2A", "Description 2A"])
df2 = pd.DataFrame([[1, 1, "Desc 4"], [2, 20, "Desc 5"], [4, 4, "Desc 6"]],
columns=["Doc Number", "Tax Amount PR", "Description PR"])
combined = pd.merge(df1, df2, how="outer", on="Doc Number")
combined.head()
Doc Number Tax Amount 2A Description 2A Tax Amount PR Description PR
1 1.0 Desc 1 1.0 Desc 4
2 2.0 Desc 1 20.0 Desc 5
3 3.0 Desc 3 NaN NaN
4 NaN NaN 4.0 Desc 6
From there, you can apply a function to each row and do the comparison of the values to produce the appropriate rule.
def case_code(row):
if row["Tax Amount 2A"] == row["Tax Amount PR"]:
return "exact"
elif pd.isna(row["Tax Amount 2A"]):
return "Addition in PR"
elif pd.isna(row["Tax Amount PR"]):
return "Addition in 2A"
elif row["Tax Amount 2A"] != row["Tax Amount PR"]:
return "mismatch"
codes = combined.apply(case_code, axis="columns")
codes
Doc Number
1 exact
2 mismatch
3 Addition in 2A
4 Addition in PR
dtype: object
The key part is to apply to each row (with axis="columns") instead of the default behavior of applying to each column.
The new codes can be added to the combined dataframe. (The 2nd line just makes the new codes the first column to match your example by re-arranging the columns and not strictly-speaking required.)
answer = combined.assign(**{"Match type": codes})
answer[["Match type"] + [*combined.columns]]
Match type Doc Number Tax Amount 2A Description 2A ...
exact 1 1.0 Desc 1 ...
mismatch 2 2.0 Desc 2 ...
Addition in 2A 3 3.0 Desc 3 ...
Addition in PR 4 NaN NaN ...
(Final table isn't showing all the columns because I couldn't get it to format correctly.) | unknown | |
d16579 | val | To keep compiler type/name checking suggest to pass a Func<InstanceDataLog, TResult> instead of array of names
public void Export<TResult>(Func<InstanceDataLog, TResult> selectProperties)
{
var grid = new GridView();
var data = TempData["InstanceDataList"];
var originalList = (List<InstanceDataLog>)TempData["InstanceDataList"];
var filteredList = originalList.Select(selectProperties).ToList();
grid.DataSource = filteredList;
grid.DataBind();
}
Then use it:
Export(data => new { Id = data.Id, Name = data.Name });
A: You could use such method to get properties:
private object getProperty(EToolsViewer.APIModels.InstanceDataLog e, string propName)
{
var propInfo =typeof(EToolsViewer.APIModels.InstanceDataLog).GetProperty(propName);
return propInfo.GetValue(e);
}
and with another function you could get all properties you want:
private dynamic getProperties(string[] props, EToolsViewer.APIModels.InstanceDataLog e )
{
var ret = new ExpandoObject() as IDictionary<string, Object>;;
foreach (var p in props)
{
ret.Add(p, getProperty(e, p));
}
return ret;
}
The problem occurs if you try to assign DataSource with expando object. Solution is described hier:
Binding a GridView to a Dynamic or ExpandoObject object
We do need one more method:
public DataTable ToDataTable(IEnumerable<dynamic> items)
{
var data = items.ToArray();
if (data.Count() == 0) return null;
var dt = new DataTable();
foreach (var key in ((IDictionary<string, object>)data[0]).Keys)
{
dt.Columns.Add(key);
}
foreach (var d in data)
{
dt.Rows.Add(((IDictionary<string, object>)d).Values.ToArray());
}
return dt;
}
and use it:
var r = lst.Select(e => getProperties(selectedcol, e)).ToList();
grid.DataSource = ToDataTable(r);
The same thing, but ready to run for LinqPad:
void Main()
{
var samples = new[] { new Sample { A = "A", B = "B", C = "C" }, new Sample { A = "A1", B = "B2", C = "C1" } };
var r = samples.Select(e => getProperties(new[] {"A", "C", "B"}, e)).ToList();
r.Dump();
}
private object getProperty(Sample e, string propName)
{
var propInfo = typeof(Sample).GetProperty(propName);
return propInfo.GetValue(e);
}
private dynamic getProperties(string[] props, Sample e)
{
var ret = new ExpandoObject() as IDictionary<string, Object>; ;
foreach (var p in props)
{
ret.Add(p, getProperty(e, p));
}
return ret;
}
public class Sample
{
public string A { get; set;}
public string B { get; set;}
public string C { get; set;}
}
With output: | unknown | |
d16580 | val | Set up a VHOST.
in /etc/hosts (or c:/windows/system32/drivers/etc/hosts) add:
127.0.0.1 dev.whatever.com
Then, in Apache's conf/extra/httpd-vhosts.conf, set up your VirtualHost, here's an example:
<VirtualHost *:80>
DocumentRoot "/var/www/bonemvc/public"
ServerName dev.whatever.com
FallbackResource index.php
<Directory "/var/www/bonemvc">
DirectoryIndex index.php
Options -Indexes +FollowSymLinks
AllowOverride none
Require all granted
</Directory>
BrowserMatch ".*MSIE.*" nokeepalive downgrade-1.0 force-response-1.0
</VirtualHost>
Finally, open Apache's httpd.conf and look for vhost, uncomment the line so the other conf file will load.
Close your browsers, restart apache, reopen your browser, and head to http://dev.whatever.com. You should get your home page without the index.php showing!
A: Try using following htaccess
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
And Also you need to search and replace
$config['uri_protocol'] ="AUTO"
by
$config['uri_protocol'] = "REQUEST_URI"
in config.php
A: Try with this code in .htaccess file:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
I Hope this working fine for xampp and wamp server
if you still have issue so please share details with me. | unknown | |
d16581 | val | The classB's hover overwrites the classA's hover in the case of a tag that has both classes, because of the order they are written in (classB's hover after classA's hover).
A solution could be:
$('.classA, .classB').hover(
// mouseover
function() {
var $this = $(this);
if($this.hasClass('classA')) {
function1();
}
if($this.hasClass('classB')) {
function3();
}
},
// mouseout
function() {
var $this = $(this);
if($this.hasClass('classA')) {
function2();
}
if($this.hasClass('classB')) {
function4();
}
});
A: AH-HA!
Ok, so sp00m's answer here were good and right - but it wasn't quite for my purpose. Because i have a fair bit of code running around, I was hoping to keep things "clean" (cleanish?). I probably should have been clearer in the original question...
See, I already had elements that needed the first hover, and elements that needed the second, so when i had elements that needed both the aim was to not have a third hover for that scenario. Code non-reuse and complexity! Boo!
What I didn't realise was that the hover that comes last will overwrite the first hover. This is probably something to do with the fact that it was targeting one class, and the first was targeting another.
The solution was this:
$('.classB, .classA').hover(){
function3,
function4
}
Happily, when i target classA using the multi selector it doesn't override the original hover.
That is, I removed classB from the class attribute for my input, and added classA to the hover selector! | unknown | |
d16582 | val | The worst cases for Insert and Delete are supposed to be O(n), see http://en.wikipedia.org/wiki/Hash_table.
When we Insert, we have to check if the value is in the table or not, hence O(n) in the worst case.
Just imagine a pathological case when all hash values are the same.
Maybe MSDN refers to average complexity.
A: O(1) is the best case, and probably the average case if you appropriately size the table. Worst case deletion for a HashTable is O(n). | unknown | |
d16583 | val | The pound sign is used to select elements with ids using querySelectorAll, but it shouldn't be used with getElementById.
Remove the pound sign here:
var errorElementId = "#" + elements[i].id + "Error";
Should be:
var errorElementId = elements[i].id + "Error";
Working Fiddle
A: You know, assuming IE 10+, you could skip all this javascript fanciness and just use the "required" attribute:
<input type="text" class="form-control" id="cmpname" name="cmpname" required>
That'll invoke the browser supported form validation.
A: Why do you have:
var errorElementId = "#" + elements[i].id + "Error";
Leave out the "#" sign.
A: If you can use jQuery
var isValid = true;
$("#companyDetails").submit(function(event) {
$("input").each(function() {
var element = $(this);
if (element.val() == "") {
isValid = false;
}
})
if (!isValid) {
alert("nopes");
}
});
FIDDLE | unknown | |
d16584 | val | Coworker found it !
RewriteCond %{THE_REQUEST} POST
RewriteCond %{THE_REQUEST} ^[A-Z]+\s//+(.*)\sHTTP/[0-9.]+$ [OR]
RewriteCond %{THE_REQUEST} ^[A-Z]+\s(.*/)/+\sHTTP/[0-9.]+$
RewriteRule .* http://%{HTTP_HOST}/%1 [P] | unknown | |
d16585 | val | Error is generated for line
tc.set_activeTabIndex(0);
We don't have built-in set_activeTabIndex() method.
You should apply appropriate CSS properties for enabling/disabling tabs.
A: You need the client control; not the DOM element.
In order to get the control use the $find method.
After that you can use the set_activeTab method.
ctrl = $find("<%= tabContainer.ClientID %>");
ctrl.set_activeTab(ctrl.get_tabs()[yourTabNumber]); | unknown | |
d16586 | val | According to http://seamframework.org/Community/HowToWriteJavaScriptInXHTML you only need to:
<a4j:loadScript src="resource://jquery.js"/>
A: My problem is :
How to use jQuery with in xhtml?
My Answer is:
1.Create an xhtml page using code given below.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="https://ajax4jsf.dev.java.net/ajax"
xmlns:rich="http://richfaces.ajax4jsf.org/rich">
<head>
<link type="text/css" href="css/flick/jquery-ui-1.8.5.custom.css" rel="stylesheet" />
<a4j:loadScript src="resource:///jquery/jquery-1.4.2.min.js" />
<a4j:loadStyle src="/jquery/jquery-ui-1.8.5.custom.css" />
<a4j:loadScript src="resource:///jquery/jquery-ui-1.8.5.custom.min.js" />
</head>
<body >
<h:form>
<rich:panel>
<h:inputText id="dp1" value="" label="test" />
<rich:jQuery selector="#dp1" name="dp1" rendered="true" timing="onload" query="datepicker({chosendate:'01/05/2005',minYear:'-20Y',maxDate: '+1Y +1M',appendText: '(dd-mm-yyyy)',changeMonth:true,changeYear:true})" ></rich:jQuery>
</rich:panel>
</h:form>
</body>
</html>
2.then try to place JQuery.xx.js & css files below order!
---WebContent
+themes
+....
...jquery-1.4.2.min.js
...jquery-ui-1.8.5.custom.css
...jquery-ui-1.8.5.custom.min.js
all these are configured in .xhtml file like above.
3.General things we need to configure for facelets, richfaces and ajax in web.xml is common,in all the way.
4.At last it worked Perfectly...
Thank You Guy's.. | unknown | |
d16587 | val | Well, "from time to time" does not sound like a situation to think much about performance improvement (unless you mean "from millisecond to millisecond") :)
Anyway, the first approach is the correct idea to do this update without a stored procedure. And yes, you must load all old related entities because updating a many-to-many relationship goes only though EFs change detection. There is no exposed foreign key you could leverage to update the relations without having loaded the navigation properties.
An example how this might look in detail is here (fresh question from yesterday):
Selecting & Updating Many-To-Many in Entity Framework 4
(Only the last code snippet before the "Edit" section is relevant to your question and the Edit section itself.)
For your second solution you can wrap the whole operation into a manually created transaction:
using (var scope = new TransactionScope())
{
using (var context = new MyContext())
{
// ... Call Stored Procedure to delete relationships in link table
// ... Insert fake objects for new relationships
context.SaveChanges();
}
scope.Complete();
}
A: Ok, solution found. Of course, pure EF solution is the first one proposed in original question.
But, if performance matters, there IS a third way, the best one, although it is SQL server specific (afaik) - one procedure with table-valued parameter. All new related IDs goes in, and the stored procedure performs delete and inserts in transaction.
Look for the examples and performance comparison here (great article, i based my solution on it):
http://www.sommarskog.se/arrays-in-sql-2008.html | unknown | |
d16588 | val | I had the same issue. This has the exact problem, the activity indicator never appers or appears too late:
async void GoDetail(object obj)
{
Busy = true;
DetailsViewModel.Initialize(_items, this.SelectedItem);
await App.Current.MainPage.Navigation.PushAsync(new xxxPage());
Busy = false;
}
This fixes it, activity indicator appears instantly...:
async void GoDetail(object obj)
{
Busy = true;
Device.BeginInvokeOnMainThread(async () =>
{
DetailsViewModel.Initialize(_items, this.SelectedItem);
await App.Current.MainPage.Navigation.PushAsync(new xxxPage());
Busy = false;
});
}
A: Try this code
public Task ShowIndicator(Func<Task> action)
{
actionEnabled = false;
IndicatorVisibility = true;
Device.BeginInvokeOnMainThread(async () =>
{
await action.Invoke();
IndicatorVisibility = false;
actionEnabled = true;
});
} | unknown | |
d16589 | val | Are you calling the method showFeed() everytime you received new data? If yes, then maybe you could try to refill the adapter instead of assigning a new one every time.
I don't know exactly what you are doing in your adapter, so I'll show you how I did it in one of my apps.
In my Activity/Fragment I do this when I want to update the list with new items:
private void refreshCalendar(ArrayList<CalendarDay> newCalendar) {
if (mAdapter == null) {
mAdapter = new CalendarAdapter(getActivity(), newCalendar);
mExpandableListView.setAdapter(mAdapter);
}
else {
mAdapter.refill(newCalendar);
}
restoreInstanceState();
}
And in the adapter:
public void refill(ArrayList<CalendarDay> newCalendar) {
mCalendar.clear();
mCalendar.addAll(newCalendar);
notifyDataSetChanged();
}
A: Maybe you could try and remove this line?
mFeedListView.setSelectionFromTop(mFirstVisibleItem, mVisibleItemOffset);
Edit: You are using this line twice in your code.
Edit: In the code in your question you are only refreshing mAdapter and not mEndlsFidAdptr . That one is still assigned a new one. Everytime you assign a new adapter to you ListView it scrolls back to the top.
A: So the solution wasn't the logical place where I was looking. Thanks a lot to bbrakenhoff for pointing me in the right direction!
My class showFeed() was called from another class called downloadFeed() my scroll position wasn't maintained because downloadFeed() was only loading 5 items when it refreshed, hence even if I maintained the correct scroll position it was not visible.
Although it may be a long shot if someone else has this problem - to fix simply create a variable to hold the total size of your scrollable list when the user performs an onClick event. Then when downloadFeed() is called again, there are more items to download instead the default 5. Then the scroll position is able to be maintained as the visible items are now present.
I ended up using mFeedListView.setSelectionFromTop(firstVisibleItem, positionOffset) | unknown | |
d16590 | val | I think I've found the solution.
When uploading a file to Azure blob, the Azure server isn't smart enough to set the content type of the file according to its extension/content, thus when downloaded by client it's misleading the browser.
The default Azure blob content type is application/octet-stream.
Check here and here for more. | unknown | |
d16591 | val | The error i get when running your code is: AttributeError: 'ResultSet' object has no attribute 'text', which is reasonable as a bs4 ResultSet is basically a list of Tag elements. You can get the text of every 'p' tag if you loop over that iterable.
text1 = []
for x in news1:
for i in x.find_all("p"):
text1.append(i.text)
Or as a one-liner, using list comprehensions:
text1 = [i.text for x in news1 for i in x.find_all("p")] | unknown | |
d16592 | val | "Outer product" comes to rescue:
(⍳10)∘.×⍳10
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
BTW, in case you are trying to learn Dyalog APL, I'd recommend having a look at "Mastering Dyalog APL". And in case you're trying to learn a different dialect, I'd recommend considering to change to Dyalog. (I'm a Dyalog-Fanboy and have made the change myself 20yrs ago. Today Dyalog appears to be practically the only APL-Interpreter that is actively developed and enhanced...) | unknown | |
d16593 | val | This is happening because .apply essentially iterates over rows (when axis=1) and applies the function to a Series that represents each row. Since Series must contain the same data type, a Series made from a row of mixed int and float types will properly promote ints to float:
In [4]: def test(x): return x
In [5]: tmp.iloc[0]
Out[5]:
item 1.0
score 0.0
Name: 0, dtype: float64
In [6]: tmp.apply(test, axis=1)
Out[6]:
item score
0 1.0 0.0
1 2.0 0.0
2 3.0 0.0
Note what happens when we select a column, though:
In [7]: tmp.iloc[:,0]
Out[7]:
0 1
1 2
2 3
Name: item, dtype: int64
In [8]: tmp.apply(test, axis=0)
Out[8]:
item score
0 1 0.0
1 2 0.0
2 3 0.0 | unknown | |
d16594 | val | There is no "official" way of telling an element is being stuck with sticky positioning as I know of right now. But you could use a IntersectionObserver.
It works by observing changes in an elements position related for example to a viewport, in the case of this code sample it checks for at least a 1px difference (threshold: 1).
const el = document.querySelector(".stickyElement")
const observer = new IntersectionObserver(
([e]) => document.querySelector(".elementThatShouldUpdate").classList.toggle("desired-class", e.intersectionRatio < 1),
{ threshold: [1] }
);
observer.observe(el);
You should also update your CSS for the sticky element to account for the 1px difference:
top: -1px;
And also account for this extra offset, so you should add either a border or a padding to this element:
padding-top: 1px;
Let me know if this helps. | unknown | |
d16595 | val | In order to ping using python, you can use the pythonping package.
You can also easily use it in flask.
A sample of the package at play is shown below.
import flask
from pythonping import ping
app = flask.Flask(__name__)
app.config["DEBUG"] = True
@app.route('/', methods=['GET'])
def home():
return ping('127.0.0.1', verbose=True)
app.run()
A: You can use the requests package to perform this operation as follows:
import requests
url = 'https://stackoverflow.com/'
is_up = requests.get(url).status_code == 200
print(f'{url}, up_status={is_up}') | unknown | |
d16596 | val | Use .getHours() and .getMinutes() like...
<html>
<button id="pressbtn1" onClick="show()">Press</button>
<script>
function show()
{
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
document.getElementById("pressbtn1").innerHTML = h+":"+m;
}
</script>
</html> | unknown | |
d16597 | val | Here you go. Handing backspace/delete made it especially challenging. That was fun! :-)
I have added this to my online portfolio of scripts at rack.pub.
function toast(a,b){b||(b=2750);var c={message:a,timeout:b};snackbarContainer.MaterialSnackbar.showSnackbar(c)}var doc=document,textArea=doc.getElementById("area"),numArray=[],backArray=[],num="",numF="",regx="",thisChar="",lastChar="",str="",index=0;window.snackbarContainer=doc.querySelector("#toast"),textArea.addEventListener("keydown",function(){var a=event.keyCode;if(str=this.value,(8==a||46==a)&&(backArray=[],index=str.length-1,lastChar=str.charAt(index),!isNaN(lastChar)||","==lastChar))for(var b=str.length-1;b>=0;b--){if(" "==str.charAt(b))return;if(isNaN(str.charAt(b))&&","!=str.charAt(b))return;backArray.push(str.charAt(b))}if(32==a&&backArray[1]){var c=backArray.reverse().slice(0,-1).join(""),d=c.replace(/\,/g,""),e=Number(d).toLocaleString().toString(),f=str.lastIndexOf(c);f>=0&&f+c.length>=str.length&&(str=str.substring(0,f)+e),this.value=str}}),textArea.addEventListener("keypress",function(){if(thisChar=this.value.slice(-1),isNaN(thisChar)){num=numArray.join(""),numArray=[],numF=Number(num).toLocaleString().toString(),regx=num+"(?!.*"+num+")",regx=new RegExp(regx);var a=this.value.replace(regx,numF);this.value=a}else{if(" "==thisChar){num=numArray.join(""),numArray=[],numF=Number(num).toLocaleString().toString(),regx=num+"(?!.*"+num+")",regx=new RegExp(regx);var a=this.value.replace(regx,numF);return void(this.value=a)}numArray.push(thisChar)}});
html body {
font-family: 'Roboto', sans-serif;
background: #f5f5f5;
}
.text-right{
text-align:right;
}
.text-center{
text-align:center;
}
.text-left{
text-align:left;
}
.thin{
font-weight: 100;
}
.heading{
font-size:3em;
}
.subtitle{
margin-top: -16px;
}
#submit{
margin-top:10px;
}
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.2.0/material.indigo-pink.min.css">
<link href="https://fonts.googleapis.com/css?family=Roboto:100,400" rel="stylesheet">
<div class="demo-layout-transparent mdl-layout mdl-js-layout">
<main class="mdl-layout__content page-content">
<section class="mdl-grid">
<div class="mdl-layout-spacer"></div>
<div class="mdl-cell mdl-cell--4-col">
<h1 class="mdl-color-text--indigo-900 text-right thin">commas.js demo</h1>
<h6 class="mdl-color-text--indigo-500 text-right subtitle">
JavaScript to automatically add commas to numbers in a text area
</h6>
</div>
<div class="mdl-layout-spacer"></div>
</section>
<section class="mdl-grid">
<div class="mdl-layout-spacer"></div>
<div class="mdl-cell mdl-cell--4-col">
<h6 class="mdl-color-text--black thin">
Basically it auto formats numbers as you type in the text area. Give it a try.
</h6>
</div>
<div class="mdl-layout-spacer"></div>
</section>
<section class="mdl-grid">
<div class="mdl-layout-spacer"></div>
<div class="mdl-textfield mdl-js-textfield mdl-cell mdl-cell--4-col">
<textarea class="mdl-textfield__input" type="text" rows= "3" id="area" ></textarea>
<label class="mdl-textfield__label" for="area">Type Here...</label>
</div>
<div class="mdl-layout-spacer"></div>
</section>
</main>
</div>
<!-- IE Compatibility shims DO NOT DELETE-->
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js""></script>
<![endif]-->
<!--[if IE]>
<script src="//cdnjs.cloudflare.com/ajax/libs/es5-shim/4.1.7/es5-shim.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/classlist/2014.01.31/classList.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/selectivizr/1.0.2/selectivizr-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/flexie/1.0.3/flexie.min.js"></script>
<link href="../assets/ie.css" rel="stylesheet">
<![endif]-->
<!-- end shims -->
<script defer src="https://code.getmdl.io/1.2.0/material.min.js"></script>
A: use replace and a regex then just Queue that up on keyup.
$(selector).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
//will replace with commas
A: That problem proved to be more challenging than I expected (I should have known better). Here is what I got, using vanilla Javascript.
You can set event handler for the onkeyup event of the TextBox:
<asp:TextBox ID="txtAutoFormat" runat="server" onkeyup="processKeyUp(this, event)" />
And here is the Javascript code:
<script type="text/javascript">
function extractDigits(str) {
return str.replace(/\D/g, '');
};
function findDigitPosition(str, index) {
var pos = 0;
for (var i = 0; i < str.length; i++) {
if (/\d/.test(str[i])) {
pos += 1;
if (pos == index) {
return i + 1;
}
}
}
};
function isCharacterKey(keyCode) {
// Exclude arrow keys that move the caret
return !(35 <= keyCode && keyCode <= 40);
};
function processKeyUp(txt, e) {
if (isCharacterKey(e.keyCode)) {
var value = txt.value;
// Save the selected text range
var start = txt.selectionStart;
var end = txt.selectionEnd;
var startDigit = extractDigits(value.substring(0, start)).length;
var endDigit = extractDigits(value.substring(0, end)).length;
// Insert the thousand separators
txt.value = extractDigits(value).replace(/(\d{1,3}|\G\d{3})(?=(?:\d{3})+(?!\d))/g, "$1,");
// Restore the adjusted selected text range
txt.setSelectionRange(findDigitPosition(txt.value, startDigit), findDigitPosition(txt.value, endDigit));
}
};
</script>
Credits:
CMS's solution to extract digits from string in Regex using javascript to return just numbers.
Alan Moore's regular expression to insert thousand separators in How do I add thousand separators with reg ex?.
Note: Ron Royston's idea of using toLocaleString is also very interesting. It could provide a more universal solution. You could replace this line of processKeyUp:
txt.value = extractDigits(value).replace(/(\d{1,3}|\G\d{3})(?=(?:\d{3})+(?!\d))/g, "$1,");
with the following:
txt.value = Number(extractNumber(value)).toLocaleString();
A: Try an input mask, here is an example:
http://digitalbush.com/projects/masked-input-plugin/
A: You can use jquery masking framework
references:
Jquery Masking
Source at git | unknown | |
d16598 | val | You should be using a get request. Post does not cache by default. You can try to get a post to cache by using .ajax() and setting cache to true and type to post. I cannot say that this will work as typically you would not expect a post to cache. I suggest using get.
E.g
$.ajax( { url: '/bla',
type : 'post',
data : dataObj,
cache : true } );
A: Use the GET keyword instead if you want to use caching. There is a similar question on SO.
A: I've noticed differences in the way ASP.NET caches responses depending upon whether the caching parameters are query string parameters or (in my case with ASP.NET MVC) route parameters.
I never completely figured out exactly what the conditions were, but this may help someone. | unknown | |
d16599 | val | Then don't use the annotation but use yaml from your metadata definition.
Documentation and Example
But be aware that every metadata definition (be it per annotation, yaml or whateever) usually is loaded only once and cached for performance reasons in production.
That means that you usually have to clear your cache to use an updated metadata definition.
Another issue to consider is when you rename an already existing document/attribute. This might require some migration activities to avoid unexpected behaviour. | unknown | |
d16600 | val | It seems to me that your data is in the wrong format, the need to be numpy arrays.
(assuming they are not allready numpy arrays)
Try converting them like so
x_train = np.array(x_train)
y_train = np.array(y_train) | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.