id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23531900
|
define('DB_NAME', 'somedb');
define('DB_USER', 'someuser');
define('DB_PASSWORD', 'somepass');
my script will be in the same folder. No I don't want to use any WordPress functions.
A: If you really don't want to include the file, as mentioned in the comments already,
we can read the file contents into an array with file().
The iterate over each line and apply some cleanup, until we get to a format we can work with:
<?php
$config = file('wp-config.php');
$dbLines = [];
foreach($config as $line){
if (stristr($line,"define('DB_")!==FALSE){
$dbLines[] = $line;
}
}
array_walk($dbLines, 'cleanup');
// apply the cleanup() function to all members of the array, basically to each line
function cleanup(&$value){
// replace the leading 'define(' and trailing closing bracket
$value = str_replace(
array("define(",");"),'',$value
);
$value = preg_replace('#\s+//(.*)#','',$value); // remove the comments
}
// at this point we have a csv structure with a single quote as the delimiter
// comma+space as a separator
$dbConfig = [];
foreach ($dbLines as $dbline){
// read the line into separate variables and build an array
list($key,$value) = (str_getcsv($dbline,', ',"'"));
$dbConfig[$key] = $value;
}
print_r($dbConfig);
This will output
Array
(
[DB_NAME] => putyourdbnamehere
[DB_USER] => usernamehere
[DB_PASSWORD] => yourpasswordhere
[DB_HOST] => localhost
[DB_CHARSET] => utf8
[DB_COLLATE] =>
)
If you want to access a single element from the array, just
print $dbConfig['DB_HOST'];
| |
doc_23531901
|
Both servers are running CentOS 6.5
One has Apache 2.2 php 5.3
And the other one is running Apache 2.4 php 5.5
One of the key functions of this app is periodically download a CSV file from a remote URL
This is done using cURL and the following code:
$filename = 'export.csv';
$url = 'http://www.someaddress.com/export/' . $filename;
$curl = curl_init();
$fd = fopen(DIR_FS_ADMIN . 'temp/' . $filename , "w");
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_FILE, $fd);
curl_exec ($curl);
curl_close ($curl);
As you can see a very simple bit of code that works great in PHP 5.3
This are the results of curl_getinfo()
[content_type] => text/csv
[http_code] => 200
[header_size] => 209
[request_size] => 95
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 1.98925
[namelookup_time] => 0.816404
[connect_time] => 0.817009
[pretransfer_time] => 0.831392
[size_upload] => 0
[size_download] => 13564110
[speed_download] => 6818705
[speed_upload] => 0
[download_content_length] => 13564110
[upload_content_length] => -1
[starttransfer_time] => 0.834829
[redirect_time] => 0
[certinfo] => Array
(
)
[redirect_url] =>
)
Error Code: 0
And these are the results of the same code working on 5.5
[content_type] =>
[http_code] => 0
[header_size] => 0
[request_size] => 0
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 126.332476
[namelookup_time] => 0.000369
[connect_time] => 0
[pretransfer_time] => 0
[size_upload] => 0
[size_download] => 0
[speed_download] => 0
[speed_upload] => 0
[download_content_length] => -1
[upload_content_length] => -1
[starttransfer_time] => 0
[redirect_time] => 0
[redirect_url] =>
[primary_ip] =>
[certinfo] => Array
(
)
[primary_port] => 0
[local_ip] =>
[local_port] => 0
)
7 Failed to connect to www.someaddress.com/export/: Connection timed out
Of course I've researched and tried a lot of options before posting here, increasing the timeout time, trying an SSL version of the resource, and playing a lot with different curl_setopt yet, I always get failed to connect from the 5.5 app.
I'm aware that some changes have been made regarding the cURL extension on 5.5 but I can find by Google searches point to uploading problems, I've also tried fully different options like using file_get_contents and still nothing, just times out.
Both servers are located in the same place, and the URL is fully open so I really doubt the issue is within the file locations since still works perfectly when I run the code on the 5.3 server.
A: Turns out the URL I was trying to reach had my server's IP blocked!
I was able to contact the webmaster and white list my IP address, now the code works fine as it was without needing any changes.
Something else to keep in mind, what made this hard to debug it that it simply times out, with no error message or any of the sorts.
A: From php manual
Uploads using the @file syntax are now only supported if the CURLOPT_SAFE_UPLOAD option is set to FALSE. CURLFile should be used instead.
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
There are "@" issue on multipart POST requests.
Solution for PHP 5.5 or later:
- Enable CURLOPT_SAFE_UPLOAD.
- Use CURLFile instead of "@".
Solution for PHP 5.4 or earlier:
- Build up multipart content body by youself.
- Change "Content-Type" header by yourself.
The CURLFile class
| |
doc_23531902
|
I'd like to utilise the automatic updating of the timestamp column when this particular row is selected. Does anyone have any clue?
A: So you want your update query to only update the timestamp column? Just update it yourself instead of relying on the automatic update:
UPDATE mytable SET tscolumn = NOW() WHERE ...
A: Just try something like :
UPDATE myTable SET someField = someField WHERE id = myId
So the data values won't move, and the automatic timestamp will be updated.
As said by GaryG, you may also update the timestamp directly.
| |
doc_23531903
|
For example the original list is,
['Ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you;', 'ask', 'what', 'you', 'can', 'do', 'for', 'your', 'country!', 'This', 'is', 'a', 'quote', 'from', 'JFK', 'who', 'is', 'a', 'former', 'American', 'President.']
and the compressed list is currently,
['Ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you;', 'ask', 'you', 'country!', 'This', 'is', 'a', 'quote', 'from', 'JFK', 'who', 'former', 'American', 'President.']
but I want it to have punctuation as separate items in the list.
My intended output is,
['Ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you', ';', 'ask', '!', 'This', 'is', 'a', 'quote', 'from', 'JFK', 'who', 'former', 'American', 'President', '.']
A: You can implement with regex.
import re
a = ['Ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you;', 'ask', 'what', 'you', 'can', 'do', 'for', 'your', 'country!', 'This', 'is', 'a', 'quote', 'from', 'JFK', 'who', 'is', 'a', 'former', 'American', 'President.']
result = re.findall(r"[\w']+|[.,!?;]",' '.join(a))
Output
['Ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you', ';', 'ask', 'what', 'you', 'can', 'do', 'for', 'your', 'country', '!', 'This', 'is', 'a', 'quote', 'from', 'JFK', 'who', 'is', 'a', 'former', 'American', 'President', '.']
Here is a demo to understand more about regex.
A: This is the code to separete the non alphabetic characters and also remove duplicates. hope it helps.
def separate(mylist):
newlist = []
test = ''
a = ''
for e in mylist:
for c in e:
if not c.isalpha():
a = c
else:
test = test + c
if a != '':
newlist = newlist + [test] + [a]
else:
newlist = newlist + [test]
test = ''
a = ''
noduplicates = []
for i in newlist:
if i not in noduplicates:
noduplicates = noduplicates + [i]
return noduplicates
I`m sure someone else can do better couse this is a bit messy but at least works.
| |
doc_23531904
|
Let's say I have the following truncated data:
# Simulate some truncated data from gamma distribution
library(truncdist)
library(fitdistrplus)
set.seed(1)
e <- rgamma(1000, scale = 148099.5, shape = 0.4887023)
left_tr <- 30000
f <- e[e > left_tr] # truncated data
Then following Fitting a lognormal distribution to truncated data in R, I would fit a gamma distribution to the truncated data.
# Fitting a gamma distribution to truncated data
fit_gamma <- function(y, left = NULL, right = NULL){
dtruncated_gamma <- function(x, scale, shape) {
dtrunc(x, "gamma", a = left, b = right, scale = scale, shape = shape)
}
ptruncated_gamma <- function(q, scale, shape) {
ptrunc(q, "gamma", a = left, b = right, scale = scale, shape = shape)
}
fitdistrplus::fitdist(y, "truncated_gamma",
method = "mle",
lower = c(0,0),
start = list(scale = 149919.5, shape = 0.8955081))
}
fit_gamma() returns an error:
fit_gamma(f, left = 30000, right = Inf)
#> Error in fitdistrplus::fitdist(y, "truncated_gamma", method = "mle", lower = c(0, : The dtruncated_gamma function must be defined
What is the way to solve this error?
Created on 2021-10-25 by the reprex package (v2.0.1)
| |
doc_23531905
|
I need to be able to display czech alphabet including characters with punctuation (such as ř, č, ž, ý, ě). I have therefore generated FPDF font files on http://fpdf.fruit-lab.de/index.php from a local Times New Roman TTF font file.
I am using the following code to render the cover.
function toISO($text) {
return iconv('UTF-8', 'ISO-8859-2', $text);
}
function buildImpressionPDF($school, $faculty, $thesisType, $firstname, $surname, $year)
{
$pdf = new FPDF();
$pdf->AddPage();
$pdf->AddFont('times', '', 'times.php');
$pdf->SetFont('times', '', 18);
$pdf->setMargins(0, 0, 0);
$pdf->SetAutoPageBreak(false);
$pdf->Cell(0, 20, toISO($school), 0, 0, 'C');
$pdf->SetY(20);
$pdf->Cell(0, 20, toISO($faculty), 0, 0, 'C');
$pdf->SetY(($pdf->h / 2) - 10);
$pdf->Cell(0, 20, toISO($thesisType), 0, 0, 'C');
$pdf->SetY(-40);
$pdf->Cell(0, 20, toISO($firstname . ' ' . $surname), 0, 0, 'C');
$pdf->SetY(-30);
$pdf->Cell(0, 20, toISO($year), 0, 0, 'C');
return $pdf;
}
The text renders fine, including punctuation, but isn't properly justified - some lines are placed more to the right than others.
I suspect that this might be a problem with the custom font. When I used the original FPDF fonts, it seemed to justify fine (but I did not investigate that thoroughly), but of course did not display punctuation properly.
What am I doing wrong?
A: Please use the TCPDF instead of FPDF Or try this
$pdf->Cell(20,10,'Title',1,1,'C');
| |
doc_23531906
|
How can I make it so that it only appears when you arrived on the page from a link-click and not from a page refresh? Is this possible? Would differentiating between a 200 and a 304 on some site-wide resource work?
| |
doc_23531907
|
pkgexec/
setup.py
pkgexec/
__init__.py
__main__.py
core.py
As per the instructions, the __main__.py's main() method is an entry point in setup.py:
from setuptools import setup, find_packages
setup(
name="pkgexec",
version="0.2.0",
packages=find_packages(),
entry_points={ "console_scripts": ["pkgexec = pkgexec.__main__:main"]},
)
I installed the package from within the pkgexec/ directory, by running pip install -e ..
Until this point, everything works as expected.
What doesn't work is executing Python scripts via this "executable" entry point. You see, the whole aim of this package is to run Python scripts that import a bunch of stuff from the package, e.g. script.py uses functionality from the pkgexec package and is "ran" through the pkgexec "executable":
pkgexec script.py -v arg1 arg2
Here is the simplified version of __main__.py:
import argparse
import sys
from pkgexec import some_stuff
def main(args=None):
if args is None:
args = sys.argv[1:]
parser = argparse.ArgumentParser()
parser.add_argument('script', help='script to run via pkgexec')
parser.add_argument(...)
cli_args = parser.parse_args()
print(f'{__name__}: Running script {cli_args.script}')
exec(open(cli_args.script).read(), globals(), globals()) # <-- ???
print(f'{__name__}: Done')
if __name__ == '__main__':
sys.exit(main())
The problem: Nothing happens for exec(open(cli_args.script).read()) (tried it with and without , globals(), globals()). The script is not executed. What am I doing wrong here?
Workarounds that I'm not keen on:
*
*I can run the script via exec() if I don't "install" the entry point. Not an option.
*I can run the script if I import it via importlib. But this is too restrictive for users of the package that are supposed to write a main() method.
A: There's something happening with the script's globals when calling exec(). I can't figure out what runpy from the standard library is doing differently, but it's certainly working. The solution in my case is to replace the exec() call with a call to runpy.run_path().
Here is the modified __main__.py script for comparison:
import argparse
import os
import runpy
import sys
from pkgexec import some_stuff
def main(args=None):
if args is None:
args = sys.argv[1:]
parser = argparse.ArgumentParser()
parser.add_argument('script', help='script to run via pkgexec')
parser.add_argument(...)
cli_args = parser.parse_args()
print(f'{__name__}: Running script {cli_args.script}')
mod = argparse.Namespace(
**runpy.run_path(cli_args.script,
run_name=os.path.basename(cli_args.script)))
print(f'{__name__}: Done')
if __name__ == '__main__':
sys.exit(main())
I'm sending the file name as run_name argument to run_path (this way the script "knows" its actual __name__ instead of the default <run_path> set by runpy).
Note that this solution is only applicable if the script to run does not contain a if __name__ == '__main__' section (which is precisely what I wanted).
UPDATE: The same effect can be achieved by doing what runpy does under the hood: compile() the code first, then exec() it afterwards:
# mod = argparse.Namespace(
# **runpy.run_path(cli_args.script,
# run_name=os.path.basename(cli_args.script)))
code = compile(open(cli_args.script).read(),
os.path.basename(cli_args.script),
'exec')
exec(code)
| |
doc_23531908
|
Thanks.
var results = from table1 in dt.AsEnumerable()
join table2 in names.AsEnumerable()
on table1.Field<int>("Id") equals table2.Field<int>("Id")
select new
{
C1 = table1.Field<int>("Id"),
C2 = table1.Field<int>("Col1"),
C3 = table1.Field<int>("Col2"),
C4 = table2.Field<String>("Name")
};
DataTable sout = dt.Clone();
sout.Columns.Add("Name", typeof(string));
foreach (var v in results)
{
sout.Rows.Add(v.C1,v.C2,v.C3,v.C4);
};
A: First set primary keys for your tables.
dt.PrimaryKey = new[] {dt.Columns["Id"]};
names.PrimaryKey = new[] { names.Columns["Id"] };
Then, if you don't mind dt changing you can merge tables with the code,
dt.Merge(names,false, MissingSchemaAction.AddWithKey);
If you mind clone dt and do the same.
| |
doc_23531909
|
I've a class that creates multiple proximity alerts (this is the important code):
public void activateAlerts(){
Database db = new Database(activity.getApplicationContext());
Cursor cursor = db.getPois();
locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
int latitudeIndex = cursor.getColumnIndex("latitude");
int longitudeIndex = cursor.getColumnIndex("longitude");
IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT);
while(cursor.moveToNext()){
double latitude = cursor.getDouble(latitudeIndex);
double longitude = cursor.getDouble(longitudeIndex);
Bundle bundle = new Bundle();
bundle.putDouble("latitude",latitude);
bundle.putDouble("longitude",longitude);
Intent intent = new Intent(PROX_ALERT_INTENT);
intent.putExtras(bundle);
Random generator = new Random();
PendingIntent pi = PendingIntent.getBroadcast(activity.getApplicationContext(), generator.nextInt(), intent, 0);
getActivity().registerReceiver(new AlertIntentReceiver(), filter);
locationManager.addProximityAlert(latitude, longitude, 2500, -1, pi);
}
Log.i("ALERT", "ALERT");
}
And this is the receiver, that shows a notification:
public void onReceive(Context context, Intent intent) {
Bundle b = intent.getExtras();
double latitude = b.getDouble("latitude");
double longitude = b.getDouble("longitude");
Log.i("ALERT", latitude+","+longitude);
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intentPi = new Intent(context, MainActivity.class);
PendingIntent pintent = PendingIntent.getActivity(context,0,intentPi,0);
Notification mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(context.getResources().getString(R.string.app_name))
.setAutoCancel(true)
.setContentText(context.getResources().getString(R.string.notification))
.addAction(R.drawable.ic_directions_grey_24dp,"Map",pintent)
.build();
notificationManager.notify(NOTIFICATION_ID,mBuilder);
}
The problem is that I'm receiving too many "BroadcastReceivers" with same point for the latitude and longitude. For example, this is the last Logcat information:
39.495412,-0.354705
39.4605203,-0.3478213
39.4605203,-0.3478213
39.4605203,-0.3478213
39.4605203,-0.3478213
39.4605203,-0.3478213
39.4605203,-0.3478213
39.4605203,-0.3478213
39.4605203,-0.3478213
39.4605203,-0.3478213
39.4605203,-0.3478213
39.4605203,-0.3478213
39.4605203,-0.3478213
39.4605203,-0.3478213
39.4605203,-0.3478213
... [same values]
What is the problem? How can I receive only different latitude and longitude?
A: maybe you have need to have a continued location update using Request Location Updates or Location Listener:
| |
doc_23531910
|
@RequestMapping(value = { "/owner/terminals/edit",
"/admin/terminals/edit" }, method = RequestMethod.POST)
public String editTerminal(@RequestParam(value = "terminalId") Long terminalId,
@ModelAttribute TerminalRawDTO terminalDto,
Principal principal, RedirectAttributes redirectAttrs, SecurityContextHolderAwareRequestWrapper securityContextHolderAwareRequestWrapper)
throws IOException {
...
I have wrote following test for this method:
Terminal terminal = Mockito.mock(Terminal.class);
Mockito.when(terminal.getTerminalId()).thenReturn(1L);
Mockito.when(terminalService.findTerminalById(anyLong())).thenReturn(terminal);
mockMvc.perform(post("/owner/terminals/edit").principal(principal).secure(true)
.param("name", "")
.param("terminalId", "1")
.param("description", "")
.param("startWorkTime", "")
.param("endWorkTime", "")
.param("mapLat", "0.0")
.param("mapLng", "0.0")
.param("terminalGroup", "1")
.param("cost", "0.0")
.param("operationSystem", "")
.param("address", "")
.param("moderationComment", "1"))
.andDo(print())
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/owner/terminals?panel=edit_error1"));
I see error:
testEditTerminal(com.terminal.controller.owner.OwnerTerminalsControllerTest): Request processing failed; nested exception is java.lang.IllegalStateException: Current request is not of type [org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper]: org.springframework.mock.web.MockHttpServletRequest@628c4ac0
How to fix it?
P.S.
If to remove SecurityContextHolderAwareRequestWrapper securityContextHolderAwareRequestWrapper from argument controller - all works fine
P.S.
I added following code to my test class:
@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(locations = "classpath:META-INF/securityContext.xml")
public class OwnerTerminalsControllerTest {
@Autowired
SecurityContextHolderAwareRequestFilter securityContextHolderAwareRequestFilter;
....
}
securityContext.xml:
<beans:beans
xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:sec="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http auto-config="true" pattern="/admin/**" authentication-manager-ref="adminAuthenticationManager">
<access-denied-handler error-page="/403" />
<custom-filter ref="concurrencyFilter" after="SECURITY_CONTEXT_FILTER"/>
<form-login login-page="/loginAdmin" login-processing-url="/admin/j_spring_security_check_admin"
default-target-url="/admin"
authentication-failure-url="/loginAdminFailed"
authentication-success-handler-ref="authAdminSuccessHandler"/>
<intercept-url pattern="/admin/j_spring_security_check_admin" access="ROLE_ANONYMOUS"/>
<intercept-url pattern="/admin/accounts/**" access="ROLE_SUPERADMIN"/>
<intercept-url pattern="/admin/users/**" access="ROLE_SUPERADMIN"/>
<intercept-url pattern="/admin/terminals/**" access="ROLE_SUPERADMIN, ROLE_TERMINAL_MODERATOR, ROLE_MODERATOR"/>
<intercept-url pattern="/admin/money/**" access="ROLE_FINANSIER, ROLE_SUPERADMIN"/>
<intercept-url pattern="/admin/moderation/**" access="ROLE_SUPERADMIN,ROLE_MODERATOR"/>
<intercept-url pattern="/admin/moderation/pictures"
access="ROLE_SUPERADMIN,ROLE_MODERATOR, ROLE_IMAGE_MODERATOR"/>
<intercept-url pattern="/admin/statistic/**" access="ROLE_SUPERADMIN"/>
<intercept-url pattern="/admin/rules/**" access="ROLE_SUPERADMIN"/>
<intercept-url pattern="/admin/terminals/addImageToTerminal"
access="ROLE_SUPERADMIN, ROLE_TERMINAL_MODERATOR, ROLE_MODERATOR"/>
<intercept-url pattern="/admin/terminals/deleteTerminalImage"
access="ROLE_SUPERADMIN, ROLE_TERMINAL_MODERATOR, ROLE_MODERATOR"/>
<intercept-url pattern="/admin/systemGroupsModeration" access="ROLE_SUPERADMIN"/>
<intercept-url pattern="/admin/adminUsers" access="ROLE_SUPERADMIN"/>
<intercept-url pattern="/admin/contentModeration/**" access="ROLE_SUPERADMIN, ROLE_MODERATOR, ROLE_IMAGE_MODERATOR"/>
<intercept-url pattern="/admin/campaignModeration/**" access="ROLE_SUPERADMIN, ROLE_MODERATOR"/>
<intercept-url pattern="/admin/monitoring" access="ROLE_SUPERADMIN"/>
<logout logout-url="/logout" logout-success-url="/loginAdmin"/>
<port-mappings>
<port-mapping http="${http.port}" https="${https.port}"/>
</port-mappings>
<session-management session-authentication-strategy-ref="sas" invalid-session-url="/" />
</http>
<http auto-config="true" authentication-manager-ref="userAuthenticationManager">
<custom-filter ref="concurrencyFilter" after="SECURITY_CONTEXT_FILTER"/>
<form-login login-page="/"
default-target-url="/member/personalAccount"
authentication-failure-url="/loginfailed" authentication-success-handler-ref="authSuccessHandler"/>
<!-- <intercept-url pattern="/common/*" filters="none" /> -->
<intercept-url pattern="/member/createCompany/addParams" access="ROLE_ANONYMOUS, ROLE_USER"/>
<intercept-url pattern="/member/**" access="ROLE_USER"/>
<intercept-url pattern="/owner/*" access="ROLE_OWNER"/>
<intercept-url pattern="/member/getImage/*"
access="ROLE_ANONYMOUS, ROLE_OWNER,ROLE_USER, ROLE_SUPERADMIN, ROLE_TERMINAL_MODERATOR, ROLE_IMAGE_MODERATOR, ROLE_CAMPAIGN_MODERATOR, ROLE_FINANSIER, ROLE_MODERATOR"/>
<logout logout-url="/logout" logout-success-url="/"/>
<port-mappings>
<port-mapping http="${http.port}" https="${https.port}"/>
</port-mappings>
<session-management session-authentication-strategy-ref="sas" invalid-session-url="/" />
</http>
<beans:bean id="userSecurityService" class="com.terminal.service.impl.UserSecurityService"/>
<beans:bean id="authSuccessHandler" class="com.terminal.filter.RoleAuthSuccessHandler"/>
<beans:bean id="authAdminSuccessHandler" class="com.terminal.filter.admin.RoleAuthAdminHandler"/>
<beans:bean id="adminSecurityService" class="com.terminal.service.admin.impl.TerminalAdminSecurityServiceImpl"/>
<beans:bean id="webexpressionHandler"
class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler"/>
<authentication-manager id="adminAuthenticationManager">
<authentication-provider user-service-ref="adminSecurityService">
<password-encoder ref="encoder"/>
</authentication-provider>
</authentication-manager>
<authentication-manager id="userAuthenticationManager">
<authentication-provider user-service-ref="userSecurityService">
<password-encoder ref="encoder"/>
</authentication-provider>
</authentication-manager>
<authentication-manager id="internalUserAuthenticationManager">
<authentication-provider user-service-ref="userSecurityService">
<password-encoder ref="noopEncoder"/>
</authentication-provider>
</authentication-manager>
<beans:bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<beans:constructor-arg index="0" value="10"/>
</beans:bean>
<beans:bean id="noopEncoder" class="org.springframework.security.crypto.password.NoOpPasswordEncoder"/>
<beans:bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"/>
<beans:bean id="sas" class="org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy">
<beans:constructor-arg>
<beans:list>
<beans:bean class="org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy">
<beans:constructor-arg ref="sessionRegistry"/>
<beans:property name="maximumSessions" value="1" />
<beans:property name="exceptionIfMaximumExceeded" value="true" />
</beans:bean>
<beans:bean class="org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy">
</beans:bean>
<beans:bean class="org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy">
<beans:constructor-arg ref="sessionRegistry"/>
</beans:bean>
</beans:list>
</beans:constructor-arg>
</beans:bean>
<beans:bean id="concurrencyFilter"
class="org.springframework.security.web.session.ConcurrentSessionFilter">
<beans:property name="sessionRegistry" ref="sessionRegistry" />
<beans:property name="expiredUrl" value="/" />
</beans:bean>
</beans:beans>
A: Your problem, is that to be able to use a SecurityContextHolderAwareRequestWrapper in the controller, the request must have been processed by a SecurityContextHolderAwareRequestFilter that will wrap the original request (here a MockHttpServletRequest) into a SecurityContextHolderAwareRequestWrapper. According to Spring Security reference manual, this filter is internal to Spring Security and is setup and run by the springSecurityFilterChain.
Your problem here is that the springSecurityFilterChain has not been called.
I could not test it, but according to Spring Framework documentation, you can register filter instances with a MockMvc:
When setting up a MockMvc, you can register one or more Filter instances:
mockMvc = standaloneSetup(new PersonController()).addFilters(
new CharacterEncodingFilter()).build();
Registered filters will be invoked through MockFilterChain from spring-test and the last filter will delegates to the DispatcherServlet.
You must manually build and configure the MockMvc in order to mimic the filter declaration in a classic web.xml:
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
In your use case, I would use something like:
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
DelegatingFilterProxy filterProxy = new DelegatingFilterProxy(
"springSecurityFilterChain", wac);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
addFilter(filterProxy, "/*").build();
}
This should work provided the securityContext.xml is used to build the wac application context.
But BEWARE. Even if it works, it adds complexity to the nice Spring test framework even for simple URL mapping tests. Because you are tying Spring security in a controller method, when the whole Spring machinery tends to favor separation of concerns. So you should ask yourself whether using SecurityContextHolderAwareRequestWrapper in a controller method is really necessary. Best pratices suggest that security should lie in intercept-url elements form simple url rules, of in method security at service level for more complex use cases. If you need to track current user, use a filter or an interceptor to put relevant information in a request of a session attribute and just use ordinary ServletRequest (of WebRequest or HttpServletRequest) in you controller if you need an element that Spring MSV does not extract for you: tests will be simpler, as will be future evolutions if you later change the security layer.
In you current use case, you are falling in another trap for your test:
*
*you declare a principal for the request
*spring security filter pass all its filters and wraps the request in a SecurityContextHolderAwareRequestWrapper... but the SecurityContext has never been populated, so the principal in the wrapped request is null!
For the principal in initial request to populate the SecurityContextHolder, you will have to setup a J2eePreAuthenticatedProcessingFilter in the security filter chain, and a PreAuthenticatedAuthenticationProvider in the authentication manager, but only for the test profile.
Alternatively, you could create from scratch a custom filter, that would:
*
*take the principal from a request
*if it is null, clear the SecurityContextHolder
*else
*
*use it to build an Authentication object (I would advise a TestingAuthenticationToken) if it is not already one
*build a SecurityContext and populates is with that Authentication object
*populates the SecurityContextHolder with that SecurityContext
*wraps the original request in a SecurityContextHolderAwareRequestWrapper
*pass the wrapped request to the filter chain
and use it in configuring the MockMvc.
It is not that complex, but it adds another class dedicated to test, that should be itself tested. And anyway, the principal in the wrapped request will be the authentication object, because the wrapped request returns what is in security context for getUserPrincipal(). That's why I said before that tying Spring Security in a controller method was a bad idea.
If you want to try it, code for the custom filter could look like:
public class TestingWrapperFilter implements Filter {
private Object credentials = "password";
private String rolePrefix = "ROLE";
@Override
public void init(FilterConfig fc) throws ServletException {
}
@Override
public void doFilter(ServletRequest sr, ServletResponse sr1, FilterChain fc) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) sr;
Principal principal = req.getUserPrincipal();
if (principal != null) {
Authentication auth;
auth = (principal instanceof Authentication) ? (Authentication) principal :
new TestingAuthenticationToken(principal, credentials);
SecurityContext sc = new SecurityContextImpl();
sc.setAuthentication(auth);
SecurityContextHolder.setContext(sc);
}
else {
SecurityContextHolder.clearContext();
}
sr = new SecurityContextHolderAwareRequestWrapper(req, rolePrefix);
fc.doFilter(sr, sr1);
}
@Override
public void destroy() {
}
public void setCredentials(Object credentials) {
this.credentials = credentials;
}
public void setRolePrefix(String rolePrefix) {
this.rolePrefix = rolePrefix;
}
}
A: "/owner/terminals/*" or "/owner/**" url should be specified in spring-security.xml to avoid that exception. if you perform test for the "/admin/terminals/edit" you will not get that kind of exception, i think. please try once..
<intercept-url pattern="/owner/**" access="ROLE_OWNER"/>
or
<intercept-url pattern="/owner/terminals/*" access="ROLE_OWNER"/>
i hope this works...
| |
doc_23531911
|
I have tried adding both:
knife[:secret_file] = "/path/to/data_bag_secret"
and
secret_file "/path/to/data_bag_secret"
Neither of these seem to encrypt my secrets when I use knife data bag create bag key
If I use knife data bag create bag key --secret-file /path/to/data_bag_secret it encrypts correctly however.
It doesn't appear to be encrypted when I go look at the data bags on https://manage.chef.io, which is why I think it's not encrypting. When I manually pass the switch it does encrypt correctly on https://manage.chef.io.
A: tl;dr: additionally pass in the command line argument --encrypt flag if you are using Chef 12+. e.g. knife data bag from file foo ./data_bags/foo.json --encrypt
Since Chef 12 you are required to pass in the --encrypt flag while using knife data bag [create|from file] commands in order for your knife[secret] or knife[secret_file configuration options in knife.rb. The main problem here is that the chef docs have not yet been updated to indicate as such. If you call knife data bag [create|from file] --help you will see the explanation of the --encrypt flag option there.
Answer sourced here: https://github.com/chef/chef/issues/3223#issuecomment-93338211.
A: So it's a bit odd but the --secret-file doesn't populate its own config value. If you look in https://github.com/chef/chef/blob/master/lib/chef/knife/data_bag_secret_options.rb#L48 you see it runs a custom proc instead, which is defined below that. Setting knife[:secret_file] should still work though, all the code related to bag encryption uses both. In general you wouldn't be using data bag create for this though, that is for the initial bag/item creation. For general update use data bag from file. Also remember that you need to remove that value from your config file to actually see the encrypted data, otherwise knife data bag show will decrypt it for you automatically.
| |
doc_23531912
|
var count = 0;
function cc(card) {
switch (card){
case 2:
case 3:
case 4:
case 5:
case 6:
count+=1;
break;
case 7:
case 8:
case 9:
count+=0;
break;
case 10:
case 'J':
case 'Q':
case 'K':
case 'A':
count-= 1;
break;
}
return count + (count > 0 ? " Bet" : " Hold");
}
cc(2); cc(3); cc(7); cc('K'); cc('A');
I know that it is there to return the count, but what is the purpose of the '?' in the statement? I thinking I understand the ":", I'm assuming it means something like "else print 'hold'.
A: It is the ternary/conditional operator. it will return:
count + "Bet" if count > 0
count + "Hold" if count <= 0 (otherwise)
| |
doc_23531913
|
A: The likely reason is that the enclosing environment associated with objects is not considered in the results of object.size(), but is written to disk when saved. Use the pryr::object_size() function to see the object size with environment included. More explanation can be found at: http://adv-r.had.co.nz/memory.html#object-size
> object.size(m1)
16200200 bytes
> pryr::object_size(m1)
215 MB
> save(m1, file="m1.rda")
> file.info("m1.rda")$size
[1] 219475772
There also has been some discussion of this issue in another question: object.size() reports smaller size than .Rdata file
A: Are you talking about the train object?
The bagging function isn't very optimized and a lot of redundant objects are saved in the forest (e.g. each terms object for every rpart model).
See the trim option of trainControl. If you only want to make predictions on that object, this will get rid of a lot of extra stuff carried over by the model object. In some cases, the call object can contain a complete copy of the data.
trim isn't implemented for every model but is it for this one.
| |
doc_23531914
|
import { PUSH_ROUTE, POP_ROUTE } from '../Constants/ActionTypes'
import { NavigationExperimental } from 'react-native'
import Login from '../Components/Login'
const {
StateUtils: NavigationStateUtils
} = NavigationExperimental
const initialState = {
index: 0,
key: 'root',
routes: [{
key: 'login',
title: 'Login',
component: Login
}]
}
function navigationState (state = initialState, action) {
switch(action.type) {
case PUSH_ROUTE:
if (state.routes[state.index].key === (action.route && action.route.key)) return state
return NavigationStateUtils.push(state, action.route)
case POP_ROUTE:
if (state.index === 0 || state.routes.length === 1) return state
return NavigationStateUtils.pop(state)
default:
return state
}
}
export default navigationState
And in my root component (NavRoot.js), the actions are handled with:
_handleBackAction() {
if (this.props.navigation.index === 0) {
return false
}
this.props.popRoute()
return true
}
_handleNavigate(action) {
switch (action && action.type) {
case 'push':
this.props.pushRoute(action.route)
return true
case 'back':
case 'pop':
return this._handleBackAction()
default:
return false
}
}
And triggered by the button (NavButton.js):
_navigate(route){
this.props._handleNavigate(route)
}
render(){
const route = {
type: 'push',
route: {
key: this.props.navKey,
title: this.props.pageName,
component: this.props.componentName
}
}
return(
<TouchableHighlight onPress={() => this._navigate(route)}>
<Text style={styles}>{pr.pageName}</Text>
</TouchableHighlight>
)
When the button (NavButton.js) is pressed for the first time, it navigates correctly. But when it is pressed again, I get the following error: should not push route with duplicated key /*'route.key: this.props.navKey' in this case*/.
All seemed to makes sense, but what may be the issue?
Thank you in advance!
A:
should not push route with duplicated key
The key property must be unique.
If you need to create the several scenes with the same key, you can pass to the reducer something like scene property and increment the key value...
function navigation(state = guestState, action) {
const { index, routes } = state
switch (action.type) {
case NAV_PUSH: {
const nextIndex = index + 1
const newState = {
...action.state,
key: `${action.state.scene}_${nextIndex}`,
}
return {
...state,
index: nextIndex,
routes: [
...routes,
newState,
],
}
}
...
}
A: You can check if your input is coming consecutively within your navigation reducer:
case 'PUSH_ROUTE':
if (state.routes[state.index].key === (action.route && action.route.key)) return state
if ((state.routes.length && state.routes[state.routes.length-1].key) === (action.route && action.route.key)) return state
return NavigationStateUtils.push(state, action.route)
| |
doc_23531915
|
State, Pop
AP,100
UP,200
TN,90
I want to plot it and so my code is as follows:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('dat.csv')
df.plot(kind='bar').set_xticklabels(df.State)
plt.show()
However, I want to replace the labels which are in another csv file,
labels.csv
Column,Name,Level,Rename
State,AP,AP,Andhra Pradesh
State,TN,TN,Tamil Nadu
State,UP,UP,Uttar Pradesh
Is it possible for me to replace the labels in the plot with the labels in my labels.csv file?
A: Using merge + set_index
df=df.merge(labels,left_on='State',right_on='Name',how='left')
df
Out[1094]:
State Pop Column Name Level Rename
0 AP 100 State AP AP Andhra Pradesh
1 UP 200 State UP UP Uttar Pradesh
2 TN 90 State TN TN Tamil Nadu
df.set_index('Rename')['Pop'].plot(kind='Bar')
| |
doc_23531916
|
All commands entered from ssh connection to s3 produces the error:
Bus error (core dumped)
Originally, I was trying to do a copy from mybucket to the server:
aws s3 cp s3://mybucket ./
but the result was the error. Even an ls command produces the error. I don't know how to fix this.
A few days ago, I expanded the system using these instructions for ebs volume.
The df -h command produces this:
Filesystem Size Used Avail Use% Mounted on
/dev/root 31G 13G 19G 40% /
devtmpfs 16G 0 16G 0% /dev
tmpfs 16G 8.0K 16G 1% /dev/shm
tmpfs 3.2G 940K 3.2G 1% /run
tmpfs 5.0M 0 5.0M 0% /run/lock
tmpfs 16G 0 16G 0% /sys/fs/cgroup
/dev/loop0 33M 33M 0 100% /snap/amazon-ssm-agent/2996
/dev/loop2 98M 98M 0 100% /snap/core/10577
/dev/loop3 98M 98M 0 100% /snap/core/10583
/dev/loop1 34M 34M 0 100% /snap/amazon-ssm-agent/3552
/dev/loop4 56M 56M 0 100% /snap/core18/1885
/dev/loop6 56M 56M 0 100% /snap/core18/1944
/dev/loop7 68M 68M 0 100% /snap/lxd/18150
tmpfs 3.2G 0 3.2G 0% /run/user/1000
tmpfs 10M 10M 0 100% /tmp
/dev/loop8 70M 70M 0 100% /snap/lxd/19032
and lsblk command produces this:
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
loop0 7:0 0 32.3M 1 loop /snap/amazon-ssm-agent/2996
loop1 7:1 0 33.3M 1 loop /snap/amazon-ssm-agent/3552
loop2 7:2 0 97.9M 1 loop /snap/core/10577
loop3 7:3 0 97.9M 1 loop /snap/core/10583
loop4 7:4 0 55.3M 1 loop /snap/core18/1885
loop6 7:6 0 55.4M 1 loop /snap/core18/1944
loop7 7:7 0 67.8M 1 loop /snap/lxd/18150
loop8 7:8 0 69.8M 1 loop /snap/lxd/19032
xvda 202:0 0 32G 0 disk
└─xvda1 202:1 0 32G 0 part /
Today, work was proceeding as normal until I entered the command:
grep -vf MergedSamplesEdited.vcf ../resources/plink.GRCh37.autosome.map
The system Killed the process.
I was then able do a few more grep / awk commands, including the one I should have done instead of the grep line above:
gawk -F$'\t' 'FNR == NR {a[$6]; next;} {if ($4 in a) {print $0 } }' oldfile.ibd ../resources/plink.GRCh37.autosome.map > newfile.ibd
Needing to copy files from s3 bucket, I tried the aws s3 command above and got the bus error.
I searched for a solution and found responses with the bus error, but those responses seemed highly specific and did not apply to my situation. For example, Git add . Gives me Bus error (core dumped).
Your help would be greatly appreciated.
A: Same issue and same setup - server restart resolved it for me.
$ sudo reboot
A: tl;dr: check your /tmp directory and free up space. aws command needs it.
We had experienced this from one of our development servers such that whenever we run any aws command results to Bus error (core dumped) error message.
We tried to reboot the server to no avail. Eventually, we noticed that the /tmp mount was full and some operations on the server are failing as well leading us to cannot create temp file for here-document: No space left on device error message which is basically the best clue that we got.
After clearing up /tmp folder, aws command run successfully.
| |
doc_23531917
|
select* from MedicationCombination mc
where mc.MedicationId = 2
And the result of the query is:
Name Dosage
----- ------
Med1 12
Med2 14
Med3 16
I want to put this query into a Stored Procedure which will take MedicationId as parameter and return result as:
Name Dosage
---- ------
Med1/Med2/Med3 12/14/16
I want to use this SP in another query which is:
select Id, Category
from Medication
Result is:
Id Category
-- --------
1 Psychotropic
I want to use SP in the above query such that the result would be like:
Id Category Name Dosage
-- -------- ---- ------
1 Psychotropic Med1/Med2/Med3 12/14/16
What could be the possible solutions?
A: It is not the job of your DBMS to format your data the way you'd like them to look, but the application langage's. Therefore, query your database with the first query you posted and use whatever language you're using to format it the way you want.
If you want to make a JOIN with another table, you have to specify conditions. If you'd just like to make a cartesian product, you can use a CROSS JOIN :
SELECT Id, Category, Name, Dosage
FROM MedicationCombination
CROSS JOIN Medication
WHERE MedicationId = 2
A: First answer:
SELECT DISTINCT @YourMedicationID AS CategoryId
( SELECT ( Name + '/' )
FROM MedicationCombination p
WHERE p.MedicationId = p2.MedicationId
ORDER BY Name
FOR
XML PATH('')
) AS NAME ,
( SELECT ( CAST(Dosage AS VARCHAR(10)) + '/' )
FROM MedicationCombination p
WHERE p.MedicationId = p2.MedicationId
ORDER BY Name
FOR
XML PATH('')
) AS Dosage
FROM MedicationCombination p2
WHERE p2.MedicationId = @YourMedicationID
GROUP BY NAME ,
MedicationId
Produces this:
CategoryId NAME Dosage
2 Med1/Med2/Med3/ 12/14/16/
Joining to your Medication Table should be trivial now.
select * from Medication m
join (result from previous query) t on t.CategoryId=m.CategoryID
| |
doc_23531918
|
these fields look like the following:
$11
7.4ms
8.5ms
11.6ms
$12
TelegramHandlerPackingInfeedHanging
TelegramHandlerPackingOrderBufferHanging
Within $12 there are 10 distinct values.
I have the following Code which is returning these 10 values as well as some out puts that I need.
#!/usr/bin/gawk -f
BEGIN {
print "Testing glly"
} #End of BEGIN
{ #Start of MID
MSG_TYPE[substr($12,match($12,":")+1,match($12,")")-15)]++;
TIME_AR[$11]++;
SUM[i++] += $11;
} #End of MID
END {
for (MSG in MSG_TYPE) {
print MSG
print "Message Count: "MSG_TYPE[MSG]
print "MIN: "
print "MAX: "
print "Total MSG: "MSG_TYPE[MSG]
print "AVG: "SUM[sum]/MSG_TYPE[MSG]"ms"
}
} #End of END
The out put I am getting so far looks like the following:
Testing glly
TelegramHandlerPackingInfeedHanging
Message Count: 65128
MIN:
MAX:
Total MSG: 65128
AVG: 0ms
TelegramHandlerPackingOrderBufferHanging
Message Count: 68473
MIN:
MAX:
Total MSG: 68473
AVG: 0ms
What I am trying to do is you may have noticed that I have 2 more arrays, TIME_AR and SUM. My question is how can I modify my current script to return a single segment for the 10 distinct values but give me a total sum of the values in the array SUM? I have tried to do this but it is returning 10 segments for each of the 10 distinct values.
Thanks in advance.
Reduced while still providing information.
Sorry, sample Input is as follows:
INFO 2016-06-15 00:00:28.273 TelegramDispatcher - --> Complete telegram dispatching took 11189.4ms (canHandle(69:TelegramHandlerTUNotification) took 0.0ms, handleTelegram took 11182.0ms, commit took 5.1ms, doACK took 1.8ms, doNAK took -0.0ms performAfterCommit took 0.3ms, failedCanHandle took 0.1ms)
INFO 2016-06-15 00:00:28.531 TelegramDispatcher - --> Complete telegram dispatching took 58.5ms (canHandle(60:TelegramHandlerPackingInfeedHanging) took 0.0ms, handleTelegram took 43.5ms, commit took 13.0ms, doACK took 1.4ms, doNAK took -0.0ms performAfterCommit took 0.3ms, failedCanHandle took 0.1ms)
INFO 2016-06-15 00:00:28.558 TelegramDispatcher - --> Complete telegram dispatching took 26.8ms (canHandle(61:TelegramHandlerPackingOrderBufferHanging) took 0.0ms, handleTelegram took 10.5ms, commit took 14.5ms, doACK took 1.2ms, doNAK took -0.0ms performAfterCommit took 0.4ms, failedCanHandle took 0.1ms)
A: This looks like more or less what you want. Your code is using the wrong value as the index to the arrays.
#!/usr/bin/gawk -f
{
key = substr($12,match($12,":")+1,match($12,")")-15)
MSG_TYPE[key]++
TIME_AR[key] += $11
}
END {
for (MSG in MSG_TYPE)
{
print MSG
print "Message Count: " MSG_TYPE[MSG]
print "AVG: " TIME_AR[MSG]/MSG_TYPE[MSG] "ms"
}
}
Extended data
INFO 2016-06-15 00:00:28.273 TelegramDispatcher - --> Complete telegram dispatching took 11189.4ms (canHandle(69:TelegramHandlerTUNotification) took 0.0ms, handleTelegram took 11182.0ms, commit took 5.1ms, doACK took 1.8ms, doNAK took -0.0ms performAfterCommit took 0.3ms, failedCanHandle took 0.1ms)
INFO 2016-06-15 00:00:28.273 TelegramDispatcher - --> Complete telegram dispatching took 7189.4ms (canHandle(69:TelegramHandlerTUNotification) took 0.0ms, handleTelegram took 11182.0ms, commit took 5.1ms, doACK took 1.8ms, doNAK took -0.0ms performAfterCommit took 0.3ms, failedCanHandle took 0.1ms)
INFO 2016-06-15 00:00:28.531 TelegramDispatcher - --> Complete telegram dispatching took 58.5ms (canHandle(60:TelegramHandlerPackingInfeedHanging) took 0.0ms, handleTelegram took 43.5ms, commit took 13.0ms, doACK took 1.4ms, doNAK took -0.0ms performAfterCommit took 0.3ms, failedCanHandle took 0.1ms)
INFO 2016-06-15 00:00:28.531 TelegramDispatcher - --> Complete telegram dispatching took 48.5ms (canHandle(60:TelegramHandlerPackingInfeedHanging) took 0.0ms, handleTelegram took 43.5ms, commit took 13.0ms, doACK took 1.4ms, doNAK took -0.0ms performAfterCommit took 0.3ms, failedCanHandle took 0.1ms)
INFO 2016-06-15 00:00:28.531 TelegramDispatcher - --> Complete telegram dispatching took 62.7ms (canHandle(60:TelegramHandlerPackingInfeedHanging) took 0.0ms, handleTelegram took 43.5ms, commit took 13.0ms, doACK took 1.4ms, doNAK took -0.0ms performAfterCommit took 0.3ms, failedCanHandle took 0.1ms)
INFO 2016-06-15 00:00:28.558 TelegramDispatcher - --> Complete telegram dispatching took 26.8ms (canHandle(61:TelegramHandlerPackingOrderBufferHanging) took 0.0ms, handleTelegram took 10.5ms, commit took 14.5ms, doACK took 1.2ms, doNAK took -0.0ms performAfterCommit took 0.4ms, failedCanHandle took 0.1ms)
Output from extended data
TelegramHandlerPackingInfeedHanging
Message Count: 3
AVG: 56.5667ms
TelegramHandlerTUNotification
Message Count: 2
AVG: 9189.4ms
TelegramHandlerPackingOrderBufferHanging
Message Count: 1
AVG: 26.8ms
| |
doc_23531919
|
{% extends 'base.html' %} {% block title %} Dashboard {% endblock %} {% block pagetitle %}
becomes
{% extends 'base.html' %} {% block title %} Dashboard {% endblock %} {% block
pagetitle %}
Note that the {% tag %} is being broken with a new line. This causes syntax errors with django templates.
I've tried most top django template extensions and this does not fix the issue.
I've also tried these settings:
"[html]": {
"editor.formatOnSave": false,
},
"html.format.wrapLineLength": 0,
"html.format.enable": false,
"prettier.disableLanguages": ["html"]
Desired Behavior:
*
*Automatically format *.html files, while preserving django template tags, not breaking them up with newlines.
*Sub-optimal (but acceptable) behavior: don't format *.html files at all.
A: I had the same issue and the only way I found that solved it is to disable the default HTML formatter. Unfortunately, I did not find a way to make it format Django template tags correctly. You can do the same if you go to VS Code Preferences > Settings > User > Extensions > HTML and uncheck 'Enable/disable default HTML formatter'.
A: I solved this by following this advice: https://stackoverflow.com/a/73892745/1257347
TLDR: install the djLint extension (and remember to do $ pip install djlint)
A: I got it to work by simply adding {{""}} between the {% tag %} that were being broken.
Example:
{% extends 'main/base.html' %} {% block title_block %}Homepage{% endblock%}
{{""}} {%block style_ref_block%}{%endblock%} {{""}} {% block body_block %}
A: This Didn't work for me.
The hack I found was to set the vscode language to jinja instead of the auto detected html
reference
A: I've also just experienced vs-code misbehaving on django template tags (i.e. deleting curly braces).
I don't like the idea of disabling HTML formatting just to support templates (i.e. vs-code Preferences/Settings/Extensions/HTML: disable (uncheck) "HTML>Format:Enable"). This is arguably a step backwards, but it does stop vs-code misbehaving.
Instead, I chose to install (vs-code Preferences/Extensions) the 'Django' extension, by Baptiste Darthenay. This was a better way to go, because it works, gracefully, preserves native vs-code HTML formatting, and includes a nice set of django snippits, which saves me keystrokes when embedding template code. Tada!
BTW, before finding Baptiste's awesome extension, I also tried keeping vs-code HTML formatting enabled, AND enabling 'HTML>Format:Templating', which promised to "Honor django and other templating language tags"; it did not.
| |
doc_23531920
|
Title|Tags
T1|"[Tag1,Tag2]"
T1|"[Tag1,Tag2,Tag3]"
T2|"[Tag3,Tag1]"
using
df = pd.read_csv('file.csv', sep='|')
the output is:
Title Tags
0 T1 [Tag1,Tag2]
1 T1 [Tag1,Tag2,Tag3]
2 T2 [Tag3,Tag1]
I know that the column Tags is a full string, since:
In [64]: df['Tags'][0][0]
Out[64]: '['
I need to read it as a list of strings like ["Tag1","Tag2"]. I tried the solution provided in this question but no luck there, since I have the [ and ] characters that actually mess up the things.
The expecting output should be:
In [64]: df['Tags'][0][0]
Out[64]: 'Tag1'
A: You can convert the string to a list using strip and split.
df_out = df.assign(Tags=df.Tags.str.strip('[]').str.split(','))
df_out.Tags[0][0]
Output:
'Tag1'
A: You can split the string manually:
>>> df['Tags'] = df.Tags.apply(lambda x: x[1:-1].split(','))
>>> df.Tags[0]
['Tag1', 'Tag2']
A: Your df['Tags'] appears to be a list of strings. If you print that list you should get ["[tag1,tag2]","[Tag1,Tag2,Tag3]","[Tag3,Tag1]"] this is why when you call the first element of the first element you're actually getting the first single character of the string, rather than what you want.
You either need to parse that string afterward. Performing something like
df['Tags'][0] = df['Tags'][0].split(',')
But as you saw in your cited example this will give you a list that looks like
in: df['Tags'][0][0]
out: '[tag1'`
What you need is a way to parse the string editing out multiple characters. You can use a simple regex expression to do this. Something like:
import re
df['Tags'][0] = re.findall(r"[\w']+", df['Tags'][0])
print(df['Tags'][0][0])
will print:
'tag1'
Using the other answer involving Pandas converters you might write a converter like this:
def clean(seq_string):
return re.findall(r"[\w']+", seq_string)
If you don't know regex, they can be quite powerful, but also unpredictable if you're not sure on the content of your input strings. The expression used here r"[\w']+" will match any common word character alpha-numeric and underscores and treat everything else as a point for re.findall to split the list at.
A: You could use the inbuilt ast.literal_eval, it works for tuples as well as lists
import ast
import pandas as pd
df = pd.DataFrame({"mytuples": ["(1,2,3)"]})
print(df.iloc[0,0])
# >> '(1,2,3)'
df["mytuples"] = df["mytuples"].apply(ast.literal_eval)
print(df.iloc[0,0])
# >> (1,2,3)
EDIT: eval should be avoided! If the the string being evaluated is os.system(‘rm -rf /’) it will start deleting all the files on your computer (here). For ast.literal_eval the string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None (here). Thanks @TrentonMcKinney :)
A: Or
df.Tags=df.Tags.str[1:-1].str.split(',').tolist()
A: I think you could use the json module.
import json
import pandas
df = pd.read_csv('file.csv', sep='|')
df['Tags'] = df['Tags'].apply(lambda x: json.loads(x))
So this will load your dataframe as before, then apply a lambda function to each of the items in the Tags column. The lambda function calls json.loads() which converts the string representation of the list to an actual list.
| |
doc_23531921
|
Thanks!
A: this is how to calculate the top position of your scrollbar
scrollbar.style.top = element.scrollTop / (element.scrollHeight / element.style.height)
you can use this onscroll of your scroll element. vice versa, this works in the other direction, when you drag your scrollbar.
sorry for this quick'n'dirty answer, will provide more information later if you liked to.
| |
doc_23531922
|
*
*Vectors
*deque
*list
*string
*set
*multiset
*map
*multimap
*stack
*queue
*priority queue.
I think, the search/find time should be based on how these STL containers are implemented internally. So it would help if information about same can be provided as well. It might vary from implementation to implementation, so answers based on commonly used data structures behind these STL containers would also help.
Thanks in advance..
| |
doc_23531923
|
A: Editing post to address comment from OP:
In future apps, you should avoid acting directly upon a UIWindow whenever possible. However, now that you are stuck with an App A that directly acts upon the window, I would suggest that instead of doing a bunch of work to make your app properly use a UIViewController, you can just make App B into an app that uses two windows:
When App B wants to show the content of App A, just instantiate a new UIWindow windowOfAppA, set its rootViewController to the rootViewController of App A, and then call '[windowOfAppA makeKeyAndVisible];'. Once App A is done doing it's work, it can resign key window status by calling '[windowOfAppB makeKeyAndVisible];'.
Again, I emphasize that the technique I am grudgingly describing is terrible style and in the future your apps should only use one window it should only act upon it when absolutely necessary. Whenever possible, do all your work through view controllers.
Previous content of this answer:
What is your ultimate goal? Are you
trying to turn App A into a part of
App B? If so, you don't have to make
any changes to your existing class
hierarchy or nib files. All you have
to do is copy all of the files from
App A to App B and instantiate App A's
root view controller from within App B
(perhaps using
presentModalViewController:animated:)
and everything should work great.
| |
doc_23531924
|
RuntimeError: Encountered unresolved custom op: Normalize.Node number 0 (Normalize) failed to prepare,
i've received below answer.
To use this you would need to use a custom built pip package. See the installation instructions for TensorFlow tensorflow.org/install/source. Also, you need to change the ops included in your built version of TF lite. The Java version has a custom op resolver see the build here: https://github.com/tensorflow/examples/blob/master/lite/examples/smart_reply/android/app/libs/cc/BUILD. You can see where the ops are registered here: https://github.com/tensorflow/examples/blob/master/lite/examples/smart_reply/android/app/libs/cc/predictor.cc#L77
But i've downloaded smartreply.tflite model directly from their
samples. So if we change the code related to custom ops, then i've to
re build the tflite model? Also if i removed the custom ops code then
the smart reply predictor will work perfectly?
| |
doc_23531925
|
At the moment to click on the button all the controls preserve its data I can access them from code behind. buut there is one control that doesn't behave in the same way. It's one of the 4 DropDownlist. When trying to do the following it just get a empty string:
string sData1 = this.DropDownList1.SelectedValue; --> works OK
string sData2 = this.DropDownList2.SelectedValue; --> works OK
string sData3 = this.DropDownList3.SelectedValue; --> works OK
string sData4 = this.DropDownList4.SelectedValue; --> is NOT working
Basically this is the HTML markup I have for each DropDownList:
<asp:DropDownList ID="DropDownLis1" runat="server"></asp:DropDownList>
<asp:DropDownList ID="DropDownLis2" runat="server"></asp:DropDownList>
<asp:DropDownList ID="DropDownLis3" runat="server"></asp:DropDownList>
<asp:DropDownList ID="DropDownLis4" runat="server"></asp:DropDownList>
I've searching on the Internet to see if there is something related but without no luck.
Another doubt I have is the following. Is there any possibility that the viewstate is full and it doesn't store the selected value of that DropDownList?
Any clue or help would very appreciate
Thanks
| |
doc_23531926
|
$(document).ready(function(){
var $rows = $('#tblData tr');
console.log("akshansh");
$('#empId, #empName,#status').on('input', function() {
var val1 = $.trim($('#empId').val()).replace(/ +/g, ' ').toLowerCase();
var val2 = $.trim($('#empName').val()).replace(/ +/g, ' ').toLowerCase();
var val3= $.trim($('#status').val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function() {
var text1 = $(this).find('tr:not(:first),td:nth-child(1)').text().replace(/\s+/g, ' ').toLowerCase();
var text2 = $(this).find('tr:not(:first),td:nth-child(2)').text().replace(/\s+/g, ' ').toLowerCase();
var text3 = $(this).find('tr:not(:first),td:nth-child(n+2)').text().replace(/\s+/g, ' ').toLowerCase();
return !~text1.indexOf(val1) || !~text2.indexOf(val2)|| !~text3.indexOf(val3);
}).hide();
});
});
Also the third column onwards are the date fields so is there a way that i can filter the data datewise?
A: You missed the : before first-child
$("#tblData tr:not(:first-child)").hide();
A: Structure your table to look like
<table id='tblData'>
<thead>
<tr></tr>
</thead>
<tbody>
</tbody>
</table>
Put your first row in the thead, then put the rest in the tbody.
That will allow you to qualify you jquery
var $rows = $('#tblData tbody tr');
| |
doc_23531927
|
My problem is that the schema operations all require the database to exist before they will work. I want to programmatically create my database and update the schema as there may be multiple databases and the creating of the database is not only a once-off operation.
I know I can do this manually by executing a create database command on a connection to the master database, but this feels wrong considering that I otherwise use NHibernate for all my database interactions. As an aside, I use a SQLite inmemory database for my unit tests so any sql I write will then have to know which database I'm using.
Is there any way to get NHibernate to create my database for me?
A: No, NHibernate will not create the database for you. Creating databases is something you usually don't want do be done on the fly. It needs many configuration parameters and this is very database specific, even database version specific.
For our product, I wrote a class that sets up the database. It is used for the installer, the integration tests and the database maintenance tool.
*
*NHibernate creates the connection using its configuration.
*my own implementation creates the database. There are different implementations for different dialects.
*NH creates the tables and other database objects
*Installer classes create initial data
There is also a special case, where a customer doesn't want to grant the right to create databases. Then we expect him to do it and skip this part.
A: We use SchemaExport to provide a schema and a Nant task to drop and recreate the database. Another Nant task runs the schema export and dataloading code which exists in the form of an integration test run by the nunit task. There is a sample here.
A: I think that creating db with NHibernate is nice, if you start to develop application with domain model. I mean - it gives an insight how your db should look. But in general - sql scripts should be used.
I heard that some developers uses NHibernate db generation for integration tests, they create lightweight sqlite db on fly.
How to generate db with NHibernate? This is how i do that:
public static void InitSessionFactory()
{
var connectionString =
ConfigurationManager
.ConnectionStrings["MyConnectionString"]
.ConnectionString;
var cfgFromXml = new Configuration();
cfgFromXml.Configure();
var cfg = Fluently.Configure(cfgFromXml)
.Database(MsSqlConfiguration.MsSql2005
.ConnectionString(x => x.Is(connectionString))
.UseReflectionOptimizer())
.Mappings(x => x.FluentMappings
.AddFromAssemblyOf<NHibernateBootstrapper>())
.ExposeConfiguration(BuildSchema);
ObjectFactory.Inject(cfg.BuildSessionFactory());
}
private static void BuildSchema(Configuration config)
{
//Creates database structure
//new SchemaExport(config)
// .Create(false, true);
}
A: Hmm, you can indeed use SchemaExport as you mention, but I see NHibernate primarely as a way to bridge the gap between OO domain model and a relational persistence storage.
That is, for me NHibernate's purpose is to persist and retrieve entities in my domain model.
When you want to do schema updates, imho, you should not use NHibernate (if possible at all), since that's not the purpose of NHibernate; there is a 'domain specific language' called SQL :) which is good at doing those things.
In order to create my database, and update my database-schema, I use Migrator.NET, which is a framework which lets you write C# classes in where you specify what needs to be done (create a table, add a column, etc...).
The advantage of this, is that Migrator.NET also supports multiple DBMS'es, so you do not end up writing DB-specific SQL code.
A: Have a look at RhinoCommons. Under Rhino.Commons.ForTesting, in UnitOfWorkTestContextDbStrategy.cs, Ayende has done some routine there that creates databases.
A: Looking for this myself as I've seen it done in java - similiar question here: Generate Database from NHibernate config files
| |
doc_23531928
|
In the generated code:
@Override
public boolean equals(Object o) {
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) return false;
Matrix matrix = (Matrix) o; // (*)
for (int i=0; i<this.values.length; i++) {
// compare entries
}
return true;
}
why does IntelliJ cast the object to type Matrix at position ((*)), when just above it checked if the classes are the same?
A: The casting to Matrix is done so later on the method you can access its methods/members and use them for the comparison (based on your logic).
A: A straight-forward and simple answer is, in Java every class by default extends Object class. That is Object class is the superclass and Matrix here is a subclass of Object class. A simple analogy is, All dogs are animals, not all animals are dogs. Hence, to assign an instance of the Object class you need to tell, it is really of a Matrix class. That's why the class was casted.
A: Type casting is necessary for 'assignment', but not for comparison.
This is the reason for the explicit use of typecasting in the assignment statement
Matrix matrix = (Matrix) o;
The object comparison using == works by verifying whether the references to the objects being compared are the same. Comparing merely the references does not need typecasting.
However, an assignment statement needs to allocate space for the object on the left, so that it can accommodate all values of the object on the right side. For this purpose, a typecast is necessary in the assignment statement.
| |
doc_23531929
|
In one of the API calls, I check if an image is present in a folder. If it is not, I create it (in code) and then send a link to it (amongst other things) back to the caller. The check if exists and creation of the image works fine in ASP.NET Core, but when I send back the link to the image, the client does not find it and hence it appears as a broken link on their web page.
See this diagram for the structure and for example the EnabledTRImage.png file.
The Url I am returning is:
http://localhost:59682/TR/128/EnabledTRImage.png
I have also tried returning:
http://localhost:59682/wwwroot/TR/128/EnabledTRImage.png
But this fails too.
One thing I have noticed is that in ASP.NET Core, creating the image in code makes it part of the Project, whereas in ASP.NET it does not. I was wondering if that had anything to do with the issue.
Unfortunately, these images are central to the Web API. So I am stuck.
Any ideas? Thanks
A: I just fixed it myself. I had not specified:
app.UseStaticFiles();
In the Startup/Configure method. That line is not there in the WebApi template (as expected I guess)
A: In the Startup/Configure method.
Instead of app.UseStaticFiles();
Specify your folder path in StaticFileOptions()
app.UseStaticFiles(new StaticFileOptions(){
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"ProductImagesFiles")),
RequestPath = new PathString("/ProductImagesFiles")
});
'
| |
doc_23531930
|
let z = (y as NSString).intValue
I want to get z to be equal to 1312000. So basically:
*
*String should get converted to int
*The integer should not have commas
*Anything after the decimal should be ignored.
A:
*
*String should get converted to int
*The integer should not have commas
*Anything after the decimal should be ignored.
I would argue that you need to do those in reverse:
*
*Get rid of everything after the decimal place
*Remove the none-numerical values
*Convert it to an Int
There are a number of ways you might do this
You could use CharacterSet.decimalDigits, something like...
"1,312,000.99".components(separatedBy: CharacterSet.decimalDigits.inverted).joined()
this is kind of messy, as the one thing I've not done, is remove the .99, but that could be done something like...
var value = "1,312,000.99"
value = String(value[value.startIndex..<value.firstIndex(of: ".")!])
note: I'm not checking to see if firstIndex is nil which it might be, so you'll need to compensate for that.
Another, possibly better, solution would be to make use of a NumberFormatter
let formater = NumberFormatter()
formater.numberStyle = .decimal
formater.locale = Locale(identifier: "en_AU")
let number = formater.number(from: "1,312,000.99")
Then you could just cast it to an Int value
let intValue = Int(number!)
Again, check number as it may be nil
A: Try code like this:
//Create a NumberFormatter that takes input strings with comma thousands separators and at least 1 decimal place
let inputFormatter = NumberFormatter()
inputFormatter.format = "###,###,###,###.#"
inputFormatter.locale = Locale(identifier: "en_US_POSIX")
var numberString = "1,234,567.88"
//Convert the input string to an Int (which truncates the decimal portion)
if let value = inputFormatter.number(from: numberString)?.intValue {
print(value)
//print( outputString)
} else {
print("Can't convert")
}
| |
doc_23531931
|
constraintlayout-compose version: 1.0.0-alpha05.
composable :
@Composable
fun comp1() {
Surface(Modifier
.fillMaxWidth()
.height(50.dp), color = Color.Red) {
ConstraintLayout(Modifier.fillMaxSize()) {
val guide_line = createGuidelineFromAbsoluteRight(.2f)
val (icon_ref, box_ref, spacer_ref) = createRefs()
Icon(Icons.Filled.Search, null,
modifier = Modifier.constrainAs(icon_ref) {
absoluteLeft.linkTo(guide_line)
absoluteRight.linkTo(parent.absoluteRight)
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
}
)
Box(Modifier
.background(Color.Blue)
.fillMaxSize()
.constrainAs(box_ref) {
absoluteLeft.linkTo(parent.absoluteLeft)
absoluteRight.linkTo(guide_line)
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
}) {}
Spacer(Modifier
.background(Color.Yellow)
.width(2.dp)
.fillMaxHeight()
.constrainAs(spacer_ref) {
absoluteRight.linkTo(guide_line)
})
}
}
}
preview:
as you can see, the items are not constrained as one would expect.
the views in the view_based ConstraintLayout wouldn't draw outside of the screen unless the constraints are messed up or it was intentional.
A: In the Box composable remove the fillMaxSize() modifier and apply the constraint width = Dimension.fillToConstraints.
Something like:
Surface(Modifier
.fillMaxWidth()
.height(50.dp), color = Color.Red) {
ConstraintLayout(Modifier.fillMaxSize()) {
val guide_line = createGuidelineFromAbsoluteRight(.2f)
val (icon_ref, box_ref, spacer_ref) = createRefs()
Icon(Icons.Filled.Search, null,
modifier = Modifier.constrainAs(icon_ref) {
start.linkTo(guide_line)
end.linkTo(parent.end)
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
}
)
Box(contentAlignment=Alignment.CenterStart,
modifier = Modifier
.background(Color.Blue)
.fillMaxHeight()
.constrainAs(box_ref) {
start.linkTo(parent.start)
end.linkTo(guide_line)
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
width = Dimension.fillToConstraints //ADD THIS
}) {
Text(text = "Text ", color = Yellow)
}
Spacer(Modifier
.background(Color.Yellow)
.width(2.dp)
.fillMaxHeight()
.constrainAs(spacer_ref) {
end.linkTo(guide_line)
})
}
}
| |
doc_23531932
|
#include <iostream>
#include <string>
#include <vector>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/size.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
struct MyStruct
{
int x;
int y;
};
BOOST_FUSION_ADAPT_STRUCT(
MyStruct,
(int, x)
(int, y)
)
#define PRINT(unused, number, data) \
std::cout << number << std::endl;
int main()
{
MyStruct s;
std::cout << boost::fusion::size(s) << std::endl;
//line below works - it iterate and write output
BOOST_PP_REPEAT(2, PRINT, "here I will pass my data")
//this won't compile
//BOOST_PP_REPEAT(boost::fusion::size(s), PRINT, "here i will pass my data")
}
How to fix problematic line so it will work when I will add more members in structure? I need solution for C++03 :(
A: Instead of using BOOST_PP_REPEAT, you can use the boost::fusion::for_each which goes through every element. example:
#include <iostream>
#include <string>
#include <vector>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/size.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/fusion/algorithm/iteration/for_each.hpp>
struct MyStruct {
int x;
int y;
};
BOOST_FUSION_ADAPT_STRUCT(
MyStruct,
(int, x)
(int, y)
)
template<typename Data>
struct PrintWithData {
PrintWithData(Data data) : data(data) {}
template<typename T>
operator()(const T& thingToBePrinted)
{
std::cout << thingToBePrinted << std::endl;
}
Data data;
};
int main()
{
MyStruct s;
//this will compile
boost::fusion::for_each(s, PrintWithData<std::string>("here I will pass my data"));
}
A: Here is exact solution for this problem (asked more general question later, and found answear which solve this problem too): https://stackoverflow.com/a/31713778/4555790
| |
doc_23531933
|
*
*On level 1 (lowest, represents on individual) there are 16 ordinal and 20 dichotomous variables,
*on level 2 there are 28 continuous variables, and
*on level 3 (top) there are 4 ordinal variables.
I've been following Simon Grund's example for modeling three-level data using mice with the mice.impute.ml.lmer-function. Naturally, I had to make some adaptations to the example model to fit my data:
*
*I tried setting model to "binary" to run a logistic mixed effects model for the dichotomous variables ("pmm" for the ordinal, "continuous" for the continuous).
*I tried added random slopes and interaction effects.
*mice.impute.2lonly.pmm was used instead of mice.impute.2lonly.norm for the top level imputation.
*I added a post processing to a level 2 variable where I set upper and lower boundaries.
However when running mice (with some variables modeled as "binary" (without random slopes or interactions), I get the following warning:
Warning message in commonArgs(par, fn, control, environment()):
“maxfun < 10 * length(par)^2 is not recommended.”
Execution of mice hangs at this point.
I ran a test with mice (1 iteration), this time with all dichotomous variables as "pmm", and this time the function completed the run. However, adding variables to random_slopes it seemingly gets stuck (running infinitely) on the imputation of the first three variables. Now, my assumption is that this is due to the relatively large dataset, making the the process computationally very demanding.
I am wondering what exactly causes this error message, and if there are ways to avoid it. Also, I would like to know if there are ways to improve computational efficiency of such a large model.
I am not very familiar with mice, but I have some thoughts regarding how the data is imputed:
I am planning to use the imputed data for a structural equation model I've built, where all the variables are grouped into indicators of latent constructs. It therefore seems natural that the indicator variables that belongs to the same construct are imputed together.
*
*In mice there is an argument called blocks which allows for multivariate imputation of the variables grouped together as list elements. However, creating blocks containing variables from different levels created the issue that I got the error message that no top level was defined in the predictorMatrix (i.e. no block set to -2). As an alternative method, it seems the formulas argument can be used in place of a predictor matrix. This options seems ideal, as it allows user defined formulas for each block. Also, if I understand the whole process correctly, the predictorMatrix is only passed on to mice.impute.2lonly.pmm and not mice.impute.ml.lmer. The question then is if the formulas argument can be used to define three-level models using lme4-syntax? ..and can these user defined models in formulas be passed on to mice.impute.ml.lmer? As a more general question, why can't mice.impute.ml.lmer be used for imputation at top level? (At least, it didn't work when I tried.)
*Then there's also an argument group_index in mice.impute.ml.lmer used to pass group identifiers to mice.impute.bygroup. From reading the documentation I am still unsure what this function actually does, as I can find little information on it. However, it seems it is designed for grouping variables together by level, but not across grouping of variables from different levels, correct? However, what would distinguish mice.impute.bygroup from creating blocks? ..and what would the difference of doing this, rather than calling models in mice.impute.ml.lmer?
*As for computational efficiency, I have no idea if grouping variables together would increase computational efficiency. I could really use some advice on this part.
| |
doc_23531934
|
At 51 frame i load another image with the same width but with 150px height.
I have this code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>masterhead</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
html, body { height:100%; background-color: #ffffff;}
body { margin:0; padding:0; overflow:hidden; }
#flashContent { width:100%; height:100%; }
</style>
</head>
<body>
<div id="flashContent">
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="980" height="235" id="masterhead" align="middle">
<param name="movie" value="masterhead.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="play" value="true" />
<param name="loop" value="true" />
<param name="wmode" value="window" />
<param name="scale" value="showall" />
<param name="menu" value="true" />
<param name="devicefont" value="false" />
<param name="salign" value="" />
<param name="allowScriptAccess" value="sameDomain" />
<!--[if !IE]>-->
<object type="application/x-shockwave-flash" data="masterhead.swf" width="980" height="235">
<param name="movie" value="eradio_masterhead.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="play" value="true" />
<param name="loop" value="true" />
<param name="wmode" value="window" />
<param name="scale" value="showall" />
<param name="menu" value="true" />
<param name="devicefont" value="false" />
<param name="salign" value="" />
<param name="allowScriptAccess" value="sameDomain" />
<!--<![endif]-->
<a href="http://www.adobe.com/go/getflash">
<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
</a>
<!--[if !IE]>-->
</object>
<!--<![endif]-->
</object>
</div>
<div>
<br> just some text </br>
</div>
</body>
</html>
Problem is that swf container doesn't resize at the frame 51.
How I ccan do that;
Thank you
A: Simply ** Flash Cant**
The SWF file is a container pre compiled file, It will not resize as the properties of the file are already declared when you compiled it and in your parameters tags.
Html divs with Css will also not resize the SWF as the page is separate and has no interactivity with the flash content already displayed.
Im not too sure if this would be possible with javascript during runtime, but that is another question....
| |
doc_23531935
|
select * from paso_string where 'AAAAAAAAA' SIMILAR TO columname
But, When I use this query into ingres 4GL show me an error when I try to compiling and show me the follow issue.
E_OS0100 Syntax error on line
The last symbol read was 'similar'
A: 4GL has its own parser, which sadly is often behind the SQL parser when it comes to new features.
The standard work-around is to put your SQL statement into a string and then do execute immediate :string;
| |
doc_23531936
|
A: Ok, This is not a absolute solution, but if you get a mail details using <Method: users.messages.get> from Gmail API by filtering "in:send" messages , Sometimes you get user name in this format {User-Name} <{email-id}> under "From" tag of the json response. But it is not certain to get user name followed by email-id. Sometimes it only gives email ID under "From" tag. I used this function below to extract user-name and email from the "From" tag:
def _get_email_and_name(self, email):
temp = email.split("<")
if (len(temp)) > 1:
temp[1] = temp[1].replace(">", "")
temp[0] = temp[0].rstrip()
return temp
else:
return None, temp[0]
A: getProfile should do the trick. Gets you their email adress. (alternate for g+ api)
| |
doc_23531937
|
add_action ( 'woocommerce_single_product_summary', 'add_my_special_image', 40 );
function add_my_special_image() {
global $product;
print '<img src="https://yoursite.com.au/wp-content/uploads/your-image-path.jpg" alt="your-image" class="my_image" />';
}
The problem ( I know that may sound silly) is how to do it for every single product on my page.
I put this snippet on the functions.php, but I cant figured out how this works for every image (the image that I want to put in every page is different).
Someone can clarify that for me?
thanks!
A: My understanding of your question is that you want to have a specific image show in that position for each product? Best option is to create a field for the product (using ACF is an easy way to do this) then instead of hardcoding the image you use the field from each product. So you would have something like:
add_action ( 'woocommerce_single_product_summary', 'add_my_special_image', 40 );
function add_my_special_image() {
global $product;
$product_id = $product->get_id();
$image = get_field('product_image_field_name', $product_id);
print '<img src="' . $image["url"] . '" alt="your-image" class="my_image" />';
}
If you use ACF, then see https://www.advancedcustomfields.com/resources/image/ for more on how to handle the image field.
| |
doc_23531938
|
the JSON is below
{
"sourceId": "1234",
"sourceType": "MONITOR",
"searchMeta": {
"startTimestamp": 1462361513,
"endTimestamp": 1462508560,
"maxResults": 10000,
"metricType": [
"clients"
],
"family": [
"Product"
],
"metricsInterval": "M5"
},
"clients": {
"One": [
{
"timestamp": 1462361400,
"avg": 2,
"min": 1,
"max": 3,
"probes": 6,
"samples": 3,
"sources": [
"123",
"234",
"345",
"456",
"567",
"789"
]
},
I was wanting to get the Probes value and the Samples value into a variable
foreach($json['clients'] as $range => $product){
echo $product['timestamp']." Probes: ".$product['probes']." Samples: ".$product['samples']." <br>";
}
Thanks in advance
A: I assume you'll have a range of clients (hence the loop). So you'll need to loop each client too as it's an array of object's.
If you visualise it, that looks like this:
CLIENTS = ARRAY(
1 => ARRAY( OBJECT{} ), // you want the OBJECT{}
....etc
)
So the below loop will get it for you.
$data = json_decode($json, TRUE);
foreach($data['clients'] as $range => $product) {
foreach($product as $element){
echo $element['timestamp']." Probes: ".$element['probes']." Samples: ".$element['samples']." <br>";
}
}
Example/Demo
Returns the following:
1462361400 Probes: 6 Samples: 3 <br>
A: The demand of OP:
I was wanting to get the Probes value and the Samples value into a
variable
Simple just name your json file as $json.
$arr = json_decode($json);
echo $samples = $arr->clients->One[0]->samples; //3
echo $probes = $arr->clients->One[0]->probes; //6
A: Try this.
$data = json_decode($json,true);
foreach($data['clients'] as $client){
echo $client['timestamp']." Probes: ".$client['probes']." Samples: ".$client['samples']." <br>";
}
| |
doc_23531939
|
Here is a snippet of my code:
import React, { useState } from "react";
import { Accordion, Card, Button, Container, Row, Col } from "react-bootstrap";
const Riddles = (props) => {
const levelStatus = {
easy: "Easy Riddles",
medium: "Intermediate Riddles",
hard: "Hard Riddles",
};
const collapseButton = "Click to close";
const [close, setClose] = useState({
easy: false,
medium: false,
hard: false,
});
// Handle click
const handleClick = (e) => {
setClose({
close.easy: true
});
};
return (
<>
<div className="riddlesection">
<Container>
<Row>
<Col className="riddlegrid" xs={12} sm={12} md={4}>
<Accordion>
<Card id="easy">
<Card.Header>
<Accordion.Toggle
id="easy"
onClick={handleClick}
value="Easy Riddles"
as={Button}
variant="link"
eventKey="0"
>
{close.easy ? levelStatus.easy : collapseButton}
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey="0">
<Card.Body>
<Row>
<Col xs={6} sm={6} md={6}>
Countdown
</Col>
<Col className="resetlink" xs={6} sm={6} md={6}>
Switch
</Col>
</Row>
<div>Hello! I'm the body</div>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
</Col>
</Row>
</Container>
</div>
</>
);
};
What can I do to achieve differently the behavior that I want?
A: you need to update the state as below
const handleClick = (e) => {
setClose(prevCloseState => {
...prevCloseState,
easy: true
})
};
| |
doc_23531940
|
I have react 17.0.2 version and I already installed leaflet & leaflet-react
this is a pic of the error message
| |
doc_23531941
|
Advance Thanks..
My view
CascadingDropDown
My ViewModel
public Nullable<System.Guid> CustomerID { get; set; }
public string CustomerName { get; set; }
public Nullable<System.Guid> CustomerContactID { get; set; }
public string ContactPerson { get; set; }
My View
<div class="col-sm-4">
<div class="form-group">
@Html.LabelFor(model => model.CustomerName , new { @class = "control-label" })
@Html.DropDownList("dropdownCustomer", new SelectList(string.Empty, "Value", "Text"), "Please select a Customer", new { @style = "width:250px;" })
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
@Html.LabelFor(model => model.ContactPerson, new { @class = "control-label" })
@Html.DropDownList("dropdownCustomerContact", new SelectList(string.Empty, "Value", "Text"), "Please select a ContactPerson", new { @style = "width:250px;" })
</div></div>
j-query code
$(function () {
$.ajax({
type: "GET",
url: "/VisitorsForm/GetCustomers",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownCustomer').append('<option value="' + value.CustomerID + '">' + value.DisplayName + '</option>');
});
}
});
$('#dropdownCustomer').change(function () {
$('#dropdownCustomerContact').empty();
$.ajax({
type: "POST",
url: "/VisitorsForm/GetContactPersobByCustomerId",
datatype: "Json",
data: { CustomerID: $('#dropdownCustomer').val() },
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownCustomerContact').append('<option value="' + value.CustomerContactID + '">' + value.ContactReference + '</option>');
});
}
});
});
});
My Controller
public ActionResult Create()
{
ViewBag.CustomerContactID = new SelectList(db.CustomerContacts, "CustomerContactID", "ContactReference");
ViewBag.CustomerID = new SelectList(db.Customers, "CustomerID", "DisplayName");
return View();
}
public JsonResult GetCustomers()
{
return Json(db.Customers.ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult GetContactPersobByCustomerId(string customerId)
{
Guid Id = Guid.Parse(customerId);
var customercontacts = from a in db.CustomerContacts where a.CustomerID == Id select a;
return Json(customercontacts);
}
[HttpPost]
public ActionResult Create(VisitorsViewModel visitorviewmodel)
{
ViewBag.CustomerContactID = new SelectList(db.CustomerContacts, "CustomerContactID", "ContactReference",visitorviewmodel .CustomerContactID );
ViewBag.CustomerID = new SelectList(db.Customers, "CustomerID", "DisplayName",visitorviewmodel .CustomerID );
var VisitorsViewObj = new VisitorsForm()
{
CustomerID = visitorviewmodel.CustomerID,
CustomerContactID = visitorviewmodel.CustomerContactID
};
A: <div class="col-sm-4">
<div class="form-group">
@Html.LabelFor(model => model.CustomerName , new { @class = "control- label" })
@Html.DropDownListFor(model => model.CustomerID, new SelectList(string.Empty, "Value", "Text"), "Please select a Customer", new { @style = "width:250px;" })
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
@Html.LabelFor(model => model.ContactPerson, new { @class = "control-label" })
@Html.DropDownListFor(model => model.CustomerContactID, new SelectList(string.Empty, "Value", "Text"), "Please select a ContactPerson", new { @style = "width:250px;" })
</div> </div>
$(function () {
$.ajax({
type: "GET",
url: "/VisitorsForm/GetCustomers",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#CustomerID').append('<option value="' + value.CustomerID + '">' + value.DisplayName + '</option>');
});
}
});
$('#CustomerID').change(function () {
$('#CustomerContactID').empty();
$.ajax({
type: "POST",
url: "/VisitorsForm/GetContactPersobByCustomerId",
datatype: "Json",
data: { CustomerID: $('#CustomerID').val() },
success: function (data) {
$.each(data, function (index, value) {
$('#CustomerContactID').append('<option value="' + value.CustomerContactID + '">' + value.ContactReference + '</option>');
});
}
});
});
});
| |
doc_23531942
|
A: Can you confirm what you are asking? Are you running a long-lived task in the Dispatcher? Killing the thread would break the CCR model, so you need to be able to signal to the thread to finish its work and yield. Assuming it's a loop that is not finishing quick enough, you might choose to enqueue a timer:
var resultTimeoutPort = new Port<DateTime>();
dispatcherQueue.EnqueueTimer(TimeSpan.FromSeconds(RESULT_TIMEOUT),
resultTimeoutPort);
and ensure the blocking thread has available a reference to resultTimeoutPort. In the blocking loop, one of the exit conditions might be:
do
{
//foomungus amount of work
}while(resultTimeoutPort.Test()==null&&
someOtherCondition)
Please post more info if I'm barking up the wrong tree.
A: You could register the thread (Thread.CurrentThread) at the beginning of your CCR "Receive" handler (or in a method that calls your method via a delegate). Then you can do your periodic check and abort if necessary basically the same way you would have done it if you created the thread manually. The catch is that if you use your own Microsoft.Ccr.Core.Dispatcher with a fixed number of threads, I don't think there is a way to get those threads back once you abort them (based on my testing). So, if your dispatcher has 5 threads, you'll only be able to abort 5 times before posting will no longer work regardless of what tasks have been registered. However, if you construct a DispatcherQueue using the CLR thread pool, any CCR threads you abort will be replaced automatically and you won't have that problem. From what I've seen, although the CCR dispatcher is recommended, I think using the CLR thread pool is the way to go in this situation.
| |
doc_23531943
|
[agghd,gjg,tomt]
How to split it so that my output looks like the following :
[[a,g,g,h,d],[g,j,g],[t,o,m,t]]
I have done the following code for now :
agghd
gjh
tomt
list2=[]
list2 = [str(sequences.seq).split() for sequences in family]
A: You can split a string to characters by calling list() on it
list1 = ['agghd', 'gjg', 'tomt']
list2 = [list(string) for string in list1]
# output: [['a', 'g', 'g', 'h', 'd'], ['g', 'j', 'g'], ['t', 'o', 'm', 't']]
A: You can try
[[eval(n) for n in str(sequences.seq).split()] for sequences in family]
| |
doc_23531944
|
When a request finishes, a new request will begin until hash returns null through the response.
Then, I need to bind all collected data into an array.
How can I build something like that in RxSwift? I would appreciate if you describe that concept.
A: You need something like this: https://gist.github.com/danielt1263/ec1032375498eb95aa260239b289d263
/**
Calls `producer` with `seed` then emits result and also passes it to `pred`. Will continue to call `producer` with new values as long as `pred` returns values.
- parameter seed: The starting value needed for the first producer call.
- parameter pred: This closure determines what the next value pass into producer should be or returns nil if no more calls are necessary.
- parameter producer: The function that produces the Single result.
- returns: An observable that emits each producer's value.
*/
func emitWhile<T, U>(seed: U, pred: @escaping (T) -> U?, producer: @escaping (U) -> Single<T>) -> Observable<T>
The seed is the hash for the first page. The pred takes the result of a network request, extracts the hash for the next page and returns it (or returns nil if there is no next page.) The producer takes the hash and returns an observable that will make the request for the page when it is subscribed to.
You will likely want to collect all the elements using either scan or reduce to emit all of the pages as a single array.
| |
doc_23531945
|
I am extremely SORRY if the question title and the question body seems to be misleading..
Here's my code below:
// PROGRAME TO FIND FACTORS OF GIVEN NUMBER"
#include <stdio.h>
void insert_element(int *factor_array[], int *base_divisor, int *index_of_array_elements)
//I heve used * because i want to ruturn more then one thing
{
*factor_array[*index_of_array_elements] = *base_divisor;
*index_of_array_elements++;
}
void factors(int number)
// I dont know if I want to return something or not so i kept it of type void
{
int base_divisor = 2, factor_array[50], index_of_array_elements = 0;
// base_divisor starts dividing given number from 2
while (number != 1)
{
if (number % base_divisor==0) //If remainder is zero then only devide number by base_divisor
{
number = number / base_divisor;
}
else //If remainder is not zero then base_divisor will be increase by 1.
{
base_divisor++;
}
// calling the function to insert element in array
insert_element(&factor_array[50], &base_divisor, &index_of_array_elements);
}
//i dont know why i did this but error is not caused by this.
printf("%ls", factor_array);
}
int main()
{
int number;
printf("\nPROGRAME TO FIND FACTORS OF GIVEN NUMBER\n\n");
printf("Enter the number to find factor: ");
scanf("%d", &number);
factors(number);
}
A: As written, the code in your post is outputting values that are not always factors. Only during the final iteration of the loop is the value for factor_array (if stored correctly) a quotient and a factor, which of course should also mean it is prime.
The following example, for simplification removes one function, and modifies the prototype of the remaining function to take a struct array argument. The struct itself contains values for quotient, factor, base. The code is also commented to explain some of the modification. In particular I hope this will help you to understand how to pass an array as a function argument, and how to use a loop to output the values in an array.
typedef struct {
long long factor;
long long quotient;
long long base;
}elements_s;
elements_s factor_array[50] = {{0}};
//REMOVED as all the work done here is moved to it's calling function
// void insert_element(size_t arr_size int *factor_array[], int *base_divisor, int *index_of_array_elements)
////I heve used * because i want to ruturn more then one thing
//{
//
// *factor_array[*index_of_array_elements] = *base_divisor;
// *index_of_array_elements++;
//
//
//}
void factors(long long number, size_t size, elements_s arr[size])//changed to pass container for results.
// I dont know if I want to return something or not so i kept it of type void
{
long long base_divisor = 2, /**factor_array[50],*/ index_of_array_elements = 0;//factor_array replaced by struct array
arr[index_of_array_elements].factor = 1;//fill array here, no need to send via function
arr[index_of_array_elements].quotient = number;
arr[index_of_array_elements].base = base_divisor;
int i=0;
// base_divisor starts dividing given number from 2
while (number != 1 && base_divisor < LLONG_MAX )
{
if (number % base_divisor==0) //If remainder is zero then only devide number by base_divisor
{
index_of_array_elements++;//index array index
number = number / base_divisor;
arr[index_of_array_elements].factor = base_divisor;//fill array here, no need to send via function
arr[index_of_array_elements].quotient = number;//fill array here, no need to send via function
arr[index_of_array_elements].base = base_divisor;//fill array here, no need to send via function
}
else //If remainder is not zero then base_divisor will be increase by 1.
{
base_divisor++;
}
//REMOVED for simplification of example (Not needed)
// calling the function to insert element in array
//insert_element(&factor_array[50], &base_divisor, &index_of_array_elements);
//insert_element(&factor_array, &base_divisor, &index_of_array_elements);
}
//i dont know why i did this but error is not caused by this.
for(i = 0;i < index_of_array_elements-1; i++)//putting into loop so all populated element of array are output
{
printf("quotient:%lld\nfactor:%lld\n", factor_array[i].quotient,factor_array[i].factor);//using %d for int
}
printf("base divisor:%lld\nfactor and quotient:%lld\nfactor:%lld\n", factor_array[i].base, factor_array[i].quotient,factor_array[i].factor);//using %d for int
}
int main(void)//this is a minumum signature for main. Anything less is not portable.
{
long long number = 0; //allows larger values up to 9223372036854775807 (LLONG_MAX)
//int factor_array[50] = {0};
size_t size = sizeof factor_array/sizeof *factor_array;
printf("\nPROGRAME TO FIND [prime] FACTORS OF GIVEN NUMBER\n\n");
printf("Enter the number to find factor...\n");
scanf("%lld", &number);//format specifier changed to accomodate larger type
factors(number, size, factor_array);//factor_array contains all the results here,
// so prinf could be used here if index were
// also passed as argument
return 0;//int main(void) requires this statement
}
Example run for value: 1234567890: (multiply all factors to test for input)
| |
doc_23531946
|
what is the output for the following code snippet?
printf(3+"Welcome"+2);
the answer I got is me (by executing it in TC++)
But I can't get the actual mechanism.
please explain me the actual mechanism behind it.
A: It's called pointer arithmetic: 2+3=5, and "me" is the rest of the string starting at offset 5.
PS: throw away that book.
A: When this is compiled the "Welcome" string becomes a const char *, pointing to the first character of the string. In C, with character strings (like any pointer), you can do pointer arithmetic. This means pointer + 5 points to 5 places beyond pointer.
Therefore ("Welcome" + 5) will point 5 characters past the "W", to the substring "me."
On a side note, as other have suggested, this doesn't sound like a good book.
A: A string (like "Welcome") is an array of characters terminated by the NUL-character (so it's actually "Welcome\0").
What you are doing, is accessing the fifth character of it (3 + 2 = 5). This character is 'm' (array indices start at 0).
printf will continue to read till it hits the NUL-character.
| |
doc_23531947
|
I'm making a custom scrollbar with css but as you can see in the picture the corner of the scrollbar track isn't like what I need, I have tried border radius for bottom right and top right but no luck, any help would be appreciated!
::-webkit-scrollbar-thumb {
background: url("/assets/scrollbar.png") no-repeat;
background-size: 9px 150px;
display: block;
}
::-webkit-scrollbar-track-piece {
background: grey;
}
A: Try using the perspective property of css to rotate it according to the picture on the right.
This code will help you to understand.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.div1{
border: 1px solid blue;
height: 200px;
width: 200px;
perspective: 200px; /* Defines how far the object is */
}
.div2{
transform-style: preserve-3d; /* Rotatingthe div as a 3d object */
transform: rotateY(45deg);
height: 60%;
display: flex; /* Flexbox for centering the text */
align-items: center;
justify-content: center;
background-color: grey;
}
</style>
<body>
<div class="div1">
Div 1
<div class="div2">
Div 2
</div>
</div>
</body>
</html>
I hope you understood. Check out this link for more. Please feel free to ask in the comments if you need more explanation.
A: Thanks to a guy in my team, we managed to solve the issue by adding the background to webkit scrollbar track.
| |
doc_23531948
|
I used
SELECT CITY
FROM STATION
MINUS
SELECT DISTINCT CITY
FROM STATION;
Should I use count() to get the number of the elements in each column or does MINUS automatically get the numbers?
BTW the code didn't work as an answer even when I used count().
The link:
https://www.hackerrank.com/challenges/weather-observation-station-4/problem
A: Your query does not do what you want. MINUS is a set-based operator, while what you need is aggregation. Here, you can take the difference between COUNT(*) (that's the total number of rows in the table) and COUNT(DISTINCT city) (that's the count of distinct values in column city):
select count(*) - count(distinct city) result
from station
| |
doc_23531949
|
Calling the delete function:
main() {
HttpClient httpClient = new HttpClient();
httpClient.delete( '35.186.145.243', 8080, '/users');
httpClient.close();
return "Success";
}
Parameters that need to be passed in are:
*
*String user_id
*String price
JSON array:
{
"user_id": "user2",
"price": "$34"
}
A: Found out the answer using HTTP client request when using delete on body method!
main() async {
String url = "http://35.186.145.243:8080/users";
Map map = {
'price': '$34',
'user_id': 'user2'
};
print(await apiRequest(url, map));
}
Future<String> apiRequest(String url, Map jsonMap) async {
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.deleteUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(jsonMap)));
HttpClientResponse response = await request.close();
String statusCode = response.statusCode.toString();
String reply = await response.transform(utf8.decoder).join();
responseMessage = statusCode;
print(statusCode);
httpClient.close();
return reply;
}
A: I recently had the same problem and the only way to Solve it was to use http client :
Future<String> apiRequest() async {
Map<String, dynamic> Object;
Object= {
'price': '$34',
'user_id': 'user2'
};
final client = http.Client();
try {
final response = await client.send(http.Request("DELETE", Uri.parse("35.186.145.243:8080"))
..headers["Content-Type"] = "application/json"
..body = json.encode(Object));
} catch (e) {
print(e);
} finally {
client.close();
}
}
| |
doc_23531950
|
The resulting XML signature should have the following format:
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
<SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
<Reference URI="">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
<DigestValue>DsP5NLca+plhp9tZvGwykfb2whQYt3CQ5sbsVd9Q9aE=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>
LrfE0po3YPvVxB/m77iBWWiR07Ghiuhuj7tO2C2LKqZK2cLrAiidt+3tjbJ3m16quCFxfh7bmjRtJsGi7a3HKtK
qY4auqrjNB62AtYrxvm+7Qd/cRacom4e3M9uF9JD1zTfoGun9w4WDfDrDaoZ+ZwUgNtf6sTYO5Ctcj5sYcD0=
</SignatureValue>
<KeyInfo>
<KeyName>7D665C81ABBE1A7D0E525BFC171F04D276F07BF2</KeyName>
</KeyInfo>
</Signature>
Can anyone provide some help with code ??
Edit:
i came up with this code :
private static Document sign(Document doc) throws InstantiationException, IllegalAccessException, ClassNotFoundException,
NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException,
FileNotFoundException, TransformerException {
String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance());
Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA256, null));
// Create the SignedInfo
SignedInfo si = fac.newSignedInfo(
fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null),
fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(512);
KeyPair kp = kpg.generateKeyPair();
KeyInfoFactory kif = fac.getKeyInfoFactory();
KeyValue kv = kif.newKeyValue(kp.getPublic());
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement());
XMLSignature signature = fac.newXMLSignature(si, ki);
signature.sign(dsc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
trans.transform(new DOMSource(doc), new StreamResult(new FileOutputStream("mySignedFile")));
return doc;
}
but the Problem is i am getting :
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
and not :
<SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
A: Here is the solution:
i find it on this link
http://mail-archives.apache.org/mod_mbox/santuario-dev/200907.mbox/%3C4A704241.9060806@sun.com%3E
the problem was RSA-SHA256 Algorithm :
here is the resulting code :
private static Document sign(Document doc) throws InstantiationException, IllegalAccessException, ClassNotFoundException,
NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException,
FileNotFoundException, TransformerException {
String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance());
DigestMethod digestMethod = fac.newDigestMethod(DigestMethod.SHA256, null);
Transform transform = fac.newTransform(ENVELOPED, (TransformParameterSpec) null);
Reference reference = fac.newReference("", digestMethod, singletonList(transform), null, null);
SignatureMethod signatureMethod = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", null);
CanonicalizationMethod canonicalizationMethod = fac.newCanonicalizationMethod(EXCLUSIVE, (C14NMethodParameterSpec) null);
// Create the SignedInfo
SignedInfo si = fac.newSignedInfo(canonicalizationMethod, signatureMethod, singletonList(reference));
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.generateKeyPair();
KeyInfoFactory kif = fac.getKeyInfoFactory();
KeyValue kv = kif.newKeyValue(kp.getPublic());
// Create a KeyInfo and add the KeyValue to it
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement());
XMLSignature signature = fac.newXMLSignature(si, ki);
signature.sign(dsc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
// output the resulting document
OutputStream os;
os = new FileOutputStream("xmlOut.xml");
trans.transform(new DOMSource(doc), new StreamResult(os));
return doc;
}
A: You got <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>, because that's what you asked for: fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null).
As you figured out and https://blogs.oracle.com/mullan/entry/using_stronger_xml_signature_algorithms states, fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", (SignatureMethodParameterSpec) null) will get you <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />.
A: These are standard XML-Signatures. See the W3 Documentation on "XML-Signature Syntax and Processing" for the specification how this can be done. A quick search on google lead to this howto written by Oracle on the integration of XML Signatures in Java: XML Digital Signature API. If you have any further problems, please shows us what you have tried.
| |
doc_23531951
|
Before rails 3 internet tells me that you must do :
<%= link_to "my text"+image_tag("image.jpg"), {:controller=>:billets}, :class => 'link_to_blog'%>
However in rails 3 i have the code of the image displayerd in my web page instead of the image. Seems now, it escape the html code.
How can i do a link_to with text and image in rails 3?
A: <%= link_to ("my text"+image_tag("image.jpg")).html_safe, {:controller=>:billets}, :class => 'link_to_blog'%>
Or
<%= link_to {:controller => :billets}, :class => 'link_to_blog' do %>
My text
<%= image_tag "image.jpg" %>
<% end %>
| |
doc_23531952
|
Is there any alternative for the below code in Struts2, I am using this in my Action classes.
String path = mapping.findForward("failurePath").getPath();
new ActionForward(path);
A: You can directly use in struts.xml
<result name="resultName" type="redirect" >failurePath.action?param1=${value1}¶m2={value2}</result>
You need to have setter and getter methods for value1 and value2 oin action class
| |
doc_23531953
|
resources :product do
resources :sales
end
Where Sale belongs_to Product, and a Sale instance can not exist without a product.
I can use link_to + @product to directly link to a product:
<%= link_to @product.name, @product %>
That produces
<a href="/products/3">Strawberry Jam</a>
If I want to do something similar for a sale, however, I can not use a @sale alone. I must involve the product. This won't work:
<%= link_to @sale.date, @sale %>
I must use something like this:
<%= link_to @sale.date, [@sale.product, @sale] %>
The first case won't work because sale_path is not defined (only product_sale_path is).
My question is: Can I add something to the Sale model so that link_to (or url_for) automatically adds the "parent" (the product, in this case) when generating the url?
I have tried looking at the implementation of url_for and I think I could do that by monkeypatching HelperMethodBuilder.url.handle_model_call, but I would rather not do that if there is another way.
A: Using shallow nesting might help:
resources :product do
resources :sales, shallow: true
end
Have a look at section 2.7.2 of the
Rails Routing guide.
A: Would using shallow routes avoid your problem by exposing direct urls to the nested resource?
resources :products do
resources :sales, only: [:index, :new, :create]
end
resources :sales, only: [:show, :edit, :update, :destroy]
Now link_to @sale will work, you only need to involve the product for index, new, create.
http://guides.rubyonrails.org/routing.html#nested-resources (scroll down to shallow nesting)
A: link_to @sale.date product_sale_path(@sale.product, @sale)
Or
link_to @sale.date product_sale_path(@sale.product_id, @sale)
Will link to the /products/:product_id/sales/:id path.
I am guessing a product can have more than one sale. To link to the index action you only need the product.
link_to product_sales_path(@sale.product)
| |
doc_23531954
|
Description:
The bean 'studentService' could not be injected as a
'com.student.service.StudentServiceImpl' because it is a JDK dynamic
proxy that implements: com.student.service.StudentService
Sample code:
@Service("studentService")
@Transactional(readOnly=false)
public class StudentServiceImpl implements StudentService {
}
public interface StudentService {
}
Action:
Consider injecting the bean as one of its interfaces or forcing the use of CGLib-based proxies by setting proxyTargetClass=true on @EnableAsync and/or @EnableCaching.
Process finished with exit code 1
What is causing this?
A: As SO already mentioned on the comment, the error occurs when you are trying to inject/autowire the implementation class instead of interface.
The bean 'studentService' could not be injected as a
'com.student.service.StudentServiceImpl' because it is a JDK dynamic
proxy that implements: com.student.service.StudentService
On the setup posted by SO,
public class StudentServiceImpl implements StudentService {
}
public interface StudentService {
}
If you autowire the interface as below you won't get an error:
@Autowired //or @Inject
StudentService studentService;
A: In your application class file add this:
@SpringBootApplication
@EnableCaching(proxyTargetClass = true)
A: in spring boot projects, try to add :
spring.aop.proxy-target-class=true
to your application.properties
OR
@EnableAspectJAutoProxy(proxyTargetClass = true)
to your spring boot entry point.
A: I had similar problem and resolved in this way
| |
doc_23531955
|
say I have 9 and 10 , then I want it to be 910, or 224 and 225 then I want it to be 224225.
A: You (likely) want string concatenation (you may also want an integer result, if that is the case, see the other answers). If this is true, about the concatenation, imagine a and b are integers:
"" + a + b
This works because the + operator is overloaded if either operand is a String. It then converts the other operand to a string (if needed) and results in a new concatenated string. You could also invoke Integer.toString(a) + Integer.toString(b) or using an appropriate String.format but those methods are more long-winded.
A: Here is my version which works when a,b >= 0.
It is a bit longer, but is 10x faster than the log approach and 5x faster than appending strings.
int concat(int a, int b)
{
if ( b == 0 )
a *= 10;
else
{
int tempB = b;
while ( tempB > 0 )
{
tempB /= 10;
a *= 10;
}
}
return a + b;
}
Feel free to modify this to work for negative numbers.
A: Anything in java.lang.* should be fair game...
int a = Integer.parseInt(Integer.toString(9) + Integer.toString(10));
Addendum:
I do not like the following the syntax because the operator overloading doesn't declare intent as clearly as the above. Mainly because if the empty string is mistakenly taken out, the result is different.
int a = Integer.parseInt(9 + "" + 10);
A: This will give you an integer back as expected but only works when b > 0.
int a = 224;
int b = 225;
int c = (int) Math.pow(10, Math.floor(Math.log10(b))+1)*a + b; // 224225
Just a quick explanation: This determines the number of digits in b, then computes a multiplication factor for a such that it would move in base 10 by one more digit than b.
In this example, b has 3 digits, floor(log10(b)) returns 2 (do this intuitively as 10^2=100, 10^3 = 1000, we're somewhere in between at 225). Then we compute a multiplication factor of 10^(2+1), this is 1000. When we multiply a by 1000 we get 224000. Adding 224000 to 225 yields the desired 224225.
This fails at b == 0 because log10(0) is undefined.
A: a + "" + b
results in error "incompatible types"
// The left operand to previousOperator.
private int leftOperand;
leftOperand = leftOperand + " " + number;
number is defined as int in the method declaration
This works
import java.lang.*
leftOperand = Integer.parseInt(Integer.toString(leftOperand) + Integer.toString(number));
| |
doc_23531956
|
It works fine in Chrome and Mozilla.
Angular Version: 1.2.29
Broken URL used: http://@gmail.com
Error
Error: A security problem occurred.
at xa
(http://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js:124:230)
at Anonymous function
(http://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js:116:319)
at Anonymous function
(http://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular-sanitize.js:145:9)
at Anonymous function
(http://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular-sanitize.js:461:11)
at r
(http://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js:7:390)
at start
(http://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular-sanitize.js:458:9)
at parseStartTag
(http://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular-sanitize.js:363:24)
at htmlParser
(http://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular-sanitize.js:293:13)
at Anonymous function
(http://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular-sanitize.js:144:7)
at Anonymous function
(http://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular-sa
Is there any workaround for this?
| |
doc_23531957
|
I want to use one of the properties on the typeahead result to populate my custom directive.
eg:
<something content='typeaheadResult.id'></something>
However it doesnt seem to update when the result is populated. I think this may be because typeaheadResult doesnt have an id property until the value is selected.
How can i bind using a subpropery of the result?
I have tried a few things such as using a computed value as an intermediate but nothing seems to work.
eg:
scope.resultId = function(){
return typeaheadResult !== undefined ? typeaheadResult.id : '';
}
the directive works fine with non-typeahead scope values.
plnkr: http://plnkr.co/edit/IKIMkeTQnbUJG3aUnT1s
| |
doc_23531958
|
e.g. db structure
| video_id | video_title | actor_ids |
1 Elia 3;4;5;6
2 Avatar 4;8;9;23
I want to select every row who has the actor_ids=4. I use the follow query in my mysql workbench which works OK for this situation
SELECT * FROM `videos` WHERE `video_actor_ids` REGEXP 4;
I would like to translate this query to a ZF2 query. I just need how to
translate it to a where clause. Can't find anything about REGEXP in the documentation.
Other solutions to do this select are (with better performance) are welcome too!
Thanks in advance,
nick
A: The first thing that comes to my mind when I see something like "3;4;5;6" is not REGEXP, but normalization. I am convinced that you should rethink the way you handle your relations. In this particular case it is many-to-many type of relation. Do yourself a favour: get rid of the "3;4;5;6" as soon as possible.
| |
doc_23531959
|
following what i have tried
$jsonarr = $_POST['ImageArr'];
$decodedjson = json_decode($jsonarr,TRUE);
for( $i=0; $i < count($decodedjson); $i++ ) {
$destdir ="uploads/".$image_unique_no;
$img = file_get_contents($decodedjson[$i]);
file_put_contents( $destdir.substr( $decodedjson[$i], strrpos($decodedjson[$i],'/')), $img);
}
A: <?php
$filesArray = $_FILES['ImageArr'];
$file_count = count($filesArray['name']);
for ($i=0; $i< $file_count; $i++)
{
move_uploaded_file($filesArray['tmp_name'][$i], "upload/".time()."_".$filesArray['name'][$i]);
}
?>
get images array posted from android device.
| |
doc_23531960
|
As for as i have searched and tried to solve the issue, i have concluded that this report gets all the subjects offered for exam in an exam session. i have to compare the subjects offered in exam session with the subjects each student had enrolled, if both are same, those should be printed on the Hall Ticket of the student.
Please help me comparing the subject fields in two models; op.exam.session (exam_session) and op.student.course (op_student_course) and in conditionally printing the subjects.
Thanx in advance.
my .py file is as under:
import time
from odoo import models, fields, api
class ReportTicket(models.AbstractModel):
_name = "report.openeducat_exam.report_ticket"
_description = "Exam Ticket Report"
def get_date(self, exam_line):
timestamp = fields.Datetime.context_timestamp
dt = fields.Datetime
schedule_start = timestamp(self, dt.from_string(exam_line.start_time))
schedule_end = timestamp(self, dt.from_string(exam_line.end_time))
schedule_start = fields.Datetime.to_string(schedule_start)
schedule_end = fields.Datetime.to_string(schedule_end)
return schedule_start[11:] + ' To ' + schedule_end[11:]
def get_subject(self, exam_session):
lst = []
for exam_line in exam_session['exam_ids']:
res1 = {
'subject': exam_line.subject_id.name,
'date': fields.Datetime.to_string(exam_line.start_time)[:10],
'time': self.get_date(exam_line),
'sup_sign': ''
}
lst.append(res1)
return lst
def get_data(self, data):
final_lst = []
exam_session = self.env['op.exam.session'].browse(
data['exam_session_id'][0])
student_search = self.env['op.student'].search(
[('course_detail_ids.course_id', '=', exam_session.course_id.id)])
for student in student_search:
student_course = self.env['op.student.course'].search(
[('student_id', '=', student.id),
('course_id', '=', exam_session.course_id.id)])
res = {
'exam': exam_session.name,
'exam_code': exam_session.exam_code,
'course': exam_session.course_id.name,
'student': student.name,
'image': student.image_1920,
'roll_number': student_course.roll_number,
'line': self.get_subject(exam_session),
}
final_lst.append(res)
return final_lst
@api.model
def _get_report_values(self, docids, data=None):
model = self.env.context.get('active_model')
docs = self.env[model].browse(self.env.context.get('active_id'))
docargs = {
'doc_ids': self.ids,
'doc_model': model,
'docs': docs,
'time': time,
'get_data': self.get_data(data),
}
return docargs
I am looking for Something like this:
def get_subject(self, exam_session):
lst = []
for exam_line in exam_session['exam_ids']:
res1 = {
'subject': exam_line.subject_id.name,
'date':
fields.Datetime.to_string(exam_line.start_time)[:10],
'time': self.get_date(exam_line),
'sup_sign': ''
}
If exam_line.subject_id.name ==
course_detail_ids.subject_id.name:
lst.append(res1)
return lst
But it gives error that object 'course _detail_id' not defined.
A: Please be informed that the error comes because inside the function you are not defined the variable course_detail_ids. I think you are trying to compare exam_line.subject_id.name with exam_session.course_id.name
| |
doc_23531961
|
hg vdiff
and then kdiff3 will come out saying there are 5 files that got modified in the project tree, and then I can go to menu bar to "Expand Directories" and see the files that have diffs, and click on each of them.
To my surprise, TortoiseSVN doesn't seem to have this function. When I look at the project folder, and right click for TortoiseSVN, the usual "Diff" action is missing from the menu bar. Is there a way to make it work like hg vdiff?
A: You can open the commit dialog (by selecting Commit in the context menu) to get a list of all files which were modified locally. Then, by double-clicking a file you can see the changes made in that file.
A: The action in the TortoiseSVN menu is called "SVN Check for modifications".
| |
doc_23531962
|
String Dategm = intent.getStringExtra("Date");
String glucose = intent.getStringExtra("Glucose");
if (Dategm != null) {
String[] ss = Dategm.split("~");
String[] aa = glucose.split("~");
for (int i = 0; i < ss.length; i++) {
x_gm.add(Long.toString(i));
y_gm.add(aa[i]);
}
System.out.println("size::" + x_gm.size());
StaticLabelsFormatter staticLabelsFormatter3 = new StaticLabelsFormatter(graphView3);
staticLabelsFormatter3.setHorizontalLabels(ss);
graphView3.getGridLabelRenderer().setLabelFormatter(staticLabelsFormatter3);
LineGraphSeries<DataPoint> series3 = new LineGraphSeries<>(Gluco());
graphView3.addSeries(series3);
series3.setColor(Color.RED);
series3.setThickness(6);
series3.setDrawBackground(true);
series3.setDrawDataPoints(true);
series3.setDataPointsRadius(7);
}
public DataPoint[] Gluco(){
int n=x_gm.size(); //to find out the no. of data-points
DataPoint[] values = new DataPoint[n]; //creating an object of type
DataPoint[] of size 'n'
for(int i=0;i<n;i++){
DataPoint v = newDataPoint(Double.parseDouble(x_gm.get(i)),Double.parseDouble(y_gm.get(i)));
values[i] = v;
}
return values;
}
| |
doc_23531963
|
echo $P4_TICKET > $P4TICKETS
Actual result : Unexpected exception while loading target: Perforce password (P4PASSWD) invalid or unset.
Expected : perforce tickets should be used from jenkins . Here i am trying to copy to my environment variable $P4TICKETS
A: *
*Is your $P4TICKETS variable actually set to the name of a file?
*Does the $P4_TICKET value set by Jenkins actually match the expected format of that file?
The $P4TICKETS value isn't necessarily set within any given client environment, so that's the first thing to check. The client will assume a default tickets file name of ~/.p4tickets, but the shell doesn't know that it should use that value for the environment variable $P4TICKETS.
The .p4tickets file contains potentially multiple tickets indexed by user/port; if Jenkins's $P4_TICKET value is just the ticket (like you'd get from p4 login -p), it won't be recognized if you just dump it into a ticket file (because the client won't know what connection it goes with).
A: P4_TICKET is just the ticket value for the credential that your jenkins' job has.
Here i am trying to copy to my environment variable $P4TICKETS
As Sam mentioned, your tickets file ($P4TICKETS) needs the server's addr and user along with the ticket value. The "p4 plugin" does not expose the server's addr so you will not be able to write out a valid row within your tickets file.
As to your question, "Trying to automate login in jenkins", I don't understand what you need to do. A "Perforce password credential" will login for you. Please give more detail.
A: Thank you Sam Stafford and J Brown. You both were right. P4TICKETS was unable to find just by ticket hash. I had to include P4PORT, P4USER and Tickets to ~/.p4tickets and then enable "ALL HOSTS" under users credentials with whom i was logging into to jenkins. This made me to login and continue
Thank you:)
| |
doc_23531964
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.datasets import MNISTSuperpixels
import torch_geometric.transforms as T
from torch_geometric.data import DataLoader
from torch_geometric.utils import normalized_cut
from torch_geometric.nn import (NNConv, graclus, max_pool, max_pool_x, global_mean_pool)
path = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', 'MNIST')
transform = T.Cartesian(cat=False)
train_dataset = MNISTSuperpixels(path, True, transform=transform)
test_dataset = MNISTSuperpixels(path, False, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)
d = train_dataset
I'm trying to use MNISTSuperpixels data for graph convolution, but I have some troubles using the example code.
Most of scripts were using
path = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', 'MNIST')
However, they gave me an error
NameError: name '__file__' is not defined and I don't understand what osp.realpath(__file__) really means.
I'm using Jupyter notebook on Ubuntu, and my working directory is
print(os.getcwd())
/home/hkimlx/GDL/pytorch_geometric/examples
which is the same directory where the sample code mnist_nn_conv.py is located.
Please help me. Thanks!
A: In notebook, you need to use double quoted "__file__" as in osp.realpath("__file__") instead of osp.realpath(__file__)
Sourced from: https://queirozf.com/entries/python-working-with-paths-the-filesystem#-nameerror-name-'file'-is-not-defined
A: Per the documentation
__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute may be missing
for certain types of modules, such as C modules that are statically
linked into the interpreter; for extension modules loaded dynamically
from a shared library, it is the pathname of the shared library file.
According the answer you can't get the path of a notebook pragrammatically. Use os.getcwd() as a workaround.
| |
doc_23531965
|
I recently changed a simple boolean parameter of a method call, and everything stopped working. It seems to not be related to my recent code change at all:
Full error message below, but first, here is the last "Caused by" line:
Caused by: com.bea.xml.XmlException: failed to load java type corresponding to
e=persistence@http://xmlns.jcp.org/xml/ns/persistence
The web adress works, and I am online. Other searches for similar error messages implies that there are some mismatches in my JPA and/or Eclipselink versions. Also, there micht be problems with my persistence.xml, but that seems to be a consequence the "failed to load java type...".
My project is an old one, first derived from a maven archetype. I have been working on improvements and upgrades for this project for a long time, and just recently this error appeared. Other answers tells me to check my JPA and/or eclipselink jar versions. I've found my eclipselink reference (see picture), but this is an automatically imported library, which I haven't touched. I am afraid I might corrupt my project setup if I start to mess around with this on my own.
How can I proceed to figure out specifically what my problem is, and how I can fix it? The only thing I can think of, is that I have renamed my project, in the pom, war etc, and that there might be a mismatch between the old project name, and the new one. The thing is, I did this several weeks ago, and everything has worked fine after that.
setup:
Full error message:
<14-01-2016 13:35:53 CET> <Error> <J2EE> <BEA-160197> <Unable to load descriptor weblogic.utils.classloaders.GenericClassLoader@17da690 finder: weblogic.utils.classloaders.CodeGenClassFinder@11803fb annotation: test-booking@/WEB-INF/lib/_wl_cls_gen.jar!/META-INF/persistence.xml of module test-booking.war. The error is weblogic.descriptor.DescriptorException: Unmarshaller failed
at weblogic.descriptor.internal.MarshallerFactory$1.createDescriptor(MarshallerFactory.java:161)
at weblogic.descriptor.BasicDescriptorManager.createDescriptor(BasicDescriptorManager.java:323)
at weblogic.application.descriptor.AbstractDescriptorLoader2.getDescriptorBeanFromReader(AbstractDescriptorLoader2.java:788)
at weblogic.application.descriptor.AbstractDescriptorLoader2.createDescriptorBean(AbstractDescriptorLoader2.java:411)
at weblogic.application.descriptor.AbstractDescriptorLoader2.loadDescriptorBeanWithoutPlan(AbstractDescriptorLoader2.java:759)
at weblogic.application.descriptor.AbstractDescriptorLoader2.loadDescriptorBean(AbstractDescriptorLoader2.java:768)
at weblogic.deployment.AbstractPersistenceUnitRegistry.loadPersistenceDescriptor(AbstractPersistenceUnitRegistry.java:177)
at weblogic.deployment.AbstractPersistenceUnitRegistry.loadPersistenceDescriptors(AbstractPersistenceUnitRegistry.java:101)
at weblogic.deployment.ModulePersistenceUnitRegistry.<init>(ModulePersistenceUnitRegistry.java:58)
at weblogic.servlet.internal.WebAppModule.setupPersistenceUnitRegistry(WebAppModule.java:1697)
at weblogic.servlet.internal.WebAppModule.getWebClassLoader(WebAppModule.java:1489)
at weblogic.servlet.internal.WebAppServletContext.initClassLoader(WebAppServletContext.java:2890)
at weblogic.servlet.internal.WebAppServletContext.<init>(WebAppServletContext.java:420)
at weblogic.servlet.internal.WebAppServletContext.<init>(WebAppServletContext.java:466)
at weblogic.servlet.internal.HttpServer.loadWebApp(HttpServer.java:414)
at weblogic.servlet.internal.WebAppModule.registerWebApp(WebAppModule.java:924)
at weblogic.servlet.internal.WebAppModule.prepare(WebAppModule.java:356)
at weblogic.application.internal.flow.ScopedModuleDriver.prepare(ScopedModuleDriver.java:176)
at weblogic.application.internal.flow.ModuleListenerInvoker.prepare(ModuleListenerInvoker.java:199)
at weblogic.application.internal.flow.DeploymentCallbackFlow$1.next(DeploymentCallbackFlow.java:391)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:83)
at weblogic.application.internal.flow.DeploymentCallbackFlow.prepare(DeploymentCallbackFlow.java:59)
at weblogic.application.internal.flow.DeploymentCallbackFlow.prepare(DeploymentCallbackFlow.java:43)
at weblogic.application.internal.BaseDeployment$1.next(BaseDeployment.java:1221)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:83)
at weblogic.application.internal.BaseDeployment.prepare(BaseDeployment.java:367)
at weblogic.application.internal.SingleModuleDeployment.prepare(SingleModuleDeployment.java:39)
at weblogic.application.internal.DeploymentStateChecker.prepare(DeploymentStateChecker.java:154)
at weblogic.deploy.internal.targetserver.AppContainerInvoker.prepare(AppContainerInvoker.java:60)
at weblogic.deploy.internal.targetserver.AppDeployment.prepare(AppDeployment.java:141)
at weblogic.management.deploy.internal.DeploymentAdapter$1.doPrepare(DeploymentAdapter.java:39)
at weblogic.management.deploy.internal.DeploymentAdapter.prepare(DeploymentAdapter.java:187)
at weblogic.management.deploy.internal.AppTransition$1.transitionApp(AppTransition.java:21)
at weblogic.management.deploy.internal.ConfiguredDeployments.transitionApps(ConfiguredDeployments.java:233)
at weblogic.management.deploy.internal.ConfiguredDeployments.prepare(ConfiguredDeployments.java:165)
at weblogic.management.deploy.internal.ConfiguredDeployments.deploy(ConfiguredDeployments.java:122)
at weblogic.management.deploy.internal.DeploymentServerService.resume(DeploymentServerService.java:173)
at weblogic.management.deploy.internal.DeploymentServerService.start(DeploymentServerService.java:89)
at weblogic.t3.srvr.SubsystemRequest.run(SubsystemRequest.java:64)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)
Caused by: com.bea.xml.XmlException: failed to load java type corresponding to e=persistence@http://xmlns.jcp.org/xml/ns/persistence
at com.bea.staxb.runtime.internal.UnmarshalResult.getPojoBindingType(UnmarshalResult.java:371)
at com.bea.staxb.runtime.internal.UnmarshalResult.determineTypeForGlobalElement(UnmarshalResult.java:326)
at com.bea.staxb.runtime.internal.UnmarshalResult.determineTypeForGlobalElement(UnmarshalResult.java:336)
at com.bea.staxb.runtime.internal.UnmarshalResult.determineRootType(UnmarshalResult.java:317)
at com.bea.staxb.runtime.internal.UnmarshalResult.unmarshalDocument(UnmarshalResult.java:168)
at com.bea.staxb.runtime.internal.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:65)
at weblogic.descriptor.internal.MarshallerFactory$1.createDescriptor(MarshallerFactory.java:150)
... 40 more
.>
<14-01-2016 13:35:53 CET> <Error> <Deployer> <BEA-149205> <Failed to initialize the application 'test-booking' due to error weblogic.application.ModuleException: Failed to load webapp: 'test-booking.war'.
weblogic.application.ModuleException: Failed to load webapp: 'test-booking.war'
at weblogic.servlet.internal.WebAppModule.prepare(WebAppModule.java:378)
at weblogic.application.internal.flow.ScopedModuleDriver.prepare(ScopedModuleDriver.java:176)
at weblogic.application.internal.flow.ModuleListenerInvoker.prepare(ModuleListenerInvoker.java:199)
at weblogic.application.internal.flow.DeploymentCallbackFlow$1.next(DeploymentCallbackFlow.java:391)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:83)
Truncated. see log file for complete stacktrace
Caused By: weblogic.deployment.EnvironmentException: Error loading the persistence descriptor WEB-INF/lib/_wl_cls_gen.jar!/META-INF/persistence.xml from the module test-booking.war. See the following stack trace for nested errors: weblogic.descriptor.DescriptorException: Unmarshaller failed
at weblogic.descriptor.internal.MarshallerFactory$1.createDescriptor(MarshallerFactory.java:161)
at weblogic.descriptor.BasicDescriptorManager.createDescriptor(BasicDescriptorManager.java:323)
at weblogic.application.descriptor.AbstractDescriptorLoader2.getDescriptorBeanFromReader(AbstractDescriptorLoader2.java:788)
at weblogic.application.descriptor.AbstractDescriptorLoader2.createDescriptorBean(AbstractDescriptorLoader2.java:411)
at weblogic.application.descriptor.AbstractDescriptorLoader2.loadDescriptorBeanWithoutPlan(AbstractDescriptorLoader2.java:759)
at weblogic.application.descriptor.AbstractDescriptorLoader2.loadDescriptorBean(AbstractDescriptorLoader2.java:768)
at weblogic.deployment.AbstractPersistenceUnitRegistry.loadPersistenceDescriptor(AbstractPersistenceUnitRegistry.java:177)
at weblogic.deployment.AbstractPersistenceUnitRegistry.loadPersistenceDescriptors(AbstractPersistenceUnitRegistry.java:101)
at weblogic.deployment.ModulePersistenceUnitRegistry.<init>(ModulePersistenceUnitRegistry.java:58)
at weblogic.servlet.internal.WebAppModule.setupPersistenceUnitRegistry(WebAppModule.java:1697)
at weblogic.servlet.internal.WebAppModule.getWebClassLoader(WebAppModule.java:1489)
at weblogic.servlet.internal.WebAppServletContext.initClassLoader(WebAppServletContext.java:2890)
at weblogic.servlet.internal.WebAppServletContext.<init>(WebAppServletContext.java:420)
at weblogic.servlet.internal.WebAppServletContext.<init>(WebAppServletContext.java:466)
at weblogic.servlet.internal.HttpServer.loadWebApp(HttpServer.java:414)
at weblogic.servlet.internal.WebAppModule.registerWebApp(WebAppModule.java:924)
at weblogic.servlet.internal.WebAppModule.prepare(WebAppModule.java:356)
at weblogic.application.internal.flow.ScopedModuleDriver.prepare(ScopedModuleDriver.java:176)
at weblogic.application.internal.flow.ModuleListenerInvoker.prepare(ModuleListenerInvoker.java:199)
at weblogic.application.internal.flow.DeploymentCallbackFlow$1.next(DeploymentCallbackFlow.java:391)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:83)
at weblogic.application.internal.flow.DeploymentCallbackFlow.prepare(DeploymentCallbackFlow.java:59)
at weblogic.application.internal.flow.DeploymentCallbackFlow.prepare(DeploymentCallbackFlow.java:43)
at weblogic.application.internal.BaseDeployment$1.next(BaseDeployment.java:1221)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:83)
at weblogic.application.internal.BaseDeployment.prepare(BaseDeployment.java:367)
at weblogic.application.internal.SingleModuleDeployment.prepare(SingleModuleDeployment.java:39)
at weblogic.application.internal.DeploymentStateChecker.prepare(DeploymentStateChecker.java:154)
at weblogic.deploy.internal.targetserver.AppContainerInvoker.prepare(AppContainerInvoker.java:60)
at weblogic.deploy.internal.targetserver.AppDeployment.prepare(AppDeployment.java:141)
at weblogic.management.deploy.internal.DeploymentAdapter$1.doPrepare(DeploymentAdapter.java:39)
at weblogic.management.deploy.internal.DeploymentAdapter.prepare(DeploymentAdapter.java:187)
at weblogic.management.deploy.internal.AppTransition$1.transitionApp(AppTransition.java:21)
at weblogic.management.deploy.internal.ConfiguredDeployments.transitionApps(ConfiguredDeployments.java:233)
at weblogic.management.deploy.internal.ConfiguredDeployments.prepare(ConfiguredDeployments.java:165)
at weblogic.management.deploy.internal.ConfiguredDeployments.deploy(ConfiguredDeployments.java:122)
at weblogic.management.deploy.internal.DeploymentServerService.resume(DeploymentServerService.java:173)
at weblogic.management.deploy.internal.DeploymentServerService.start(DeploymentServerService.java:89)
at weblogic.t3.srvr.SubsystemRequest.run(SubsystemRequest.java:64)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)
Caused by: com.bea.xml.XmlException: failed to load java type corresponding to e=persistence@http://xmlns.jcp.org/xml/ns/persistence
at com.bea.staxb.runtime.internal.UnmarshalResult.getPojoBindingType(UnmarshalResult.java:371)
at com.bea.staxb.runtime.internal.UnmarshalResult.determineTypeForGlobalElement(UnmarshalResult.java:326)
at com.bea.staxb.runtime.internal.UnmarshalResult.determineTypeForGlobalElement(UnmarshalResult.java:336)
at com.bea.staxb.runtime.internal.UnmarshalResult.determineRootType(UnmarshalResult.java:317)
at com.bea.staxb.runtime.internal.UnmarshalResult.unmarshalDocument(UnmarshalResult.java:168)
at com.bea.staxb.runtime.internal.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:65)
at weblogic.descriptor.internal.MarshallerFactory$1.createDescriptor(MarshallerFactory.java:150)
... 40 more
at weblogic.deployment.AbstractPersistenceUnitRegistry.loadPersistenceDescriptor(AbstractPersistenceUnitRegistry.java:179)
at weblogic.deployment.AbstractPersistenceUnitRegistry.loadPersistenceDescriptors(AbstractPersistenceUnitRegistry.java:101)
at weblogic.deployment.ModulePersistenceUnitRegistry.<init>(ModulePersistenceUnitRegistry.java:58)
at weblogic.servlet.internal.WebAppModule.setupPersistenceUnitRegistry(WebAppModule.java:1697)
at weblogic.servlet.internal.WebAppModule.getWebClassLoader(WebAppModule.java:1489)
Truncated. see log file for complete stacktrace
>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="test-booking">
</persistence-unit>
</persistence>
| |
doc_23531966
|
I found QTIWorks to implement the questions, QTIWorks contain LTI provider so I try connect with it through Moodle and it is working.
now I need to make my platform as tool consumer to connect with QTIWorks, my platform is coded with java, so I'm searching for an example to implement tool consumer in java but I can't find.
so, How I can implement tool consumer in my platform please?
Thanks in advance.
A: Sakai is a tool consumer implemented in java, so you might look at their source code: Sakai github page
But you will probably find the most useful information about implementing a tool consumer by looking at the LTI 1.2 implementation guide
| |
doc_23531967
|
Following is my TS code to retrieve the data:
ionViewDidLoad(){
this.customerId = this.navParams.get('data');
this.customerProvider.getData(this.customerId).snapshotChanges().subscribe(x =>{
this.listOne = x
this.listOne.forEach(y =>{
this.listTwo = this.customerProvider.getListDetails(this.customerId, y.key).snapshotChanges()
console.log(this.listTwo)
})
})
}
Following is the HTML:
<ion-item>
{{(listTwo | async)?.key}}
</ion-item>
The problem is the list shows only 1 item whereas the firebase db has 3 items with key. Following is the console screenshot
Following is the output
Following are the providers:
getFile(customerId){
return this.afDb.list(`response/${customerId}`)
}
getFileDetails(customerId, listOne): AngularFireObject<any>{
return this.afDb.object(`response/${customerId}/${listOne}`)
}
Seeems like forEach or AngularFire Object issue but not sure.
A: snapshotChanges() returns an Observable of type AngularFireAction, you have to first map it to filter the data from it. That's also why you are just getting one list. Try:
this.customerProvider
.getData(this.customerId).snapshotChanges()
.map(filter => {
return filter.map(c => (
// return keys only
c.payload.key
));
}
).subscribe(x => {
this.listOne = x;
console.log(x);
this.listOne.forEach(y =>{
this.listTwo = this.customerProvider
.getListDetails(this.customerId, y.key).snapshotChanges()
.map(filter => {
filter.map(c => (c.payload.val()))
})
})
console.log(this.listTwo);
});
Hope this helps. I recently started learning Angular too. So any feedback would be appreciated.
| |
doc_23531968
|
EXAMPLE:
dir=~\first\
cat test.sh
outputs ls -l ~\first\
dir=~\second\
cat test.sh
outputs ls -l ~\second\
How can I do that?
A: Escaping $dir as \$dir or '$dir' will write out the variable name instead of its value. If you want the script to print the value of $dir then you could write out an entire echo command.
echo 'echo "$dir"' > test.sh
A: Then your script should contain something like this:
ls -l "$1" | ...
Then you can pass in the dir when you execute the script:
./script path/to/whatever
A: To evaluate a cmd you can use $().
dir=~
$( echo "ls -l $dir" > test.sh )
A: Staring into my crystal ball (that is, guessing wildly at what you're actually asking)....
if dir=foo in your current shell, and you want to invoke your script so that it lists the contents of foo, all you need to do is put dir in the environment. That is, try one of:
dir=baz ./test.sh # script runs with dir == baz
export dir
dir=foo
./test.sh # script runs with dir == foo
dir=bar
./test.sh # script runs with dir == bar
| |
doc_23531969
|
When i try to update content of all countdown using id, it works only for first div.
<html>
<head> </head>
<body>
<p id="countdown"></p>
<p id="countdown"></p>
<p id="countdown"></p>
<p id="countdown"></p>
<p id="countdown"></p>
<p id="countdown"></p>
<script>
var end = new Date('03/24/2016 08:00 PM');
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById('countdown').innerHTML = 'EXPIRED!';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
document.getElementById('countdown').innerHTML = days + ' Days ';
document.getElementById('countdown').innerHTML += hours + ' Hours ';
document.getElementById('countdown').innerHTML += minutes + ' Mins ';
document.getElementById('countdown').innerHTML += seconds + ' Secs';
}
timer = setInterval(showRemaining, 1000);
</script>
</body>
</html>
A: Id must be unique. You can use class instead. You can get all elements by class name using document.getElementsByClassName. After that you can use Array.prototype.forEach to iterate over all elements and set innerHTML property.
<p class="countdown"></p>
<p class="countdown"></p>
<p class="countdown"></p>
<p class="countdown"></p>
<p class="countdown"></p>
<p class="countdown"></p>
<script>
var end = new Date('03/24/2016 08:00 PM');
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function setAllCountdownInnerHtml(html) {
var allElements = document.getElementsByClassName('countdown');
Array.prototype.forEach.call(allElements, function(ele) {
ele.innerHTML = html;
});
}
function showRemaining() {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
setAllCountdownInnerHtml('EXPIRED!');
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
var html = days + ' Days ' + hours + ' Hours ' + minutes + ' Mins ' + seconds + ' Secs';
setAllCountdownInnerHtml(html);
}
timer = setInterval(showRemaining, 1000);
</script>
See demo here https://jsfiddle.net/v3y4b3ux/
A: Rename your ids to be unique...
<p id="countdown1"></p>
<p id="countdown2"></p>
<p id="countdown3"></p>
<p id="countdown4"></p>
<p id="countdown5"></p>
then use a for loop to write to each one separately...
var time = days + ' Days ' + hours + ' Hours ' + minutes + ' Mins ' + seconds + ' Secs';
for(var i = 1; i < 6; i++){
document.getElementById('countdown' + i).innerHTML = time;
}
| |
doc_23531970
|
private lateinit var binding: ActivityMainBinding
private var exoPlayer: ExoPlayer? = null
private var playbackPosition = 0L
private var playWhenReady = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
preparePlayer()
}
private fun preparePlayer() {
exoPlayer = ExoPlayer.Builder(this).build()
exoPlayer?.playWhenReady = true
binding.playerView.player = exoPlayer
val defaultHttpDataSourceFactory = DefaultHttpDataSource.Factory()
val mediaItem =
MediaItem.fromUri(URL)
val mediaSource =
HlsMediaSource.Factory(defaultHttpDataSourceFactory).createMediaSource(mediaItem)
exoPlayer?.setMediaSource(mediaSource)
exoPlayer?.seekTo(playbackPosition)
exoPlayer?.playWhenReady = playWhenReady
exoPlayer?.prepare()
}
private fun releasePlayer() {
exoPlayer?.let { player ->
playbackPosition = player.currentPosition
playWhenReady = player.playWhenReady
player.release()
exoPlayer = null
}
}
override fun onStop() {
super.onStop()
releasePlayer()
}
override fun onPause() {
super.onPause()
releasePlayer()
}
override fun onDestroy() {
super.onDestroy()
releasePlayer()
}
companion object {
const val URL =
"sample m3u8 file URL here"
}
Please help me tweak or make the code play mp4 files. Please bare with me I'm totally new to Android development and ExoPlayer. I will greatly appreciate your help.
A: For each media type you should use the proper MediaSource in exoplayer. For MP4 file you need to use ProgressiveMediaSource as stated here, but in your code you are using HlsMediaSource which is only suitable for hls (m3u8) files.
A: You should make like this:
private lateinit var binding: ActivityMainBinding
private var exoPlayer: ExoPlayer? = null
private var playbackPosition = 0L
private var playWhenReady = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
preparePlayer()
}
private fun preparePlayer() {
exoPlayer = ExoPlayer.Builder(this).build()
exoPlayer?.playWhenReady = true
binding.playerView.player = exoPlayer
val defaultHttpDataSourceFactory = DefaultHttpDataSource.Factory()
val mediaItem =
MediaItem.fromUri(URL)
val mediaSource = ProgressiveMediaSource.Factory(defaultHttpDataSourceFactory)
.createMediaSource(mediaItem)
exoPlayer?.setMediaSource(mediaSource)
exoPlayer?.seekTo(playbackPosition)
exoPlayer?.playWhenReady = playWhenReady
exoPlayer?.prepare()
}
private fun releasePlayer() {
exoPlayer?.let { player ->
playbackPosition = player.currentPosition
playWhenReady = player.playWhenReady
player.release()
exoPlayer = null
}
}
override fun onStop() {
super.onStop()
releasePlayer()
}
override fun onPause() {
super.onPause()
releasePlayer()
}
override fun onDestroy() {
super.onDestroy()
releasePlayer()
}
companion object {
const val URL = "https://storage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
}
| |
doc_23531971
|
new_result = requests.get(url+offset)
while len(new_result) == 1000:
new_result = requests.get(url+offset).json()
result += new_result
offset += 1000
I can't seem to find an analogous solution without going recursive which I would like to avoid. Is there a way to accomplish this in Javascript? If recursion is the only way forward are there any recommended patterns?
A: If it is ok for you using async/await, you can do something like this:
let newResult = await fetch(url+offset)
while (newResult.length === 1000) {
newResult = await requests.get(url+offset);
result += await newResult.json();
offset += 1000;
}
A: Assuming you don't want to async/await, it's fine to 'recur' from your then() callback. It looks like recursion, but you're not actually increasing the stack with every iteration.
This is because the callback you passed to then() is indirectly called from the main event loop.
You simply can't use a straight-up loop because the process is asynchronous, unless you use co-routines (requires a browser that supports generators) or async/await.
| |
doc_23531972
|
header("Location:sweetalertbutton2.php?update=success");} ?>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<form id="form1" name="frmUser" control="" class="form-group" action="" method="post">
<button><input type="submit" name="lupushilang" value="Sahkan" class="btn sahkan" id="submit"> </button>
</form>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@8"></script>
<script type="text/javascript">
$('.sahkan').on('click', function (event) {
event.preventDefault();
Swal.fire({
title: 'are you sure?',
text: "This book will be delete.",
type: 'warning',
showCancelButton: true,
cancelButtonColor:'#d33',
cancelButtonText: "Tidak",
confirmButtonColor:'#3085d6',
confirmButtonText: 'Teruskan',
}).then((result) => {
if (result.isConfirmed) {
form.submit();
}
})
});
</script>
hello, senior StackOverflow. in new in world coding. so I try to pop up submit button and run the process after I click submit button. but it immediately runs the top PHP code. please help me senior so I can learn form StackOverflow senior . Thank you senior
| |
doc_23531973
|
copy Documents G:/Seagate_backup/Documents
What I assumed was that copy would create the Documents directory on my backup drive and then copy the contents of the C: Documents directory into it. That is not what happened!
I proceeded to wipe my hard-drive and re-install the operating system, thinking I had backed up the important files, only to find out that copy seemingly concatenated all the C: Documents files of different types (.doc, .pdf, .txt, etc) into one file called "Documents." This file is of course unreadable but opening it in Notepad reveals what happened. I can see some of my documents which were plain text throughout the massively long file.
How do I undo this!!? It's terrible because I was actually helping a friend and was so sure of myself but now this has happened. The only thing I can think of doing is searching for some common separator amongst the concatenated files and write some sort of script to split the file back apart. But then I would have to guess the extensions of each of the pieces...
A: Merging files together in the fashion that copy uses, discards important file system information such as file size and file name. While the file name may not be as important the size is. Both parameters are used by the OS to discriminate files.
This problem might sound familiar if you have damaged your file allocation table before and all files disappeared. In both cases, you will end up with a binary blob (be it an actual disk or something like your file which might resemble a disk image) that lacks any size and filename information.
Fortunately, this is where a lot of file system recovery tools can help. They are specialized in matching patterns. Specifically they are looking for giveaway clues to what type a file is of, where it starts and what it's size is.
This is for instance enabled by many file types having a set of magic numbers that are used to allow a program to check if a file really is of the type that the extension claims to be.
In principle it is possible to undo this process more or less well.
You will need to use data recovery tools or other analysis tools like binwalk to extract the concatenated binary blob. Essentially the same tools that are used to recover deleted files should be able to extract your documents again. Without any filename of course. I recommend renaming the file to a disk image (.img) and either mounting it from within the operating system as a virtual harddisk (don't worry that it has no file system - it should show up as an unformatted drive) or directly using a data recovery tool or analysis tool which can read binary files (binwalk, for instance, can do that directly, but may not find all types of files as it's mainly for unpacking firmware images that may be assembled in the same or a similar way to how your files ended up).
| |
doc_23531974
|
Documents/JoeInstaller.cpp:33:43: error: use of undeclared identifier 'buffer'
memset(buffer, (char)NULL, sizeof(buffer)))
^
Documents/JoeInstaller.cpp:33:16: error: use of undeclared identifier 'buffer'
memset(buffer, (char)NULL, sizeof(buffer)))
Here is the code I have so far:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <stdio.h>
#include <curl/curl.h>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
float pythonver;
int main(int argc, char* argv[]){
cout << "Press enter\n::";
if (cin.get() == '\n')
char buffer[1000];
FILE* progOutput;
progOutput = popen("which python3.6", "r");
if (!progOutput) {
cerr<<"npopen failedn";
exit(1);
}
memset(buffer, (char)NULL, sizeof(buffer)))
if (fread(buffer, sizeof(char), sizeof(char) * sizeof(buffer), progOutput) < 0) {
cerr<<"nfread failedn";
exit(1);
}
if (pclose(progOutput) < 0) {
cerr<<"npclose failedn";
exit(1);
}
pythonver << atof(buffer<<endl.c_str());
if (pythonver) {
cout << "Hooray! Now you need to install python3.6 or later from source!";
}
In sum, what I am trying to do is get the version of python. I am doing this via a popen and saving the results to a string. While doing this a come across the error.
A: There's a missing curly brace on this line:
if (cin.get() == '\n')
Therefore, the branch only covers the next line (see Notes here at the end of page), which is the declaration of buffer:
if (cin.get() == '\n')
char buffer[1000];
// buffer is out of scope here
Depending on what you want, you need to add curly braces around the whole block, or some parts of it, to keep buffer alive as long as it is used.
| |
doc_23531975
|
<c:forEach items="${myModel.myList}" var="obj">
<div id="${obj.id}" onclick="selectObject(this);"><span>${obj.name}</span></div>
<form:hidden path="myModel.selectedObj" />
</c:forEach>
i want the hidden input of obj in the list that his id is equal to the selectedObj to not be disabled, and every other hidden input i want to be disabled. This is what i tried:
<form:hidden path="myModel.selectedObj" <c:out value="${obj.id != myModel.selectedObj.id ? "disabled=\"disabled\"" : ""}"></c:out> />
as i said, this didn't work out. any thoughts?
A: Try with this piece of code:
<c:forEach items="${myModel.myList}" var="obj">
<div id="${obj.id}" onclick="selectObject(this);"><span>${obj.name}</span></div>
<c:if test="${obj.id eq myModel.selectedObj.id}">
<form:hidden path="myModel.selectedObj" />
</c:if>
<c:if test="${obj.id ne myModel.selectedObj.id}">
<form:hidden path="myModel.selectedObj" disabled="disabled" />
</c:if>
</c:forEach>
Or you can use a <c:choose /> , with <c:when /> and <c:otherwise /> tags:
<c:forEach items="${myModel.myList}" var="obj">
<div id="${obj.id}" onclick="selectObject(this);"><span>${obj.name}</span></div>
<c:choose>
<c:when test="${obj.id eq myModel.selectedObj.id}">
<form:hidden path="myModel.selectedObj" />
</c:when>
<c:otherwise>
<form:hidden path="myModel.selectedObj" disabled="disabled" />
</otherwise>
</c:choose>
</c:foreach>
| |
doc_23531976
|
for i in iterations:
...
context = i.name
render(request, template, {context: context})
return render(request, template, {context: context})
A: in your loop you're overwriting the HTTP response and also the context, so that would not work anyway. The loop should create some array or list.
names = []
for i in iterations:
...
names.append(i.name)
return render(request, template, {'names': names})
and in your template:
{% for name in names%} {{ name }} {% endfor %}
If your really want to render it first (for example if you want to add some html snippet), you could use render_to_string
rendered_str = []
for i in iterations:
...
rendered_str.append(render_to_string('my_snippet.html', {'name': i.name}))
| |
doc_23531977
|
After deploying it to Google Cloud by use of 'gcloud app deploy' I get the everything up and running.
However...when I open the following URL in the browser: https://webserverurl.com/webserver.properties , the webserver.properties file can be approached and is in turn downloaded immediately.
How can I prevent this from happening and make sure that such properties files are inaccessible from outside?
A: The problem is that when you use this line:
app.use('/', express.static(__dirname + '/'));
you are giving access to your root directory. See this for a definition of __dirname. If you want to give access to a specific folder you can do this:
Lets say your root directory is src and you fave a dir with static files called src/myfiles. In order to give acces to files in myfiles you can use this line:
app.use('/mypathname', express.static('myfiles'));
where:
*
*'/mypathname' is the part pertaining your URL. In your case it would be https://webserverurl.com/mypathname/any-file-name.jpg
*express.static('myfiles') is the name of your local dir.
See this guide.
Hope this helps
| |
doc_23531978
|
I know iOS do not allow to run when go into background mode. I am going to declare my app using GPS to use some others specific functions. Does it conflict Apple policy? Can I upload to App Store later?
| |
doc_23531979
|
"mixing versions can lead to runtime crashes"
I made this project using the assistant of android studio
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.firebase:firebase-core:16.0.1'
implementation 'com.google.firebase:firebase-messaging:17.0.0'
}
A: Try updating your 'com.google.firebase:firebase-core:16.0.1' to '16.0.6'. It's the most up-to-date version.
| |
doc_23531980
|
(a) Server A - 192.0.0.161:8800
(b) Server B - 192.0.0.161:8801
At the same time, I have two client instances (Client A & Client B) that will connect to each server. In other words, Client A will connect to Server A, while Client B will connect to Server B. In ideal case, when Server A broadcast message (Msg A), only Client A shall receive the message only. However, I face problem that Client A and Client B received message from Server A when Server A and Server B broadcast message at the same time. Any idea of this problem?
| |
doc_23531981
|
What could be the problem and the solution? Many thanks!!
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<link rel="stylesheet" type="text/css" href="welcome.css">
<title>Vokabeltrainer</title>
</head>
<body>
<div class="left"></div>
<h1>VokabelTester</h1>
<div class="form">
<form action="http://localhost:8080/vokabulary/Welcome" method="get">
<div class="table">
<table>
<tr><th>Sprachen</th></tr>
<tr><td>Englisch<input type="checkbox" value="englisch" name="language" checked="checked"/></td></tr>
<tr><td>Französisch<input type="checkbox" value="franzoesisch" name="language" checked="checked"/></td></tr>
<tr><td>Italienisch<input type="checkbox" value="italienisch" name="language" checked="checked"/></td></tr>
<tr><td>Spanisch<input type="checkbox" value="spanisch" name="language" checked="checked"/></td></tr>
<tr><td>Portugiesisch<input type="checkbox" value="portugiesisch" name="language" checked="checked"/></td></tr>
</table>
</div>
<div class="login">
<h2>Anmeldung</h2>
Name:<input type="text" name="name"/><br/>
Passwort:<input type="password" name="password"/><br/>
Login<input type="radio" name="login" value="login" checked="checked"/><br/>
Registration<input type="radio" name="login" value="registration"/><br/>
<input type="submit" value="LOS GEHT'S"/>
</div>
</form>
</div>
</body>
</html>
CSS:
body{background-color: #6cc034; margin: 0; font-family: Calibri}
h1{margin: 0px;}
.left{display: block; margin: 0;height: 100%; width: 30%; float: left; background-color: green;}
.form{float: left; background-color: orange; width: 50%; border-style: dotted;}
.table{float:left; width:200px; display: block;}
th{font-size: 16pt; width: 150px; text-align: left; height: 60px;}
h2{font-size: 16pt; display: block; background-color: red;}
td{text-align: right; font-size: 14pt;}
.login{font-size: 14pt; display: block; background-color: blue; height: 200px; border-style: dashed;}
A: Remove the float:left from your .table declaration like so: http://jsbin.com/wanuyewewome/1/edit
A: I added float: left for the login div which fixed the problem.
| |
doc_23531982
|
This is my current code:
int Dictionary::processFilePhrases(string file) {
vector<string> wordList;
string word;
string phrase;
ifstream fin;
fin.open(file.c_str());
while (fin >> word) {
wordList.push_back(word);
}
fin.close();
for (int i=0; i<wordList.size(); i++){
phrase += wordList[i] + " ";
cout << phrase << endl;
}
return wordCount;
}
for example:
input file text: "The next frontier for game-playing artificial intelligence"
The goal is to output words so its like:
the
the next
the next frontier
next
next frontier
next frontier for
frontier
frontier for
frontier for game-playing
...
etc.
A: Well the "concatenating" loop runs once over all the words you got, so that's why you get all the words.
The way you describe the wanted output, it seems like you want two loops, nested inside each other, where the inner loops from one to n, and where n is the current value from the outer loop.
Perhaps something like
for (unsigned i = 0; i < wordList.size(); ++i)
{
std::string phrase;
for (unsigned j = 0; j <= i; ++j)
{
phrase += wordList[j];
phrase += ' '; // Spacing between words
}
std::cout << phrase << '\n';
}
If we now step through the code above, in the first iteration of the outer loop, i is equal to zero. In the inner loop we loop while j is less than or equal to i (which now is zero), which means the inner loop will iterate only once, making phrase equal to the string "The " (with the input you have given in the question).
Once the inner loop finishes the phrase is printed, and the outer loop iterates, which makes i equal to one. The inner loop now iterates two times (for j being zero and one) constructing the phrase "The next ".
Of course this doesn't exactly do what you want, printing only up to three words at a time, and starting with the next word after the three first words have been printed. You probably need yet another loop, to handle the one to three counting. The above is a starting point though, and I suggest you experiment with that, and other loops outside the outer, in between, and as a new inner loop. Experimentation and failure is how you learn.
A: Something like this(I didn't run it):
int Dictionary::processFilePhrases(string file) {
vector<string> wordList;
string word;
ifstream fin;
fin.open(file.c_str());
while (fin >> word) {
wordList.push_back(word);
}
fin.close();
for (int i=0; i<wordList.size(); i++){
string phrase;
for (int j = i; j < i + 3 && j < wordList.size(); ++j) {
phrase += wordList[j] + " ";
cout << phrase << endl;
}
cout << phrase << endl;
}
return wordCount;
}
| |
doc_23531983
|
Caused by: SyntaxError: ("no viable alternative at input 'if'" , ('<iostream>', 107, 14, ' if b.getType() != Material.WATER:\n'))
Here's my code:
removable = True
ticker_vertical = 0.0
ticker_horisontal = (random.random() * 2 * math.pi)
l = sender.getLocation()
b = l.getBlock()
entity = l.getWorld().spawnFallingBlock(l, b.getType(), b.getData())
if args[0] == "spawn":
if l.getBlock().getType() != Material.AIR:
entity.setMetadata("vortex", FixedMetadataValue(PyPlugin, "protected")
if b.getType() != Material.WATER: #this is line which is causing error
b.setType(Material.AIR)
else:
pass
else:
pass
l = sender.getLocation()
radius = math.sin(ticker_vertical * 2)
v = Vector(radius * math.cos(horisontal), 0.5, radius * math.sin(horisontal))
b1 = entity.getLocation().add(v.clone().normalize()).getBlock()
if b1.getType() != Material.AIR:
new_blocks.add(b.getLocation(), b.getType(), b.getData())
entities = entity.getNearbyEntities(1.0, 1.0, 1.0)
for e in entities:
if e.hasMetaData("vortex"):
new_blocks.add(entity)
entity.setVelocity(v)
if ticker_vertical < 1.0:
ticker_vertical += 0,05
elif args[0] == "stop":
entity.remove()
Thanks in advance!
A: You're missing a closing parenthesis on line 9:
entity.setMetadata("vortex", FixedMetadataValue(PyPlugin, "protected")
should be:
entity.setMetadata("vortex", FixedMetadataValue(PyPlugin, "protected"))
A: Look at the preceding line; you are missing a ) closing parenthesis:
entity.setMetadata("vortex", FixedMetadataValue(PyPlugin, "protected")
# ^--- closes there ----^
# ^ --- open but no close --^
Further down you used a comma instead of a decimal point:
if ticker_vertical < 1.0:
ticker_vertical += 0,05
You probably wanted:
if ticker_vertical < 1.0:
ticker_vertical += 0.05
You can (and should) remove all the:
else:
pass
lines, they do nothing whatsover and are not needed.
| |
doc_23531984
|
at java.base/java.lang.ClassLoader$NativeLibrary.load0(Native Method)
at java.base/java.lang.ClassLoader$NativeLibrary.load(Unknown Source)
at java.base/java.lang.ClassLoader$NativeLibrary.loadLibrary(Unknown Source)
at java.base/java.lang.ClassLoader.loadLibrary0(Unknown Source)
at java.base/java.lang.ClassLoader.loadLibrary(Unknown Source)
at java.base/java.lang.Runtime.loadLibrary0(Unknown Source)
at java.base/java.lang.System.loadLibrary(Unknown Source)
at java.desktop/sun.font.FontManagerNativeLibrary$1.run(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.desktop/sun.font.FontManagerNativeLibrary.<clinit>(Unknown Source)
at java.desktop/sun.font.SunFontManager$1.run(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.desktop/sun.font.SunFontManager.<clinit>(Unknown Source)
at java.base/java.lang.Class.forName0(Native Method) at java.base/java.lang.Class.forName(Unknown Source) at java.desktop/sun.font.FontManagerFactory$1.run(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.desktop/sun.font.FontManagerFactory.getInstance(Unknown Source)
at java.desktop/java.awt.Font.getFont2D(Unknown Source)
at java.desktop/java.awt.Font$FontAccessImpl.getFont2D(Unknown Source)
at java.desktop/sun.font.FontUtilities.getFont2D(Unknown Source)
at java.desktop/sun.java2d.SunGraphics2D.checkFontInfo(Unknown Source)
at java.desktop/sun.java2d.SunGraphics2D.getFontInfo(Unknown Source)
at java.desktop/sun.java2d.pipe.GlyphListPipe.drawString(Unknown Source)
at java.desktop/sun.java2d.pipe.ValidatePipe.drawString(Unknown Source)
at java.desktop/sun.java2d.SunGraphics2D.drawString(Unknown Source)
at Main.main(Main.java:13)
This exception is thrown when calling Graphics2D#drawString, this code is executed in the IDE JvDroid, Android 10, Honor 10 lite. Is there any way to install this library (maybe load using the System methods)
| |
doc_23531985
|
So, once he clicked the login button, granted the permissions for the application, but for a specific part of the application I need for example the create_events permission but I don't want it from everyone, just from those who want to use that party of my application.
Thanks, John
A: It took me a while to figure this one out. What you have to do is prompt to "login" again. If the user is already logged in, Facebook checks what permissions you are asking for in the "login" function against what is already granted. If some permissions are not yet granted, Facebook prompts the user for those extra permissions, NOT to re-login.
That you use the login function to prompt for additional permission I think is counter intuitive. But this is how you would prompt for different permissions only when needed, which is what Facebook recommends.
FB.login(function(response) {
...
}, {'perms':'read_stream,publish_stream,offline_access'});
http://developers.facebook.com/docs/reference/javascript/fb.login/
A: Here is the PHP implementation:
$loginUrl = $facebook->getLoginUrl(array(
"scope" => "read_stream,publish_stream"
));
| |
doc_23531986
|
I would like to show every odd number post in the style 1 and even number posts in style 2
Below is my template file:
<?php /* Template Name: Home v2 */ get_header(); ?>
<main role="main">
<!-- section -->
<section>
<?php
$temp = $wp_query; $wp_query= null;
$wp_query = new WP_Query(); $wp_query->query('showposts=' . $theme_options['blog-post-per-page'] . '&paged='.$paged);
while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
<div class="tiles-block w-clearfix">
<div class="float-left">
<div class="content-block w-clearfix">
<h5 class="black travel"><?php echo the_category();?></h5>
<h1 class="black mastheading"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h1>
<div class="date-block w-container">
<div class="black mini-date"> <?php echo get_the_date(); ?></div>
<img class="mini-icon" src="<?php echo get_template_directory_uri() . '/images/comment-icon.png' ?>">
<div class="black mini-date">32</div>
<img class="mini-icon" src="<?php echo get_template_directory_uri() . '/images/heart-icon.png' ?>">
<div class="black mini-date">14</div>
</div>
<div class="black iltalica"><?php the_excerpt(); ?></div>
<a class="a8 cta w-button" href="<?php the_permalink(); ?>">continue reading</a>
</div>
</div>
<div class="float-left natural-forest">
<div class="thumb">
<?php the_post_thumbnail('full'); ?>
</div>
</div>
<img class="right-arrow" src="<?php echo get_template_directory_uri() . '/images/right-arrow.png' ?>" />
</div>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
The code above works good. but it gives only style 1.
I already have html setup for style 2 but don't know how to implement in the code above.
This is my style2 block
<div class="tiles-block w-clearfix">
<div class="float-right">
<div class="content-block w-clearfix">
<h5 class="black photography">PHOTOGRAPHY</h5>
<h1 class="black mastheading">title test</h1>
<div class="date-block w-container">
<div class="black mini-date">October 26, 2016</div>
<img class="mini-icon" src="http://aa.com/aa.png">
<div class="black mini-date">15</div>
<img class="mini-icon" src="http://bb.com/bb.png">
<div class="black mini-date">13</div>
</div>
<div class="black iltalica">Lorem Ipsuim dolor....</div>
<a class="a8 cta w-button" href="#">continue reading</a></div>
</div>
<div class="float-left window-light">
<div class="thumb">
<img src="<?php echo get_template_directory_uri() . '/images/post2.png' ?>" />
</div>
</div>
<img class="left-arrow" src="http://cc.com/cc.png">
</div>
A: This will get a little messy in PHP because you'd need several if statements. You might consider naming some of the inner divs the same, and making only the outer divs different names, and doing more of the work in CSS. That said, here's how you would do it:
Set a flag that changes each time through the loop, and check the value of the flag before you output your HTML.
$style_flag = 1;
while ($wp_query->have_posts()) : $wp_query->the_post();
//check the value
if ($style_flag == 1){
// output style 1
} else {
// output style 2
}
// do everything else you need to do in the loop
// switch the value of the flag
$style_flag = $style_flag * -1;
end while;
Back to CSS for a moment, though. Check out the nth-child selector if you're not familiar with it already: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child
A: I have found the solution to my problem.
<?php query_posts('showposts=0'); ?>
<?php
$i = 1;
?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<?php if(($i % 2) == 0) { ?>
<div class="tiles-block w-clearfix">
<div class="float-right">
<div class="content-block w-clearfix">
<h5 class="black photography"><?php echo the_category();?></h5>
<h1 class="black mastheading"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h1>
<div class="date-block w-container">
<div class="black mini-date"><?php echo get_the_date(); ?></div>
<img class="mini-icon" src="<?php echo get_template_directory_uri() . '/images/comment-icon.png' ?>">
<div class="black mini-date">32</div>
<img class="mini-icon" src="<?php echo get_template_directory_uri() . '/images/heart-icon.png' ?>">
<div class="black mini-date">14</div>
</div>
<div class="black iltalica"><?php the_excerpt(); ?></div>
<a class="a8 cta w-button" href="<?php the_permalink(); ?>">continue reading</a></div>
</div>
<div class="float-left window-light">
<div class="thumb">
<?php the_post_thumbnail('full'); ?>
</div>
</div>
<img class="left-arrow" src="<?php echo get_template_directory_uri() . '/images/left-arrow.png' ?>">
</div>
<?php } elseif (($i % 2) !== 0) { ?>
<div class="tiles-block w-clearfix">
<div class="float-left">
<div class="content-block w-clearfix">
<h5 class="black travel"><?php echo the_category();?></h5>
<h1 class="black mastheading"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h1>
<div class="date-block w-container">
<div class="black mini-date"><?php echo get_the_date(); ?></div>
<img class="mini-icon" src="<?php echo get_template_directory_uri() . '/images/comment-icon.png' ?>">
<div class="black mini-date">32</div>
<img class="mini-icon" src="<?php echo get_template_directory_uri() . '/images/heart-icon.png' ?>">
<div class="black mini-date">14</div>
</div>
<div class="black iltalica"><?php the_excerpt(); ?></div>
<a class="a8 cta w-button" href="<?php the_permalink(); ?>">continue reading</a>
</div>
</div>
<div class="float-left natural-forest">
<div class="thumb">
<?php the_post_thumbnail('full'); ?>
</div>
</div>
<img class="right-arrow" src="<?php echo get_template_directory_uri() . '/images/right-arrow.png' ?>" />
</div>
<?php } ?>
<?php $i++; ?>
<?php endwhile; ?>
<?php endif; ?>
| |
doc_23531987
|
A: One way data binding -
The model values are automatically assigned to the HTML placeholder elements specified through the data binding notation, but the HTML elements don't change the values in the model(one way).
Example :
Controller :
app.controller('MainCtrl', function($scope) {
$scope.firstName = 'John';
});
HTML :
<span>First name:</span> {{firstName}}<br />
Two Way Data Binding -
The model values are automatically assigned to the HTML placeholder elements specified through the data binding notation, where HTML elements can change the value in the model(two way).
Example :
Controller :
app.controller('MainCtrl', function($scope) {
$scope.firstName = 'John';
});
HTML
<span>First name:</span> {{firstName}}<br />
<span>Set the first name: <input type="text" ng-model="firstName"/></span><br />
In above example we can change firstName model value with the help of HTML Input element.
Working example : http://plnkr.co/edit/GxqBiOoNFuECn55R4uJZ?p=preview
A: Retrieved from the AngularJS homepage (2015.06.02):
<!doctype html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
</head>
<body>
<div>
<label>Name:</label>
<input type="text" ng-model="yourName" placeholder="Enter a name here">
<hr>
<h1>Hello {{yourName}}!</h1>
</div>
</body>
</html>
This is possibly the simplest example of two-way data binding in Angular.
The <input> is associated to a yourName model, and the same model is used to fill the content of the <h1> tag. Modifying one will automatically update the other.
Although the data binding in the example can be seen as one-way, because you can't modify the <h1> directly, this should get you started. The AngularJS docs and tutorials contain a lot of great resources.
| |
doc_23531988
|
class Body extends Component {
state= {
input: '',
oprStatus: false,
check: false,
count: 0,
oprArray: null
} }
now as i know that i cant update the 'oprArray' array inside the state by using push
so what i was thinking that what if i declare a variable outside the class and update that array and then update the 'oprArray' inside state
array.push(2);
this.setState({
oprArray: array
)}
A: That doesn't solve the problem, because you'd still be mutating state rather than setting new state. Once you've set oprArray: array in your state the first time, the state and the global array variable are both pointing to the same array. The next time, that push is modifying state directly — which is a no-no with React state.
To add a new item into your oprArray, you do it like this:
this.setState(({oprArray}) => ({oprArray: [...oprArray, 2]}));
That:
*
*Uses the callback form of setState, which is necessary when you're modifying state (a new oprArray with the new entry, 2) based on existing state (the previous contents of oprArray).
*Creates a new array with the additional item, via spread notation.
Live Example:
const {Component} = React;
class Body extends Component {
state = {
input: '',
oprStatus: false,
check: false,
count: 0,
oprArray: null
};
componentDidMount() {
// Since your state starts with `null`, I assume you receive initial data
// via ajax or similar; emulated here with a timeout
setTimeout(() => {
this.setState({oprArray: [0, 1]}); // Initial data isn't based on existing state
// Now set up getting more data later
setTimeout(() => {
// Additional data
this.setState(({oprArray}) => ({oprArray: [...oprArray, 2]}));
}, 800);
}, 800);
}
render() {
const {oprArray} = this.state;
return (
<div>oprArray: {oprArray ? oprArray.join(", ") : "(none)"}</div>
);
}
}
ReactDOM.render(<Body />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script>
| |
doc_23531989
|
Thanks!!!
A: I doubt this has its own name, as it's trivially isomorphic to the normal TSP.
*
*From standard TSP to this: Given a directed weighted graph for TSP, with a start/end node, split the start/end node into a start node and an end node, with all the outgoing edges on the start node and all the incoming edges on the end node.
*From this to standard TSP: Remove all outgoing edges from the end node; add a single edge from the end node to the start node (which is now the start/end node).
| |
doc_23531990
|
Fatal error: Can't use function return value in write context in [path]/admincp/global.php(226) : eval()'d code on line 12
when I try to use fopen/fsockopen, and such functions to retrieve remote data.
My code is:
http://pastebin.com/crLB429N
I have tried using fopen/fread, and fsockopen/fgets. I don't even know where to start to debug this.
I would appreciate any help given, thank you!
A: empty() can only evaluate variables - not function return values. Your first conditional is using empty(ini_get(...))
Try:
$base_dir = ini_get('open_basedir');
if(function_exists('curl_init') && !ini_get("safe_mode") && empty($base_dir))
| |
doc_23531991
|
I currently generate image embeddings using this function below for locally saved images:
def generate_img_embedding(img_file_path):
images = [
Image.open(img_file_path)
]
# Encoding a single image takes ~20 ms
embeddings = embedding_model.encode(img_str)
return embeddings
also I start the Yolov5 objection detection with image cropping as follows
def start_camera(productid):
print("Attempting to start camera")
# productid = "11011"
try:
command = " python ./yolov5/detect.py --source 0 --save-crop --name "+ id +" --project ./cropped_images"
os.system(command)
print("Camera runnning")
except Exception as e:
print("error starting camera!", e)
How can I modify the YOLOv5 model to pass the cropped images into my embedding function in real time?
A: Just take a look at the detect.py supplied with yolov5, the file you are running. The implementation is pretty short (~150 SLOC), I would recommend re-implementing it or modifying for your use case.
Key points, omitting a lot of (important, but standard and easily understandable) data transforms and parameter parsing, are as follows:
device = select_device(device)
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data)
# Code selecting FP16/FP32 omitted here
model.warmup(imgsz=(1 if pt else bs, 3, *imgsz), half=half)
for path, im, im0s, vid_cap, s in dataset:
im = torch.from_numpy(im).to(device)
# Image transforms omitted
pred = model(im, augment=augment, visualize=visualize) # stage 1
pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det) # stage 2
for i, det in enumerate(pred):
if len(det):
# Rescale boxes from img_size to im0 size
det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
# --> This is where you would access detections in real time! <--
Most of the code's logic is handling the I/O (in particular, dataset loading is handled by either LoadStreams or LoadImages from yolov5's utils), the rest is just rescaling input images, loading a torch model, and running detection and NMS. No rocket science here.
The least effort path for you would be just copying the entire thing and implementing your embeddings under
for *xyxy, conf, cls in reversed(det):
Instead of saving to file, you would get (x, y, w, h) and crop the image using e.g. Pillow's Image.crop() or slice the numpy array directly. Whichever works for you depends on the implementation of your embedding_model.encode.
| |
doc_23531992
|
public static void radix(int [] list){
int [] bin = new int[10];
ArrayQueue<Integer> part = new ArrayQueue<Integer>(); // EDIT What would I do with this queue??
int num = 0;
for(int i=0;i<list.length;i++)
{
bin[i] = 0;
}
for(int pass=0;pass<list.length;pass++)
{
for(int num=0;num<list.length;num++)
{
int digit=findPlace(bin[pass], num);
}
bin[digit].add(list[num]); // add to the bin
}
// Put back into list
for(int h=0; h<10; h++)
{
while(!bin[h].isEmpty())
{
list[num] = bin[queueNum].remove();
num++;
}
}
}
public static int getPlace (int x, int place)
{return x/place % 10;}
I also made a method to find the bucket, So i just need to know how I would put it into an array, would I just do this? part.add(getPlace(x, place));?
A: Your array, bin doesn't act like a queue just because you want it to :) Arrays don't have methods like add() and remove(). You have two choices on how to fix this:
*
*Program in the proper handling for queues yourself: A queue consists of an array and two pointers into that array, traditionally called head and tail. You'd have to write your own methods to add and remove, which would work with the array and the pointers and take care of an empty queue or an overflowing one.
*Use Java's built-in Queue class. It's documented in the library's Javadocs. Don't know if your assignment intends for you to build your own queue, though.
Update with another detail:
You asked how to extract a single digit from a number. It's easiest working from the least significant digits (LSD) as suggested in the Wikipedia article. To do that:
*
*To extract the last digit, do digit = number % 10 (that's the modulo operation). You will get an integer between 0 and 9 inclusive.
*To strip off the last digit, simply divide by 10. Then you can pull off another digit.
*Since you'll need to be looking at the n-th last digit of a number several times, you would do well to put this functionality into a separate method.
You can use your 0 thru 9 to select the right queue to put your number on.
When you've finished queueing all your numbers into the 10 buckets, you need to copy them from there back into a single list. Then repeat as long as there are still digits in any number that you haven't processed.
| |
doc_23531993
|
I put the code to show the super attributes options (using a dropdown list) of a configurable product in the following file: magento\app\design\frontend\default\theme-name\template\checkout\cart\item\default.phtml.
I found a line with this code:
<?php if ($_options = $this->getOptionList()):?>
After that, I put my code to show the attribute dropdown list for configurable products, and its working fine, but I need to update the super attribute option values for that product when I select another option from the super attribute dropdown list. Below is my code to show the dropdown:
<?php
if($this->getProduct()->isConfigurable()){
$_product = Mage::getModel('catalog/product')->load($this->getProduct()->getId());
Mage::getBlockSingleton('catalog/product_view_type_configurable')->unsetData();
$_configurable = Mage::getBlockSingleton('catalog/product_view_type_configurable')->setData('product', $_product);
$_cdata = json_decode($_configurable->getJsonConfig());
$_current = array();
foreach((array)$this->getOptionList() as $_option) {
$_current[$_option['label']]=$_option['value'];
}
foreach($_cdata->attributes as $attribute) {
?>
<strong><?php echo $attribute->label;
$catchlabel = $attribute->label;
if($catchlabel == 'Clipboard Color'):
$SelectOptions = "selectAtt";
else:
$SelectOptions = "selectFont";
endif;
?>
</strong>
<select style="width: 150px;"
name="cart[<?php echo $_item->getId() ?>][option][<?php echo $attribute->id ?>]"
id="<?php echo $_item->getId(); ?>_<?php echo $attribute->id; ?>"
class="<?php echo $SelectOptions; ?>">
<?php
foreach($attribute->options as $option) {
?>
<option
<?php echo ($_current[$attribute->label]==$option->label) ? ' selected' : '' ?>
value="<?php echo $option->id ?>">
<?php echo $option->label ?>
</option>
<?php
}
?>
</select>
<script type="text/javascript">
jQuery('#<?php echo $_item->getId(); ?>_<?php echo $attribute->id; ?>').change(function() {
var getOption = jQuery('#<?php echo $_item->getId(); ?>_<?php echo $attribute->id; ?>').val();
// something to do here for update attibute options for current product
alert(getOption);
});
</script> <?php
}
}
?>
please tell me how to update the super attribute options of the selected configurable product.
A: You need to submit the new configuration info to a controller action that handles the updates.
Magento has no such controller action, BUT, when you edit a single configurable product in the cart you get the product view with a slightly different markup. The form in that page is used to edit the product in the cart instead of adding a new one.
You should check the algorithm in that controller action and create a module with a controller that applies that algorithm on every product in your cart
| |
doc_23531994
|
All I have found so far are Calendar and CalendarRule views. The problem with the CalendarRule is that the rule is written with a pattern like
"FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,TU,WE,TH,FR"
I can not find a way to use this in SQL query.
A: Assuming working days are mon to fri and your calendar table is linked to the resources table by calendar.workingdays = resources.daysworked, if not obviously adjust them to suit.
SELECT EXTRACT(dow FROM timestamp (to_timestamp(c.workingdays), "YYYY-MM-DD")), r.facility
FROM Calendar c
LEFT JOIN Resources r ON c.workingdays = r.daysworked
WHERE EXTRACT(dow FROM timestamp (to_timestamp(c.workingdays, "YYYY-MM-DD"))
NOT IN (0,6)
| |
doc_23531995
|
Sheets("Survey Data").columns("A").NumberFormat = "0"
Sheets("Survey Data").columns("A").VerticalAlignment = x1Bottom
Sheets("Survey Data").columns("A").HorizontalAlignment = xlCenter
Sheets("Survey Data").columns("A").ColumnWidth = 5
When checking output, the NumberFormat seems to have worked, but not the three following statements.
A: Try changing
Sheets("Survey Data").columns("A").VerticalAlignment = x1Bottom
to
Sheets("Survey Data").columns("A").VerticalAlignment = xlBottom
I see a "1" (One) instead of a "l" (L). It should be xlBottom and not x1Bottom
| |
doc_23531996
|
I was looking at fetching them using the search API. Is this a reasonable way to do it? I guess the only way to identify model files is to use attributes.fileType in the filter? And then look at the relationships.derivatives data. Or is there some other way to search for models?
A: Unfortunately, your request is not supported by the Search API currently. With my experience, extracting relationships.derivatives out is the only way manually from the API responses that contain this attribute e.g.
*
*GET projects/:project_id/folders/:folder_id/contents
*GET projects/:project_id/items/:item_id/tip
*GET projects/:project_id/items/:item_id/versions
| |
doc_23531997
|
<form method="post" id="myform1">
<input type="submit" value="submit" />
</form>
document.getElementById("myform1").submit();
This jsfiddle does not work:
<form method="post" id="myform2">
<input type="submit" id="submit" value="submit" />
</form>
document.getElementById("myform2").submit();
Difference between them submit button has id in second code.
Why?
Note: while working this question, I encountered situation
A: the difference is the type of the button not the id
first example the type of the input is submit which submits forms. second example the type is button which doesn't submit forms
after OP editted question:
see that if you change the id of the submit button to basicly anything other than "submit" it works...
A: This is noted on various sites such as this:
http://www.joezimjs.com/javascript/dont-name-inputs-action-submit/
Having a button with id='submit' is also a known issue in jquery that hasn't been resolved
http://bugs.jquery.com/ticket/1414
Presumably because the issue is outside of jquery's control and it'd require a hack.
I'd be interested to know exactly why.
| |
doc_23531998
|
select
c.name,
SUM(case when RTRIM(TO_CHAR(mor.sent_at , 'Month')) = 'January' THEN 1 END) as "January",
SUM(case when RTRIM(TO_CHAR(mor.sent_at , 'Month')) = 'February' THEN 1 END) as "February",
SUM(case when RTRIM(TO_CHAR(mor.sent_at , 'Month')) = 'March' THEN 1 END) as "March",
SUM(case when RTRIM(TO_CHAR(mor.sent_at , 'Month')) = 'April' THEN 1 END) as "April",
SUM(case when RTRIM(TO_CHAR(mor.sent_at , 'Month')) = 'May' THEN 1 END) as "May",
SUM(case when RTRIM(TO_CHAR(mor.sent_at , 'Month')) = 'June' THEN 1 END) as "June",
SUM(case when RTRIM(TO_CHAR(mor.sent_at , 'Month')) = 'July' THEN 1 END) as "July",
SUM(case when RTRIM(TO_CHAR(mor.sent_at , 'Month')) = 'August' THEN 1 END) as "August",
SUM(case when RTRIM(TO_CHAR(mor.sent_at , 'Month')) = 'September' THEN 1 END) as "September",
SUM(case when RTRIM(TO_CHAR(mor.sent_at , 'Month')) = 'October' THEN 1 END) as "October",
SUM(case when RTRIM(TO_CHAR(mor.sent_at , 'Month')) = 'November' THEN 1 END) as "November",
SUM(case when RTRIM(TO_CHAR(mor.sent_at , 'Month')) = 'December' THEN 1 END) as "December"
from analytics_outbox mo
inner join analytics_outbox_recipient mor on mor.analytics_outbox_id = mo.id
inner join customer c on c.id = mo.customer_id
group by c.name
Current Output:
name |january|february|march |april |may |june|july|august|september|october|november|december|
----------------------------------+-------+--------+------+-------+-------+----+----+------+---------+-------+--------+--------+
ABC | | | 1| 2| | | | | | | | |
DEF | 11| 24| 34| 32| 19| | | | | | | |
GEH | 9| 3| 7| 18| 22| | | | | | | |
IJK | | | | 1| | | | | | | | |
A: Dynamic result column names are only possible with dynamic SQL.
This should do the job efficiently, save the dynamic column names:
SELECT c.name
, to_char(t.mon, 'Month YYYY') AS report_month
, count(*) FILTER (WHERE mor.sent_at >= t.mon - interval '12 mon' AND mor.sent_at < t.mon - interval '11 mon') AS mon1
, count(*) FILTER (WHERE mor.sent_at >= t.mon - interval '11 mon' AND mor.sent_at < t.mon - interval '10 mon') AS mon2
, count(*) FILTER (WHERE mor.sent_at >= t.mon - interval '10 mon' AND mor.sent_at < t.mon - interval '09 mon') AS mon3
-- etc.
FROM analytics_outbox mo
JOIN analytics_outbox_recipient mor ON mor.analytics_outbox_id = mo.id
JOIN customer c ON c.id = mo.customer_id
, (SELECT date_trunc('month', now())) AS t(mon) -- add once for ease of use
GROUP BY 1;
This compares unaltered values from sent_at to a constant value (computed once), which is cheaper than running each value through multiple functions before comparison.
Possible corner case issues with time zone and timestamp vs. timestamptz unresolved due to missing input.
| |
doc_23531999
|
using (var cont = _entities)
{
var query = cont.ParentTable;
if(includechild1)
query.Include("Child1");
if(includechild1)
query.Include("Child2");
return query.ToList();
}
The above code is not including child objects.But the below code does
_entities.ParentTable.Include("Child1").ToList();
Please some one suggest an idea.
A: Set result of include to variable:
using (var cont = _entities)
{
var query = cont.ParentTable;
if(includechild1)
query = query.Include("Child1");
if(includechild1)
query = query.Include("Child2");
return query.ToList();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.